当前位置: 首页 > news >正文

Flutter 状态管理新境界:多Provider并行驱动UI

前言

在上一篇文章中,我们讨论了如何使用 ProviderFlutter 中进行状态管理。

本篇文章我们来讨论如何使用多个 Provider

Flutter 中,使用 Provider 管理多个不同的状态时,你可以为每个状态创建一个单独的 ChangeNotifierProvider,并在需要的地方使用 Provider.of<T>(context)Consumer<T>来访问这些状态。

接下来让我们正式开始使用:

为每个状态创建类

为每个需要管理的状态创建一个类,并确保这些类继承自 ChangeNotifier

class Counter with ChangeNotifier {int _count = 0;int get count => _count;void increment() {_count++;notifyListeners();}
}class ThemeSwitcher with ChangeNotifier {bool _isDarkTheme = false;bool get isDarkTheme => _isDarkTheme;void toggleTheme() {_isDarkTheme = !_isDarkTheme;notifyListeners();}
}

在应用的根或需要的地方提供状态

使用 ChangeNotifierProvider 来包裹你的应用或特定的 widget,并为每个状态提供一个 create 函数来创建其对应的实例。

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';void main() {runApp(MyApp());
}class MyApp extends StatelessWidget {Widget build(BuildContext context) {return MultiProvider(providers: [ChangeNotifierProvider(create: (context) => Counter()),ChangeNotifierProvider(create: (context) => ThemeSwitcher()),],child: MaterialApp(home: MyHomePage(),),);}
}

在 widget 中访问状态

使用 Provider.of<T>(context)Consumer<T> 在需要的地方访问状态。

class MyHomePage extends StatelessWidget {Widget build(BuildContext context) {final counter = Provider.of<Counter>(context);final themeSwitcher = Provider.of<ThemeSwitcher>(context);return Scaffold(appBar: AppBar(title: Text('Multiple Providers Example'),),body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Text('You have pushed the button this many times:',),Text('${counter.count}',style: Theme.of(context).textTheme.headline4,),Switch(value: themeSwitcher.isDarkTheme,onChanged: (value) {themeSwitcher.toggleTheme();},),],),),floatingActionButton: FloatingActionButton(onPressed: () {counter.increment();},tooltip: 'Increment',child: Icon(Icons.add),),);}
}

更新状态

在状态类中修改属性,并调用 notifyListeners() 来通知所有监听这个状态的 widget 进行更新。

class Counter with ChangeNotifier {int _count = 0;int get count => _count;void increment() {_count++;notifyListeners();  // 通知所有监听这个状态的widget进行更新}
}class ThemeSwitcher with ChangeNotifier {bool _isDarkTheme = false;bool get isDarkTheme => _isDarkTheme;void toggleTheme() {_isDarkTheme = !_isDarkTheme;notifyListeners();  // 通知所有监听这个状态的widget进行更新}
}

完整示例

下面是一个例子,展示了如何使用 Provider 来管理两个不同的状态:

代码如下(示例):

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';void main() {runApp(MyApp());
}class MyApp extends StatelessWidget {Widget build(BuildContext context) {return MultiProvider(providers: [ChangeNotifierProvider(create: (context) => Counter()),ChangeNotifierProvider(create: (context) => ThemeSwitcher()),],child: MaterialApp(home: MyHomePage(),),);}
}class Counter with ChangeNotifier {int _count = 0;int get count => _count;void increment() {_count++;notifyListeners();}
}class ThemeSwitcher with ChangeNotifier {bool _isDarkTheme = false;bool get isDarkTheme => _isDarkTheme;void toggleTheme() {_isDarkTheme = !_isDarkTheme;notifyListeners();}
}class MyHomePage extends StatelessWidget {Widget build(BuildContext context) {final counter = Provider.of<Counter>(context);final themeSwitcher = Provider.of<ThemeSwitcher>(context);return Scaffold(appBar: AppBar(title: Text('Multiple Providers Example'),),body: Center(child: Column(mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[Text('You have pushed the button this many times:',),Text('${counter.count}',style: Theme.of(context).textTheme.headline4,),Switch(value: themeSwitcher.isDarkTheme,onChanged: (value) {themeSwitcher.toggleTheme();},),],),),floatingActionButton: FloatingActionButton(onPressed: () {counter.increment();},tooltip: 'Increment',child: Icon(Icons.add),),);}
}

运行结果如下

总结

本文主要介绍了在 Flutter 中如何使用多个 Provider 进行状态管理。

类似的状态管理还有 BlocGetX 的使用,后续会继续分享它们的使用方式,欢迎关注。

– 欢迎点赞、关注、转发、收藏【我码玄黄】,gonghao同名

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 快捷:通过胶水语言实现工作中测试流程并行、加速
  • nginx全局块的user指令
  • 基于 Vue 3 和 Element Plus 构建图书管理系统
  • 计算机毕业设计Python深度学习游戏推荐系统 Django PySpark游戏可视化 游戏数据分析 游戏爬虫 Scrapy 机器学习 人工智能 大数据毕设
  • Airdrop 2049 第二季如何捕捉全新机遇?专家大咖带你揭秘!
  • B树:深入解析与实战应用
  • 华为的热机备份和流量限制
  • 纯净IP的判断标准及代理深度分析
  • Unity3d开发google chrome的dinosaur游戏
  • 数据可视化入门
  • 【CPO-TCN-BiGRU-Attention回归预测】基于冠豪猪算法CPO优化时间卷积双向门控循环单元融合注意力机制
  • https 单向认证和双向认证
  • Postfix+Dovecot+Roundcube开源邮件系统搭建系列1-2:系统搭建目标+MariaDB数据库配置(MySQL)
  • 网络规划设计师教程(第二版) pdf
  • 数据库系统概论:数据库完整性
  • 【css3】浏览器内核及其兼容性
  • Angular2开发踩坑系列-生产环境编译
  • Asm.js的简单介绍
  • co模块的前端实现
  • css布局,左右固定中间自适应实现
  • Java 网络编程(2):UDP 的使用
  • Linux下的乱码问题
  • passportjs 源码分析
  • springMvc学习笔记(2)
  • SQLServer之索引简介
  • 编写高质量JavaScript代码之并发
  • 名企6年Java程序员的工作总结,写给在迷茫中的你!
  • 爬虫模拟登陆 SegmentFault
  • 使用Swoole加速Laravel(正式环境中)
  • 思否第一天
  • ​flutter 代码混淆
  • "无招胜有招"nbsp;史上最全的互…
  • ### RabbitMQ五种工作模式:
  • #android不同版本废弃api,新api。
  • #大学#套接字
  • (1)虚拟机的安装与使用,linux系统安装
  • (23)Linux的软硬连接
  • (26)4.7 字符函数和字符串函数
  • (CVPRW,2024)可学习的提示:遥感领域小样本语义分割
  • (Pytorch框架)神经网络输出维度调试,做出我们自己的网络来!!(详细教程~)
  • (ZT)出版业改革:该死的死,该生的生
  • (附源码)计算机毕业设计SSM基于java的云顶博客系统
  • (附源码)计算机毕业设计SSM智能化管理的仓库管理
  • (七)MySQL是如何将LRU链表的使用性能优化到极致的?
  • (限时免费)震惊!流落人间的haproxy宝典被找到了!一切玄妙尽在此处!
  • (转)视频码率,帧率和分辨率的联系与区别
  • .describe() python_Python-Win32com-Excel
  • .halo勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .NET 8 中引入新的 IHostedLifecycleService 接口 实现定时任务
  • .NET 项目中发送电子邮件异步处理和错误机制的解决方案
  • .pub是什么文件_Rust 模块和文件 - 「译」
  • @Autowired和@Resource的区别
  • [ C++ ] STL priority_queue(优先级队列)使用及其底层模拟实现,容器适配器,deque(双端队列)原理了解
  • []AT 指令 收发短信和GPRS上网 SIM508/548
  • [17]JAVAEE-HTTP协议