从 Firebase 检索后,Flutter setState 函数未更新列表。
我正在尝试开发一个 Flutter 应用程序。我没有更新 setState() 函数中的列表。该列表已成功从 firebase 检索。我已在 Services.dart
文件中编写了 firebase 连接。
但是我的方法 _getList()
没有获取 main.dart
文件中的值。
main.dart
class DetailsPageState extends State<DetailsPage> {
List<Product> list;
@override
void initState() {
_checkUser(); // for getting user id from firebase auth
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Container(
child:new Text("data");
);
)
}
void _checkUser(){
debugPrint("Entering in _checkUser");
this.firebaseAuth.onAuthStateChanged.listen((firebaseUser)async{
_getList(firebaseUser.uid);
});
}
void _getList(String id)
debugPrint("Entering in _getList");
Services.retrieveItems(firestore, uid).then((onValue){
setState(() {
list=onValue;
debugPrint("items list:"+onValue.length.toString());
debugPrint("items list:"+listCart.length.toString());
});
});
}
}
Services.dart
static Future<List> retrieveItems(Firestore firestore, String userId) async {
List<Product> items = new List<Product>();
try {
firestore.collection("Items").document(userId)
.collection("ItemsMain").snapshots().listen((QuerySnapshot snapshot) {
List docList = snapshot.documents;
items = snapshot.documents.map((documentSnapshot) => Product.fromMap(documentSnapshot.data)).toList();
debugPrint("items:"+items.length.toString());
//return items;
});
} on Exception catch (e) {
print (e.toString());
}
debugPrint("items 2:"+items.length.toString());
return items;
}
预期结果:
输入_checkUser
进入_getList
项目:6
项目 2:6
项目列表:6
项目列表:6
实际结果:
输入_checkUser
进入_getList
项目列表:0
项目列表:0
项目 2:0
项目:6
最佳答案
您将在元素装载之前将其退回。解决此问题的最简单方法是在 retrieveItems
中使用 await
来等待从 Firestore 加载数据:
static Future<List> retrieveItems(Firestore firestore, String userId) async {
List<Product> items = new List<Product>();
var snapshot = await firestore.collection("Items").document(userId)
.collection("ItemsMain").getDocuments()
List docList = snapshot.documents;
items = snapshot.documents.map((documentSnapshot) => Product.fromMap(documentSnapshot.data)).toList();
debugPrint("items:"+items.length.toString());
return items;
}
你会注意到我:
- 调用
get()
而不是listen()
。由于listen()
开始主动监视集合,因此无法判断它何时“完成”。另一方面,get()
返回文档一次,然后完成。 - 删除了异常处理,只是为了使代码更具可读性。但我也建议仅在您实际处理异常时才在这样的功能代码中添加异常处理程序。将“记录并继续”处理程序留给更高级别的代码,例如您的 main 方法。
关于Firebase 列表未在设置状态下更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53867404/