class ValueListenableBuilderComponent extends StatefulWidget {
const ValueListenableBuilderComponent({Key? key, required this.title})
: super(key: key);
final String title;
@override
State<ValueListenableBuilderComponent> createState() {
return ValueListenableBuilderState();
}
}
class ValueListenableBuilderState
extends State<ValueListenableBuilderComponent> {
// 定义一个ValueNotifier,当数字变化时会通知 ValueListenableBuilder
final ValueNotifier<int> _counter = ValueNotifier<int>(0);
static const double textScaleFactor = 1.5;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: ValueListenableBuilder<int>(
builder: (BuildContext context, int value, Widget? child) {
// builder 方法只会在 _counter 变化时被调用
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
child!,
Text("$value 次", textScaleFactor: textScaleFactor),
],
);
},
valueListenable: _counter,
// 当子组件不依赖变化的数据,且子组件开销比较大时,指定 child 属性来缓存子组件
child: const Text("点击了 ", textScaleFactor: textScaleFactor),
),
),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {
_counter.value += 1;
}),
);
}
}
Flutter 按需rebuild(ValueListenableBuilder)
猜你喜欢
转载自blog.csdn.net/xiaopihair123/article/details/124940757
今日推荐
周排行