Flutter开发中Firestore取值打印正常但存入List Map后读取为Null问题
问题原因
- 初始化顺序错误:
popularPlacesList在_HomneState类实例化时就完成了初始化赋值,此时还没有调用异步请求方法getPopularPlaces,全局变量studioName处于默认的null状态,列表第一个元素的name字段直接存入了此时的null值。 - 异步执行时序问题:
getPopularPlaces是异步方法,Firestore网络请求属于耗时操作,会在State初始化、页面首次渲染完成后才会返回结果,此时给studioName赋的新值不会自动同步到已经初始化完成的popularPlacesList中。 - 状态未触发更新:就算后续修改了
studioName的值,没有调用setState通知Flutter刷新UI,ListView也不会读取到最新的数值。
解决方案
调整代码逻辑,把变量放到State内部管理,请求完成后手动更新列表并触发UI刷新,修改后的参考代码如下:
class Homne extends StatefulWidget { @override _HomneState createState() => _HomneState(); } class _HomneState extends State<Homne> { CollectionReference users = FirebaseFirestore.instance.collection('PopularPlacesList'); // 把变量移到State内部管理,避免全局变量污染 String? studioName; // 初始化列表时动态字段先占位 List<Map<String, String>> popularPlacesList = [ { 'name': '加载中', 'image': 'assets/popular_places/miami.jpg', 'property': '783 properties' }, { 'name': 'Singapore', 'image': 'assets/popular_places/singapore.jpg', 'property': '593 properties' }, { 'name': 'New York', 'image': 'assets/popular_places/newyork.jpg', 'property': '1025 properties' }, { 'name': 'Venice', 'image': 'assets/popular_places/venice.jpg', 'property': '290 properties' }, { 'name': 'Vietnam', 'image': 'assets/popular_places/vietnam.jpg', 'property': '193 properties' } ]; @override void initState() { super.initState(); // 页面初始化时触发异步请求 getPopularPlaces(); } getPopularPlaces() async { final snapShot = await FirebaseFirestore.instance .collection('PopularPlacesList') .doc('ksx1hVJn4Jf46ACFBbp7') .get(); var data = snapShot.data(); if(data != null && data['name'] != null){ // 赋值后更新列表并触发UI刷新 setState(() { studioName = data['name']; popularPlacesList[0]['name'] = studioName!; }); } } // 原有build方法、ListView代码无需调整 }
内容的提问来源于stack exchange,提问作者M A
相关产品推荐
相关产品推荐

