Search code examples
androidflutterstatic-variableshot-reload

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


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"),
      ),
    );
  }
}

Solution

  • 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((){});
      }
    }