Home > Blockchain >  RangeError (index): Invalid value: Only valid value is 0: 1 flutter fetch api
RangeError (index): Invalid value: Only valid value is 0: 1 flutter fetch api

Time:11-24

I can't fetch the next address

but I can fetch sequence shipto 0

RangeError (index): Invalid value: Only valid value is 0: 1

after some fixes type 'sting' is not a subtype of type 'int' of 'index'

The data in the address will be included in the same set of items.

Please help me I am practicing fetch api

List<dynamic> pos = <dynamic>[];
bool isLoading = false;
 @override
void initState() {
super.initState();
this.fetchMos();
 }

 Future fetchMos() async {
var client = http.Client();
String mosUrl =
    ',';
var url = Uri.parse(mosUrl);
var headers = {'Client-Token': ''};
var response = await client.get(url, headers: headers);
if (response.statusCode == 200) {
  var items = jsonDecode((utf8.decode(response.bodyBytes)))['items'];

  setState(() {
    pos = items;
    isLoading = false;
  });
} else {
  setState(() {
    pos = [];
    isLoading = false;
  });
}


                     

                    

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    elevation: 0.0,
  ),
  body: ListView.builder(
    itemBuilder: (context, index) {
      if (pos.length > 0) {
        return _listItem(index);
      } else {
        return Center(child: CircularProgressIndicator());
      }
    },
    itemCount: pos.length   1,
  ),
  );
 }

_listItem(index) {
return Card(
  child: ListTile(
    leading: const CircleAvatar(
      child: Icon(Icons.emoji_emotions),
    ),
    title: Text(
      pos[index]['addr1'],
      style: const TextStyle(
        fontSize: 17,
        fontWeight: FontWeight.bold,
      ),
    ),
    subtitle: Text(
      pos[index]['shipto'],
    ),
  ),
);
}





{
"items": [
    {
        "custnum": "",
        "name": "",
        "address": [
            {
                "shipto": 0,
                "addr1": "",
                "thanon": "",
                "tambon": "",
                "amphur": "",
                "prov_code": "",
                "province": "",
                "zipcode": "",
                "country": "",
                "contact": "",
                "postcode": ""
            },
            {
               "shipto": 1,
                "addr1": "",
                "thanon": "",
                "tambon": "",
                "amphur": "",
                "prov_code": "",
                "province": "",
                "zipcode": "",
                "country": "",
                "contact": "",
                "postcode": ""
            },
            {
                "shipto": 2,
                "addr1": "",
                "thanon": "",
                "tambon": "",
                "amphur": "",
                "prov_code": "",
                "province": "",
                "zipcode": "",
                "country": "",
                "contact": "",
                "postcode": ""
            },
            {
                "shipto": 3,
                "addr1": "",
                "thanon": "",
                "tambon": "",
                "amphur": "",
                "prov_code": "",
                "province": "",
                "zipcode": "",
                "country": "",
                "contact": "",
                "postcode": ""
            }
        ]
    }
],
"total_records": 1,
"total_pages": 1,
"current_page": 1

CodePudding user response:

Currently your variable pos does not contain addresses. You should add the following code after var items = jsonDecode((utf8.decode(response.bodyBytes)))['items'];

var addresses = (items[0] as Map<String, dynamic>)['address'] as List;
setState(() {
  pos = addresses;
  loading = false;
});

Then in ListView.builder change parameter itemCount to pos.length.

Lastly, you are trying to give integer as parameter to Text widget, which only accepts String, so change current code to the following.

Text(
  pos[index]['shipto'].toString(),
)

Remark: Learn about data models and JSON serialization in Dart, don't use map/json, but try using models.

CodePudding user response:

If you set the itemCount of ListView.builder widget, you'll get an index error.

Try changing your code to this

 @override
 Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(
    elevation: 0.0,
  ),
  body: ListView.builder(
    itemBuilder: (context, index) {
      if (pos.length > 0) {
        return _listItem(index);
      } else {
        return Center(child: CircularProgressIndicator());
      }
    },
    itemCount: pos.length, // change here
  ),
  );
 }
  • Related