我正在使用Future,根据用户输入来搜索Firebase用户。然后,future将结果作为列表返回,但是future构建器无法在UI中显示数据。如何在用户界面中构建此数据?另外,使用Future Builder是这样做的正确方法吗?
FutureBuilder(
future: userSearch(_userSearchController.text),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else {
return new CircularProgressIndicator();
}
},
)
Future userSearch(String userSearch) async {
QuerySnapshot result = await Firestore.instance
.collection("users")
.where("name", isEqualTo: userSearch)
.getDocuments();
final List<DocumentSnapshot> docs = result.documents;
return docs;
}
使用流编辑
StreamBuilder(
stream: userSearch(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
print(snapshot.data.length);
return ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return userWidget(snapshot.data[index].data);
});
} else {
return new CircularProgressIndicator();
}
},
)
Stream<dynamic> userSearch() async* {
print("User Search");
QuerySnapshot result = await Firestore.instance
.collection("users")
.where("name", isEqualTo: _userSearchController.text.toLowerCase())
.getDocuments();
yield result.documents;
}
答案 0 :(得分:1)
由于已经满足了基于userInput的搜索,因此您应该使用Streambuilder。将来只会返回一次,但是只要更改返回值,streambuilder就会始终重建您的小部件。
要构建UI,可以使用ListView.builder:
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return BuildYourWidget(snapshot.data[index]);
});
} else {
return CircularProgressionIndicator();
}
BuilYourWidget(dynamic yoursnapshotdata) {
return ListTile(trailing: Text('hello'), title: Text(yoursnapshotdata));
}