如何从Cloud FireStore在TextFormField中提供initialValue

时间:2020-05-20 19:33:27

标签: firebase flutter dart

我正在尝试通过表单更新Cloud Firestore中的数据。我需要将Firestore中已存储的字段显示为TextFormField中的initialValue。

获取的数据通过print()打印在控制台上,但在TextFormField中什么都没有显示。

initialValue与我用于print()的代码行相同。

也可以正确提取数据。

这是代码:

var initData = {
'title': '',
 };

void didChangeDependencies() async{
super.didChangeDependencies();
await Firestore.instance
    .collection('${widget.collection}')
    .document('${widget.title}')
    .get()
    .then((value) {
  setState(() {
    initData = {
      'title': value.data['title'],
    };
  });
});

if (isValid) {
  _formKey.currentState
      .save();
  }
  widget.submitFn(
    _title,)
 }

@override
Widget build(BuildContext context) {

print(initData['title']); // the fetched data is printed in the console

return Form(
  key: _formKey,
 Column(
   children: <Widget>[
               TextFormField(
                  initialValue: initData['title'], // this doesnt show anything on the TextFormField,
                  decoration: InputDecoration(
                      labelText: 'Enter Product Name',
                      contentPadding: EdgeInsets.all(5)),
                  validator: (value) {
                    if (value.isEmpty) {
                      return 'Enter a the Product Title';
                    }
                    return null;
                  },
                  onSaved: (value) {
                    _title = value;
                  },
                ),
              ),
            ),
           }

3 个答案:

答案 0 :(得分:1)

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  TextEditingController controller;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    controller = TextEditingController();
    controller.text = "hiii";  //Here you can provide a default value when your app starts.
    controller.addListener(() {
      print(controller.text);
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: SafeArea(
          child: Center(
            child: Form(
              child: TextField(
                controller: controller,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

答案 1 :(得分:0)

如果您检查TextFormField的构造函数,则可以将initialValue传递给它。因此,您只需要从Firestore获取数据并将其传递到initialValue中的TextFormField

String data = "Some value fetched from firestore";
TextFormField(
  initialValue:data,
)

答案 2 :(得分:0)

Firestore获取数据需要时间。从Firestore获取之前,不能将其设置为初始值。因此,您必须设置文本字段的初始值,并同时从firestore中查询值,然后再将其设置为文本字段。