[Solved] FLUTTER: RangeError (index): Index out of range: no indices are valid: 0 (Pass Parameters)

Question

Asked by G28 on December 11, 2021 (source).

I hope you can help me find a way to solve this problem that arises, I am trying to pass the data from the list and the index to the next tab.

but I get this error: RangeError (index): Index out of range: no indices are valid: 0

I leave the code that I use.

so I get the data and fill the list:

 Future<List> getData() async {
    final response = await http.get(url);
    return json.decode(response.body);
  }

body: FutureBuilder<List>(
        future: getData(),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? ItemList(
                  list: snapshot.data ?? [],
                )
              : new Center(
                  child: CircularProgressIndicator(),
                );
        },
      )

And so I try to get the index and the list and where the error points to me:

  class ItemList extends StatelessWidget {
  
  const ItemList({Key? key, required this.list}) : super(key: key);

  final List list;

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.isEmpty ? 0 : list.length,
      itemBuilder: (context, i) {
        return Container(
          padding: const EdgeInsets.all(10.0),
          child: GestureDetector(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => Detail(list: list, index: i),//<----errror
                ),
              );
            },

my other tab is like this:

class Detail extends StatefulWidget {
  List list = [];
  int index = 0;
  Detail({index, list});

  @override
  _DetailState createState() => _DetailState();
}

I recover it in the following way:

widget.list[widget.index]['id']

json

[{" id ":" 1 "," nombre de usuario ":" Victor "," contraseña ":" 12345 "," nivel ":" admin "}, {" id ":"5"," nombre de usuario ":" sekia "," contraseña ":" 12345 "," nivel ":" cliente "}]

Answer

Question answered by h8moss (source).

The problem comes from the way you are initializing your Detail page

Detail({index, list});

You need to add this to the initialization, like this:

Detail({this.index, this.list});

I believe that should solve the problem.

FLUTTER FLUTTER-FUTUREBUILDER FLUTTER-LISTVIEW FLUTTER-WEB
SHARE: