【发布时间】:2020-03-12 21:25:00
【问题描述】:
我需要从 API 获取数据并将其放入 ListView。它通过按下 FloatingActionButton 调用“_refresh()”方法来实现。它收到 10 只猫并将其放入列表中。 在这个方法中,我调用了另一个方法“_builtListView()”,它应该创建一个 ListView 元素及其 Cat 行,但似乎猫在另一个方法中消失了,尽管它发生在一个类中。
class _MyHomePageState extends State<MyHomePage> {
var catList = new List<Cat>();
void _refresh() {
var catsFuture = fetchCats();
catsFuture.then((catList) {
print("Future cats catch: " + catList.length.toString() + " cats.");
_builtListView();
});
setState(() { });
}
Future<List<Cat>> fetchCats() async {
// getting cats code
print("fetchCats(): " + catListFetched.length.toString() + " cats.");
return catListFetched;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: _builtListView(),
floatingActionButton: FloatingActionButton(
onPressed: _refresh,
tooltip: 'Refresh',
child: Icon(Icons.refresh),
),
);
}
Widget _builtListView() {
if (catList.isEmpty)
print("_builtListView, catList is empty!");
return ListView.builder(
itemCount: catList == null ? 0 : catList.length,
itemBuilder: (context, index) {
return ListTile(
title: Text("Text " + index.toString()), //catList[index].toString()),
);
},
);
}
}
我在控制台看到了什么:
I/flutter (10172): _builtListView, catList is empty!
//_refresh
I/flutter (10172): _builtListView, catList is empty!
I/flutter (10172): fetchCats(): 10 cats.
I/flutter (10172): Future cats catch: 10 cats.
I/flutter (10172): _builtListView, catList is empty!
我没有得到什么?
【问题讨论】:
标签: android flutter dart future