在Listview.builder中建立索引

时间:2020-11-12 01:29:05

标签: flutter flutter-layout

我从REST api收到的响应看起来像这样

useFactory: reducer.bootstrap()

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

这是我的用户界面代码

{
    "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
            }
        ]
    }
}

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

2 个答案:

答案 0 :(得分:1)

正如@xion所述,您正在为newsfeed数组使用author索引。您应该做的是将每个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)),
                        ],
                      );
                    }),
              ]),
            ),
        ),
    );
  }
}

屏幕截图:

screenshot

答案 1 :(得分:0)

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

也许您应该为您的作者需要另一个循环

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