[英]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...一个是无国籍单独制作的...
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..')),
);
}
}
Use const with key constructor将 const 与键构造函数一起使用
class MyWidget extends StatelessWidget {
const MyWidget({Key? key}) : super(key: key);
And use并使用
const MyWidget(),
The mywidget eventhough is a stateless widget its placed inside a stateful widget. mywidget 尽管是一个无状态小部件,但它放置在有状态小部件中。 So each time the stateful widget ia built it will rebuild the stateless widget too
因此,每次构建有状态小部件时,它也会重建无状态小部件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.