我需要从API获取数据并将其放入ListView。它是通过按FloatingActionButton调用“ _refresh()”方法来发生的。它可以接收10只猫,并列在清单中。在此方法中,我调用了另一个方法“ _builtListView()”,该方法应该创建一个ListView元素及其Cat行,但是,尽管它发生在一个类中,但cats似乎在另一种方法中消失了。
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!
我没有得到什么?
您的错误属于_refresh
功能。处理未来时,请访问