简体   繁体   中英

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

been stuck on this for a bit. Firebase Real Time Database using SDK.

I am able to successfully print the correct data in the original listening event but it does not seem to persist outside of it. Been trying a bunch of different things but the docs say this should work.

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
    ),

This is the expected behavior. Since the data is has to come from the.network, it may take some time before it is available and happens asynchronously. Since your rendering code doesn't wait for that (it can't, as that would block the user from using the app), you Text(map.length.toString()) uses the initial value of the map that you gave it here: Map<dynamic, dynamic> map = {} .

The solution is to either store the map in the state of the widget, as calling setState will cause Flutter to redraw the widget, or to use a StreamBuilder to accomplish the same.

An example of that last approach would look something like this:

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())
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM