簡體   English   中英

RangeError(索引):無效值:有效值范圍為空:0 | Flutter Firebase

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

嘿那里。 所以我的問題是,當頁面加載時它會顯示以下錯誤 1-2 秒,但隨后數據顯示完美。 它不應該發生,因為我已經向“FutureBuilder”提供了“initialData”。 誰能告訴我我錯過了什么。

注意:我不能使用if(snapshot.connectionState == ConnectionState.waiting) return CircleProgressIndicator(); 因為我正在使用 PageView.builder 並且當我移動到第二頁時它再次刷新並自動進入第一頁

═══════ 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
...
════════════════════════════════════════════════════════════════════════════════

這是我的代碼:

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),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              ),
            );
        },
      ),

您的問題:您嘗試訪問不存在的列表索引處的值。 這是因為,提供的初始數據是一個空列表。 當“FutureBuilder”第一次被調用時,它包含的所有代碼都使用初始數據執行。 所以前兩行會拋出一個錯誤消息,因為你試圖從列表中獲取第一個和第二個元素,而實際上它是空的並且沒有第一個或第二個元素。

解決方案:您必須自己決定如何向用戶顯示數據仍在加載。 但是,如果您的列表可能為空或可能僅包含一個元素,則在嘗試從列表中訪問這些項目之前,您必須檢查是否是這種情況。

所以只需使用:

if (snapshot.data.length > 1)

在執行之前:

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

我真的希望我能幫上忙:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM