質問

Wondering if anyone here could help?

Using Polymer Dart I've set up a service to load a Json feed using the following code:

Future loadService(){
    return HttpRequest.getString(_serviceURL)
    .then(buildView)
    .catchError(handleError);
}        

When this code executed, it does successfully hit my buildView function, but I'm also getting an error printed out from my handle error function:

void handleError(Error error){
    print(error);
}

I have 3 items in my json feed:

[
  {
    "module": "module-1",
    "data": {
      "title": "Dynamic Title 1",
      "text": "This is the dynamic text for content block 1."
    }
  },
  {
    "module": "module-2",
    "data": {
      "title": "Dynamic Title 2",
      "text": "This is the dynamic text for content block 2."
    }
  },
  {
    "module": "module-3",
    "data": {
      "title": "Dynamic Title 3",
      "text": "This is the dynamic text for content block 3."
    }
  }
]

The error I'm getting is: "RangeError: 3".

I can't find a lot of information about what could be causing this. It doesn't seem to be hindering my app, but I would like to clear it up if at all possible. If anyone has any suggestions, I'm all ears.

Thanks!

Edit: as per the suggestion by Günter Zöchbauer

Now I understand the .catchError() function catches errors from the .then() function. I thought it was only going to catch errors around the HttpRequest itself failing.

In buildView I was looping through the json object using a for loop like this:

void buildView(String jsonString){

    contentBlocks = JSON.decode(jsonString);        
    DivElement wrapper = $['content-modules-wrapper'];

    for(int i=0; i < contentBlocks.length; i++){
      Element element = new Element.tag(contentBlocks[i]['module']);
      wrapper.children.add(element);
    }
}

Which is wrong, because .length takes the JSON string length (300 something characters) which i think is a bit weird since I've converted it to an object.. anyway, i fixed it by changing the function to this:

void buildView(String jsonString){

    contentBlocks = JSON.decode(jsonString);        
    DivElement wrapper = $['content-modules-wrapper'];

    contentBlocks.forEach((block){
      Element element = new Element.tag(block['module']);
      wrapper.children.add(element);
    });
}

Is there a way to get the number of items in a json object like I was trying to do or should you always just loop through it using forEach()?

役に立ちましたか?

解決

This error is probably from your buildView. The indexes of the result are from 0 to 2 not from 1 to 3.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top