user2895656
user2895656

Reputation: 57

Flutter globals variables are not refreshed when hot reload

I start with flutter and I would like to learn more. In order to make my life easier, I declared global variables when I started my application.

The errorMessage variable is null at startup.

But if it fills up because it finds an error in the execution and displays the message to me, it does not return to null when I hot reload my application and keeps the error message which blocks me.


class HomeController extends StatefulWidget {
  HomeController({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _HomeControllerState createState() => _HomeControllerState();
}

class _HomeControllerState extends State<HomeController> {

  String errorMessage; // => My exemple of global variable
  bool debugFunctionStart = true;

  final _formKey = GlobalKey<FormState>();

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

And an exemple of function in my application :

functionChoose(List item,String key, int value){
    Map<String, dynamic> result;
    if(item.length > 0){
      List selectedInList = item.where((c) => c[key] == value).toList();
      result = selectedInList.first;
    }else{
      errorMessage = "ERROR ! not works ...";// => found an error
      print(errorMessage);
    }
    return result;
  }

How to do that ?

Upvotes: 1

Views: 1256

Answers (2)

Sergey Salnikov
Sergey Salnikov

Reputation: 1781

Hot reload keeps states it is intended behavior

You can set errorMessage to null in state reasseble() method

Called whenever the application is reassembled during debugging, for example during hot reload.

Afterall I would recomend you to read about statemanagement

Upvotes: 1

Rechem MEG
Rechem MEG

Reputation: 309

it may be because hot reloading saves the current state, just restart the app by clicking the green circular arrow if you're on vscode, and this should fix it.

Upvotes: 1

Related Questions