gpt4 book ai didi

flutter - StatefulBuilder 与 StatefulWidget

转载 作者:行者123 更新时间:2023-12-04 04:30:59 27 4
gpt4 key购买 nike

StatefulBuilder有什么区别和 StatefulWidget ?什么时候应该使用一个而不是另一个?
乍一看,它们似乎很相似。StatefulBuilder被定义为:

A platonic widget that both has state and calls a closure to obtain its child widget



虽然 StatefulBuilder被定义为:

A widget that has mutable state

最佳答案

一般使用 Builderbuild 中创建小部件树时内联方法。当您需要访问 context 时,这通常很有帮助。在您的小部件子树中。例如:
另见此 SO question

 @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: Builder(builder: (thisLowerContext) {
return RaisedButton(
onPressed: () => Scaffold.of(thisLowerContext)
.showSnackBar(SnackBar(content: Text("button was clicked"))));
}));
}

使用 StatefulBuilder当您需要访问 setState那个子树。这将仅重建 StatefulBuilder及其子树。
class _SomeWidgetState extends State<HomeScreen> {
Data data;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Home"),
),
body: StatefulBuilder(builder: (thisLowerContext, innerSetState) {
if (data == null) {
return RaisedButton(
child: Text("Load data"),
onPressed: () async {
Scaffold.of(thisLowerContext)
.showSnackBar(SnackBar(content: Text("Loading data...")));
var loadedData = await _loadData();
innerSetState(() => data = loadedData);
});
} else {
return RaisedButton(
child: Text("Reload data"),
onPressed: () async {
Scaffold.of(thisLowerContext).showSnackBar(
SnackBar(content: Text("Reloading data...")));
var loadedData = await _reloadData();
innerSetState(() => data = loadedData);
});
}
}));
}
}

关于flutter - StatefulBuilder 与 StatefulWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56445912/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com