Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Stateless widget rebuild on refresh in flutter

I have created a demo,

I have made a stateful home screen where a column containing two containers.

one is stateless made separately…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

On scaffold I have placed refresh button to change randomly color but I don’t want to make changes to stateless widget , but it changes on refresh..

To make my point clear I have made this demo, actually I am stuck in my app

here is my code

class HomeScreen extends StatefulWidget {

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
       appBar: AppBar(
         backgroundColor: Color.fromRGBO(Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), 1),

         title: Text('Demo'),
      actions: [IconButton(onPressed: (){

        setState(() {

        });
      }, icon: Icon(Icons.refresh))],

      ),

      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
         Container(
           height: 100,
           color: Color.fromRGBO(Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), 1),
         ),
          MyWidget(),
        ],
      )
    );
  }
}

class MyWidget extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      color: Color.fromRGBO(Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), 1),
      child: Center(child: Text('Why this ,stateless ,also changed on refresh..')),

    );
  }
}

>Solution :

Use const with key constructor

class MyWidget extends StatelessWidget {
  const MyWidget({Key? key}) : super(key: key);

And use

const MyWidget(),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading