如何在Flutter中构建动态列表?

Pat*_*cow 10 listview asynchronous flutter

我将这个小部件附加到一个Scaffold正文.小部件获取一个async返回json对象的方法.

我想从该json对象动态构建一个列表.问题是屏幕是空的.出于某种原因,当列表准备好或类似的东西时,这个小部件需要刷新自己.

有任何想法吗?

class TestList extends StatelessWidget {
  final quiz;

  TestList({this.quiz});

  @override
  Widget build(BuildContext context) {
    var listArray = [];

    this.quiz.then((List value) {   // this is a json object

      // loop through the json object
      for (var i = 0; i < value.length; i++) {

        // add the ListTile to an array
        listArray.add(new ListTile(title: new Text(value[i].name));

      }
    });

    return new Container(
        child: new ListView(
      children: listArray     // add the list here.
    ));
  }
}
Run Code Online (Sandbox Code Playgroud)

Hem*_*Raj 11

您可以使用它setState来重建UI.

例:

class TestList extends StatefulWidget {

  final Future<List> quiz;

  TestList({this.quiz});

  @override
  _TestListState createState() => new _TestListState();

}

class _TestListState extends State<TestList> {

  bool loading = true;

  _TestListState(){
    widget.quiz.then((List value) {

      // loop through the json object
      for (var i = 0; i < value.length; i++) {

        // add the ListTile to an array
        listArray.add(new ListTile(title: new Text(value[i].name));

        }

            //use setState to refresh UI
            setState((){
          loading = false;
        });

    });
  }

  @override
  Widget build(BuildContext context) {

    List<Widget> listArray = [];

    return new Container(
        child: new ListView(
            children: loading?[]:listArray     // when the state of loading changes from true to false, it'll force this widget to reload
        ));

  }

}
Run Code Online (Sandbox Code Playgroud)


Ser*_*ace 6

您可以使用 FutureBuilder 来帮助处理小部件状态:

new FutureBuilder<List>(
  future: widget.quiz,
  builder:
      (BuildContext context, AsyncSnapshot<List> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none:
        return new Text('Waiting to start');
      case ConnectionState.waiting:
        return new Text('Loading...');
      default:
        if (snapshot.hasError) {
          return new Text('Error: ${snapshot.error}');
        } else {
          return new ListView.builder(
              itemBuilder: (context, index) =>
                  new Text(snapshot.data[index].name),
              itemCount: snapshot.data.length);
        }
    }
  },
)
Run Code Online (Sandbox Code Playgroud)

基本上,它会根据未来状态通知 builder 上指定的方法。一旦 future 收到一个值并且不是错误,您可以使用 ListView.builder 来制作列表,这是当所有项目都是相同类型时创建列表的便捷方法。

更多信息请访问https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html