【问题标题】:Indexing in Listview.builderListview.builder 中的索引
【发布时间】:2021-02-24 00:39:30
【问题描述】:

我从 REST api 得到的响应如下所示

{
    "result": {
        "newsfeed": [
            {
                "_id": "5fa52495f0e30a0017f4dccf",
                "video": null,
                "image": null,
                "author": [
                    {
                        "_id": "5f6a412d2ea9350017bec99f",
                        "userProfile": {
                            "visits": 0,
                            "bio": "Nothing for you ",
                            "gender": "Male",
                            "university": "Bells University Of Technology"
                        },
                        "name": "Jo Shaw ",
                        "__v": 0
                    }
                ],
                "text": "have you seen this ?",
                "campus": "Technology",
                "isLiked": false
            }
        ]
    }
}

我正在使用 FutureBuilder 来处理获取数据,FutureBuilder 返回一个 ListView.builder,我使用它来构建我的布局,具体取决于响应中的项目数

这是我的 UI 的代码

     return Scaffold(
        body: FutureBuilder<TimelineModel>(
          future: _future,
          builder: (context, snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
                return Text('none');
              case ConnectionState.waiting:
                return Center(
                  child: CircularProgressIndicator(),
                );
              case ConnectionState.active:
                return Text('');
              case ConnectionState.done:
                if (snapshot.hasError || snapshot.data == null) {
                  return Scaffold(
                    backgroundColor: Theme.of(context).backgroundColor,
                    body: Column(
                      children: [
                        Container(
                          child: Center(
                            child: Text("It's empty here"),
                          ),
                        ),
                      ],
                    ),
                  );
                }  else {
                  print("length: " +
                      snapshot.data.result.newsfeed.length.toString());
                  return RefreshIndicator(
                    onRefresh: _getData,
                    child: ListView(
                      children: [
                        ListView.builder(
                            itemCount: snapshot.data.result.newsfeed.length,
                            itemBuilder: (context, index) {
                              return Column(
                                      children: <Widgets>[
//This line of code works properly and no error is gotten 
                                    Text( snapshot.data.result.newsfeed[index].text),

//Once I put in this line of code, i receive a range error (RangeError (index): Invalid value: Only valid value is 0: 1)
                                  Text(snapshot.data.result.newsfeed[index].author[index].name),
                                 ],
                              );
                           }
                         )
                       ]
                     )
                   )
                 }
               }
             }
           )
         );

这是我尝试执行 snapshot.data.result.newsfeed[index].author[index].name 或使用作者数组内对象中的任何项目时看到的错误

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    正如@xion 提到的,您正在为author 数组使用newsfeed 索引。您应该做的是将每个 newsfeed 项目中的所有作者分配给字符串,然后改用该值。下面的代码可以让您了解应该做什么。由于我无权访问您的 API,因此我对您的 json 响应进行了硬编码。

    class MyApp extends StatefulWidget {
      MyApp({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      MyAppState createState() => MyAppState();
    }
    
    class MyAppState extends State<MyApp> {
      var testJson = json.decode('''
      {
        "result": {
          "newsfeed": [
            {
              "_id": "5fa52495f0e30a0017f4dccf",
              "video": null,
              "image": null,
              "author": [
                {
                  "_id": "5f6a412d2ea9350017bec99f",
                  "userProfile": {
                    "visits": 0,
                    "bio": "Nothing for you ",
                    "gender": "Male",
                    "university": "Bells University Of Technology"
                  },
                  "name": "Jo Shaw ",
                  "__v": 0
                },
                {
                  "_id": "5f6a412d2ea9350017bec99f",
                  "userProfile": {
                    "visits": 0,
                    "bio": "Nothing for you ",
                    "gender": "Male",
                    "university": "Bells University Of Technology"
                  },
                  "name": "Jo Shaw ",
                  "__v": 0
                }
              ],
              "text": "have you seen this ?",
              "campus": "Technology",
              "isLiked": false
            }
          ]
        }
      }
      ''');
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                appBar: AppBar(
                  title: Text(widget.title),
                ),
                body: Center(
                  child: ListView(children: [
                    ListView.builder(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        itemCount: testJson["result"]["newsfeed"].length,
                        itemBuilder: (context, index) {
                          String authors = '';
                          List<dynamic> authorsArray = testJson["result"]["newsfeed"][index]["author"];
                          for (int i = 0; i < authorsArray.length; i++) {
                            authors += i == (authorsArray.length - 1) ? authorsArray[i]["name"].toString() : authorsArray[i]["name"].toString() + ", ";
                          }
                          return Column(
                            children: [
                              Padding(
                                padding: EdgeInsets.all(10.0),
                                child: Text(
                                  "Title: " +
                                      testJson["result"]["newsfeed"][index]["text"],
                                  style: TextStyle(
                                      fontWeight: FontWeight.bold, fontSize: 18.0),
                                ),
                              ),
                              Text("Authors: " + authors,
                                  style: TextStyle(
                                      color: Colors.black54,
                                      fontStyle: FontStyle.italic)),
                            ],
                          );
                        }),
                  ]),
                ),
            ),
        );
      }
    }
    

    截图:

    【讨论】:

    • 这很好用,我不得不对 for 循环进行一些调整,因为它一直在迭代,所以我删除了 authors += i 并且只是做了 i == (authorsArray.length - 1) ?作者 = authorsArray[i]["name"].toString() : authors = authorsArray[i]["name"].toString() + ", ";
    【解决方案2】:

    您的作者正在访问与您的新闻源相同的索引

    也许您应该为您的作者提供另一个循环

     ListView.builder(
                                itemCount: snapshot.data.result.newsfeed.length,
                                itemBuilder: (context, index) {
                                  return Column(
                                          children: <Widgets>[
                                        Text( snapshot.data.result.newsfeed[index].text),
    Text(snapshot.data.result.newsfeed[index].author[index].name), // <--- this line author[Index] hits error, not news the newsfeed
                                     ],
                                  );
                               }
                             )
    

    【讨论】:

    • 好的,你能不能给个代码来告诉你怎么做?
    猜你喜欢
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-03-14
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多