gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:31:49 25 4
gpt4 key购买 nike

我将此小部件附加到 Scaffold 主体上。小部件获得一个返回 json 对象的 async 方法。

我想从那个 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.
));
}
}

最佳答案

您可以使用 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
));

}

}

关于listview - 如何在 Flutter 中构建动态列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47826776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com