1 全局变量-Global类
在“lib/common”目录下创建一个Global
类,它主要管理APP的全局变量,定义如下:
// 提供五套可选主题色
const _themes = <MaterialColor>[
Colors.blue,
Colors.cyan,
Colors.teal,
Colors.green,
Colors.red,
];
class Global {
static late SharedPreferences _prefs;
static Profile profile = Profile();
// 网络缓存对象
static NetCache netCache = NetCache();
// 可选的主题列表
static List<MaterialColor> get themes => _themes;
// 是否为release版
static bool get isRelease => bool.fromEnvironment("dart.vm.product");
//初始化全局信息,会在APP启动时执行
static Future init() async {
WidgetsFlutterBinding.ensureInitialized();
_prefs = await SharedPreferences.getInstance();
var _profile = _prefs.getString("profile");
if (_profile != null) {
try {
profile = Profile.fromJson(jsonDecode(_profile));
} catch (e) {
print(e);
}
}else{
// 默认主题索引为0,代表蓝色
profile= Profile()..theme=0;
}
// 如果没有缓存策略,设置默认缓存策略
profile.cache = profile.cache ?? CacheConfig()
..enable = true
..maxAge = 3600
..maxCount = 100;
//初始化网络请求相关配置
Git.init();
}
// 持久化Profile信息
static saveProfile() =>
_prefs.setString("profile", jsonEncode(profile.toJson()));
}
init()
需要在App启动时就要执行,所以应用的main
方法如下:
void main() => Global.init().then((e) => runApp(MyApp()));
一定要确保Global.init()
方法不能抛出异常,否则 runApp(MyApp())
根本执行不到。
2 共享状态
1、有了全局变量,还需要考虑如何跨组件共享状态。 当然,如果将要共享的状态全部用全局变量替代也是可以的,但是这在Flutter开发中并不是一个好主意,因为组件的状态是和UI相关,而在状态改变时会期望依赖该状态的UI组件会自动更新,如果使用全局变量,那么必须得去手动处理状态变动通知、接收机制以及变量和组件依赖关系。
2、这些信息改变后都要立即通知其他依赖的该信息的Widget更新,所以应该使用ChangeNotifierProvider
,另外,这些信息改变后都是需要更新Profile信息并进行持久化的。综上所述,可以定义一个ProfileChangeNotifier
基类,然后让需要共享的Model继承自该类即可,ProfileChangeNotifier
定义如下:
class ProfileChangeNotifier extends ChangeNotifier {
Profile get _profile => Global.profile;
@override
void notifyListeners() {
Global.saveProfile(); //保存Profile变更
super.notifyListeners(); //通知依赖的Widget更新
}
}
1. 用户状态
用户状态在登录状态发生变化时更新、通知其依赖项,定义如下:
class UserModel extends ProfileChangeNotifier {
User get user => _profile.user;
// APP是否登录(如果有用户信息,则证明登录过)
bool get isLogin => user != null;
//用户信息发生变化,更新用户信息并通知依赖它的子孙Widgets更新
set user(User user) {
if (user?.login != _profile.user?.login) {
_profile.lastLogin = _profile.user?.login;
_profile.user = user;
notifyListeners();
}
}
}
2. APP主题状态
主题状态在用户更换APP主题时更新、通知其依赖项,定义如下:
class ThemeModel extends ProfileChangeNotifier {
// 获取当前主题,如果为设置主题,则默认使用蓝色主题
ColorSwatch get theme => Global.themes
.firstWhere((e) => e.value == _profile.theme, orElse: () => Colors.blue);
// 主题改变后,通知其依赖项,新主题会立即生效
set theme(ColorSwatch color) {
if (color != theme) {
_profile.theme = color[500].value;
notifyListeners();
}
}
}