Home > Software design >  TextField input won't print to console?
TextField input won't print to console?

Time:05-23

I'm trying to use a custom TextField widget in my AddNoteScreen. I don't know why it's not printing the TextField input or how to get it to work. I thought having the TextEditingController was all it needed.. I'm new.. sorry to post so much code I don't know how else to explain.

Here is my custom widget:

class MyWidget extends StatefulWidget {

final Widget textFields;

  MyWidget(
    {required this.textFields});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {

 TextEditingController notesController = TextEditingController();

  List<TextField> textFields = [];

  @override
  void initState() {
    super.initState();
    textFields.add(_buildTextField());
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10, right: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
          Radius.circular(10),
        ),
        color: Colors.white,
      ),
      height: 300,

      alignment: Alignment.centerLeft,
      child: ListView(
        children: textFields, 
        ),
    );
  }

  TextField _buildTextField() {
    return TextField(
        style: TextStyle(
          color: Colors.black,
          fontSize: 18,
        ),
        decoration: InputDecoration(
          prefix: Icon(
            Icons.circle,
            size: 10,
            color: Colors.black,
          ),
          prefixIconConstraints: BoxConstraints(
            minWidth: 20,
            minHeight: 10,
            maxHeight: 10,
            maxWidth: 20,
          ),
        ),
        autofocus: true,
        onSubmitted: (_) {
          setState(() {
           textFields.add(_buildTextField());
           notesController.text   ' ';
         });
       }
     );
  }    
}

My AddNoteScreen:

class AddNoteScreen extends StatefulWidget {

User user;
 AddNoteScreen({
     required this.user,
   });

@override
  State<AddNoteScreen> createState() => _AddNoteScreenState();
}

class _AddNoteScreenState extends State<AddNoteScreen> {

TextEditingController notesController = TextEditingController();
FirebaseFirestore firestore = FirebaseFirestore.instance;
bool loading = false;

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

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor:Color (0xFF162242),
        elevation: 0,
      ),

      body: GestureDetector(
        onTap: () {
      FocusScope.of(context).unfocus();
      notesController.text = '';
    },
        child: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(20),
            child: Column(children: [


Container(
                padding: EdgeInsets.only(left: 10, right: 10),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(10),),
                  color: Colors.white,
                ),
                child: MyWidget(
                  textFields: TextField(
                   style: TextStyle (color:  Color(0xFF192A4F),fontSize: 18,),
                   textCapitalization: TextCapitalization.sentences,
                   controller: notesController,
                 decoration: InputDecoration(
                          enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.transparent),
                          ),
                        ),
                        ),
              ),
              ),

 SizedBox(height: 50,),
              loading ? Center (child: CircularProgressIndicator(),) : Container(
                height: 50,
                
                width: MediaQuery.of(context).size.width,
                child: ElevatedButton(
                  
                  
                  onPressed: ()async{
                    
      
                  if (
                    notesController.text.isEmpty)
                    {

                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("All feilds are required")));
      
                    } else {
                      
                      setState(() {
                        loading = true;
                      });
                      
                      await FirestoreService().insertNote(notesController.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),
          ),
        ),
        
      ),
      //color:Color (0xFF162242)
      
                //ElevatedButton.styleFrom(primary: Color (0xFF162242),),
                ),
              ),
            ]),),
            ),
      ),
 );

My FirestoreService page:

class FirestoreService{

  FirebaseFirestore firestore = FirebaseFirestore.instance;

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

And my NoteModel Screen:

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

breakpoint

breakpoint2

Any help is appreciated!

CodePudding user response:

I believe you are storing an empty note, which is the reason why the result from the database is empty.

This line:

if (notesController.text.isNotEmpty) // show error message

should become this:

if (notesController.text.isEmpty) // show error message

Also, this should probably change, too:

// This does nothing:
new TextEditingController().clear();

// To clear the controller:
notesController.text = '';

UPDATE

Change your code as follows to test if something gets written into the database. Once this works, figure out how to use MyWidget correctly, as there are issues in there, too.

// OLD CODE

child: MyWidget(
  textFields: TextField(
    style: TextStyle (color:  Color(0xFF192A4F),fontSize: 18,),
    textCapitalization: TextCapitalization.sentences,
    controller: notesController,
    decoration: InputDecoration(
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.transparent),
      ),
    ),
    ),
),

// NEW CODE

child: TextField(
    style: TextStyle (color:  Color(0xFF192A4F),fontSize: 18,),
    textCapitalization: TextCapitalization.sentences,
    controller: notesController,
    decoration: InputDecoration(
      enabledBorder: UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.transparent),
      ),
    ),
),

I suggest to always only change small parts of code and ensure that your code works at each small step. Do not make too many changes at once.

  • Related