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..')),
);
}
}
CodePudding user response:
Use const with key constructor
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
And use
const MyWidget(),
CodePudding user response:
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