簡體   English   中英

Flutter Firebase 實時數據庫不在偵聽器代碼之外存儲值

[英]Flutter Firebase real time database not storing values outside of listener code

一直堅持這一點。 Firebase 使用 SDK 的實時數據庫。

我能夠在原始監聽事件中成功地打印出正確的數據,但它似乎並沒有在它之外持續存在。 一直在嘗試一堆不同的東西,但文檔說這應該有效。

Widget build(BuildContext context) {
  Map<dynamic, dynamic> map = {}; 

  DatabaseReference materials =
      FirebaseDatabase.instance.ref('Users/${widget.uid}/materials');

  materials.onValue.listen((DatabaseEvent event) {
    map = event.snapshot.value as Map;
    print(map);
    print(map.keys.elementAt(0).toString());
    print(map.length); //HERE IT PRINTS 4 AS IT SHOULD AND ALL ABOVE DATA CORRECT
  });

  return Scaffold(
    backgroundColor: Colors.grey[400],
    appBar: AppBar(
      automaticallyImplyLeading: false,
      backgroundColor: Colors.grey[600],
      centerTitle: true,
      title: Text(map.length.toString()), //HERE IT PRINTS 0 AND ALL THE REST OF THE CODE USING MAP VALUES ARE NULL
    ),

這是預期的行為。 由於數據必須來自網絡,因此可能需要一些時間才能可用並且異步發生。 由於您的渲染代碼不會等待它(它不能,因為那樣會阻止用戶使用該應用程序),您Text(map.length.toString())使用您給它的 map 的初始值這里: Map<dynamic, dynamic> map = {}

解決方案是將 map 存儲在小部件的 state 中,因為調用setState將導致 Flutter 重繪小部件,或者使用StreamBuilder來完成相同的操作。

最后一種方法的示例如下所示:

title: StreamBuilder(
  stream: materials.onValue,
  builder: (context, AsyncSnapshot<Event> snapshot) {
    if (snapshot.hasData && !event.hasError && event.data.snapshot.value != null) {
      map = snapshot.snapshot.value as Map
      return Text(map.length.toString())
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM