Harsh Butani
Harsh Butani

Reputation: 1

Flutter TextFormField not updating list on form save

I'm encountering an issue with a Flutter application where I have a form with multiple TextFormFields. Specifically, I'm having trouble with the TextFormField for capturing ingredients. Here's the setup:

I have a _ingredientsController bound to a TextFormField. When the form is saved (_formKey.currentState!.save()), I expect _ingredients to be updated with the list of ingredients split from _ingredientsController.text. However, after saving the form, _ingredients remains empty ([]), despite _ingredientsController.text showing the correct input.

Steps I've Taken:

  1. Initialized _ingredientsController in initState().
  2. We implemented onSaved callback in the TextFormField to update _ingredients from _ingredientsController.text.
  3. Ensured that _formKey.currentState!.validate() is called before _formKey.currentState!.save() in the submit button handler.
  4. Used print statements to debug and check the state of _ingredients immediately after form save and within _saveRecipe().

Expected Behavior:

After saving the form, _ingredients should contain the list of ingredients split from _ingredientsController.text. For example, if the user inputs "Ingredient 1\nIngredient 2" in the form, _ingredients should be ['Ingredient 1', 'Ingredient 2'].

Actual Behavior: Despite _ingredientsController.text showing correct input, _ingredients remains [] after form save, as confirmed by debug print statements.

Here i provide code for Reference :


class _AddRecipeScreenState extends ConsumerState<AddRecipeScreen> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _ingredientsController = TextEditingController();
  List<String> _ingredients = [];

  @override
  void initState() {
    super.initState();
    _ingredientsController.text = _ingredients.join('\n');
  }

  @override
  void dispose() {
    _ingredientsController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: ListView(
            children: [

              // here is the text form field

              TextFormField(
                controller: _ingredientsController,
                maxLines: null,
                keyboardType: TextInputType.multiline,
                decoration: InputDecoration(
                  labelText: 'Ingredients',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter ingredients';
                  }
                  return null;
                },
                onSaved: (value) {
                  _ingredients = value!.split('\n');
                },
              ),

              // on saved button
              ElevatedButton(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _formKey.currentState!.save();
                    print('Ingredients after form saved: $_ingredients');
                    _saveRecipe();
                  }
                },
                child: Text('Add Recipe'),
              ),
            ],
          ),
        ),
      ),
    );
  }

   // function to saveRecipe

  Future<void> _saveRecipe() async {
    print("Now Let's check ingredients : " + _ingredients.toString());

    // Proceed with saving recipe to Firestore or perform other actions
    final mealModel = MealModel(
      ingredients: _ingredients,
    );

    // Call your function to add recipe to Firestore or perform other actions
    addRecipeToFirestore(mealModel);
  }
}

my Flutter Version is :

Flutter 3.22.1 • channel stable • https://github.com/flutter/flutter.git Framework • revision a14f74ff3a (3 weeks ago) • 2024-05-22 11:08:21 -0500
Engine • revision 55eae6864b Tools • Dart 3.4.1 • DevTools 2.34.3

Upvotes: 0

Views: 56

Answers (0)

Related Questions