Why is the value of a variable "ButtonCount" declared before the build method not retaining its value in flutter

33 Views Asked by At

From my understanding of flutter and dart, when a widget is rebuilt or when I use hot reload, the values of variables declared before the build function are retained.

However, this is not the case with my code. When I click on Hot reload, the value of the ButtonCount is reset to default zero instead of retaining the value after several clicks.

import 'package:flutter/material.dart';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        appBar: AppBar(
          title: Text('Dicee'),
          backgroundColor: Colors.blue,
        ),
        body: DicePage(),
      ),
    ),
  );
}




class DicePage extends StatefulWidget {

  @override
  State<DicePage> createState() => _DicePageState();

}

class _DicePageState extends State<DicePage> {
  int ButtonCount=0;

  @override
  Widget build(BuildContext context) {
    int ButtonCount1=0;
    return   Container(
        child: Center(
          child: Row(
            children: [

              Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: TextButton(
                        onPressed: () {
                          ButtonCount++;
                          print(ButtonCount);
                        },
                        child: Image.asset("Pictures/dice1.png")),
                  )),
              Expanded(child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextButton(
                    onPressed: () {
                      ButtonCount1++;
                      print(ButtonCount1);
                    },
                    child: Image.asset("Pictures/dice2.png")),
              )),

            ],
          ),
        )
    );
    ;
  }
}

I am expecting that after increasing the value of ButtonCount to four and clicking on hot reload, the value of ButtonCount still be four and not be reset to zero.

1

There are 1 best solutions below

0
jun On

The value of ButtonCount resets during a hot reload in Flutter because the widget tree is rebuilt, which calls the constructor of your _DicePageState class again. This causes ButtonCount to revert to its initial value (0 in your case). To maintain the value across hot reloads, declare ButtonCount as a static variable:

static int buttonCount = 0;

This approach is useful for simple state persistence during development but may not be suitable for all scenarios.