Izwan
Izwan

Reputation: 53

Flutter Display value from Realtime Database. Got Index Error

I just started using flutter for web. Currently I'm trying to display data from realtime database. and this is the code that fetch the data and display it.

class Company extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    DatabaseReference refe = database().ref('Company');
    return Scaffold(
      appBar: AppBar(),
      body: StreamBuilder(
        stream: database().ref('Company').onValue,
        builder: (context, snap) {
          if (snap.hasData) {
            List key1 = [];
            List item1 = [];
            int len;
            refe.once("value").then(
              (data) {
                len = data.snapshot.numChildren();
                var a = data.snapshot.toJson();
                a.forEach(
                  (key, values) {
                    key1.add(key);
                    item1.add(values);
                  },
                );
              },
            );

            return ListView.builder(
              itemCount: len,
              itemBuilder: (context, index) {
                return Row(
                  children: [
                    Expanded(
                      child: Card(child: Text(item1[index]['compName'])),
                    ),
                    Expanded(
                      child: Card(child: Text(item1[index]['companyID'])),
                    ),

                    //Text('Company Name'),
                  ],
                );
              },
            );
          } else
            return CircularProgressIndicator();
        },
      ),
    );
  }
}

The code itself runs fine but i got an error just below the results i display.

Displayed the data but have flutter error below it

The following IndexError was thrown building: RangeError (index): Index out of range: index should be less than 25: 25

Does anyone know the reason for the error?

Upvotes: 2

Views: 266

Answers (1)

Vitor
Vitor

Reputation: 840

Welcome to Stack Overflow, that's actually a simple problem. as @ClaudioCastro said, you're trying to access an item out of range, it happens when you have an array (list) and you try to access an item that is not available in it. For example:

List list = [1, 2, 3] // index 0, 1, 2

if you try to access an element that doesn't exist:

print(list[3]) // RangeError (index): Index out of range

As @ClaudioCastro also said, this is coming from your ListView builder which you are probably giving a higher number to the itemCount than you should.

Try to print the value of len and item1.length, so then check if you get the same result.

Upvotes: 1

Related Questions