Flutter 封装GlobalKey 实现局部刷新

95 篇文章 0 订阅

封装类:

///封装 通用局部刷新工具类
typedef BuildWidget = Widget Function();

// ignore: must_be_immutable
class PartRefreshWidget extends StatefulWidget {
  ///具体需要刷新的widget
  BuildWidget _child;

  ///Key 外部使用的GlobalKey
  PartRefreshWidget(Key key, this._child) : super(key: key);

  @override
  PartRefreshWidgetState createState() => PartRefreshWidgetState(_child);
}

class PartRefreshWidgetState extends State<PartRefreshWidget> {
  BuildWidget _child;

  PartRefreshWidgetState(this._child);

  @override
  Widget build(BuildContext context) {
    return _child.call();
  }

  ///暴露给外部调用 刷新ui的方法
  void update() {
    setState(() {});
  }
}

 

//使用:

main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'TestWidget',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('test2'),
        ),
        body: GlobalKeyDemo(),
      ),
    );
  }
}

class GlobalKeyDemo extends StatefulWidget {
  @override
  _GlobalKeyDemoState createState() => _GlobalKeyDemoState();
}

class _GlobalKeyDemoState extends State<GlobalKeyDemo> {
  int _count = 0;

  //使用1 创建GlobalKey
  GlobalKey<PartRefreshWidgetState> globalKey = new GlobalKey();

  @override
  Widget build(BuildContext context) {
    print('----------------initState');

    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
           //使用2 创建通用局部刷新widget
          PartRefreshWidget(globalKey, () {
            ///创建需要局部刷新的widget
            return Text('变化的:$_count',style: TextStyle(color: Colors.green),);
          }),
          Text('不变的: $_count'),
          RaisedButton(
            onPressed: () {
              //点击
              _count++;
             //使用3调用刷新方法
              globalKey.currentState.update();
            },
          )
        ],
      ),
    );
  }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值