Why hot reload in flutter is influencing static variable incremented inside build method?

393

This problem is due to the fact that each time you hot reload your program, the build method runs automatically. so you should avoid using checkIfIncremented++; inside this function. I am not sure why you use this code and what is your purpose, but you can use this code if you want to incrementcheckIfIncremented only at the first load:

bool firstLoad = true;

 @override
void didChangeDependencies() {
  super.didChangeDependencies();
  if(firstLoad){
     checkIfIncremented++;
     firstLoad = false;
     setState((){});
  }
}
Share:
393
Rontu Barhoi
Author by

Rontu Barhoi

Updated on December 22, 2022

Comments

  • Rontu Barhoi
    Rontu Barhoi over 1 year

    I am trying the following code and while hot reloading it is incrementing static variable checkIfIncremented variable. Please someone explain me why is it so ??

    import 'package:flutter/material.dart';
    void main()=>runApp(MaterialApp(
      home: TrialApp(),
    ));
    class TrialApp extends StatefulWidget {
    
      @override
      _TrialAppState createState() => _TrialAppState();
    }
    
    class _TrialAppState extends State<TrialApp> {
      static int checkIfIncremented = 0;
      @override
      Widget build(BuildContext context) {
        checkIfIncremented++;
        return Scaffold(
          body: Center(
            child: Text("This variable is getting incremented after each hot reload : $checkIfIncremented"),
          ),
        );
      }
    }
    
    • pskink
      pskink almost 3 years
      beacuse if you hot reload the build method has to be called - otherwise you would not see any changes made by you
    • pskink
      pskink almost 3 years
      read api.flutter.dev/flutter/widgets/State/build.html for more info on how build method should be implemented
    • pskink
      pskink almost 3 years
      sure, your welcome
  • Rontu Barhoi
    Rontu Barhoi almost 3 years
    Thanks a lot for the explanation. I was learning how hot reload influences different states so tried this code to check if we can update the screen every time by hot reloading and look at the effect. Thanks.