Map<String, TextEditingController> notesControllers 的空文本?

Empty text for Map<String, TextEditingController> notesControllers?

我收到错误消息“所有字段都是必需的”。我不确定 Map<String,TextEditingController> 是如何工作的。我试过搜索,但找不到太多关于 MapTextEditingController 一起使用的信息。只是想知道我是否在正确的轨道上,或者我是否应该做一些不同的事情。我正在尝试 post 一个不断增长 TextField 的注释(每次用户点击提交时都会出现一个新的 TextField)。但是使用我无法打印的代码或 post 超过 1 行形成 TextFields。我可以使用 notesControllers 来 print/post 来自所有 TextFields 的用户输入吗?

很抱歉,如果您看到我提出的类似问题,这是在尝试解决此问题的第 10 天。非常感谢任何帮助。

这是我尝试过的一些方法:

class AddNoteScreenEdit extends StatefulWidget {
  User user;
  AddNoteScreenEdit({
    required this.user,
  });

  @override
  State<AddNoteScreenEdit> createState() => _AddNoteScreenEditState();
}

class _AddNoteScreenEditState extends State<AddNoteScreenEdit> {
  // TextEditingController notesController = TextEditingController();
  Map<String, TextEditingController> notesControllers = {};
  // List<TextEditingController> noteControllers = [];

  FirebaseFirestore firestore = FirebaseFirestore.instance;

  bool loading = false;

  String? str;

  List<TextField> textFields = [];

  @override
  void initState() {
    super.initState();
    textFields.add(_buildTextField(notesControllers));
    //notesControllers;
    // notesControllers[str]?.text;
    // notesControllers[str]?.text = 'test';
    // notesControllers[str]?.text = [] as String;
    // TextEditingController notesControllers = TextEditingController(text: str);
  }

  @override
  Widget build(BuildContext context) {
    // var str = [];
    //var stringListReturnedFromApiCall = [] as String;
    //var stringListReturnedFromApiCall = [];
    // var noteControllers = TextEditingController(text: str);
    //var noteControllers = TextEditingController(text: str);

    // Map<String, TextEditingController> notesControllers = {};
    // //var textFields = <TextField>[];
    // // textFields.add(_buildTextField());
    // stringListReturnedFromApiCall.forEach((str) {
    //   var notesController = new TextEditingController(text: str);
    //   notesControllers.putIfAbsent(str, () => notesController);
    //   return textFields.add(TextField(controller: notesControllers));
    //   // return textFields.add(_buildTextField());
    // });

    //      var stringListReturnedFromApiCall = [];

    //  Map<String, TextEditingController> notesEditingControllers = {};
    //   var textFields = <TextField>[];
    //  textFields.add(_buildTextField());
    //  stringListReturnedFromApiCall.forEach((str) {
    //    var notesEditingController = new TextEditingController(text: str);
    //    notesEditingControllers.putIfAbsent(str, () => notesEditingController);
    //    return textFields.add(TextField(controller: notesEditingController));
    //  });

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF162242),
        elevation: 0,
      ),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(20),
            child: Column(children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 10, right: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(
                    Radius.circular(10),
                  ),
                  color: Colors.white,
                ),
                child:
                    // TextField(controller: noteControllers)
                    ListView(
                  children: textFields,
                  shrinkWrap: true,
                ),
              ),
              loading
                  ? Center(
                      child: CircularProgressIndicator(),
                    )
                  : Container(
                      height: 50,
                      width: MediaQuery.of(context).size.width,
                      child: ElevatedButton(
                        onPressed: () async {
                          //  () => stringListReturnedFromApiCall.forEach((str) async {
                          // print(notesControllers[str]?.text);

                          if (notesControllers[str] != null) {
                            return loading
                                ? Center(child: CircularProgressIndicator())
                                : print(notesControllers[str]?.text);
                          } else if (notesControllers[str]?.text.isEmpty ??
                              true) {
                            ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                                content: Text("All fields are required")));
                          } else {
                            setState(() {
                              loading = true;
                            });
                            await FirestoreServiceEdit().insertNote(
                                notesControllers[str]!.text, widget.user.uid);

                            CollectionReference notes =
                                firestore.collection('notes');
                            QuerySnapshot allResults = await notes.get();
                            allResults.docs.forEach((DocumentSnapshot result) {
                              print(result.data());
                            });

                            setState(() {
                              loading = false;
                            });

                            Navigator.pop(context);
                          }
                        },
                        //),
                        // ),
                        child: Text(
                          "Add Note",
                          style: TextStyle(
                            fontSize: 25,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        style: ButtonStyle(
                          backgroundColor:
                              MaterialStateProperty.all(Color(0xFF162242)),
                          shape:
                              MaterialStateProperty.all<RoundedRectangleBorder>(
                            RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(10.0),
                            ),
                          ),
                        ),
                      ),
                    ),
            ]),
          ),
        ),
      ),
    );
  }

  TextField _buildTextField(
      Map<String, TextEditingController> notesControllers) {
    return TextField(
        //controller: notesControllers,
        //controller: notesControllers[str],
        // controller: TextEditingController(),
        style: TextStyle(
          color: Colors.black,
          fontSize: 18,
        ),
        decoration: InputDecoration(
          prefix: Icon(
            Icons.circle,
            size: 8,
            color: Colors.black,
          ),
        ),
        autofocus: true,
        onSubmitted: (String? str) {
          setState(() {
            textFields.add(_buildTextField(notesControllers));

            // notesControllers[str]?.text = 'test';
            // TextEditingController notesControllers = TextEditingController(text: str);
            // notesControllers;
            // notesControllers[str]?.text;
            //  notesControllers[str]?.text = str ?? '';
            // notesControllers[str]?.text = [] as String;
            // var noteControllers = TextEditingController(text: str);

            // var stringListReturnedFromApiCall = [];
            // var stringListReturnedFromApiCall = ['test', 'testing', 'test'];

            // Map<String, TextEditingController> notesControllers = {};
            // // var textFields = <TextField>[];
            // // textFields.add(_buildTextField());
            // stringListReturnedFromApiCall.forEach((str) {
            //   var notesController = new TextEditingController(text: str);
            //   notesControllers.putIfAbsent(str, () => notesController);
            //   return textFields.add(TextField(controller: notesController));
            //   //return textFields.add(_buildTextField());
            // });
          });
        });
  }
}
class NoteModelEdit {
  String id;
  String? notes;
  String userId;

  NoteModelEdit({
    required this.id,
    required this.notes,
    required this.userId
  });

  factory NoteModelEdit.fromJson(DocumentSnapshot snapshot){
    return NoteModelEdit(
      id: snapshot.id,
      notes: snapshot['notes'],
      userId: snapshot['userId']
      );  
  }
}
class FirestoreServiceEdit{

  FirebaseFirestore firestore = FirebaseFirestore.instance;

  Future insertNote(String? notes, String? userId)async{
    try{
      await firestore.collection('notes').add({
        "notes":notes,
        "userId":userId
      });
    } catch (e) {}
  }
}

主屏幕:

 body: StreamBuilder(
        stream: FirebaseFirestore.instance.collection("notes").where('userId', isEqualTo: user.uid).snapshots(),
        builder: (context, AsyncSnapshot snapshot){
          if (snapshot.hasData){
            if(snapshot.data.docs.length > 0){
              return ListView.builder(
                itemCount: snapshot.data.docs.length,
                itemBuilder: (context,index) {
                  NoteModelEdit note = NoteModelEdit.fromJson(snapshot.data.docs[index]);
                  return Card(
                    margin: EdgeInsets.only(top: 16, left: 10, right: 10, bottom: 16),
                    child: Column(
                        children: [
                            ListTile(title: Center(child: 
                            Text(note.notes!),),
                            ),

感谢您的宝贵时间!

您可以保留 TextFieldTextEditingController 的列表并使用 ListView.builder 来显示它们。在每次提交时,只需将一个新字段和控制器添加到您的列表中。当你想保存时,循环浏览你的控制器列表并抓取每个文本。

StatefulWidget:

中初始化您的列表
final List<TextField> _textFields = [];
final List<TextEditingController> _controllers = [];

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

void _addTextField() {
  final controller = TextEditingController();
  _textFields.add(
    TextField(
      controller: controller,
      onSubmitted: (_) => setState(() => _addTextField()),
    ),
  );
  _controllers.add(controller);
}

在您的父窗口小部件内:

ListView.builder(
  itemCount: _textFields.length,
  itemBuilder: (_, index) {
    return _textFields[index];
  }
),

这里有一个快速 example 可以让你开始。