skip to Main Content

I want the TextFormFied value to persist even when navigating to another page and coming back.

I think it can be achieved by using Provider. but don’t know how to update the controller with the proivder class instance variable.

Here is the code I tried.

TextFormField on UI

TextFormField(
  amountController: amountController,
  onChanged: (value){
    provider.amount(value);
  },
)),
                        

Provider methode to get user entered value.

String? value ;

amount(String newAmount) {
  value = newAmount;
  notifyListeners();
}

I don’t know whether it’s correct or not.
Let me know how to update the amountController by value.

If this approach is wrong, Please let me know. What are the possible ways to achieve it?

2

Answers


  1. As you have attached very less code, let’s see you have done these below things right:

    1. Created a Model class:
      model class that holds the state you want to persist. This will be the class you provide using ChangeNotifierProvider, with having a function which will save the value and notify the listeners.

    2. Wrapped your widget tree with Provider, simple thing.

    3. Saving the value and using it with the help of Provider:

    import 'package:flutter/material.dart';
    import 'package:provider/provider.dart';
    
    class MyApp extends StatelessWidget {
      final TextEditingController amountController = TextEditingController();
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            body: Column(
              children: [
                TextFormField(
                  controller: amountController,
                  onChanged: (value) {
                    Provider.of<MyModel>(context, listen: false).updateAmount(value);
                  },
                ),
                Text('Amount: ${Provider.of<MyModel>(context).amount}'),
              ],
            ),
          ),
        );
      }
    }
    
    Login or Signup to reply.
  2. If you have a stateful widget here, you could set text of your controller inside initState function like this:

    @override
    void initState() {
      super.initState();
      amountController.text = context.read<TestProvider>().value ?? '';
    }
    

    so when you get to this page, text field is initialized with the value from provider.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search