Rangeerror (index) error: Invalid value: Valid value range is Empty: 0

Asked

Viewed 847 times

0

An error occurred that I don’t know how to fix in Flutter:

Rangeerror (index): Invalid value: Valid value range is Empty: 0

The idea is to load a profile page and this data is recovered with http.post via JSON.

The problem is because the object does not exist until it finishes loading the JSON that comes via HTTP.

But I don’t know how to fix it. Follow my code:

class ProfilePage extends StatefulWidget {
  @override
  MapScreenState createState() => MapScreenState();
}

class MapScreenState extends State<ProfilePage> {

  var users = new List<Users>();

  MapScreenState() {
   // Recupera os dados via json
    _getDataProfile();
  }

_getDataProfile() async {
    var token = "ASDSDSADCSADASDSADASD";

    final ws = Webservice();
    ws.startLoading(context);

    ws.getPerfil(token).then((ret) {
      String retorno = ret["data"].toString();

      setState(() {
        Iterable lista = json.decode(json.encode(ret["data"]));
        users = lista.map((model) => Users.fromJson(model)).toList();

      });
    });

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemBuilder: (BuildContext context, int index) {

            log(users[index].user_name.toString());
          }
        },
      ),
  }
}

How to solve the users[index]? 'Cause he doesn’t exist until he finishes loading the http.post

1 answer

0


To wait for a request and only then build your screen, you need to use the Widget FutureBuilder, below I leave an example:

Future<List<Users>> _getDataProfile() async {
    var token = "ASDSDSADCSADASDSADASD";

    final ws = Webservice();
    ws.startLoading(context);

    final ret = await ws.getPerfil(token);
    String retorno = ret["data"].toString();
    Iterable lista = json.decode(json.encode(ret["data"]));
    var users = lista.map((model) => Users.fromJson(model)).toList();
    return users;
}

@override
Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<String>(
        future: _getDataProfile,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if (!snapshot.hasData)
                return Center(child: Text("Carregando..."));
            
            List<Users> users = snapshot.data;

            return ListView.builder(
              itemBuilder: (BuildContext context, int index) {
                log(users[index].user_name.toString());
              }
            ),
        })
    )
}

~~ There may be some minor errors in the type of method variables _getDataProfile() but then you adjust.

You can read a little more about this widget in the documentation Futurebuilder.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.