| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- // 提供五套可选主题色
- import 'dart:convert';
- import 'package:dio/dio.dart';
- import 'package:e2ee_chat/common/api.dart';
- import 'package:e2ee_chat/model/profile.dart';
- import 'package:e2ee_chat/objectbox.g.dart';
- import 'package:flutter/material.dart';
- import 'package:objectbox/objectbox.dart';
- import 'package:permission_handler/permission_handler.dart';
- import '../presenter/login.dart';
- const _themes = <MaterialColor>[
- Colors.blue,
- Colors.cyan,
- Colors.teal,
- Colors.green,
- Colors.red,
- ];
- void debug(Object? o) {
- if (!Global.isRelease) {
- print(o);
- }
- }
- class Global {
- static GlobalKey<NavigatorState> navigatorKey = GlobalKey();
- static final Image defaultAvatar = Image.asset(
- "imgs/avatar.jpg",
- width: 80,
- );
- static final int profileId = 1;
- static Profile profile = Profile();
- // 可选的主题列表
- static List<MaterialColor> get themes => _themes;
- // 是否为release版
- static bool get isRelease => bool.fromEnvironment("dart.vm.product");
- static final String emptyToken = "token";
- static get locales => [
- const Locale('zh'), // 中文简体
- const Locale('en'), // 美国英语
- //其它Locales
- ];
- static Future<bool> checkPermission() async {
- bool status = await Permission.storage.isGranted;
- return status ? true : await Permission.storage.request().isGranted;
- }
- static listenIsLogin() async {
- while (true) {
- if (!profile.isLogin && (profile.isLogout || !await LoginModel().login())) {
- debug("offline detected! navigate to login route");
- await Global.navigatorKey.currentState?.pushNamed("login");
- }
- await Future.delayed(Duration(seconds: 1));
- }
- }
- //初始化全局信息,会在APP启动时执行
- static init() async {
- debug('Init begin');
- bool status = await checkPermission();
- assert(status, "permission error");
- Store store = await openStore();
- var box = store.box<Profile>();
- profile = box.get(profileId) ?? Profile();
- store.close();
- profile.isLogin = false;
- debug('Init profile: id: ${profile.id}, username: ${profile.username}, token: ${await profile.token}, isLogout: ${profile.isLogout}');
- await Api.init();
- listenIsLogin();
- /*
- debug('Init login');
- try {
- await UserModel().login(); // must await, or can not catch error
- } on DioError catch(e) {
- debug('Init login failed');
- }
- */
- debug('Global init end');
- }
- // 持久化Profile信息
- static saveProfile() async {
- debug('save profile: username: ${profile.username}, isLogout: ${profile.isLogout}');
- Store store = await openStore();
- var box = store.box<Profile>();
- box.removeAll();
- box.put(profile);
- store.close();
- }
- }
|