StatefulBuilder与StatefulWidget

时间:2019-06-04 14:25:00

标签: flutter

StatefulBuilderStatefulWidget有什么区别?什么时候应该使用一个代替另一个?
乍一看它们看起来很相似。
StatefulBuilder定义为:

  

一个柏拉图式小部件,既有状态又调用一个闭包来获取其子小部件

定义了StatefulBuilder时:

  

状态可变的小部件

1 个答案:

答案 0 :(得分:-1)

在通过build方法创建窗口小部件树时,通常使用Builder内联。当您需要访问小部件子树中的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);
                });
          }
        }));
  }
}