39.跨组件状态共享

导入插件:

provider: ^4.0.4

导入包 :

import 'package:provider/provider.dart';

核心代码 :

class MyHomePage2 extends StatelessWidget {
 @override
  Widget build(BuildContext context) {
    //订阅者,订阅ProviderDemoNotifier,在根节点声明
    return ChangeNotifierProvider<ProviderDemoNotifier>(
        create: (_) => ProviderDemoNotifier(),
        child: Scaffold(
          appBar: AppBar(
            title: Text('provider demo'),
          ),
          //获取发布者更新的数据
          body: Consumer(builder: (BuildContext context, ProviderDemoNotifier notifier, Widget child) =>
              Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  //调用了get方法
                  Text(notifier.index.toString()),
                  SizedBox(height: 10,width: double.infinity,),
                  RaisedButton(onPressed: (){
                    notifier.index++;//调用了set方法,会对Consumer中使用到notifier的数据进行更新
                  }, child: Text('加1'),)
                ],
              ),
          )
        ));
  }
}

//发布者
class ProviderDemoNotifier extends ChangeNotifier {
  //提供让各个组件共享的数据
  int _index = 1;
  //getter方法,方便各个组件直接调用数据
  int get index => _index;
  //setter方法,方便各个组件更改数据
  set index(int value) {
    _index = value;
    notifyListeners();  //调用此方法可刷新页面,将最新的数据传给订阅者使用
  }

}

效果:

40.对话框

AlertDialog(
        title: Text("提示"),
        content: Text("您确定要删除当前文件吗?"),
        actions: <Widget>[
          FlatButton(
            child: Text("取消"),
            onPressed: () => Navigator.of(context).pop(), //关闭对话框
          ),
          FlatButton(
            child: Text("删除"),
            onPressed: () {
              // ... 执行删除操作
              Navigator.of(context).pop(true); //关闭对话框
            },
          ),
        ],
      ),

效果:

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐