Future fetchData() async{
List<Profile> list=[];
list = await Firestore.instance
.collection("users").getDocuments().then((querySnapshot){
querySnapshot.documents.forEach((document) {
list.add( Profile(
photos: [document['photoUrl'],],
name: document['nickname'],
age: 2,
distance: 2,
education: '3',
bio:"a"
));
});
print(list);
print('list');
return list; //[Instance of 'Profile']
});
}
class _MainControllerState extends State<MainController> {
@override
Widget build(BuildContext context) {
return new Container(
padding: EdgeInsets.fromLTRB(0.0, 60.0, 0.0, 30.0),
child: FutureBuilder(
future: fetchData(),
builder: (
BuildContext context,
AsyncSnapshot snapshot,
){
if (snapshot.connectionState == ConnectionState.done ) {
if (snapshot.data == null) {
print(snapshot);//AsyncSnapshot<dynamic>(ConnectionState.done, null, null)
return Text('no data');
} else {
print('matches');
print(snapshot);
List<Match> matches = snapshot.data
.map((Profile profile) => Match(profile: profile))
.toList();
return CardStack(
matchEngine: MatchEngine(matches: matches),
);
}
} else if (snapshot.error) {
print('matches1');
} else {
print('matches2');
}
return CardStack();
},
),
);
}
}
当我打印出列表时,我可以得到[Profile的实例],但是当我在快照中打印数据时,我只能得到AsyncSnapshot(ConnectionState.done,null,null),如何解决该错误?
我试图将snapshot.connectionState == ConnectionState.done更改为snapshot.has数据。但它不起作用。
最佳答案
FutureBuilder
不知道从fetchData()
返回什么,因此必须指定要返回的List<Profile>
。由于没有类型的Future
与Future<void>
相同。
更换:
Future fetchData() async{...}
与:
Future<List<Profile>> fetchData() async{...}
同样,用
FutureBuilder
分隔代替:
builder: (
BuildContext context,
AsyncSnapshot snapshot,
){...}
做这个:
builder: (
BuildContext context,
AsyncSnapshot<List<Profile>> snapshot,
){...}
希望这可以帮助。
关于firebase - futureBuilder无法从快照获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61981602/