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((){});
}
}
Author by
Rontu Barhoi
Updated on December 22, 2022Comments
-
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 almost 3 yearsbeacuse if you hot reload the
build
method has to be called - otherwise you would not see any changes made by you -
pskink almost 3 yearsread api.flutter.dev/flutter/widgets/State/build.html for more info on how
build
method should be implemented -
pskink almost 3 yearssure, your welcome
-
-
Rontu Barhoi almost 3 yearsThanks 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.