如何从cloud_firestore获取数据并在flutter中将其显示在TextField中

时间:2020-01-26 11:48:01

标签: database firebase flutter google-cloud-firestore

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

“在此TextFormField中,我正在显示该值,但它显示为空

“我正在尝试以这种方式执行此操作,但是它在Android Emaluater TextFormField中显示了空值

3 个答案:

答案 0 :(得分:1)

TextFormField的初始值仅用于初始化其TextController。 TextFormField的值由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();
  }

答案 1 :(得分:0)

尝试这种方法

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

答案 2 :(得分:0)

使用await等待数据被提取:

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