Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

RangeError (index): Invalid value: Valid value range is empty: 0 | Flutter Firebase

Hy there. So my problem is this when the page loads it shows the follwing error for 1-2 seconds but then the data shows perfectly. It shouldn't have happen because i have provided "initialData" to "FutureBuilder". Can anybody tells me what i am missing.

Note: I cannot use if(snapshot.connectionState == ConnectionState.waiting) return CircleProgressIndicator(); because i am using PageView.builder and when i move to 2nd page it refresh again and come to 1st page automatically

═══════ Exception caught by widgets library ═══════════════════════════════════
The following RangeError was thrown building FutureBuilder<List<dynamic>>(dirty, state: _FutureBuilderState<List<dynamic>>#bad68):
RangeError (index): Invalid value: Valid value range is empty: 0

The relevant error-causing widget was
FutureBuilder<List<dynamic>>
When the exception was thrown, this was the stack
#0      List.[] (dart:core-patch/growable_array.dart:177:60)
#1      _TasksState.build.<anonymous closure>
#2      _FutureBuilderState.build
#3      StatefulElement.build
#4      ComponentElement.performRebuild
...
════════════════════════════════════════════════════════════════════════════════

Here is my code:

body: FutureBuilder(
        initialData: [],
        future: Future.wait([
          getRequests(),
          getCNIC(),
          ]),
        builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
          indexLength = snapshot.data[0].length;
          cnicCheck = snapshot.data[1];
          if (indexLength == 0)
            return SizedBox(
              child: Center(
                child: Text(
                  "No Buyer Requests",
                  style: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 20,
                      color: kPrimaryColor),
                ),
              ),
            );
            return SizedBox(
              child: PageView.builder(
                itemCount: indexLength,
                physics: PageScrollPhysics(),
                controller: PageController(viewportFraction: 1.0),
                onPageChanged: (int index) => setState(() => _index = index),
                itemBuilder: (_, i) {
                  return SingleChildScrollView(
                    child: Card(
                      margin: EdgeInsets.all(10),
                      child: Wrap(
                        children: <Widget>[
                          ListTile(
                            leading: CircleAvatar(
                                backgroundColor: kPrimaryColor.withOpacity(0.8),
                                backgroundImage:
                                    AssetImage('assets/images/nullUser.png'),
                                child: snapshot.data[0][i]['PhotoURL'] != null
                                    ? ClipRRect(
                                        borderRadius: BorderRadius.circular(50),
                                        child: Image.network(
                                          snapshot.data[0][i]['PhotoURL'],
                                          width: 50,
                                          height: 50,
                                          fit: BoxFit.cover,
                                        ),
                                      )
                                    : ClipRRect(
                                        borderRadius: BorderRadius.circular(50),
                                        child: Image.asset(
                                          'assets/images/nullUser.png',
                                          width: 50,
                                          height: 50,
                                          fit: BoxFit.cover,
                                        ),
                                      )),
                            title: Text(
                              snapshot.data[0][i]['Email'],
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w700,
                                color: Colors.black.withOpacity(0.7),
                              ),
                            ),
                            subtitle: Text(
                              snapshot.data[0][i]['Time'],
                              style: TextStyle(
                                  color: Colors.black.withOpacity(0.6)),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(16.0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.stretch,
                              children: [
                                Container(
                                  decoration: BoxDecoration(
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(5)),
                                    color: Colors.grey[200],
                                  ),
                                  padding: EdgeInsets.all(10),
                                  child: Text(
                                    snapshot.data[0][i]['Description'],
                                    style: TextStyle(
                                        color: Colors.black.withOpacity(0.6)),
                                  ),
                                ),
                                SizedBox(
                                  height: 8,
                                ),
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(5)),
                                      border:
                                          Border.all(color: Colors.grey[300])),
                                  child: ListTile(
                                    leading: Icon(Icons.category_outlined),
                                    title: Text(
                                      'Category : ${snapshot.data[0][i]['Category']}',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 8),
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(5)),
                                      border:
                                          Border.all(color: Colors.grey[300])),
                                  child: ListTile(
                                    leading: Icon(Icons.location_pin),
                                    title: Text(
                                      snapshot.data[0][i]['Location'],
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 8),
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(5)),
                                      border:
                                          Border.all(color: Colors.grey[300])),
                                  child: ListTile(
                                    leading: Icon(
                                      Icons.attach_money,
                                      color: kGreenColor,
                                    ),
                                    title: Text(
                                      'Budget : Rs.${snapshot.data[0][i]['Budget']}',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: kGreenColor,
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(height: 8),
                                Container(
                                  decoration: BoxDecoration(
                                      borderRadius:
                                          BorderRadius.all(Radius.circular(5)),
                                      border:
                                          Border.all(color: Colors.grey[300])),
                                  child: ListTile(
                                    leading: Icon(Icons.timer),
                                    title: Text(
                                      'Duration : ${snapshot.data[0][i]['Duration']}',
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.grey,
                                      ),
                                    ),
                                  ),
                                ),
                                SizedBox(
                                  height: 35,
                                ),
                                RaisedButton(
                                      padding:
                                          EdgeInsets.symmetric(vertical: 10),
                                      child: Text('Send Offer'),
                                      textColor: Colors.white,
                                      color: Colors.green,
                                      onPressed: () {
                                        if (cnicCheck == "verified") {
                                          print(cnicCheck);
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (_) => SendOffer(snapshot.data[0][i].id),
                                            ),
                                          );
                                        } else {
                                          Navigator.push(
                                            context,
                                            MaterialPageRoute(
                                              builder: (_) => VerifyCNIC(),
                                            ),
                                          );
                                        }
                                      },
                                    ),
                                SizedBox(
                                  height: 15,
                                ),
                                Center(
                                  child: Text(
                                    "${i + 1}/$indexLength",
                                    style: TextStyle(fontSize: 13),
                                  ),
               

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem: You try to access a value at an index of the list that does not exist. This is because, the provided initial data is an empty list. When the ′FutureBuilder′ first gets called all the code that it contains is executed using the initial data. And so the first two lines would throw an error message because you try to get the first and the second element from the list when it is in fact empty and does not have a first or second element.

The solution: You have to decide for yourself handle how you show your user that the data is still loading. But if there is the possibility that your list may be empty or may only contain one element you definitely have to check if this is the case before you try accessing these items from the list.

So just use:

if (snapshot.data.length > 1)

before you execute:

indexLength = snapshot.data[0].length;
cnicCheck = snapshot.data[1];

I really hope I could help :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...