简体   繁体   中英

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

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

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();
  }

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']);
          }
        },
      ),
    )

使用await等待数据被获取:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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