diff --git a/assets/magnetic_declination.db b/assets/magnetic_declination.db new file mode 100644 index 0000000..fc6fc05 Binary files /dev/null and b/assets/magnetic_declination.db differ diff --git a/lib/components/region_selector.dart b/lib/components/region_selector.dart index c5cd852..6069565 100644 --- a/lib/components/region_selector.dart +++ b/lib/components/region_selector.dart @@ -71,100 +71,14 @@ class RegionSelector extends StatelessWidget { ], )), ), + const SizedBox( + height: 20, + ), + Text( + '磁偏角 : ${regionProvider.tempDeclination}°', + style: const TextStyle(fontSize: 24), + ) ], ))); } } - -// class RegionSelector extends StatefulWidget { -// const RegionSelector({Key key}) : super(key: key); -// -// @override -// State createState() => _RegionSelectorState(); -// } -// -// class _RegionSelectorState extends State { -// final Future _prefs = SharedPreferences.getInstance(); -// -// // final rp = RegionProvider() -// String provinceName; -// String cityName; -// -// @override -// initState() { -// // provinceName = Provider.of(context).provinceName; -// // cityName = Provider.of(context).cityName; -// _prefs.then((prefs) { -// if (prefs.getString('REGION') != null) { -// final region = -// RegionData.fromJson(jsonDecode(prefs.getString('REGION'))); -// provinceName = region.provinceName; -// cityName = region.cityName; -// } -// }); -// } -// -// // 拼接城市 -// String spliceCityName(String pname, String cname) { -// if (pname == '') return '未选择城市'; -// StringBuffer sb = StringBuffer(); -// sb.write(pname); -// if (cname == '') return sb.toString(); -// sb.write(' - '); -// sb.write(cname); -// return sb.toString(); -// } -// -// @override -// Widget build(BuildContext context) { -// return SizedBox( -// height: 100, -// child: Consumer( -// builder: (context, regionProvider, child) => Column( -// children: [ -// InkWell( -// onTap: () { -// Pickers.showAddressPicker(context, -// addAllItem: false, -// initProvince: regionProvider.provinceName, -// initCity: regionProvider.cityName, -// onConfirm: (p, c, t) { -// regionProvider.updateRegion(p, c); -// setState(() { -// provinceName = p; -// cityName = c; -// }); -// }); -// }, -// child: Container( -// constraints: const BoxConstraints(minHeight: 42), -// padding: const EdgeInsets.fromLTRB(10, 0, 12, 0), -// decoration: BoxDecoration( -// border: Border.all(color: Colors.grey), -// borderRadius: BorderRadius.circular(6), -// ), -// child: Row( -// // mainAxisSize: MainAxisSize.min, -// mainAxisAlignment: MainAxisAlignment.spaceBetween, -// crossAxisAlignment: CrossAxisAlignment.center, -// children: [ -// Text(spliceCityName(regionProvider.provinceName, -// regionProvider.cityName)), -// // SizedBox(width: 8), -// Row( -// children: [ -// InkWell( -// child: Icon(Icons.close, -// size: 20, color: Colors.grey[500]), -// onTap: () {}), -// Icon(Icons.keyboard_arrow_down, -// size: 28, color: Colors.grey[500]), -// ], -// ) -// ], -// )), -// ), -// ], -// ))); -// } -// } diff --git a/lib/main.dart b/lib/main.dart index 391d61b..7d6224d 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -10,17 +10,7 @@ import 'package:provider/provider.dart'; void main() { ///屏幕刷新率和显示率不一致时的优化 // GestureBinding.instance.resamplingEnabled = true; - runApp( - MultiProvider( - providers: [ - ChangeNotifierProvider( - create: (context) => RegionProvider(), - ), - ChangeNotifierProvider(create: (context) => TokenProvider()), - ], - child: const MyApp(), - ), - ); + runApp(const MyApp()); } class MyApp extends StatelessWidget { @@ -29,23 +19,31 @@ class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { - return MaterialApp( - title: '风水罗盘', - theme: ThemeData( - primarySwatch: createMaterialColor(const Color(0xCFA77300)), + return MultiProvider( + providers: [ + ChangeNotifierProvider( + create: (context) => RegionProvider(), + ), + ChangeNotifierProvider(create: (context) => TokenProvider()), + ], + child: MaterialApp( + title: '风水罗盘', + theme: ThemeData( + primarySwatch: createMaterialColor(const Color(0xCFA77300)), + ), + debugShowCheckedModeBanner: false, + home: const BottomNavigationWidget(), + localizationsDelegates: const [ + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + ], + supportedLocales: const [ + //此处 + Locale('zh'), + Locale('en'), + ], ), - debugShowCheckedModeBanner: false, - home: const BottomNavigationWidget(), - localizationsDelegates: const [ - GlobalMaterialLocalizations.delegate, - GlobalWidgetsLocalizations.delegate, - GlobalCupertinoLocalizations.delegate, - ], - supportedLocales: const [ - //此处 - Locale('zh'), - Locale('en'), - ], ); } } diff --git a/lib/net/dio_utils.dart b/lib/net/dio_utils.dart index f363143..540d3a8 100644 --- a/lib/net/dio_utils.dart +++ b/lib/net/dio_utils.dart @@ -21,10 +21,10 @@ class DioUtils { bool isProxy = false; //网络代理地址 - String proxyIp = "192.168.0.107"; + String proxyIp = "10.0.2.2"; //网络代理端口 - String proxyPort = "8888"; + String proxyPort = "7890"; DioUtils._internal() { BaseOptions options = new BaseOptions(); @@ -135,8 +135,8 @@ class DioUtils { // _dio.options.headers["content-type"]="multipart/form-data"; //发起post请求 try { - Response response = await _dio.post(url, - data: form ?? jsonMap, cancelToken: cancelTag); + Response response = + await _dio.post(url, data: form ?? jsonMap, cancelToken: cancelTag); //响应数据 dynamic responseData = response.data; @@ -216,8 +216,8 @@ class DioUtils { // _dio.options.headers["content-type"]="multipart/form-data"; //发起post请求 try { - Response response = await _dio.post(url, - data: form ?? jsonMap, cancelToken: cancelTag); + Response response = + await _dio.post(url, data: form ?? jsonMap, cancelToken: cancelTag); //响应数据 dynamic responseData = response.data; @@ -260,15 +260,15 @@ class DioUtils { loginInfo.msg = "响应超时"; break; case DioErrorType.response: - // 响应错误 + // 响应错误 loginInfo.msg = "响应错误"; break; case DioErrorType.cancel: - // 取消操作 + // 取消操作 loginInfo.msg = "已取消"; break; case DioErrorType.other: - // 默认自定义其他异常 + // 默认自定义其他异常 loginInfo.msg = "网络请求异常"; break; } @@ -316,8 +316,10 @@ class LoginInfo { String msg; String token; - LoginInfo({this.success = true, this.code = 200, this.token, this.msg="登陆成功"}); - LoginInfo.error({this.success = false, this.code = 201, this.msg="请求异常"}); + LoginInfo( + {this.success = true, this.code = 200, this.token, this.msg = "登陆成功"}); + + LoginInfo.error({this.success = false, this.code = 201, this.msg = "请求异常"}); } class RegisterInfo { @@ -325,7 +327,8 @@ class RegisterInfo { int code; String msg; + RegisterInfo({this.success = true, this.code = 200, this.msg = "注册成功"}); - RegisterInfo({this.success = true, this.code = 200, this.msg="注册成功"}); - RegisterInfo.error({this.success = false, this.code = 201, this.msg="请求异常"}); + RegisterInfo.error( + {this.success = false, this.code = 201, this.msg = "请求异常"}); } diff --git a/lib/pages/compass_page.dart b/lib/pages/compass_page.dart index fb05662..1653268 100644 --- a/lib/pages/compass_page.dart +++ b/lib/pages/compass_page.dart @@ -268,7 +268,7 @@ class _CompassState extends State { context: context, builder: (BuildContext context) { return AlertDialog( - title: Text('选择城市校准磁偏角'), + title: const Text('选择城市校准磁偏角'), content: RegionSelector(), actions: [ TextButton( diff --git a/lib/pages/login_page.dart b/lib/pages/login_page.dart index 9be9a6c..2ff33c1 100644 --- a/lib/pages/login_page.dart +++ b/lib/pages/login_page.dart @@ -188,8 +188,8 @@ class _LoginPageState extends State { if (userName.trim().length != 11) { Fluttertoast.showToast( msg: "请输入11位手机号", - backgroundColor: Colors.red, - textColor: Colors.orange, + backgroundColor: Colors.orange, + textColor: Colors.white, fontSize: 20.0); return; } @@ -218,7 +218,7 @@ class _LoginPageState extends State { if (responseInfo.success) { Map res = {"token": responseInfo.token.toString()}; LoginBean loginBean = LoginBean.fromMap(res); - TokenHelper.getInstance.loginBean = loginBean; + // TokenHelper.getInstance.loginBean = loginBean; // 将token添加到状态管理器中 Provider.of(context, listen: false).setToken(loginBean); Fluttertoast.showToast(msg: "登录成功"); diff --git a/lib/pages/personal_login_page.dart b/lib/pages/personal_login_page.dart index 5186699..698b04d 100644 --- a/lib/pages/personal_login_page.dart +++ b/lib/pages/personal_login_page.dart @@ -21,13 +21,13 @@ class _PersonalLoginPageState extends State { return Scaffold( appBar: AppBar( - title: Text("个人中心"), + title: const Text("个人中心"), ), body: Container( width: double.infinity, child: Column( children: [ - Padding(padding: EdgeInsets.only(top: 80)), + const Padding(padding: EdgeInsets.only(top: 80)), SizedBox( height: 120, child: ClipRRect( @@ -35,15 +35,15 @@ class _PersonalLoginPageState extends State { child: Image.asset("assets/images/ic_launcher.png"), ), ), - Padding(padding: EdgeInsets.only(top: 30)), + const Padding(padding: EdgeInsets.only(top: 30)), ListTile( - title: Text("关于我们"), + title: const Text("关于我们"), trailing: const Icon(Icons.arrow_forward_ios_sharp), leading: const Icon(Icons.account_circle), onTap: () {}, ), ListTile( - title: Text("退出登陆"), + title: const Text("退出登陆"), trailing: const Icon(Icons.arrow_forward_ios_sharp), leading: const Icon(Icons.cancel_rounded), onTap: () async { @@ -74,7 +74,7 @@ class _PersonalLoginPageState extends State { }); if (isExit) { - TokenHelper.getInstance.clear(); + // TokenHelper.getInstance.clear(); //在状态管理器中清除token Provider.of(context, listen: false) .clearToken(); diff --git a/lib/states/region.dart b/lib/states/region.dart index fe32ba4..464caa7 100644 --- a/lib/states/region.dart +++ b/lib/states/region.dart @@ -1,7 +1,13 @@ import 'dart:convert'; +import 'dart:io'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_pickers/address_picker/locations_data.dart'; +import 'package:path/path.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:sqflite/sqflite.dart'; import '../models/region.dart'; @@ -14,6 +20,10 @@ class RegionProvider extends ChangeNotifier { String _cityName = ''; String _tempProvinceName = ''; String _tempCityName = ''; + double _declination = 0.0; + double _tempDeclination = 0.0; + + Database db; String get provinceName => _provinceName; @@ -23,39 +33,93 @@ class RegionProvider extends ChangeNotifier { String get tempCityName => _tempCityName; + double get tempDeclination => _tempDeclination; + + double get declination => _declination; + final Future _prefs = SharedPreferences.getInstance(); - loadRegionData() { - _prefs.then((prefs) { - if (prefs.getString('REGION') != null) { - final region = - RegionData.fromJson(jsonDecode(prefs.getString('REGION'))); - _provinceName = region.provinceName; - _cityName = region.cityName; - _tempProvinceName = region.provinceName; - _tempCityName = region.cityName; - notifyListeners(); + loadRegionData() async { + db = await loadDatabase(); + final prefs = await _prefs; + if (prefs.getString('REGION') != null) { + final region = RegionData.fromJson(jsonDecode(prefs.getString('REGION'))); + _provinceName = region.provinceName; + _cityName = region.cityName; + _tempProvinceName = region.provinceName; + _tempCityName = region.cityName; + // WidgetsFlutterBinding.ensureInitialized(); + List cityCode = Address.getCityCodeByName( + provinceName: _provinceName, cityName: _cityName); + if (cityCode.length == 2) { + List> decMap = await db.rawQuery( + "SELECT declination FROM magnetic_declination WHERE cityId == ${cityCode[1]}"); + _declination = decMap[0]['declination']; + _tempDeclination = decMap[0]['declination']; + } else { + _declination = 0.0; + _tempDeclination = 0.0; } - }); + + notifyListeners(); + } } - updateRegion(pname, cname) { - // _provinceName = pname; - // _cityName = cname; + Future loadDatabase() async { + var databasesPath = await getDatabasesPath(); + var path = join(databasesPath, "magnetic_declination.db"); + var exists = await databaseExists(path); + if (!exists) { + print("Creating new copy from asset"); + try { + await Directory(dirname(path)).create(recursive: true); + } catch (_) {} + // Copy from asset + ByteData data = + await rootBundle.load(join("assets", "magnetic_declination.db")); + List bytes = + data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); + // Write and flush the bytes written + await File(path).writeAsBytes(bytes, flush: true); + } else { + print("Opening existing database"); + } +// open the database + Database _db = await openDatabase(path, readOnly: true); + return _db; + } + + // 存储临时的省市名称,不会保存本地 + void updateRegion(pname, cname) async { _tempProvinceName = pname; _tempCityName = cname; - + List cityCode = Address.getCityCodeByName( + provinceName: _tempProvinceName, cityName: _tempCityName); + print(cityCode); + if (cityCode.length == 2) { + List> decMap = await db.rawQuery( + "SELECT declination FROM magnetic_declination WHERE cityId == ${cityCode[1]}"); + print(decMap); + _tempDeclination = decMap[0]['declination']; + } else { + _tempDeclination = 0.0; + } notifyListeners(); } + //更新磁偏角 + void updateDeclination(pname, cname) {} + //将临时变量保存到正式变量,并保存本地 - saveRegion() { + void saveRegion() { _provinceName = _tempProvinceName; _cityName = _tempCityName; + _declination = _tempDeclination; print(_tempCityName); final region = { "provinceName": _tempProvinceName, - 'cityName': _tempCityName + 'cityName': _tempCityName, + // 'declination': _tempDeclination }; _prefs.then((prefs) { prefs.setString('REGION', jsonEncode(region)); @@ -64,16 +128,18 @@ class RegionProvider extends ChangeNotifier { } // 覆盖临时的变量 - resetTemp() async { + void resetTemp() async { _tempProvinceName = _provinceName; _tempCityName = _cityName; + _tempDeclination = _declination; notifyListeners(); } // 将临时的省市名设为空 - clearTemp() { + void clearTemp() { _tempProvinceName = ''; _tempCityName = ''; + _tempDeclination = 0.0; notifyListeners(); } } diff --git a/lib/states/token.dart b/lib/states/token.dart index 0a44375..0d9cc73 100644 --- a/lib/states/token.dart +++ b/lib/states/token.dart @@ -12,7 +12,7 @@ class TokenProvider extends ChangeNotifier { bool get isLogin => _loginBean != null; - loadToken() { + void loadToken() { Map map = SPUtil.getObject("token_bean"); if (map != null) { //加载缓存 @@ -21,13 +21,15 @@ class TokenProvider extends ChangeNotifier { notifyListeners(); } - clearToken() { + void clearToken() { _loginBean = null; + SPUtil.remove("token_bean"); notifyListeners(); } - setToken(LoginBean lb) { + void setToken(LoginBean lb) { _loginBean = lb; + SPUtil.saveObject("token_bean", lb); notifyListeners(); } } diff --git a/pubspec.lock b/pubspec.lock index 6d74914..d225852 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -192,7 +192,7 @@ packages: source: hosted version: "2.0.2" path: - dependency: transitive + dependency: "direct main" description: name: path url: "https://mirrors.tuna.tsinghua.edu.cn/dart-pub/" @@ -315,6 +315,20 @@ packages: url: "https://mirrors.tuna.tsinghua.edu.cn/dart-pub/" source: hosted version: "1.8.2" + sqflite: + dependency: "direct main" + description: + name: sqflite + url: "https://mirrors.tuna.tsinghua.edu.cn/dart-pub/" + source: hosted + version: "2.0.2+1" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + url: "https://mirrors.tuna.tsinghua.edu.cn/dart-pub/" + source: hosted + version: "2.2.1+1" stack_trace: dependency: transitive description: @@ -343,6 +357,13 @@ packages: url: "https://mirrors.tuna.tsinghua.edu.cn/dart-pub/" source: hosted version: "1.1.0" + synchronized: + dependency: transitive + description: + name: synchronized + url: "https://mirrors.tuna.tsinghua.edu.cn/dart-pub/" + source: hosted + version: "3.0.0+2" term_glyph: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 5b7fa74..b2e8307 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,6 +32,8 @@ dependencies: url: https://gitee.com/liang-fu/flutter_serial_port_api.git flutter_pickers: ^2.1.9 provider: ^6.0.3 + sqflite: ^2.0.2+1 + path: ^1.8.1 dev_dependencies: flutter_test: @@ -52,6 +54,7 @@ flutter: - assets/index.html - assets/test.js - assets/images/ + - assets/magnetic_declination.db fonts: - family: iconfont # 从 iconfont.json 中获取