封装类:
///封装 通用局部刷新工具类 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(); }, ) ], ), ); } }