Flutter中Firebase实时数据库数据仅热重载时加载问题求助
Hey there! I totally get where you're stuck—this is a super common pitfall when working with async data loading in Flutter. Let's break down the issue and fix it step by step.
问题根源
Your _fetchList function correctly pulls data from Firebase, but you never tell Flutter to rebuild the UI after the data finishes loading. When the widget initializes, initState triggers _fetchList, but the Firebase call is asynchronous. By the time the data comes back and gets added to postsList, the initial build method has already run (showing that "Nothing available!" text).
When you hot reload, Flutter rebuilds the widget, and since postsList now holds the cached data from the earlier async call, it finally shows up correctly.
解决方案
You just need to wrap the code that updates postsList in a setState call. This tells Flutter that the state has changed and triggers an immediate UI rebuild. We'll also add a check for snap.value being null to avoid crashes if there's no data in your "Posts" node.
Here's the updated _fetchList function:
_fetchList() async { DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts"); postsRef.once().then((DataSnapshot snap){ // Clear existing entries first to avoid duplicates if we call this function again postsList.clear(); if(snap.value != null){ var KEYS = snap.value.keys; var DATA = snap.value; for(var individualKey in KEYS){ Posts posts = Posts( DATA[individualKey]["date"], DATA[individualKey]["description"], DATA[individualKey]["time"], ); postsList.add(posts); } // Notify Flutter to rebuild the UI with the new data setState(() {}); } }); }
额外优化小建议
- Add a loading state: You might want to add a
bool isLoadingvariable to your state. Set it totruebefore the Firebase call, then set it tofalseinside thethenblock (withsetState). In yourbuildmethod, show aCircularProgressIndicatorwhenisLoadingis true—this gives users feedback while data loads. - Use async/await instead of then: For cleaner code, you could rewrite the function with async/await syntax:
_fetchList() async { DatabaseReference postsRef = FirebaseDatabase.instance.reference().child("Posts"); DataSnapshot snap = await postsRef.once(); postsList.clear(); if(snap.value != null){ var KEYS = snap.value.keys; var DATA = snap.value; for(var individualKey in KEYS){ Posts posts = Posts( DATA[individualKey]["date"], DATA[individualKey]["description"], DATA[individualKey]["time"], ); postsList.add(posts); } setState(() {}); } }
That should fix your issue completely—now the data will load automatically when the widget initializes, no more needing to hot reload!
内容的提问来源于stack exchange,提问作者Kshitiz Goel

