Flutter - Hot reload - Change the value from outside of the State.build function

304

Solution 1

I know this is a little late but try accessing it through the getter function. I'm hoping this would help someone else.

class TextState extends State<TextWidget>{
    @override
    Widget build(BuildContext context) => Text(Values.text); //Changed from Text('EXAMPLE')
}

--- In different file ---


class Values{
   // Returning as a function.
    static String get text { 
     return 'EXAMPLE'
    };
}

Solution 2

This is expected behavior.

In Dart, static fields are lazily initialized. This means that the first time you run a Flutter app and a static field is read, it is set to whatever value its initializer was evaluated to. Global variables and static fields are treated as state, and are therefore not reinitialized during hot reload.

See here for more details.

Share:
304
stackunderflow
Author by

stackunderflow

Updated on December 02, 2022

Comments

  • stackunderflow
    stackunderflow over 1 year

    For managability purpose, I've built the app with the values including texts, dimensions, colors, paths, and etc, all been put into different files other than the StatefulWidget class files. I never looking for the solution for this problem before so I did it the harder way, moving the variables out after finalizing the widget's interface. Below for example.

    class TextState extends State<TextWidget>{
        @override
        Widget build(BuildContext context) => Text(Values.text); //Changed from Text('EXAMPLE')
    }
    
    --- In different file ---
    
    class Values{
        static String text = 'EXAMPLE';
    }
    

    But today I need to redesign the app, top to bottom. Of course unfortunately when I change the variables' value, hot reload ignores it because it's considered to be a state value, except in my case it's actually not a runtime state update.

    Is there any solution so I can change the values and see the result without tediously hot restart everytime and also without have to reverse my code half way in order for hot reload to work?. Thank you in advance.

  • stackunderflow
    stackunderflow over 1 year
    actually i already converted my code to use provider. but getter is the answer. just change assignment to 'get =>' and done