skip to Main Content

I need to set the value of a TextEditingController during the widget build method.

The problem is that every time the widget rebuilds, the _controller value resets to to it’s original state and the new value disappears:

final TextEditingController _controller = new TextEditingController();

Widget _build(BuildContext context) {
   
   myString = "Value only available in widget build";

   new TextField(
      keyboardType: TextInputType.number,
      inputFormatters: [FilteringTextInputFormatter.digitsOnly],
      controller: _controller..text = myString,
   ),

}

In the above example myString is declared during widget build. Unfortunately, it cannot be declared duing initState, hence my problem.

How can I set the _controller value only during the first build and prevent it from resetting to it’s original value after the widget rebuilds itself?

Any suggestions?

2

Answers


  1. From what you are saying, you don’t need to use StoreConnector for widget you don’t want to update when updating your store. You could definitely do something like this:

    
    String? myString;
    
    Widget build(BuildContext context) {
       if (myString == null) {
         //Once myString is assigned it will not update.
         myString = StoreProvider.of<YourClass>(context).state.myString;
         _controller.text = myString;
       }
       return TextField(
          keyboardType: TextInputType.number,
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
          controller: _controller,
       );
    }
    
    

    Also, if you want to do it with StoreConnector<> you can do:

     return StoreConnector(
       builder: (context, value) {
         return TextField(
          keyboardType: TextInputType.number,
          inputFormatters: [FilteringTextInputFormatter.digitsOnly],
          controller: _controller,
         );
       }, 
       rebuildOnChange: false, //Add this line to stop rebuilding when store changes.
     );
    
    Login or Signup to reply.
  2. You can set text controller value into initState() of your page so it will be prevent it to reset after rebuild

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