1

I have created a demo,

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

one is stateless made separately...

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..')),

    );
  }
}

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
Irfan Ganatra
  • 967
  • 3
  • 13
  • 1
    ``Random()`` !!!!! – OMi Shah Aug 13 '22 at 10:28
  • Keep in mind that any build() can be called 60 times per second, and your code should work identically, so build needs to be fast and idempotent. It's just an optimization that it is called fewer times than that. Your build is not idempotent, and thus broken. – Randal Schwartz Aug 13 '22 at 18:31

2 Answers2

1

Use const with key constructor

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

And use

const MyWidget(),
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
1

The mywidget eventhough is a stateless widget its placed inside a stateful widget. So each time the stateful widget ia built it will rebuild the stateless widget too

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30