How to fetch the data from cloud_firestore and display it in the TextField in flutter

穿精又带淫゛_ 提交于 2021-01-28 11:34:04

问题


Padding(
padding: const EdgeInsets.all(14.0),
 child: Container(
   child: TextFormField(
     initialValue: fullName,
       cursorColor: Colors.deepPurpleAccent,
         decoration: InputDecoration(
          hintText: 'Full Name',
            focusedBorder: InputBorder.none,
             focusColor: Colors.deepPurpleAccent,
             enabledBorder: OutlineInputBorder(
             borderSide: BorderSide(
              color: Colors.deepPurpleAccent,
                 ),
                ),
              ),
            ),
          ),
        ),



String fullName;
void _fetchUserData() async {
try {
  FirebaseUser _currentUser = await FirebaseAuth.instance.currentUser();
  String authid =_currentUser.uid;
  Firestore.instance.collection('UserData').document('$authid').get().then((ds) {
    if(ds.exists)
    {
      setState(() {
       fullName = ds.data['FullName'];
      });
    }

  });

} catch (e) {
  print(e);
}

}

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

" In this TextFormField I am displaying that value but it is displaying null

" I am trying to do this in this manner but it is showing the null value in the Android Emaluater TextFormField


回答1:


TextFormField's initial value is only used to initialize its TextController. The TextFormField's value is maintained by the TextEditingController.

  final controller = TextEditingController();

  void _fetchUserData() async {
    // do something
    setState(() {
      controller.text = "your text";
    });
  }

  Widget build(BuildContext context) {
    return TextFormField(
      controller: controller,
    );
  }

  void dispose() {
    myController.dispose();
    super.dispose();
  }



回答2:


Try this approach

Scaffold(
      body: StreamBuilder<QuerySnapshot>(
        stream: Firestore.instance.collection('news').snapshots(),
        builder: (BuildContext context,
            AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError)
            return new Text('Error: ${snapshot.error}');
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return new Center(
                child: CircularProgressIndicator(),
              );
            default:
              return Text(snapshot.data.documents[0]['title']);
          }
        },
      ),
    )



回答3:


Use await to wait for the data to be fetched:

await Firestore.instance.collection('UserData').document('$authid').get().then((ds){


来源:https://stackoverflow.com/questions/59918010/how-to-fetch-the-data-from-cloud-firestore-and-display-it-in-the-textfield-in-fl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!