Flutter如何从Firebase实时数据库获取当前用户名并展示在导航抽屉
问题原因
你的getUsername函数没有正确返回异步查询的结果:你在.then回调中返回的用户名只会传递给回调本身,外层的getUsername函数没有返回任何有效Future对象,导致FutureBuilder始终无法拿到返回的用户名数据,一直停留在加载状态。
修正方案
你可以选择以下任意一种方式修改getUsername函数:
方案1:保留.then写法,增加return
Future<String> getUsername() async { final ref = FirebaseDatabase.instance.reference(); User cuser = await firebaseAuth.currentUser; // 这里增加return,把数据库查询的Future返回给外层函数 return ref.child('User_data').child(cuser.uid).once().then((DataSnapshot snap) { final String userName = snap.value['name'].toString(); print(userName); return userName; }); }
方案2:改用更直观的async/await写法(更推荐)
Future<String> getUsername() async { final ref = FirebaseDatabase.instance.reference(); User cuser = await firebaseAuth.currentUser; // 直接await数据库查询结果,不需要嵌套.then回调 DataSnapshot snap = await ref.child('User_data').child(cuser.uid).once(); final String userName = snap.value['name'].toString(); print(userName); return userName; }
额外优化建议
可以给FutureBuilder增加错误状态处理,避免出现异常时无提示:
FutureBuilder<String>( future: getUsername(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Text("Loading data...", style: TextStyle( fontFamily: 'Montserrat', fontSize: 13, color: const Color(0xff000000), fontWeight: FontWeight.w700, ), textAlign: TextAlign.left, ); } if (snapshot.hasError) { return Text("加载失败: ${snapshot.error}", style: TextStyle( fontFamily: 'Montserrat', fontSize: 13, color: Colors.red, fontWeight: FontWeight.w700, ), textAlign: TextAlign.left, ); } if (snapshot.hasData) { return Text( snapshot.data!, style: TextStyle( fontFamily: 'Montserrat', fontSize: 13, color: const Color(0xff000000), fontWeight: FontWeight.w700, ), textAlign: TextAlign.left, ); } return Text("暂无数据", style: TextStyle( fontFamily: 'Montserrat', fontSize: 13, color: const Color(0xff000000), fontWeight: FontWeight.w700, ), textAlign: TextAlign.left, ); }, )
内容的提问来源于stack exchange,提问作者Nabia Salman
相关产品推荐
相关产品推荐

