从Cloud Firestore获取数据并为Flutter应用显示

问题描述 投票:0回答:2

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

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

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();
  }
database firebase flutter google-cloud-firestore flutter-layout
2个回答
0
投票

此错误是因为,您应该像这样初始化用户变量var users = {};代替var user;


0
投票

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

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

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

    String myEmail = "[email protected]";
    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");
          }
        }

但是我认为可能会有更好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.