一、前言
在Flutter中用到setState(() {});
来进行刷新,不过这种方式常常会导致整个UI进行刷新在性能上不是很好,因此官方提供了StatefulBuilder
来进行局部刷新
二、演示代码
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
///StatefulBuilder测试
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('YM------父控件刷新');
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: Center(
child: Container(
child: Column(
children: [
_buildChild(),
RaisedButton(
onPressed: (){
_setter(() {
_count++;
});
},
child: Text('第二种计数方式'),
)
],
),
),
),
),
);
}
}
int _count = 0;
StateSetter _setter;
_buildChild() => StatefulBuilder(
builder: (BuildContext context, StateSetter setState){
_setter = setState;
print('YM------子控件刷新');
return Container(
child: Column(
children: [
Text('计数:$_count'),
RaisedButton(
onPressed: (){
setState(() {
_count++;
});
},
child: Text('第一种计数方式'),
)
],
),
);
},
);
三、参考链接
-
Flutter 小技巧实现通用的局部刷新: