繁体   English   中英

从云 Firestore 获取数据并显示给 Flutter 应用程序

[英]Getting Data from cloud Firestore and showing for flutter app

我有一个个人资料屏幕。 并从云存储获取数据并显示在配置文件屏幕中。

我想检索数据时没有问题,但问题出在显示时。 我不知道我是怎么搞砸的? 现在错误仅显示“正在加载”文本。 帮我

class Profile extends StatefulWidget {
 @override
 _ProfileState createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
 bool userFlag = false;
 var users;

 @override
 void initState() {
   // TODO: implement initState
   super.initState();
   UserManagement().getData().then((QuerySnapshot docs){
      userFlag = true;
      users = docs.documents[0].data;
   });
 }
 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text('Profile'),
     ),
     body: Container(
       padding: EdgeInsets.all(50),
       child: Column(
         children:<Widget>[
         name(),
         ],
       ),
     ),
   );
 }

Widget name() {
   return Container(
     child: Row(
       mainAxisAlignment: MainAxisAlignment.start,
       children: <Widget>[
         Text(
           "Name",
           style: TextStyle(fontWeight: FontWeight.w600,fontSize: 18),
         ),
         SizedBox(
           width: 45,
         ),
           userFlag ? Text(users['Name'],
           style: TextStyle(fontWeight: FontWeight.w400,fontSize: 18),
         )
       :Text('Loading'),
       ],
     ),
   );
 }

为了获取数据,我有:

getData(){
    return Firestore.instance
        .collection('users').getDocuments();
  }

我以这种方式获取和使用数据:

QuerySnapshot Users = await _fs
        .collection("users")
        .getDocuments();

它将为您提供用户集合中的所有用户。 所以为了特定地检索一个用户,我使用了“for循环”。

    String myEmail = "email@gmail.com";
    String username;

    for (var user in users.documents) {
          if ( myEmail == user.data["email"]){
            // you have all the field for the user using "myEmail".
            username = user.data["username"];
          } else {
            print("There is no User with this email");
          }
        }

但我认为可能有更好的方法来做到这一点。

这个错误是因为,你应该像var users = {};一样初始化你的用户变量var users = {}; 而不是var user;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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