方法2不填充名字

潘卡伊

关于

从Firebase获取当前用户数据。

方法1

var currentUser = FirebaseAuth.instance.currentUser;
if (currentUser != null) {
  var user = FirebaseFirestore.instance
      .collection("tblusers")
      .doc(currentUser.uid)
      .get()
      .then((DocumentSnapshot documentSnapshot) {
    if (documentSnapshot.exists) {
      _controllerFirstName.text = documentSnapshot.data()["first_name"];
    }
  });
}

我上面的代码行工作正常。下面是完整的代码。

class AccountForm extends StatelessWidget {
  var firstName = "";
  
  TextEditingController _controllerFirstName = new TextEditingController();
  var _accountFormKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    var currentUser = FirebaseAuth.instance.currentUser;
    if (currentUser != null) {
      var user = FirebaseFirestore.instance
          .collection("tblusers")
          .doc(currentUser.uid)
          .get()
          .then((DocumentSnapshot documentSnapshot) {
        if (documentSnapshot.exists) {
          _controllerFirstName.text = documentSnapshot.data()["first_name"];
        }
      });
    }

    return Form(
        key: _accountFormKey,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(children: <Widget>[
          Container(
              margin: EdgeInsets.symmetric(horizontal: 10),
              child: Column(children: [
                TextFormField(
                  controller: _controllerFirstName,
                  validator: (value) {
                    if (value.isEmpty) {
                      return "Error";
                    }
                  },
                ),
                ElevatedButton(
                    onPressed: () {
                      if (_accountFormKey.currentState.validate()) {}
                    },
                    child: Text("Submit"))
              ]))
        ]));
  }
}

然后,我尝试通过添加以下类来改进代码。新代码如下所示。但是,这不会填充名字

方法2

class UserModel {
  var first_name;

  UserModel(
      {this.first_name});
}

class UserProvider {
  UserModel userModel;

  UserModel getUserData() {
    var currentUser = FirebaseAuth.instance.currentUser;
    if (currentUser != null) {
      var user = FirebaseFirestore.instance
          .collection("tblusers")
          .doc(currentUser.uid)
          .get()
          .then((DocumentSnapshot documentSnapshot) {
        if (documentSnapshot.exists) {
          userModel = UserModel(
              first_name: documentSnapshot.data()["first_name"]
        }
      });
    }
  }
}

小部件类

class AccountForm extends StatelessWidget {
  var firstName = "";

  TextEditingController _controllerFirstName = new TextEditingController();

  var _accountFormKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    var provider = new UserProvider();
    var result = provider.getUserData();
    _controllerFirstName.text = result.first_name;

    return Form(
        key: _accountFormKey,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Column(children: <Widget>[
          Container(
              margin: EdgeInsets.symmetric(horizontal: 10),
              child: Column(children: [
                TextFormField(
                  controller: _controllerFirstName,
                  validator: (value) {
                    if (value.isEmpty) {
                      return MinMaxMessages.RequiredFirstName;
                    } 
                  }                  
                ),                
                ElevatedButton(
                    onPressed: () {
                      if (_accountFormKey.currentState.validate()) {}
                    },
                    child: Text("Submit"))
              ]))
        ]));
  }
}
糊状的

您的实现几乎没有问题。

调用getUserData()您的构建方法。每次重新构建此小部件时,您都在调用此方法。相反,更好的解决方案是将此类转换为StatefulWidget并在initState()方法中调用一次

返回类型getUserData()为UserModel,但是我真的看不到您将其返回到哪里,因此这可能是这里的主要问题。

这是代码:

class UserModel {
  var first_name;

  UserModel({this.first_name});
}

class UserProvider {
  UserModel getUserData() async {
    var currentUser = FirebaseAuth.instance.currentUser;

    if (currentUser != null) {
      var snapshot = await FirebaseFirestore.instance
          .collection("tblusers")
          .doc(currentUser.uid)
          .get();

      return UserModel(first_name: snapshot.data()["first_name"]);
    }

    return null;
  }
}

我已经将您的小部件转换为有状态的,并添加了initState()方法。

class AccountForm extends StatefulWidget {
  @override
  _AccountFormState createState() => _AccountFormState();
}

class _AccountFormState extends State<AccountForm> {
  var _accountFormKey = GlobalKey<FormState>();

  UserProvider userProvider = new UserProvider();
  TextEditingController controllerFirstName = new TextEditingController();
  UserModel userModel;

  @override
  void initState() {
    super.initState();
    asyncInit();
  }

  void asyncInit() async {
    userModel = await userProvider.getUserData();

    if (userModel != null) {
      controllerFirstName.text = userModel.first_name;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _accountFormKey,
      autovalidateMode: AutovalidateMode.onUserInteraction,
      child: Column(
        children: <Widget>[
          Container(
            margin: EdgeInsets.symmetric(horizontal: 10),
            child: Column(
              children: [
                TextFormField(
                  controller: controllerFirstName,
                  validator: (value) {
                    if (value.isEmpty) {
                      return MinMaxMessages.RequiredFirstName;
                    }
                  },
                ),
                ElevatedButton(
                  child: Text("Submit"),
                  onPressed: () {
                    if (_accountFormKey.currentState.validate()) {}
                  },
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章