Flutter

Flutter局部刷新组件

2020-03-07  本文已影响0人  mtko

当界面复杂,嵌套多个子widget时,经常有刷新单个或者局部widget的需求,每次写业务时创建GlobalKey太繁琐不够优雅,使用provider状态控制类刷新可能功能又过重。习惯命令式刷新的同学,可以参考此文

RefreshableStatefulWidget

abstract class RefreshableStatefulWidget extends StatefulWidget {
  RefreshableStatefulWidget({Key key})
      : super(key: key is GlobalKey ? key : GlobalKey());

  void reload() {
    if (key is! GlobalKey) {
      return;
    }
    final aKey = key as GlobalKey;
    aKey.currentState.setState(() {});
  }
}

RefreshableView

class RefreshableView extends RefreshableStatefulWidget {
  final Widget Function(BuildContext cntext) builder;

  RefreshableView({Key key, @required this.builder})
      : assert(builder != null),
        super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _RefreshableViewState(builder);
  }
}

class _RefreshableViewState extends State<RefreshableView> {
  final Widget Function(BuildContext cntext) builder;
  _RefreshableViewState(this.builder);

  @override
  Widget build(BuildContext context) {
    return builder(context);
  }
}

使用

 _aRefreshableView = RefreshableView(builder: (BuildContext context) {
  return ListView.builder(
           itemCount: 10,
           itemBuilder: (BuildContext context, int index) {
           return Text("data$index");
         });
 });
  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
        navigationBar: _navigationBar,
        child: Column(
          children: <Widget>[
            Text("data"),
            Image.asset("image"),
            _aRefreshableView
          ],
        ));
  }
await request(); 
_aRefreshableView.reload(); // 网络请求回调后reload
上一篇 下一篇

猜你喜欢

热点阅读