首页 > 其他分享 >flutter 杂项 —— Stateful 与 Stateless 的更新

flutter 杂项 —— Stateful 与 Stateless 的更新

时间:2022-08-17 22:01:55浏览次数:62  
标签:Stateless return builder BuildContext value Stateful context StatefulBuilder flu

一、使用 StatefulBuilder 单独更新某个组件的状态

示例:

await showDialog<void>(
  context: context,
  builder: (BuildContext context) {
    int? selectedRadio = 0;
    return AlertDialog(
      content: StatefulBuilder(
        builder: (BuildContext context, StateSetter setState) {
          return Column(
            mainAxisSize: MainAxisSize.min,
            children: List<Widget>.generate(4, (int index) {
              return Radio<int>(
                value: index,
                groupValue: selectedRadio,
                onChanged: (int? value) {
                  setState(() => selectedRadio = value);
                },
              );
            }),
          );
        },
      ),
    );
  },
);

StatefulBuilder 源码:

class StatefulBuilder extends StatefulWidget {
  const StatefulBuilder({
    Key? key,
    required this.builder,
  }) : assert(builder != null),
       super(key: key);

  final StatefulWidgetBuilder builder;

  @override
  _StatefulBuilderState createState() => _StatefulBuilderState();
}

class _StatefulBuilderState extends State<StatefulBuilder> {
  @override
  Widget build(BuildContext context) => widget.builder(context, setState);
}

二、StatelessWidget 局部更新

示例:

Row(
  children: <Widget>[
    Text("同时删除子目录?"),
    // 通过Builder来获得构建Checkbox的`context`,
    // 这是一种常用的缩小`context`范围的方式
    Builder(
      builder: (BuildContext context) {
        return Checkbox(
          value: _withTree,
          onChanged: (bool value) {
            (context as Element).markNeedsBuild();
            _withTree = !_withTree;
          },
        );
      },
    ),
  ],
)

标签:Stateless,return,builder,BuildContext,value,Stateful,context,StatefulBuilder,flu
From: https://www.cnblogs.com/lemos/p/16596919.html

相关文章