请教老师, 如何防止组件 rebuild ?
来源:6-11 Flutter 页面生命周期实战指南
慕圣2430575
2022-07-24
经常碰到非叶子节点
的Widget进行setState
时会导致其子组件重复的build
操作, 像前端框架 React
有生命周期方法 shouldComponentUpdate
来确认组件是否进行重新渲染
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: const MyHomePage(title: 'Flutter Demo Home Page'),
),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int counter = 0;
void initState() {
super.initState();
}
Widget build(BuildContext context) {
print("build parent");
return ListView(children: [
SonWidget(),
FloatingActionButton(onPressed: (){
setState((){
counter ++;
});
})
],);
}
}
class SonWidget extends StatefulWidget{
const SonWidget({Key? key}) : super(key: key);
State<StatefulWidget> createState() => _SonState();
}
class _SonState extends State<SonWidget>{
Widget build(BuildContext context) {
print("build son");
return Container();
}
}
写回答
1回答
-
CrazyCodeBoy
2022-07-24
建议将需要频繁build的部分单独封装成一个widget,这样可以控制build的范围。012022-07-24
相似问题