diff --git a/.gitignore b/.gitignore index df27b4c..e617ab5 100644 --- a/.gitignore +++ b/.gitignore @@ -43,8 +43,13 @@ app.*.map.json /android/app/profile /android/app/release -# 暂时不关注ios的构建 +# 暂时不关注其他的构建 ios +linux +macos +web +windows + **/_demos **/_tests @@ -67,4 +72,5 @@ ios **/_old_readme/* **bak* +**_bak* **_self* diff --git a/CHANGELOG.md b/CHANGELOG.md index f429de4..4cb7f3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes to this project will be documented in this file. +## 0.2.1-beta.1 + +- refactor: + - 饮食模块中 AI 大模型响应改为流式,可以更快看到结果输出 + - 稍微简化了动作和食物的 json 文件导入 +- chore: + - 升级到 flutter3.24.4,同步更新工具依赖库到最新 + - 移除 Android 外其他平台环境内容 +- fix: + - 修正饮食记录页面,指定餐次图片更新页面重复异动未按预期执行的问题 + - 检查大部分地方的 setState 前是否已经挂载 + - Card 的阴影样式稍微统一 + - 减少了一些无意义的 print 输出 + ## 0.2.0-beta.1 - feat: diff --git a/_dev_logs/dev_records.md b/_dev_logs/dev_records.md index f7f0061..31b5ca1 100644 --- a/_dev_logs/dev_records.md +++ b/_dev_logs/dev_records.md @@ -16,6 +16,83 @@ 这是无关紧要的东西,记录一些开发过程中的细节,防止以为我忘记了。 +- 2023-12-30 appbar 的 action 都优先 iconbutton + +### 2024-11-12 起 重构小记 + +- perf: 基本就是清除 print 语句,检查 setState 前是否已经挂载,Card 的阴影大小,Padding 的边距值大小,和少量的 bug 修复。 + +#### 2024-12-03 + +- refactor: 重构调用大模型 API 为流式响应。 + +#### 2024-12-02 + +- 饮食大模块 + +#### 2024-11-26 + +- 我的模块 + +#### 2024-11-16 + +- 训练日志的导出模块 + +#### 2024-11-15 + +- exercise 动作模块 +- workout 训练模块 +- plan 计划模块 + +#### 2024-11-13 + +- 手记模块 +- 锻炼首页、饮食首页 + +### 2024-11-11 + +#### 升级 flutter 版本,更新兼容依赖 + +```sh +$ flutter --version +Flutter 3.24.4 • channel stable • https://github.com/flutter/flutter.git +Framework • revision 603104015d (2 周前) • 2024-10-24 08:01:25 -0700 +Engine • revision db49896cf2 +Tools • Dart 3.5.4 • DevTools 2.37.3 +``` + +### 2024-07-12 + +- fix:修正较新版本 Android 下存储权限未正常获取的问题. +- feat:添加了对饮食模块下“餐食相册”和“饮食日记”页面中指定餐次的食物图片,进行“AI 分析”的功能。 + +#### 餐食相册的备份还原 + +问题描述: + +- 因为餐次的照片的上传是使用`FormBuilderFilePicker`实现的,底层是`file_picker`,实际是把图片缓存到了该库默认的位置,类似`/data/user/0/com.swm.free_fitness/cache/file_picker/菜品识别1.jpg`; +- 所以在重新安装 app,再恢复饮食日志的时候,餐次图片的地址就是上述缓存的位置; +- 但由于卸载了 app,应用缓存的数据都丢了,也就无法再看到餐次图片了,那这个图片地址的备份实际没有作用了; + - 当然,食物摄入量等其他信息不受影响。 + +TODO 思路: + +- 第一种: + - 上传时,把图片文件存入 db; + - 展示、备份恢复等直接处理图片文件数据 +- 第二种: + - 上传时,依旧把图片放到`FormBuilderFilePicker`的默认到缓存中; + - 备份时,把图片文件从缓存中获取(比如存为单独的图片 zip),连同 db 中的其他导出的 json 数据一起备份到压缩包; + - 恢复时,把图片放到缓存路径,然后把 json 数据中的图片地址替换为缓存路径; +- 第三种(预计使用这种**就跟导入基础动作的图片一样**,但同样的问题有 2:1 权限、2 直接在文件管理器中误删): + - 上传时,把图片放到外部路径,卸载 app 不删除图片缓存; + - 展示、备份恢复等使用外部存储的路径; + - 现在上传的餐食图片会保留在`/storage/emulated/0/FREE-FITNESS/MealPhotos`,应用卸载后该位置的图片也不会被删除。 + +### 2024-07-08 + +- feat:添加了 dio http client 的自定义封装;添加在“饮食”-“饮食日记”页面中“AI 对话助手”功能。 + ### 2024-07-06 #### 升级 flutter 版本,更新兼容依赖 @@ -544,38 +621,6 @@ dart devtools --appSizeBase=apk-code-size-analysis_09.json -### 2024-07-08 - -- feat:添加了 dio http client 的自定义封装;添加在“饮食”-“饮食日记”页面中“AI 对话助手”功能。 - -### 2024-07-12 - -- fix:修正较新版本 Android 下存储权限未正常获取的问题. -- feat:添加了对饮食模块下“餐食相册”和“饮食日记”页面中指定餐次的食物图片,进行“AI 分析”的功能。 - -#### 餐食相册的备份还原 - -问题描述: - -- 因为餐次的照片的上传是使用`FormBuilderFilePicker`实现的,底层是`file_picker`,实际是把图片缓存到了该库默认的位置,类似`/data/user/0/com.swm.free_fitness/cache/file_picker/菜品识别1.jpg`; -- 所以在重新安装 app,再恢复饮食日志的时候,餐次图片的地址就是上述缓存的位置; -- 但由于卸载了 app,应用缓存的数据都丢了,也就无法再看到餐次图片了,那这个图片地址的备份实际没有作用了; - - 当然,食物摄入量等其他信息不受影响。 - -TODO 思路: - -- 第一种: - - 上传时,把图片文件存入 db; - - 展示、备份恢复等直接处理图片文件数据 -- 第二种: - - 上传时,依旧把图片放到`FormBuilderFilePicker`的默认到缓存中; - - 备份时,把图片文件从缓存中获取(比如存为单独的图片 zip),连同 db 中的其他导出的 json 数据一起备份到压缩包; - - 恢复时,把图片放到缓存路径,然后把 json 数据中的图片地址替换为缓存路径; -- 第三种(预计使用这种**就跟导入基础动作的图片一样**,但同样的问题有 2:1 权限、2 直接在文件管理器中误删): - - 上传时,把图片放到外部路径,卸载 app 不删除图片缓存; - - 展示、备份恢复等使用外部存储的路径; - - 现在上传的餐食图片会保留在`/storage/emulated/0/FREE-FITNESS/MealPhotos`,应用卸载后该位置的图片也不会被删除。 - ### TODO - i18n 的中英文不全,很多地方使用的是` box.read('language') == "en" ? "AI analysis" : 'AI分析',`投机方式,如果系统就是英文那显示的还是中文。 diff --git a/android/app/build.gradle b/android/app/build.gradle index bc14f99..d6ec15f 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -32,12 +32,27 @@ def keystorePropertiesFile = rootProject.file('key.properties') android { namespace "com.swm.free_fitness" - compileSdkVersion flutter.compileSdkVersion - ndkVersion flutter.ndkVersion + // compileSdkVersion flutter.compileSdkVersion + // 安卓14(API 34) - java17 - AGP8 + compileSdkVersion 34 + // ndkVersion flutter.ndkVersion + ndkVersion = "26.1.10909125" + // 2024-11-16 升级到java 17 compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + // sourceCompatibility JavaVersion.VERSION_1_8 + // targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + kotlinOptions { + // jvmTarget = '1.8' + jvmTarget = '17' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' } // 在构建应用时打包压缩的原生库 @@ -48,14 +63,6 @@ android { } } - kotlinOptions { - jvmTarget = '1.8' - } - - sourceSets { - main.java.srcDirs += 'src/main/kotlin' - } - defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.swm.free_fitness" diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 3c472b9..40dc7c0 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip +# distributionUrl=https\://services.gradle.org/distributions/gradle-7.5-all.zip +distributionUrl = https\://services.gradle.org/distributions/gradle-8.7-all.zip \ No newline at end of file diff --git a/android/settings.gradle b/android/settings.gradle index 3ed3e4d..f07f587 100644 --- a/android/settings.gradle +++ b/android/settings.gradle @@ -18,11 +18,15 @@ pluginManagement { plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" - id "com.android.application" version "7.3.0" apply false - // id "org.jetbrains.kotlin.android" version "1.7.10" apply false - // 有些库需要更新的kotlin版本 - // https://stackoverflow.com/questions/70919127/your-project-requires-a-newer-version-of-the-kotlin-gradle-plugin-android-stud - id "org.jetbrains.kotlin.android" version "2.0.0" apply false + // id "com.android.application" version "7.3.0" apply false + // // id "org.jetbrains.kotlin.android" version "1.7.10" apply false + // // 有些库需要更新的kotlin版本 + // // https://stackoverflow.com/questions/70919127/your-project-requires-a-newer-version-of-the-kotlin-gradle-plugin-android-stud + // id "org.jetbrains.kotlin.android" version "2.0.0" apply false + + id 'com.android.application' version '8.6.0' apply false + id 'com.android.library' version '8.6.0' apply false + id 'org.jetbrains.kotlin.android' version '2.0.20' apply false } include ":app" \ No newline at end of file diff --git a/lib/apis/paid_llm_apis.dart b/lib/apis/paid_llm_apis.dart index 7f14614..126f79f 100644 --- a/lib/apis/paid_llm_apis.dart +++ b/lib/apis/paid_llm_apis.dart @@ -1,39 +1,144 @@ -// ignore_for_file: avoid_print - import 'dart:convert'; +import 'dart:async'; +import 'dart:typed_data'; +import '../common/utils/tools.dart'; import '../dio_client/cus_http_client.dart'; import '../dio_client/cus_http_request.dart'; -import '../dio_client/interceptor_error.dart'; import '../models/paid_llm/common_chat_completion_state.dart'; import '../models/paid_llm/common_chat_model_spec.dart'; import '_self_keys.dart'; /// -/// 这里都是用自己的账号,要付费的 +/// 这里 _self_keys 都是用自己的账号,要付费的 +/// final Map cusAKMap = { +/// ApiPlatform.lingyiwanwu: 'xxxxx', +/// }; /// +/// 添加流式响应的类 +class StreamWithCancel { + final Stream stream; + final Future Function() cancel; + + StreamWithCancel(this.stream, this.cancel); + + static StreamWithCancel empty() { + return StreamWithCancel( + const Stream.empty(), + () async {}, + ); + } +} + +/// +/// dio 中处理SSE的解析器 +/// 来源: https://github.com/cfug/dio/issues/1279#issuecomment-1326121953 +/// +class SseTransformer extends StreamTransformerBase { + const SseTransformer(); + @override + Stream bind(Stream stream) { + return Stream.eventTransformed(stream, (sink) => SseEventSink(sink)); + } +} + +class SseEventSink implements EventSink { + final EventSink _eventSink; + + String? _id; + String _event = "message"; + String _data = ""; + int? _retry; + + SseEventSink(this._eventSink); + + @override + void add(String event) { + if (event.startsWith("id:")) { + _id = event.substring(3); + return; + } + if (event.startsWith("event:")) { + _event = event.substring(6); + return; + } + if (event.startsWith("data:")) { + _data = event.substring(5); + return; + } + if (event.startsWith("retry:")) { + _retry = int.tryParse(event.substring(6)); + return; + } + if (event.isEmpty) { + _eventSink.add( + SseMessage(id: _id, event: _event, data: _data, retry: _retry), + ); + _id = null; + _event = "message"; + _data = ""; + _retry = null; + } + + // 自己加的,请求报错时不是一个正常的流的结构,是个json,直接添加即可 + if (isJsonString(event)) { + _eventSink.add( + SseMessage(id: _id, event: _event, data: event, retry: _retry), + ); + + _id = null; + _event = "message"; + _data = ""; + _retry = null; + } + } + + @override + void addError(Object error, [StackTrace? stackTrace]) { + _eventSink.addError(error, stackTrace); + } + + @override + void close() { + _eventSink.close(); + } +} + +class SseMessage { + final String? id; + final String event; + final String data; + final int? retry; + + const SseMessage({ + this.id, + required this.event, + required this.data, + this.retry, + }); +} + /// 获取流式响应数据 -Future> getChatResp( +Future> getChatRespStream( ApiPlatform platform, List messages, { String? model, + bool stream = true, }) async { - var body = CCReqBody(model: model, messages: messages); - - var start = DateTime.now().millisecondsSinceEpoch; + var body = CCReqBody( + model: model, + messages: messages, + stream: stream, + ); try { - // 如果选择的平台不存在,抛错 var spec = platformUrls.where((e) => e.platform == platform).toList(); - if (spec.isEmpty) { - return throw Exception("未找到${platform.name}的配置"); + throw Exception("未找到${platform.name}的配置"); } - // 存在,则拼接访问的地址 var path = spec.first.url; - var header = { "Content-Type": "application/json", "Authorization": "Bearer ${cusAKMap[platform]!}", @@ -43,36 +148,90 @@ Future> getChatResp( path: path, method: HttpMethod.post, headers: header, + responseType: stream ? CusRespType.stream : CusRespType.json, data: body, ); - if (respData.runtimeType == String) { - respData = json.decode(respData); - } + if (stream) { + var responseStream = respData.stream as Stream>; + + var streamController = StreamController(); + StreamTransformer> unit8Transformer = + StreamTransformer.fromHandlers( + handleData: (data, sink) { + sink.add(List.from(data)); + }, + ); + + var subscription = responseStream + // 创建一个自定义的 StreamTransformer 来处理 Uint8List 到 String 的转换。 + .transform(unit8Transformer) + .transform(const Utf8Decoder()) + // 将输入的 Stream 按照行(即换行符 \n 或 \r\n)进行分割,并将每一行作为一个单独的事件发送到输出流中。 + .transform(const LineSplitter()) + .transform(const SseTransformer()) + .listen( + (event) { + // print( + // "【Event】 ${event.id}, ${event.event}, ${event.retry}, ${event.data}", + // ); - var end = DateTime.now().millisecondsSinceEpoch; - print("CC 响应耗时: ${(end - start) / 1000} 秒"); - - return [CCRespBody.fromJson(respData)]; - } on HttpException catch (e) { - // 这里是拦截器抛出的http异常的处理 - print("aaaaaaaaaaaaa ${e.runtimeType}---${e.msg}"); - return [ - CCRespBody( - customReplyText: e.toString(), - error: RespError(code: "10001", type: "http异常", message: e.toString()), - ) - ]; + // 正常的分段数据 + // 如果包含DONE,是正常获取AI接口的结束 + if ((event.data).contains('[DONE]')) { + if (!streamController.isClosed) { + streamController.add(CCRespBody(customReplyText: '[DONE]')); + streamController.close(); + } + } else { + final jsonData = json.decode(event.data); + final commonRespBody = CCRespBody.fromJson(jsonData); + if (!streamController.isClosed) { + streamController.add(commonRespBody); + } + } + }, + onDone: () { + // 流处理完手动补一个结束子串 + if (!streamController.isClosed) { + streamController.add(CCRespBody(customReplyText: '[DONE]-onDone')); + streamController.close(); + } + }, + onError: (error) { + if (!streamController.isClosed) { + streamController.addError(error); + streamController.close(); + } + }, + ); + + Future cancel() async { + // ???占位用的,先发送最后一个手动终止的信息,再实际取消(手动的更没有token信息了) + if (!streamController.isClosed) { + streamController.add(CCRespBody(customReplyText: '[手动终止]')); + } + + await subscription.cancel(); + if (!streamController.isClosed) { + streamController.close(); + } + } + + // 返回可取消的流 + return StreamWithCancel(streamController.stream, cancel); + } else { + // 如果不是流式的,直接返回结果 + if (respData.runtimeType == String) { + respData = json.decode(respData); + } + + return StreamWithCancel( + Stream.value(CCRespBody.fromJson(respData)), + () async {}, + ); + } } catch (e) { - // 这里是其他异常处理 - print("bbbbbbbbbbbbbbbb ${e.runtimeType}---$e"); - // API请求报错,显示报错信息 - return [ - CCRespBody( - customReplyText: e.toString(), - // 这里的code和msg就不是api返回的,是自行定义的,应该抽出来 - error: RespError(code: "10000", type: "其他异常", message: e.toString()), - ) - ]; + rethrow; } } diff --git a/lib/common/components/cus_cards.dart b/lib/common/components/cus_cards.dart index 46fad42..11b2e30 100644 --- a/lib/common/components/cus_cards.dart +++ b/lib/common/components/cus_cards.dart @@ -1,66 +1,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -/// 子组件是带text的容器的卡片 -/// 用于显示模块首页一排两列的标题 -buildSmallCoverCard( - BuildContext context, - Widget widget, - String title, { - String? routeName, -}) { - return Card( - clipBehavior: Clip.hardEdge, - elevation: 5, - child: InkWell( - splashColor: Theme.of(context).splashColor, - onTap: () { - if (routeName != null) { - // 这里需要使用pushName 带上指定的路由名称,后续跨层级popUntil的时候才能指定路由名称进行传参 - Navigator.pushNamed(context, routeName); - } else { - Navigator.of(context).push( - MaterialPageRoute( - builder: (BuildContext ctx) => widget, - ), - ); - } - }, - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - children: [ - Icon( - Icons.bar_chart, - size: 72.sp, - ), - Center( - child: Text( - title, - style: TextStyle( - fontSize: 20.sp, - fontWeight: FontWeight.bold, - color: Theme.of(context).primaryColor, - ), - ), - ), - ], - ), - // child: Container( - // color: Theme.of(context).secondaryHeaderColor, - // child: Center( - // child: Text( - // title, - // style: TextStyle( - // fontSize: 20.sp, - // fontWeight: FontWeight.bold, - // color: Theme.of(context).primaryColor, - // ), - // ), - // ), - // ), - ), - ); -} +import '../../models/cus_app_localizations.dart'; +import '../utils/tool_widgets.dart'; +import '../utils/tools.dart'; /// 子组件是带listtile和图片的一行row容器的卡片 /// 用于显示模块首页一排一个带封面图的标题 @@ -74,9 +17,20 @@ buildCoverCard( }) { return Card( clipBehavior: Clip.hardEdge, - elevation: 5, + elevation: 2.sp, child: InkWell( - onTap: () { + onTap: () async { + bool isGranted = await requestStoragePermission(); + + if (!context.mounted) return; + if (!isGranted) { + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + "无存储授权", + ); + } + if (routeName != null) { // 这里需要使用pushName 带上指定的路由名称,后续跨层级popUntil的时候才能指定路由名称进行传参 Navigator.pushNamed(context, routeName); @@ -118,3 +72,83 @@ buildCoverCard( ), ); } + +/// +/// 运动或饮食主页面的入口卡片 +/// 上面函数式的部件写法 +/// +class CusCoverCard extends StatelessWidget { + final Widget targetPage; + final String title; + final String subtitle; + final String imageUrl; + final String? routeName; + + const CusCoverCard({ + super.key, + required this.targetPage, + required this.title, + required this.subtitle, + required this.imageUrl, + this.routeName, + }); + + @override + Widget build(BuildContext context) { + return Card( + clipBehavior: Clip.hardEdge, + elevation: 2.sp, + child: InkWell( + onTap: () async { + bool isGranted = await requestStoragePermission(); + + if (!context.mounted) return; + if (!isGranted) { + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + "无存储授权", + ); + } + + if (routeName != null) { + Navigator.pushNamed(context, routeName!); + } else { + Navigator.of(context).push( + MaterialPageRoute( + builder: (BuildContext ctx) => targetPage, + ), + ); + } + }, + child: Center( + child: Row( + children: [ + Expanded( + flex: 2, + child: Padding( + padding: EdgeInsets.all(5.sp), + child: Image.asset(imageUrl, fit: BoxFit.scaleDown), + ), + ), + Expanded( + flex: 3, + child: ListTile( + title: Text( + title, + style: TextStyle( + fontSize: 20.sp, + fontWeight: FontWeight.bold, + color: Theme.of(context).primaryColor, + ), + ), + subtitle: Text(subtitle), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/common/utils/db_diary_helper.dart b/lib/common/utils/db_diary_helper.dart index 2480dbc..8407f25 100644 --- a/lib/common/utils/db_diary_helper.dart +++ b/lib/common/utils/db_diary_helper.dart @@ -141,8 +141,6 @@ class DBDiaryHelper { // 将JSON字符串写入临时文件 await tempFile.writeAsString(jsonStr); - - // print('表 $tableName 已成功导出到:$tempFilePath'); } } @@ -219,8 +217,6 @@ class DBDiaryHelper { // 查询每页指定数量的数据,但带上总条数 return CusDataResult(data: list, total: totalCount ?? 0); } catch (e) { - print('Error at queryDiaryByKeyword: $e'); - // ???抛出异常来触发回滚的方式是 sqflite 中常用的做法 rethrow; } } @@ -270,8 +266,6 @@ class DBDiaryHelper { // 查询每页指定数量的数据,但带上总条数 return list; } catch (e) { - print('Error at queryDiaryByDateRange: $e'); - // ???抛出异常来触发回滚的方式是 sqflite 中常用的做法 rethrow; } } diff --git a/lib/common/utils/db_dietary_helper.dart b/lib/common/utils/db_dietary_helper.dart index 6f3259e..374b4ce 100644 --- a/lib/common/utils/db_dietary_helper.dart +++ b/lib/common/utils/db_dietary_helper.dart @@ -143,8 +143,6 @@ class DBDietaryHelper { // 将JSON字符串写入临时文件 await tempFile.writeAsString(jsonStr); - - // print('表 $tableName 已成功导出到:$tempFilePath'); } } @@ -254,9 +252,6 @@ class DBDietaryHelper { } }); } catch (e) { - // Handle the error - print('Error inserting food with serving info: $e'); - // 抛出异常来触发回滚的方式是 sqflite 中常用的做法 rethrow; } // 返回成功插入的食品编号和营养素编号列表 @@ -298,8 +293,6 @@ class DBDietaryHelper { ); }); } catch (e) { - // Handle the error - print('Error updating food with serving info: $e'); rethrow; } } @@ -386,7 +379,6 @@ class DBDietaryHelper { whereArgs: [id], ); - print("删除食物营养素 $itemRows"); // 如果没有被使用,则物理删除;否则就逻辑删除 if (itemRows.isEmpty) { batch.delete( @@ -463,8 +455,6 @@ class DBDietaryHelper { ), ); - print('Total count: $totalCount'); - // 查询每页指定数量的数据,但带上总条数 return CusDataResult(data: foods, total: totalCount ?? 0); } diff --git a/lib/common/utils/db_training_helper.dart b/lib/common/utils/db_training_helper.dart index 81e33e9..d2e1e1b 100644 --- a/lib/common/utils/db_training_helper.dart +++ b/lib/common/utils/db_training_helper.dart @@ -148,8 +148,6 @@ class DBTrainingHelper { // 将JSON字符串写入临时文件 await tempFile.writeAsString(jsonStr); - - // print('表 $tableName 已成功导出到:$tempFilePath'); } } @@ -258,8 +256,6 @@ class DBTrainingHelper { // 查询每页指定数量的数据,但带上总条数 return CusDataResult(data: list, total: totalCount ?? 0); } catch (e) { - print('Error at queryExerciseByKeyword: $e'); - // 抛出异常来触发回滚的方式是 sqflite 中常用的做法 rethrow; } } @@ -335,14 +331,9 @@ class DBTrainingHelper { sql += ' WHERE ${where.join(' AND ')}'; } - print(sql); - print("whereArgs $whereArgs"); - int totalCount = Sqflite.firstIntValue(await db.rawQuery(sql, whereArgs)) ?? 0; - print('Total count: $totalCount'); - final list = maps.map((row) => Exercise.fromMap(row)).toList(); // 返回时数据列表(使用时先转型)和总数 @@ -481,7 +472,6 @@ class DBTrainingHelper { whereArgs: [action.exerciseId], ); - // print("exerciseRows----${exerciseRows.length}"); // ???理论上这里只有查到1个exercise,且不应该差不多(暂不考虑异常情况) if (exerciseRows.isNotEmpty) { var ad = ActionDetail( diff --git a/lib/common/utils/db_user_helper.dart b/lib/common/utils/db_user_helper.dart index 28c53fe..cebe8a4 100644 --- a/lib/common/utils/db_user_helper.dart +++ b/lib/common/utils/db_user_helper.dart @@ -334,7 +334,6 @@ class DBUserHelper { return rst; } catch (e) { // Handle the error - print('Error at updateIntakeDailyGoalByUser: $e'); // 抛出异常来触发回滚的方式是 sqflite 中常用的做法 rethrow; } diff --git a/lib/common/utils/tool_widgets.dart b/lib/common/utils/tool_widgets.dart index 8f9af14..a6ecfc3 100644 --- a/lib/common/utils/tool_widgets.dart +++ b/lib/common/utils/tool_widgets.dart @@ -3,6 +3,7 @@ import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'dart:math' as math; @@ -341,3 +342,100 @@ void showSnackMessage( ScaffoldMessenger.of(context).showSnackBar(snackBar); } + +/// 强制收起键盘 +unfocusHandle() { + // 这个不一定有用,比如下面原本键盘弹出来了,跳到历史记录页面,回来之后还是弹出来的 + // FocusScope.of(context).unfocus(); + + // FocusScope.of(context).requestFocus(FocusNode()); + + FocusManager.instance.primaryFocus?.unfocus(); +} + +/// 通用的底部信息弹窗 +commonMDHintModalBottomSheet( + BuildContext context, + String title, + String message, { + double? msgFontSize, +}) { + showModalBottomSheet( + context: context, + builder: (BuildContext context) { + return Container( + // height: MediaQuery.of(context).size.height / 4 * 3, + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.only( + topLeft: Radius.circular(15.sp), + topRight: Radius.circular(15.sp), + ), + ), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + mainAxisSize: MainAxisSize.min, + children: [ + Padding( + padding: EdgeInsets.symmetric(horizontal: 20.sp), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text(title, style: TextStyle(fontSize: 18.sp)), + TextButton( + child: Text(CusAL.of(context).closeLabel), + onPressed: () { + Navigator.pop(context); + unfocusHandle(); + }, + ), + ], + ), + ), + Divider(height: 2.sp, thickness: 2.sp), + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(10.sp), + child: MarkdownBody( + data: message, + selectable: true, + // 设置Markdown文本全局样式 + styleSheet: MarkdownStyleSheet( + // 普通段落文本颜色(假定用户输入就是普通段落文本) + p: TextStyle(fontSize: msgFontSize, color: Colors.black), + // ... 其他级别的标题样式 + // 可以继续添加更多Markdown元素的样式 + ), + ), + ), + ), + ), + ], + ), + ); + }, + ); +} + +/// json文件导入时显示的行中文本 +buildRichTextItem( + String text, + Color? color, { + TextAlign textAlign = TextAlign.start, +}) { + return RichText( + textAlign: textAlign, + text: TextSpan( + children: [ + TextSpan( + text: text, + style: TextStyle( + fontSize: CusFontSizes.itemContent, + color: color, + ), + ), + ], + ), + ); +} diff --git a/lib/common/utils/tools.dart b/lib/common/utils/tools.dart index ca1cbe4..ba19c25 100644 --- a/lib/common/utils/tools.dart +++ b/lib/common/utils/tools.dart @@ -1,3 +1,4 @@ +import 'dart:convert'; import 'dart:io'; import 'dart:math'; @@ -317,3 +318,17 @@ Future requestStoragePermission() async { return false; } } + +/// 判断字符串是否为json字符串 +bool isJsonString(String str) { + // 去除字符串中的空白字符和注释 + final cleanedStr = + str.replaceAll(RegExp(r'\s+'), '').replaceAll(RegExp(r'//.*'), ''); + + try { + json.decode(cleanedStr); + return true; + } on FormatException { + return false; + } +} diff --git a/lib/dio_client/cus_http_client.dart b/lib/dio_client/cus_http_client.dart index 9940144..28ad29f 100644 --- a/lib/dio_client/cus_http_client.dart +++ b/lib/dio_client/cus_http_client.dart @@ -11,6 +11,7 @@ class HttpUtils { static Future get({ required String path, Map? queryParameters, + CusRespType? responseType, bool showLoading = true, bool showErrorMessage = true, }) { @@ -18,6 +19,7 @@ class HttpUtils { path: path, method: HttpMethod.get, queryParameters: queryParameters, + responseType: responseType, showLoading: showLoading, showErrorMessage: showErrorMessage, ); @@ -28,6 +30,7 @@ class HttpUtils { required String path, required HttpMethod method, dynamic headers, + CusRespType? responseType, // 可以自定义返回类型(默认是json) dynamic data, bool showLoading = true, bool showErrorMessage = true, @@ -36,6 +39,7 @@ class HttpUtils { path: path, method: HttpMethod.post, headers: headers, + responseType: responseType, data: data, showLoading: showLoading, showErrorMessage: showErrorMessage, diff --git a/lib/dio_client/cus_http_request.dart b/lib/dio_client/cus_http_request.dart index a99dbf3..f2be5d1 100644 --- a/lib/dio_client/cus_http_request.dart +++ b/lib/dio_client/cus_http_request.dart @@ -32,9 +32,6 @@ class HttpRequest { sendTimeout: HttpOptions.sendTimeout, baseUrl: HttpOptions.baseUrl, contentType: HttpOptions.contentType, - // 2024-03-12 目前需要用的接口就 login成功的返回时text/html,其他的都是application/json。 - // 所以暂时就不全部拍成文本格式了 - // responseType: ResponseType.plain, ); dio = Dio(options); @@ -78,6 +75,7 @@ class HttpRequest { required String path, //接口地址 required HttpMethod method, //请求方式 Map? headers, // 可以自定义一些header + CusRespType? responseType, // 可以自定义返回类型(默认是json) dynamic data, //数据 Map? queryParameters, bool showLoading = true, //加载过程 @@ -99,12 +97,14 @@ class HttpRequest { Options options = Options( method: methodValues[method], headers: headers, + responseType: responseTypeValues[responseType], ); try { if (showLoading) { - //EasyLoading.show(status: 'loading...'); + EasyLoading.show(status: 'loading...'); } + Response response = await HttpRequest.dio.request( path, data: data, @@ -150,3 +150,17 @@ enum HttpMethod { patch, head, } + +enum CusRespType { + bytes, + json, + plain, + stream, +} + +const Map responseTypeValues = { + CusRespType.bytes: ResponseType.bytes, + CusRespType.json: ResponseType.json, + CusRespType.plain: ResponseType.plain, + CusRespType.stream: ResponseType.stream, +}; diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c12b949..7c98224 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -152,7 +152,7 @@ "description": "训练跟练页面相关栏位" }, - + "noTtsEngine":"No available TTS engine", "followTtsLabel": "{num, select, 0{Ready, the next action is } 1{It's half the time.} 2{Start} 3{Congratulations,the workout is over.} 4{Take a break, the next action} other{其他} }", "@followTtsLabel": { "description": "训练跟练页面tts相关文字" @@ -185,6 +185,7 @@ "dayNumber":"Day {number}", + "dayCount":"total {number} day(s)", "incompleteLabel":"Never Completed", @@ -351,6 +352,7 @@ "switchUser":"Switch User", + "noteLabel":"note", "tipLabel":"Notification", "itemLabel":"{num} item(s)", @@ -396,7 +398,8 @@ "settingLabels": "{ setting, select, 0{Basic Info} 1{Weight Trend} 2{Intake Goal} 3{Training Setting} 4{Backup & Restore} 5{More Settings} other{Unknown Setting} }", "exportRangeNote":"Select export range", - + + "importJsonButtons": "{ num, select, 0{Select Json} 1{Clear Data} other{Unknown Setting} }", "importJsonError":"Import json file error", "importJsonErrorText":"Filename:\n{path}\n\nError:\n{msg}", diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6b53c0d..c05b4fa 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -160,6 +160,7 @@ "description": "训练跟练页面相关栏位" }, + "noTtsEngine":"无可用TTS引擎", "followTtsLabel": "{num, select, 0{预备开始,下一个动作:} 1{一半时间了} 2{开始} 3{祝贺,锻炼已结束} 4{休息一下,下一个动作:} other{其他} }", "@followTtsLabel": { "description": "训练跟练页面tts相关文字,不会显示,但语音会用到" @@ -190,6 +191,7 @@ }, "dayNumber":"第 {number} 天", + "dayCount":"共 {number} 天", "incompleteLabel":"从未跟练", @@ -361,7 +363,7 @@ - + "noteLabel":"提示", "tipLabel":"提示", "itemLabel":"{num} 项", @@ -402,6 +404,7 @@ "exportRangeNote":"选择导出范围", + "importJsonButtons": "{ num, select, 0{选择文件} 1{清空数据} other{未知设置} }", "importJsonError":"导入json文件出错", "importJsonErrorText":"文件名称:\n{path}\n\n错误信息:\n{msg}", diff --git a/lib/layout/app.dart b/lib/layout/app.dart index 428abd3..0d45943 100644 --- a/lib/layout/app.dart +++ b/lib/layout/app.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flex_color_scheme/flex_color_scheme.dart'; import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; @@ -26,8 +24,8 @@ class _FreeFitnessAppState extends State { // 应用程序的根部件 @override Widget build(BuildContext context) { - print("getUserId---${box.read(LocalStorageKey.userId)}"); - print("language mode---${box.read('language')} ${box.read('mode')}"); + debugPrint("getUserId--${box.read(LocalStorageKey.userId)}"); + debugPrint("language--${box.read('language')}; mode--${box.read('mode')}"); return ScreenUtilInit( designSize: const Size(360, 640), // 1080p / 3 ,单位dp @@ -79,10 +77,20 @@ class _FreeFitnessAppState extends State { /// 跟随系统的浅色和深色和手动选择的一样 theme: box.read('mode') == 'system' // 跟随系统的默认浅色是一个绿色主题 - ? FlexThemeData.light(scheme: FlexScheme.greenM3) + ? FlexThemeData.light( + scheme: FlexScheme.greenM3, + // 2024-11-11 flutter更新到3.24.4、对应插件更新到最新版本时,不添加这个为false效果和之前不一样了 + useMaterial3: false, + ) : box.read('mode') == 'dark' - ? FlexThemeData.dark(scheme: FlexScheme.mandyRed) - : FlexThemeData.light(scheme: FlexScheme.aquaBlue), + ? FlexThemeData.dark( + scheme: FlexScheme.mandyRed, + useMaterial3: false, + ) + : FlexThemeData.light( + scheme: FlexScheme.aquaBlue, + useMaterial3: false, + ), // 使用了initalRoute就不能使用home了,参看文档: // https://flutter.cn/docs/cookbook/navigation/named-routes#2-define-the-routes diff --git a/lib/layout/home.dart b/lib/layout/home.dart index cd3ed43..0bdf86a 100644 --- a/lib/layout/home.dart +++ b/lib/layout/home.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; @@ -67,6 +65,7 @@ class _HomePageState extends State { }, ).then((value) { if (value == false) { + if (!mounted) return; EasyLoading.showToast(CusAL.of(context).noStorageHint); } }); @@ -84,8 +83,7 @@ class _HomePageState extends State { return PopScope( // 点击返回键时暂停返回 canPop: false, - onPopInvoked: (didPop) async { - print("didPop-----------$didPop"); + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) { return; } diff --git a/lib/layout/init_guide_page.dart b/lib/layout/init_guide_page.dart index ef1780e..421d9b7 100644 --- a/lib/layout/init_guide_page.dart +++ b/lib/layout/init_guide_page.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'dart:io'; import 'package:device_info_plus/device_info_plus.dart'; @@ -19,7 +17,7 @@ import 'home.dart'; /// /// 当用户首次进入app时,需要他填写一个用户名,作为默认的userId=1的初始用户。 /// 不填的话就使用随机数或者获取手机型号? -/// 填入或者自动获取手机型号之后,讲这个唯一用户存入sqlite和storage,下次启动时获取storage的数据。 +/// 填入或者自动获取手机型号之后,将这个唯一用户存入sqlite和storage,下次启动时获取storage的数据。 /// /// 如果启动app时获取storage的用户信息是空,就认为是首次使用,就跳动此登录页面。 /// 如果能获取到,就从这里跳转到主页面去 @@ -47,7 +45,7 @@ class _InitGuidePageState extends State { userName: "FF-user", userCode: "FF-user", gender: genderOptions.first.value, - description: "一位富有爱心的free-fitness用户", + description: "一位富有爱心的 free-fitness 用户", password: "123456", dateOfBirth: "1994-07-02", height: 170, @@ -101,7 +99,7 @@ class _InitGuidePageState extends State { ), ); }).toList(), - onChanged: (CusLabel? value) async { + onChanged: (CusLabel? value) { setState(() { selectedGender = value?.value; }); @@ -195,7 +193,7 @@ class _InitGuidePageState extends State { await _userHelper.insertUserList([defaultUser]); // 注意用户编号类型要一致都用int,storage支持的类型String, int, double, Map and List await box.write(LocalStorageKey.userId, 1); - await box.write(LocalStorageKey.userName, username); + await box.write(LocalStorageKey.userName, defaultUser.userName); var bmi = _currentWeight / (_currentHeight / 100 * _currentHeight / 100); // 新增体重趋势信息 @@ -235,13 +233,13 @@ class _InitGuidePageState extends State { defaultUser.userName = "$deviceName 用户"; defaultUser.userName = deviceName; - defaultUser.description = "一位在使用free-fitness的$deviceName用户"; + defaultUser.description = "一位在使用 free-fitness 的$deviceName用户"; // ???这里应该检查保存是否成功 await _userHelper.insertUserList([defaultUser]); // 注意用户编号类型要一致都用int,storage支持的类型String, int, double, Map and List await box.write(LocalStorageKey.userId, 1); - await box.write(LocalStorageKey.userName, "$deviceName 用户"); + await box.write(LocalStorageKey.userName, "$deviceName用户"); if (!mounted) return; Navigator.pushReplacement( diff --git a/lib/layout/themes/cus_font_size.dart b/lib/layout/themes/cus_font_size.dart index 0ea6bfb..9c51c8d 100644 --- a/lib/layout/themes/cus_font_size.dart +++ b/lib/layout/themes/cus_font_size.dart @@ -7,6 +7,7 @@ class CusFontSizes { // 一般的卡片或者ListTile中的标题、子标题、正文的大小 static double itemTitle = 18.sp; + static double itemSmallTitle = 16.sp; static double itemSubTitle = 14.sp; static double itemContent = 12.sp; static double itemSubContent = 10.sp; diff --git a/lib/layout/themes/cus_theme.dart b/lib/layout/themes/cus_theme.dart index b8ab16c..7b2232c 100644 --- a/lib/layout/themes/cus_theme.dart +++ b/lib/layout/themes/cus_theme.dart @@ -10,27 +10,27 @@ ThemeData lightTheme = ThemeData( // 文本主题 // 定制好一些文本样式,后续直接使用,例如:`style: Theme.of(context).textTheme.bodySmall` // 否则就是默认的 - textTheme: const TextTheme( + textTheme: TextTheme( displayLarge: TextStyle( - fontSize: 96, fontWeight: FontWeight.w300, color: Colors.black), + fontSize: 96.sp, fontWeight: FontWeight.w300, color: Colors.black), displayMedium: TextStyle( - fontSize: 60, fontWeight: FontWeight.w400, color: Colors.black), + fontSize: 60.sp, fontWeight: FontWeight.w400, color: Colors.black), displaySmall: TextStyle( - fontSize: 48, fontWeight: FontWeight.w400, color: Colors.black), + fontSize: 48.sp, fontWeight: FontWeight.w400, color: Colors.black), headlineMedium: TextStyle( - fontSize: 34, fontWeight: FontWeight.w400, color: Colors.black), + fontSize: 34.sp, fontWeight: FontWeight.w400, color: Colors.black), headlineSmall: TextStyle( - fontSize: 24, fontWeight: FontWeight.w400, color: Colors.black), + fontSize: 24.sp, fontWeight: FontWeight.w400, color: Colors.black), titleLarge: TextStyle( - fontSize: 20, fontWeight: FontWeight.w500, color: Colors.black), + fontSize: 20.sp, fontWeight: FontWeight.w500, color: Colors.black), bodyLarge: TextStyle( - fontSize: 16, fontWeight: FontWeight.w400, color: Colors.black87), + fontSize: 16.sp, fontWeight: FontWeight.w400, color: Colors.black87), bodyMedium: TextStyle( - fontSize: 14, fontWeight: FontWeight.w400, color: Colors.black87), + fontSize: 14.sp, fontWeight: FontWeight.w400, color: Colors.black87), bodySmall: TextStyle( - fontSize: 12, fontWeight: FontWeight.w400, color: Colors.black54), + fontSize: 12.sp, fontWeight: FontWeight.w400, color: Colors.black54), labelLarge: TextStyle( - fontSize: 14, fontWeight: FontWeight.w500, color: Colors.white), + fontSize: 14.sp, fontWeight: FontWeight.w500, color: Colors.white), ), // appbar主题 appBarTheme: AppBarTheme( @@ -61,11 +61,11 @@ final ThemeData darkTheme = ThemeData( cardColor: Colors.black, secondaryHeaderColor: Colors.grey, primarySwatch: Colors.red, - textTheme: const TextTheme( + textTheme: TextTheme( displayLarge: TextStyle( - fontSize: 52.0, + fontSize: 52.sp, fontWeight: FontWeight.w500, ), - bodyLarge: TextStyle(fontSize: 18), + bodyLarge: TextStyle(fontSize: 18.sp), ), ); diff --git a/lib/models/dietary_state.dart b/lib/models/dietary_state.dart index 74caf8a..85305d6 100644 --- a/lib/models/dietary_state.dart +++ b/lib/models/dietary_state.dart @@ -31,7 +31,7 @@ class Food { 'category': category, 'contributor': contributor, 'gmt_create': gmtCreate, - "is_deleted": isDeleted, + "is_deleted": isDeleted == true ? 1 : 0, }; } diff --git a/lib/models/paid_llm/common_chat_completion_state.dart b/lib/models/paid_llm/common_chat_completion_state.dart index b947cbc..a552c78 100644 --- a/lib/models/paid_llm/common_chat_completion_state.dart +++ b/lib/models/paid_llm/common_chat_completion_state.dart @@ -1,13 +1,10 @@ import 'dart:convert'; -/// 2027-07-08 零一万物 API 的入参出参 +/// 2024-07-08 零一万物 API 的入参出参 /// /// 所以这里减少数量,就使用最简单的,下划线连接模式的入参和出参 /// CC对应ChatCompletions => CCMessage = ChatCompletionsMessage /// -/// 因为付费,为了省钱,就统一使用非流式的,节约token -/// -/// class CCMessage { String role; // 注意,图像理解的话,这个还需要是比较复杂的数组(String或VisionContent) @@ -27,49 +24,29 @@ class CCMessage { } /// -/// yi-vision 图像理解时,需要的类型 +/// delta和message是否类似,不过role和content都可选 +/// 第一条只有role,中间的只有content,最后一条两者都没有,就只`{}` /// -// "content": [ -// { -// "type": "image_url", -// "image_url": { -// "url": "https://platform.lingyiwanwu.com/assets/sample-table.jpg" -// } -// }, -// { -// "type": "text", -// "text": "请详细描述一下这张图片。" -// } -// ] -// 2024-07-12 暂时不使用这个class,直接在调用处手动拼接上面的json -class VisionContent { - String? type; - ImageUrl? imageUrl; - String? text; - - VisionContent({this.type, this.imageUrl, this.text}); - - factory VisionContent.fromJson(Map json) => VisionContent( - type: json["type"], - imageUrl: json["image_url"] == null - ? null - : ImageUrl.fromJson(json["image_url"]), - text: json["text"], - ); - - Map toJson() => - {"type": type, "image_url": imageUrl?.toJson(), "text": text}; -} +class CCDelta { + String? role; + String? content; + List? quote; -class ImageUrl { - String? url; + CCDelta({ + this.role, + this.content, + this.quote, + }); - ImageUrl({this.url}); + // 从字符串转 + factory CCDelta.fromRawJson(String str) => CCDelta.fromJson(json.decode(str)); + // 转为字符串 + String toRawJson() => json.encode(toJson()); - factory ImageUrl.fromJson(Map json) => - ImageUrl(url: json["url"]); + factory CCDelta.fromJson(Map json) => + CCDelta(role: json["role"], content: json["content"]); - Map toJson() => {"url": url}; + Map toJson() => {"role": role, "content": content}; } /// @@ -142,20 +119,27 @@ class CCUsage { /// class CCChoice { int? index; - CCMessage message; + CCMessage? message; + CCDelta? delta; List? quote; - String finishReason; + String? finishReason; CCChoice({ this.index, - required this.message, + this.message, + this.delta, this.quote, - required this.finishReason, + this.finishReason, }); factory CCChoice.fromJson(Map json) => CCChoice( index: json["index"], - message: CCMessage.fromJson(json["message"]), + message: json["message"] == null + ? null + : CCMessage.fromJson(json["message"] as Map), + delta: json["delta"] == null + ? null + : CCDelta.fromJson(json["delta"] as Map), quote: json["quote"] == null ? [] : List.from( @@ -166,7 +150,8 @@ class CCChoice { Map toJson() => { "index": index, - "message": message.toJson(), + "message": message?.toJson(), + "delta": delta?.toJson(), "quote": quote == null ? [] : List.from(quote!.map((x) => x.toJson())), @@ -284,7 +269,7 @@ class CCRespBody { RespError? error; /// 2024-06-06 3个不同的搞成一样的显示文本,我现在是需要用到显示的值,其他的都暂时不考虑 - String customReplyText; + String? customReplyText; CCRespBody({ this.id, @@ -294,22 +279,24 @@ class CCRespBody { this.choices, this.usage, this.error, - required this.customReplyText, - }); - - factory CCRespBody.fromJson(Map json) { - var customReplyText = "<未取得数据……>"; - - // 直接显示答案 - if (json["choices"] != null) { - var temp = List.from( - json["choices"]!.map((x) => CCChoice.fromJson(x)), - ); - if (temp.isNotEmpty) { - customReplyText = temp.first.message.content; - } + String? customReplyText, + }) : customReplyText = customReplyText ?? _generatecusText(choices); + + // 自定义的响应文本(比如流式返回最后是个[DONE]没法转型,但可以自行设定;而正常响应时可以从其他值中得到) + static String _generatecusText(List? choices) { + // 非流式的 + if (choices != null && choices.isNotEmpty && choices[0].message != null) { + return choices[0].message?.content ?? ""; + } + // 流式的 + if (choices != null && choices.isNotEmpty && choices[0].delta != null) { + return choices[0].delta?.content ?? ""; } + return ''; + } + + factory CCRespBody.fromJson(Map json) { return CCRespBody( id: json["id"], object: json["object"], @@ -320,9 +307,9 @@ class CCRespBody { : List.from( json["choices"]!.map((x) => CCChoice.fromJson(x)), ), - usage: CCUsage.fromJson(json["usage"]), + usage: json["usage"] == null ? null : CCUsage.fromJson(json["usage"]), error: json["error"] == null ? null : RespError.fromJson(json["error"]), - customReplyText: customReplyText, + customReplyText: json['customReplyText'] as String?, ); } @@ -336,6 +323,7 @@ class CCRespBody { : List.from(choices!.map((x) => x.toJson())), "usage": usage?.toJson(), "error": error?.toJson(), + "customReplyText": customReplyText, }; } diff --git a/lib/models/paid_llm/llm_chat.dart b/lib/models/paid_llm/llm_chat.dart index 9a07f24..278f114 100644 --- a/lib/models/paid_llm/llm_chat.dart +++ b/lib/models/paid_llm/llm_chat.dart @@ -14,14 +14,14 @@ class ChatMessage { // 之前是 isFromUser 是否来自用户,但角色有3种:system、user、assistant // 所以改判断,role!=user就不是来自用户 final String role; - final String content; // 文本内容 + String content; // 文本内容 // 有可能对话存在输入图片(假如后续一个用户对话中存在图片切来切去,就最后每个问答来回都存上图片) final String? imageUrl; - final bool? isPlaceholder; // 是否是等待响应时的占位消息 + /// 2024-06-15 限时限量有token限制,所以存放每次对话的token消耗 - final int? promptTokens; // 输入的token数 - final int? completionTokens; // 输出的token数 - final int? totalTokens; + int? promptTokens; // 输入的token数 + int? completionTokens; // 输出的token数 + int? totalTokens; ChatMessage({ required this.messageId, @@ -29,7 +29,6 @@ class ChatMessage { required this.role, required this.content, this.imageUrl, - this.isPlaceholder, this.promptTokens, this.completionTokens, this.totalTokens, @@ -42,7 +41,6 @@ class ChatMessage { 'role': role, 'content': content, 'image_url': imageUrl, - 'is_placeholder': isPlaceholder, 'prompt_tokens': promptTokens, 'completion_tokens': completionTokens, 'total_tokens': totalTokens, @@ -60,7 +58,6 @@ class ChatMessage { role: map['role'] as String, content: map['content'] as String, imageUrl: map['image_url'] as String?, - isPlaceholder: bool.tryParse(map['is_placeholder']), promptTokens: int.tryParse(map['prompt_tokens']), completionTokens: int.tryParse(map['completion_tokens']), totalTokens: int.tryParse(map['total_tokens']), @@ -73,7 +70,6 @@ class ChatMessage { role: json["role"], content: json["content"], imageUrl: json["image_url"], - isPlaceholder: bool.tryParse(json["is_placeholder"]), promptTokens: int.tryParse(json["prompt_tokens"]), completionTokens: int.tryParse(json["completion_tokens"]), totalTokens: int.tryParse(json["total_tokens"]), @@ -85,7 +81,6 @@ class ChatMessage { "role": role, "content": content, "image_url": imageUrl, - "is_placeholder": isPlaceholder, "prompt_tokens": promptTokens, "completion_tokens": completionTokens, "total_tokens": totalTokens, @@ -102,7 +97,6 @@ class ChatMessage { "role": "$role", "content": ${jsonEncode(content)}, "image_url": "$imageUrl", - "is_placeholder":"$isPlaceholder", "prompt_tokens":"$promptTokens", "completion_tokens":"$completionTokens", "total_tokens":"$totalTokens" diff --git a/lib/models/training_state.dart b/lib/models/training_state.dart index d147b7d..6d25ac9 100644 --- a/lib/models/training_state.dart +++ b/lib/models/training_state.dart @@ -50,7 +50,8 @@ class Exercise { 'primary_muscles': primaryMuscles, 'secondary_muscles': secondaryMuscles, 'images': images, - 'is_custom': isCustom, + // sqlite不支持bool类型,这个值是int类型 + 'is_custom': isCustom == true ? 1 : 0, 'contributor': contributor, 'gmt_create': gmtCreate, 'gmt_modified': gmtModified, diff --git a/lib/views/diary/diary_modify_rich_text.dart b/lib/views/diary/diary_modify_rich_text.dart index c24fa5c..573f2ce 100644 --- a/lib/views/diary/diary_modify_rich_text.dart +++ b/lib/views/diary/diary_modify_rich_text.dart @@ -137,9 +137,9 @@ class _DiaryModifyRichTextState extends State { // 新增手记时,在没有保存的情况下点击重置,则不将修改状态改为false,只是清空当前的内容;只有点击返回时才退出当前页面。 resetInitData() { - // 标签清空 - _formKey.currentState?.fields['mood']?.didChange(""); - _formKey.currentState?.fields['category']?.didChange([]); + // 标签清空(心情可以多选,分类只能单选) + _formKey.currentState?.fields['mood']?.didChange([]); + _formKey.currentState?.fields['category']?.didChange(""); initTags = []; _tagTextController.text = ""; @@ -189,6 +189,7 @@ class _DiaryModifyRichTextState extends State { tempDiary.gmtCreate = getCurrentDateTime(); var newDiaryId = await _dbHelper.insertDiary(tempDiary); + if (!mounted) return; setState(() { initDiaryId = newDiaryId; }); @@ -200,6 +201,7 @@ class _DiaryModifyRichTextState extends State { await _dbHelper.updateDiary(tempDiary); } + if (!mounted) return; setState(() { isEditing = !isEditing; // 2024-07-06 现在编辑文本是否只读在控制器配置了,需要要先改是否修改,再修改控制器 @@ -228,7 +230,7 @@ class _DiaryModifyRichTextState extends State { return PopScope( // 点击返回键时暂停返回 canPop: false, - onPopInvoked: (didPop) async { + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) { return; } @@ -333,12 +335,14 @@ class _DiaryModifyRichTextState extends State { // 能查到结果,将其数据格式化显示 if (temp.isNotEmpty) { + if (!mounted) return; setState(() { initFormatData(temp.first); }); } } else { // ???如果是新增时的撤销,那就退出当前页面,还是清空已有数据但还是修改状态?? + if (!mounted) return; setState(() { // 2023-11-27 暂时先清空已有数据,并保持编辑状态;再点击退出时才手动退出 resetInitData(); @@ -356,7 +360,7 @@ class _DiaryModifyRichTextState extends State { ], ), body: Scrollbar( - thickness: 10, + thickness: 10.sp, // 设置交互模式后,滚动条和手势滚动方向才一致 interactive: true, radius: Radius.circular(5.sp), @@ -370,7 +374,7 @@ class _DiaryModifyRichTextState extends State { controller: _scrollController, child: GestureDetector( onTap: () { - FocusScope.of(context).unfocus(); + unfocusHandle(); }, child: Padding( padding: EdgeInsets.fromLTRB(5.sp, 5.sp, 10.sp, 5.sp), @@ -391,7 +395,7 @@ class _DiaryModifyRichTextState extends State { // 标题和标签选择放在一个折叠栏中,方便修改正文时折叠起来能显示更多内容 _buildTitleAndTags() { return Card( - elevation: 3, + elevation: 2.sp, child: ExpansionTile( title: buildTitleArea(), tilePadding: EdgeInsets.symmetric(horizontal: 5.sp), @@ -435,7 +439,7 @@ class _DiaryModifyRichTextState extends State { // 预览时不显示边框 border: isEditing ? OutlineInputBorder( - borderRadius: BorderRadius.circular(10.0), + borderRadius: BorderRadius.circular(10.sp), ) : InputBorder.none, // 设置透明底色 @@ -461,7 +465,7 @@ class _DiaryModifyRichTextState extends State { if (!isEditing) // 这个更小 Wrap( - spacing: 5, + spacing: 5.sp, children: [ ...initTags.map((tag) { return buildSmallButtonTag( @@ -544,7 +548,7 @@ class _DiaryModifyRichTextState extends State { // 在编辑状态下才显示工具栏 if (isEditing) Card( - elevation: 3, + elevation: 2.sp, child: ExpansionTile( title: Text(CusAL.of(context).richTextToolNote), leading: const Icon(Icons.tag, color: Colors.green), @@ -562,13 +566,13 @@ class _DiaryModifyRichTextState extends State { SizedBox( width: 1.sw, child: QuillToolbar.simple( - configurations: QuillSimpleToolbarConfigurations( - controller: _controller, - // 这几个默认没开启 - // showSmallButton: true, - // showAlignmentButtons: true, - // showDirection: true, - ), + controller: _controller, + configurations: const QuillSimpleToolbarConfigurations( + // 这几个默认没开启 + // showSmallButton: true, + // showAlignmentButtons: true, + // showDirection: true, + ), ), ), @@ -624,9 +628,9 @@ class _DiaryModifyRichTextState extends State { ), child: QuillEditor.basic( focusNode: quillFocusNode, + controller: _controller, configurations: QuillEditorConfigurations( autoFocus: false, - controller: _controller, scrollable: true, expands: true, padding: EdgeInsets.all(5.sp), @@ -775,7 +779,7 @@ class _DiaryModifyRichTextState extends State { hintText: CusAL.of(context).diaryTagsNote, contentPadding: EdgeInsets.symmetric(vertical: 2.sp), border: OutlineInputBorder( - borderRadius: BorderRadius.circular(10.0), + borderRadius: BorderRadius.circular(10.sp), ), // 设置透明底色 filled: true, diff --git a/lib/views/diary/index_table_calendar.dart b/lib/views/diary/index_table_calendar.dart index a09dc1e..097663e 100644 --- a/lib/views/diary/index_table_calendar.dart +++ b/lib/views/diary/index_table_calendar.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:intl/intl.dart'; @@ -75,6 +73,7 @@ class _DiaryTableCalendarState extends State { endDate: endDate, ); + if (!mounted) return; setState(() { diaryList = temp; // 初始化时设定当前选中的日期就是聚焦的日期 @@ -110,7 +109,7 @@ class _DiaryTableCalendarState extends State { // 当某个日期被长按可以新增备注??? _onDayLongPressed(DateTime selectedDay, DateTime focusedDay) { - print("日期被长按了---$selectedDay --$focusedDay"); + debugPrint("日期被长按了---$selectedDay --$focusedDay"); } // 当日期范围被选中时 @@ -159,7 +158,7 @@ class _DiaryTableCalendarState extends State { ), child: Text(CusAL.of(context).diaryLables("1")), ), - TextButton.icon( + IconButton( onPressed: () { Navigator.push( context, @@ -176,7 +175,6 @@ class _DiaryTableCalendarState extends State { _queryDairyList(_focusedDay); }); }, - label: Text(CusAL.of(context).addLabel("")), icon: const Icon(Icons.add), style: ButtonStyle( foregroundColor: WidgetStateProperty.all(Colors.white), @@ -298,7 +296,7 @@ class _DiaryTableCalendarState extends State { var chipLength = initTags.length + initMoods.length + 1; return Card( - elevation: 3, + elevation: 2.sp, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, diff --git a/lib/views/diary/index_timeline.dart b/lib/views/diary/index_timeline.dart index bde5ffa..b1f40f4 100644 --- a/lib/views/diary/index_timeline.dart +++ b/lib/views/diary/index_timeline.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:intl/intl.dart'; @@ -89,8 +87,6 @@ class _IndexTimelineState extends State { List newData = temp.data as List; - print(newData); - // 如果没有更多数据,则在底部显示回弹 if (newData.isEmpty) { if (!mounted) return; @@ -101,6 +97,7 @@ class _IndexTimelineState extends State { ); } + if (!mounted) return; // 设置查询结果 setState(() { // 因为没有分页查询,所有这里直接替换已有的数组 @@ -115,7 +112,7 @@ class _IndexTimelineState extends State { /// 处理点击了搜索按钮 _handleSearch() { // 取消键盘输入框聚焦 - FocusScope.of(context).unfocus(); + unfocusHandle(); setState(() { diaryList.clear(); currentPage = 1; @@ -226,8 +223,8 @@ class _IndexTimelineState extends State { isFirst: index == 0, isLast: index == diaryList.length - 1, indicatorStyle: IndicatorStyle( - width: 65, - height: 40, + width: 65.sp, + height: 40.sp, indicator: _CusIndicator( category: '${diaryItem.category}', // borderColor: borderColor, @@ -286,11 +283,12 @@ class _IndexTimelineState extends State { // 内外边距 padding: EdgeInsets.all(2.sp), margin: EdgeInsets.all(2.sp), - // color: Colors.transparent, - // 装饰和颜色不能同时设置 + color: Colors.transparent, + // // 装饰和颜色不能同时设置,有装饰颜色就放装饰里面 // decoration: BoxDecoration( // border: Border.all(color: Colors.black54, width: 1), // borderRadius: BorderRadius.circular(10), + // color: Colors.transparent, // ), // 不要用ListTile,很难看也很难布局 child: Column( @@ -418,6 +416,7 @@ class _IndexTimelineState extends State { await _dbHelper.deleteDiaryById(diaryItem.diaryId!); // 删除后重新查询 + if (!mounted) return; setState(() { currentPage = 1; // 数据库查询的时候会从0开始offset pageSize = 10; @@ -439,7 +438,7 @@ class _IndexTimelineState extends State { } } -// 自定义的时间线指示器养蛇 +// 自定义的时间线指示器样式 class _CusIndicator extends StatelessWidget { const _CusIndicator({ required this.category, diff --git a/lib/views/dietary/foods/add_food_serving_info.dart b/lib/views/dietary/foods/add_food_serving_info.dart index b9d94cd..c599a3d 100644 --- a/lib/views/dietary/foods/add_food_serving_info.dart +++ b/lib/views/dietary/foods/add_food_serving_info.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -54,7 +52,7 @@ class _FoodServingInfoModifyState extends State { body: ListView( children: [ Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: SingleChildScrollView( child: FormBuilder( key: _servingInfoformKey, diff --git a/lib/views/dietary/foods/add_food_with_serving.dart b/lib/views/dietary/foods/add_food_with_serving.dart index 2c3c728..e63822d 100644 --- a/lib/views/dietary/foods/add_food_with_serving.dart +++ b/lib/views/dietary/foods/add_food_with_serving.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -15,8 +13,8 @@ import '../../../models/dietary_state.dart'; import 'add_food_serving_info.dart'; import 'common_utils_for_food_modify.dart'; -// 目前这个是食物新增时使用,新增时会同时至少新增一条单份食物营养素信息。 -// 而食物某一单份营养素信息的修改可以在食物详情找到修改入口,但食物基本信息的修改入口还不明确 +// 目前这个是食物新增时使用,新增时会同时至少新增一条单份食物营养素信息(add_food_serving_info)。 +// 而食物某一单份营养素信息的修改可以在食物详情找到修改(新增+删除)入口 class AddfoodWithServing extends StatefulWidget { const AddfoodWithServing({super.key}); @@ -156,7 +154,7 @@ class _AddfoodWithServingState extends State { return ListView( children: [ Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: SingleChildScrollView( child: FormBuilder( key: _foodFormKey, @@ -272,7 +270,7 @@ class _AddfoodWithServingState extends State { // 单份营养素详情页面返回后的处理逻辑 _handleServingFormCallback(value) { // 从编辑单份营养素详情回来不要聚焦输入框 - FocusScope.of(context).requestFocus(FocusNode()); + unfocusHandle(); if (value != null) { // 此页面是新增食物带营养素,所以没有食物信息 diff --git a/lib/views/dietary/foods/common_utils_for_food_modify.dart b/lib/views/dietary/foods/common_utils_for_food_modify.dart index a3270d9..2c4a03c 100644 --- a/lib/views/dietary/foods/common_utils_for_food_modify.dart +++ b/lib/views/dietary/foods/common_utils_for_food_modify.dart @@ -1,8 +1,7 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; +import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:form_builder_file_picker/form_builder_file_picker.dart'; import 'package:form_builder_validators/form_builder_validators.dart'; @@ -273,7 +272,7 @@ buildFoodModifyFormColumns( labelText: CusAL.of(context).foodLabels("4"), ), - const SizedBox(height: 10), + SizedBox(height: 10.sp), // 上传活动示例图片(静态图或者gif) FormBuilderFilePicker( name: 'images', diff --git a/lib/views/dietary/foods/detail_modify_food.dart b/lib/views/dietary/foods/detail_modify_food.dart index b464384..916b5c5 100644 --- a/lib/views/dietary/foods/detail_modify_food.dart +++ b/lib/views/dietary/foods/detail_modify_food.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -13,8 +11,10 @@ import '../../../models/cus_app_localizations.dart'; import '../../../models/dietary_state.dart'; import 'common_utils_for_food_modify.dart'; -// 新增的时候用旧的food_modify和food_serving_info_modify_form。 -// 而在食物成分的详情页面进行修改时,是食物基本信息和指定单份营养素分开修改,所以有_base关键字 +// 新增的时候用 add_food_with_serving (新增食物必须有至少一份营养素信息) +// 而在食物成分的详情页面进行修改时,是食物基本信息和指定单份营养素分开修改 +// detail_modify_food 修改食物基本信息 +// detail_modify_serving_info 修改(新增+删除)指定单份营养素信息 class DetailModifyFood extends StatefulWidget { // 专门在食物详情中修改食物基本信息 final Food food; @@ -39,11 +39,9 @@ class _DetailModifyFoodState extends State { super.initState(); // 如果有食物有图片,则显示图片(不能放在下面那个callback中,会在表单初始化完成之后再赋值,那就没有意义了) - setState(() { - if (widget.food.photos != null && widget.food.photos != "") { - initImages = convertStringToPlatformFiles(widget.food.photos!); - } - }); + if (widget.food.photos != null && widget.food.photos != "") { + initImages = convertStringToPlatformFiles(widget.food.photos!); + } // 这是在表单初始化之后再赋值给栏位 WidgetsBinding.instance.addPostFrameCallback((_) { @@ -134,7 +132,7 @@ class _DetailModifyFoodState extends State { return ListView( children: [ Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: SingleChildScrollView( child: FormBuilder( key: _foodFormKey, @@ -150,7 +148,7 @@ class _DetailModifyFoodState extends State { ), ), Padding( - padding: EdgeInsets.only(left: 20.sp, right: 20.sp, top: 20.sp), + padding: EdgeInsets.all(20.sp), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ diff --git a/lib/views/dietary/foods/detail_modify_serving_info.dart b/lib/views/dietary/foods/detail_modify_serving_info.dart index 9250976..c473599 100644 --- a/lib/views/dietary/foods/detail_modify_serving_info.dart +++ b/lib/views/dietary/foods/detail_modify_serving_info.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -135,7 +133,7 @@ class _DetailModifyServingInfoState extends State { body: ListView( children: [ Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: SingleChildScrollView( child: FormBuilder( key: _servingInfoformKey, diff --git a/lib/views/dietary/foods/food_json_import.dart b/lib/views/dietary/foods/food_json_import.dart index b473904..58fb269 100644 --- a/lib/views/dietary/foods/food_json_import.dart +++ b/lib/views/dietary/foods/food_json_import.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -15,6 +13,11 @@ import '../../../layout/themes/cus_font_size.dart'; import '../../../models/cus_app_localizations.dart'; import '../../../models/food_composition.dart'; +/// +/// 2024-11-14 +/// 为了减少干扰信息,只支持单个(其实也可以多个)json导入 +/// 不再处理json文件夹的导入 +/// class FoodJsonImport extends StatefulWidget { const FoodJsonImport({super.key}); @@ -29,87 +32,21 @@ class _FoodJsonImportState extends State { bool isLoading = false; // 解析后的食物营养素列表(文件和食物都不支持移除) List foodComps = []; - // 上传的json文件列表 - List jsons = []; // 构建json文件加载成功后的锻炼数据表格要用到 // 待上传的动作数量已经每个动作的选中状态 int exerciseItemsNum = 0; List exerciseSelectedList = [false]; - /// ???可以考虑在打开文件夹或者文件时,删除已选择的文件夹或文件(现在是追加,不会去重) - // 上传指定文件夹,处理里面所有指定格式的json - Future _openFileExplorer() async { - // 用户选择指定文件夹 - String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); - // 如果有选中文件夹,遍历出里面所有json结尾的文件 - if (selectedDirectory != null) { - setState(() { - isLoading = true; - }); - - Directory directory = Directory(selectedDirectory); - List jsonFiles = directory - .listSync() - .where((entity) => entity.path.toLowerCase().endsWith('.json')) - .map((entity) => File(entity.path)) - .toList(); - - setState(() { - jsons.addAll(jsonFiles); - }); - - for (File file in jsonFiles) { - try { - String jsonData = await file.readAsString(); - - // 如果一个json文件只是一个动作,那就加上中括号;如果本身就是带了中括号的多个,就不再加 - List foodEnergyMapList = - jsonData.trim().startsWith("[") && jsonData.trim().endsWith("]") - ? json.decode(jsonData) - : json.decode("[$jsonData]"); - - var temp = foodEnergyMapList - .map((e) => FoodComposition.fromJson(e)) - .toList(); - - setState(() { - foodComps.addAll(temp); - // 更新需要构建的表格的长度和每条数据的可选中状态 - exerciseItemsNum = foodComps.length; - exerciseSelectedList = - List.generate(exerciseItemsNum, (int index) => false); - }); - } catch (e) { - // 弹出报错提示框 - if (!mounted) return; - - commonExceptionDialog( - context, - CusAL.of(context).importJsonError, - CusAL.of(context).importJsonErrorText(file.path, e.toString), - ); - - setState(() { - isLoading = false; - }); - // 中止操作 - return; - } - } - setState(() { - isLoading = false; - }); - } else { - // User canceled the picker - return; - } - } - // 用户可以选择多个json文件 Future _openJsonFiles() async { - FilePickerResult? result = - await FilePicker.platform.pickFiles(allowMultiple: true); + FilePickerResult? result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['json', 'JSON'], + allowMultiple: true, + ); + + if (!mounted) return; if (result != null) { setState(() { isLoading = true; @@ -130,6 +67,7 @@ class _FoodJsonImportState extends State { .map((e) => FoodComposition.fromJson(e)) .toList(); + if (!mounted) return; setState(() { foodComps.addAll(temp); // 更新需要构建的表格的长度和每条数据的可选中状态 @@ -140,7 +78,6 @@ class _FoodJsonImportState extends State { } catch (e) { // 弹出报错提示框 if (!mounted) return; - commonExceptionDialog( context, CusAL.of(context).importJsonError, @@ -230,19 +167,16 @@ class _FoodJsonImportState extends State { } } // 保存完了,情况数据,并弹窗提示。 + if (!mounted) return; setState(() { - setState(() { - jsons = []; - foodComps = []; - // 更新需要构建的表格的长度和每条数据的可选中状态 - exerciseItemsNum = 0; - exerciseSelectedList = [false]; + foodComps = []; + // 更新需要构建的表格的长度和每条数据的可选中状态 + exerciseItemsNum = 0; + exerciseSelectedList = [false]; - isLoading = false; - }); + isLoading = false; }); - if (!mounted) return; showDialog( context: context, builder: (context) { @@ -289,9 +223,6 @@ class _FoodJsonImportState extends State { /// 最上方的功能按钮区域 _buildButtonsArea(), - /// json文件列表不为空才显示对应区域 - if (jsons.isNotEmpty) ..._buildJsonFileInfoArea(), - /// 食物组成列表不为空且大于50条,简单的列表展示 if (foodComps.isNotEmpty && foodComps.length > 50) ..._buildFoodServingListArea(), @@ -312,42 +243,29 @@ class _FoodJsonImportState extends State { mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Expanded( - child: IconButton( - onPressed: _openFileExplorer, - icon: Icon( - Icons.drive_folder_upload, - size: CusIconSizes.iconMedium, - color: Theme.of(context).primaryColor, - ), - ), - ), - Expanded( - child: IconButton( + child: TextButton( onPressed: _openJsonFiles, - icon: Icon( - Icons.file_upload, - size: CusIconSizes.iconMedium, - color: Theme.of(context).primaryColor, + child: Text( + CusAL.of(context).importJsonButtons('0'), + style: TextStyle(fontSize: CusFontSizes.flagSmall), ), ), ), Expanded( - child: IconButton( - onPressed: () { - setState(() { - jsons = []; - foodComps = []; - // 更新需要构建的表格的长度和每条数据的可选中状态 - exerciseItemsNum = 0; - exerciseSelectedList = [false]; - }); - }, - icon: Icon( - Icons.clear, - size: CusIconSizes.iconMedium, - color: foodComps.isNotEmpty - ? Theme.of(context).primaryColor - : Theme.of(context).disabledColor, + child: TextButton( + onPressed: foodComps.isNotEmpty + ? () { + setState(() { + foodComps = []; + // 更新需要构建的表格的长度和每条数据的可选中状态 + exerciseItemsNum = 0; + exerciseSelectedList = [false]; + }); + } + : null, + child: Text( + CusAL.of(context).importJsonButtons('1'), + style: TextStyle(fontSize: CusFontSizes.flagSmall), ), ), ), @@ -356,31 +274,6 @@ class _FoodJsonImportState extends State { ); } - // 构建json文件列表区 - _buildJsonFileInfoArea() { - return [ - Text( - CusAL.of(context).jsonFiles, - style: TextStyle(fontSize: CusFontSizes.itemSubTitle), - textAlign: TextAlign.start, - ), - SizedBox( - height: 100.sp, - child: ListView.builder( - shrinkWrap: true, - itemCount: jsons.length, - itemBuilder: (context, index) { - return Text( - jsons[index].path, - style: TextStyle(fontSize: CusFontSizes.itemContent), - textAlign: TextAlign.start, - ); - }, - ), - ), - ]; - } - // 当上传的食物营养素信息超过50条,就单纯的列表展示 _buildFoodServingListArea() { return [ @@ -414,40 +307,29 @@ class _FoodJsonImportState extends State { verticalDirection: VerticalDirection.up, children: [ Expanded( - child: RichText( - textAlign: TextAlign.start, - text: TextSpan( - children: [ - TextSpan( - text: '${index + 1} - ', - style: TextStyle( - fontSize: CusFontSizes.itemSubTitle, - color: Colors.green, - ), - ), - TextSpan( - text: "${foodComps[index].foodCode} - ", - style: TextStyle( - fontSize: CusFontSizes.itemSubTitle, - color: Colors.grey, - ), - ), - TextSpan( - text: "${foodComps[index].foodName} - ", - style: TextStyle( - fontSize: CusFontSizes.itemSubTitle, - color: Colors.red, - ), - ), - TextSpan( - text: "${foodComps[index].energyKCal}", - style: TextStyle( - fontSize: CusFontSizes.itemSubTitle, - color: Colors.lightBlue, - ), - ), - ], - ), + child: buildRichTextItem( + '${index + 1}', + Colors.green, + textAlign: TextAlign.center, + ), + ), + Expanded( + child: buildRichTextItem( + '${foodComps[index].foodCode}', + Colors.grey, + ), + ), + Expanded( + flex: 4, + child: buildRichTextItem( + '${foodComps[index].foodName}', + Colors.red, + ), + ), + Expanded( + child: buildRichTextItem( + '${foodComps[index].energyKCal}', + Colors.lightBlue, ), ), ], diff --git a/lib/views/dietary/foods/food_nutrient_detail.dart b/lib/views/dietary/foods/food_nutrient_detail.dart index 104e2e0..3514b0e 100644 --- a/lib/views/dietary/foods/food_nutrient_detail.dart +++ b/lib/views/dietary/foods/food_nutrient_detail.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -53,14 +51,12 @@ class _FoodNutrientDetailState extends State { void initState() { super.initState(); - setState(() { - fsInfo = widget.foodItem; + fsInfo = widget.foodItem; - // 更新需要构建的表格的长度和每条数据的可选中状态(初始状态是都未选中) - servingItemsNum = fsInfo.servingInfoList.length; - servingSelectedList = - List.generate(servingItemsNum, (int index) => false); - }); + // 更新需要构建的表格的长度和每条数据的可选中状态(初始状态是都未选中) + servingItemsNum = fsInfo.servingInfoList.length; + servingSelectedList = + List.generate(servingItemsNum, (int index) => false); } // @@ -71,6 +67,7 @@ class _FoodNutrientDetailState extends State { widget.foodItem.food.foodId!, ); + if (!mounted) return; if (newItem != null) { setState(() { fsInfo = newItem; @@ -90,7 +87,7 @@ class _FoodNutrientDetailState extends State { Widget build(BuildContext context) { return PopScope( canPop: false, - onPopInvoked: (didPop) async { + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) return; // 返回上一页时,返回是否被修改标识,用于父组件判断是否需要重新查询 @@ -126,14 +123,17 @@ class _FoodNutrientDetailState extends State { ...buildFoodTable(fsInfo), /// 展示所有单份的数据,不用实时根据摄入数量修改值 - Text( - CusAL.of(context).foodNutrientInfo, - style: TextStyle( - fontSize: CusFontSizes.pageTitle, - fontWeight: FontWeight.bold, - color: Colors.green, + Padding( + padding: EdgeInsets.all(5.sp), + child: Text( + CusAL.of(context).foodNutrientInfo, + style: TextStyle( + fontSize: CusFontSizes.pageTitle, + fontWeight: FontWeight.bold, + color: Colors.green, + ), + textAlign: TextAlign.left, ), - textAlign: TextAlign.left, ), /// 当有单份营养素被选中后,显示删除或修改(仅单个被选中时)按钮;默认即可新增 @@ -161,12 +161,12 @@ class _FoodNutrientDetailState extends State { ), ), - SizedBox(height: 20.sp), + SizedBox(height: 10.sp), Card( - elevation: 5, + elevation: 2.sp, child: buildFoodServingDataTable(fsInfo), ), - SizedBox(height: 20.sp), + SizedBox(height: 10.sp), ], ), ), @@ -204,6 +204,7 @@ class _FoodNutrientDetailState extends State { if (value != null && value == true) { refreshFoodAndServing(); // 如果食物相关数据被修改,则变动标识设为true + if (!mounted) return; setState(() { isModified = true; }); @@ -323,6 +324,7 @@ class _FoodNutrientDetailState extends State { ).then((value) { // 因为默认有选中新增单份营养素的类型,所以返回true确认新增时,一定有该type if (value != null && value) { + if (!mounted) return; Navigator.push( context, MaterialPageRoute( @@ -336,6 +338,7 @@ class _FoodNutrientDetailState extends State { if (value != null && value == true) { refreshFoodAndServing(); // 如果食物相关数据被修改,则变动标识设为true + if (!mounted) return; setState(() { isModified = true; }); @@ -355,26 +358,29 @@ class _FoodNutrientDetailState extends State { } return [ - Text( - CusAL.of(context).foodBasicInfo, - style: TextStyle( - fontSize: CusFontSizes.flagMedium, - fontWeight: FontWeight.bold, - color: Colors.green, + Padding( + padding: EdgeInsets.all(5.sp), + child: Text( + CusAL.of(context).foodBasicInfo, + style: TextStyle( + fontSize: CusFontSizes.flagMedium, + fontWeight: FontWeight.bold, + color: Colors.green, + ), + textAlign: TextAlign.start, ), - textAlign: TextAlign.start, ), Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: Table( // 设置表格边框 border: TableBorder.all( color: Theme.of(context).disabledColor, ), // 设置每列的宽度占比 - columnWidths: const { - 0: FlexColumnWidth(4), - 1: FlexColumnWidth(9), + columnWidths: { + 0: FixedColumnWidth(100.sp), + 1: const FlexColumnWidth(1), }, defaultVerticalAlignment: TableCellVerticalAlignment.middle, children: [ @@ -402,7 +408,7 @@ class _FoodNutrientDetailState extends State { ), ), buildImageCarouselSlider(imageList), - SizedBox(height: 20.sp), + SizedBox(height: 10.sp), ]; } diff --git a/lib/views/dietary/foods/index.dart b/lib/views/dietary/foods/index.dart index fb2e489..b2b630e 100644 --- a/lib/views/dietary/foods/index.dart +++ b/lib/views/dietary/foods/index.dart @@ -66,6 +66,7 @@ class _DietaryFoodsState extends State { var newData = temp.data as List; + if (!mounted) return; setState(() { foodItems.addAll(newData); itemsCount = temp.total; @@ -93,7 +94,7 @@ class _DietaryFoodsState extends State { query = searchController.text; }); // 在当前上下文中查找最近的 FocusScope 并使其失去焦点,从而收起键盘。 - FocusScope.of(context).unfocus(); + unfocusHandle(); _loadFoodData(); } @@ -189,38 +190,12 @@ class _DietaryFoodsState extends State { }); }, ), - // Row( - // children: [ - // TextButton( - // onPressed: () { - // Navigator.push( - // context, - // MaterialPageRoute( - // builder: (context) => const AddfoodWithServing()), - // ).then((value) { - // // 不管是否新增成功,这里都重新加载;因为没有清空查询条件,所以新增的食物关键字不包含查询条件中,不会显示 - // if (value != null) { - // setState(() { - // foodItems.clear(); - // currentPage = 1; - // }); - // _loadFoodData(); - // } - // }); - // }, - // child: Text( - // CusAL.of(context).notFound, - // style: TextStyle(fontSize: 14.sp, color: Colors.white), - // ), - // ), - // ], - // ), ], ), body: Column( children: [ Padding( - padding: EdgeInsets.all(8.sp), + padding: EdgeInsets.all(5.sp), child: Row( children: [ Expanded( @@ -263,6 +238,79 @@ class _DietaryFoodsState extends State { ); } + // 点击跳转到营养素详情页 + void _onItemTap(FoodAndServingInfo fsi) { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => FoodNutrientDetail( + foodItem: fsi, + ), + ), + ).then((value) { + // 从详情页返回后需要重新查询,因为不知道在内部是不是有变动单份营养素。 + // 有变动,退出不刷新,再次进入还是能看到旧的;但是返回就刷新对于只是浏览数据不友好。 + // 因此,详情页会有一个是否被异动的标志,返回true则重新查询;否则就不更新 + if (value != null && value) { + setState(() { + foodItems.clear(); + currentPage = 1; + }); + _loadFoodData(); + } + }); + } + + // 长按显示删除弹窗 + void _onItemLongPress(Food food) { + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text(CusAL.of(context).deleteConfirm), + content: Text( + CusAL.of(context).deleteNote('\n${food.product}(${food.brand})'), + ), + actions: [ + TextButton( + onPressed: () { + Navigator.pop(context, false); + }, + child: Text(CusAL.of(context).cancelLabel), + ), + TextButton( + onPressed: () { + Navigator.pop(context, true); + }, + child: Text(CusAL.of(context).confirmLabel), + ), + ], + ); + }, + ).then((value) async { + if (value != null && value) { + try { + await _dietaryHelper.deleteFoodWithServingInfo(food.foodId!); + + if (!mounted) return; + // 删除后重新查询 + setState(() { + foodItems.clear(); + currentPage = 1; + }); + _loadFoodData(); + } catch (e) { + if (!mounted) return; + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + e.toString(), + ); + } + } + }); + } + _buildSimpleFoodTile(FoodAndServingInfo fsi, int index) { var food = fsi.food; var servingList = fsi.servingInfoList; @@ -286,7 +334,7 @@ class _DietaryFoodsState extends State { "${CusAL.of(context).mainNutrients('2')} ${formatDoubleToString(firstServing?.protein ?? 0)} ${CusAL.of(context).unitLabels('0')}"; return Card( - elevation: 5, + elevation: 2.sp, child: ListTile( // 食物名称 title: Text( @@ -307,77 +355,11 @@ class _DietaryFoodsState extends State { softWrap: true, overflow: TextOverflow.ellipsis, ), + // 点击显示营养素详情 + onTap: () => _onItemTap(fsi), - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => FoodNutrientDetail( - foodItem: fsi, - ), - ), - ).then((value) { - // 从详情页返回后需要重新查询,因为不知道在内部是不是有变动单份营养素。 - // 有变动,退出不刷新,再次进入还是能看到旧的;但是返回就刷新对于只是浏览数据不友好。 - // 因此,详情页会有一个是否被异动的标志,返回true则重新查询;否则就不更新 - if (value != null && value) { - setState(() { - foodItems.clear(); - currentPage = 1; - }); - _loadFoodData(); - } - }); - }, // 长按点击弹窗提示是否删除 - onLongPress: () { - showDialog( - context: context, - builder: (context) { - return AlertDialog( - title: Text(CusAL.of(context).deleteConfirm), - content: Text( - CusAL.of(context) - .deleteNote('\n${food.product}(${food.brand})'), - ), - actions: [ - TextButton( - onPressed: () { - Navigator.pop(context, false); - }, - child: Text(CusAL.of(context).cancelLabel), - ), - TextButton( - onPressed: () { - Navigator.pop(context, true); - }, - child: Text(CusAL.of(context).confirmLabel), - ), - ], - ); - }, - ).then((value) async { - if (value != null && value) { - try { - await _dietaryHelper.deleteFoodWithServingInfo(food.foodId!); - - // 删除后重新查询 - setState(() { - foodItems.clear(); - currentPage = 1; - }); - _loadFoodData(); - } catch (e) { - if (!mounted) return; - commonExceptionDialog( - context, - CusAL.of(context).exceptionWarningTitle, - e.toString(), - ); - } - } - }); - }, + onLongPress: () => _onItemLongPress(food), ), ); } @@ -387,8 +369,8 @@ class _DietaryFoodsState extends State { var servingList = fsi.servingInfoList; var foodName = "${food.product} (${food.brand})"; - return Card( - elevation: 5, + var card = Card( + elevation: 2.sp, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, @@ -397,12 +379,12 @@ class _DietaryFoodsState extends State { width: 1.sw, child: Container( decoration: BoxDecoration( - borderRadius: BorderRadius.circular(5.0), // 设置所有圆角的大小 + borderRadius: BorderRadius.circular(5.sp), // 设置所有圆角的大小 // 设置展开前的背景色 // color: const Color.fromARGB(255, 195, 198, 201), ), child: Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: RichText( textAlign: TextAlign.start, maxLines: 2, @@ -487,6 +469,12 @@ class _DietaryFoodsState extends State { ], ), ); + + return GestureDetector( + onTap: () => _onItemTap(fsi), + onLongPress: () => _onItemLongPress(food), + child: card, + ); } _buildDataCell(String text) { diff --git a/lib/views/dietary/index.dart b/lib/views/dietary/index.dart index be8fd3b..ef4182d 100644 --- a/lib/views/dietary/index.dart +++ b/lib/views/dietary/index.dart @@ -1,7 +1,4 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; -import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../common/components/cus_cards.dart'; import '../../common/global/constants.dart'; @@ -21,84 +18,43 @@ class Dietary extends StatefulWidget { class _DietaryState extends State { @override Widget build(BuildContext context) { - // 计算屏幕剩余的高度 - double screenHeight = MediaQuery.of(context).size.height - - MediaQuery.of(context).padding.top - - MediaQuery.of(context).padding.bottom - - kToolbarHeight - - kBottomNavigationBarHeight - - 2 * 12.sp; // 减的越多,上下空隙越大 - return Scaffold( // 避免搜索时弹出键盘,让底部的minibar位置移动到tab顶部导致溢出的问题 resizeToAvoidBottomInset: false, - appBar: AppBar( - title: Text(CusAL.of(context).dietary), - ), - body: buildFixedBody(screenHeight), - ); - } - - /// 可视页面固定等分居中、不可滚动的首页 - buildFixedBody(double screenHeight) { - return Center( - child: Column( + appBar: AppBar(title: Text(CusAL.of(context).dietary)), + body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - // SizedBox( - // height: screenHeight / 4, - // child: buildSmallCoverCard( - // context, - // const DietaryReports(), - // CusAL.of(context).dietaryReports, - // ), - // ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const DietaryReports(), - CusAL.of(context).dietaryReports, - CusAL.of(context).dietaryReportsSubtitle, - reportImageUrl, - ), + child: CusCoverCard( + targetPage: const DietaryReports(), + title: CusAL.of(context).dietaryReports, + subtitle: CusAL.of(context).dietaryReportsSubtitle, + imageUrl: reportImageUrl, ), ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const DietaryFoods(), - CusAL.of(context).foodCompo, - CusAL.of(context).foodCompoSubtitle, - dietaryNutritionImageUrl, - ), + child: CusCoverCard( + targetPage: const DietaryFoods(), + title: CusAL.of(context).foodCompo, + subtitle: CusAL.of(context).foodCompoSubtitle, + imageUrl: dietaryNutritionImageUrl, ), ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const MealPhotoGallery(), - CusAL.of(context).mealGallery, - CusAL.of(context).mealGallerySubtitle, - dietaryMealImageUrl, - ), + child: CusCoverCard( + targetPage: const MealPhotoGallery(), + title: CusAL.of(context).mealGallery, + subtitle: CusAL.of(context).mealGallerySubtitle, + imageUrl: dietaryMealImageUrl, ), ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const DietaryRecords(), - CusAL.of(context).dietaryRecords, - CusAL.of(context).dietaryRecordsSubtitle, - dietaryLogCoverImageUrl, - ), + child: CusCoverCard( + targetPage: const DietaryRecords(), + title: CusAL.of(context).dietaryRecords, + subtitle: CusAL.of(context).dietaryRecordsSubtitle, + imageUrl: dietaryLogCoverImageUrl, ), ), ], diff --git a/lib/views/dietary/meal_gallery/meal_photo_gallery.dart b/lib/views/dietary/meal_gallery/meal_photo_gallery.dart index 605c069..6d9bc8c 100644 --- a/lib/views/dietary/meal_gallery/meal_photo_gallery.dart +++ b/lib/views/dietary/meal_gallery/meal_photo_gallery.dart @@ -69,6 +69,7 @@ class _MealPhotoGalleryState extends State { dateSort: "DESC", ); + if (!mounted) return; setState(() { photoItems.addAll(temp); currentPage++; @@ -113,7 +114,7 @@ class _MealPhotoGalleryState extends State { if (photoList.isNotEmpty) { return Card( - elevation: 5, + elevation: 2.sp, child: Column( children: [ SizedBox(height: 10.sp), diff --git a/lib/views/dietary/records/add_intake_item/index.dart b/lib/views/dietary/records/add_intake_item/index.dart index dc9f601..fc20c3f 100644 --- a/lib/views/dietary/records/add_intake_item/index.dart +++ b/lib/views/dietary/records/add_intake_item/index.dart @@ -120,7 +120,7 @@ class _AddIntakeItemState extends State /// 处理点击了搜索按钮 _handleSearch() { // 取消键盘输入框聚焦 - FocusScope.of(context).unfocus(); + unfocusHandle(); setState(() { foodItems.clear(); currentPage = 1; @@ -146,6 +146,7 @@ class _AddIntakeItemState extends State List newData = temp.data as List; + if (!mounted) return; setState(() { foodItems.addAll(newData); currentPage++; @@ -205,6 +206,7 @@ class _AddIntakeItemState extends State } List result = uniqueObjects.values.toList(); + if (!mounted) return; setState(() { dfiwfsList = result; // 要根据实际list的数量设置录每个列表项是否被选中 @@ -243,11 +245,11 @@ class _AddIntakeItemState extends State try { var rst = await _dietaryHelper.insertDailyFoodItemList(tempList); + if (!mounted) return; if (rst.isNotEmpty) { - if (!mounted) return; - Navigator.of(context).pop(dropdownValue.enLabel); } + setState(() { isRecentLoading = false; }); @@ -367,13 +369,6 @@ class _AddIntakeItemState extends State onPressed: _saveSelectedRecentListToDb, icon: const Icon(Icons.save), ), - // TextButton( - // onPressed: _saveSelectedRecentListToDb, - // child: Text( - // CusAL.of(context).addLabel(""), - // style: TextStyle(color: Theme.of(context).canvasColor), - // ), - // ), /// 当tab是食物列表时,才显示增加食物的按钮 if (isShowAddButton) @@ -473,7 +468,7 @@ class _AddIntakeItemState extends State /// buildSimpleFoodListTabView() { return Padding( - padding: EdgeInsets.all(8.sp), + padding: EdgeInsets.all(5.sp), child: Column( children: [ /// 搜索区域 @@ -502,7 +497,7 @@ class _AddIntakeItemState extends State /// 查询条件输入行 _buildSearchRowArea() { return Padding( - padding: EdgeInsets.symmetric(horizontal: 10.sp), + padding: EdgeInsets.symmetric(horizontal: 5.sp), child: Row( children: [ Expanded( @@ -534,7 +529,7 @@ class _AddIntakeItemState extends State var foodEnergy = (fistServingInfo.energy / constants.oneCalToKjRatio); return Card( - elevation: 2, + // elevation: 2.sp, child: ListTile( // 食物名称 title: Text( diff --git a/lib/views/dietary/records/add_intake_item/simple_food_detail.dart b/lib/views/dietary/records/add_intake_item/simple_food_detail.dart index bdcef25..4c725bb 100644 --- a/lib/views/dietary/records/add_intake_item/simple_food_detail.dart +++ b/lib/views/dietary/records/add_intake_item/simple_food_detail.dart @@ -65,10 +65,8 @@ class _SimpleFoodDetailState extends State { void initState() { super.initState(); - setState(() { - // 因为有新增单位,可能需要修改食物详情信息,所以使用单独的变量 - fsInfo = widget.foodItem; - }); + // 因为有新增单位,可能需要修改食物详情信息,所以使用单独的变量 + fsInfo = widget.foodItem; // ---这里显示的摄入量和单位(营养素的食物单份数据)根据来源不同,取值也不同 // 新增的时候,一个食物有多种单份营养素,默认取第一个 @@ -210,6 +208,7 @@ class _SimpleFoodDetailState extends State { onlyNotDeleted: false, ); + if (!mounted) return; if (newItem != null) { setState(() { // 更新当前食物的单份营养素列表 @@ -244,7 +243,7 @@ class _SimpleFoodDetailState extends State { ), ), body: Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: ListView( children: [ // 修改数量和单位 @@ -252,9 +251,10 @@ class _SimpleFoodDetailState extends State { SizedBox(height: 10.sp), // 饮食日记主界面点击知道item进来有“移除”和“修改”,点指定餐次新增进来则显示“新增” buildButtonsRowArea(), - SizedBox(height: 10.sp), + SizedBox(height: 20.sp), // 主要营养素表格 buildNutrientTableArea(), + SizedBox(height: 20.sp), // 详细营养素区域 buildAllNutrientTableArea(), ], @@ -418,13 +418,13 @@ class _SimpleFoodDetailState extends State { DecoratedBox( // 设置背景色 decoration: BoxDecoration( - color: Theme.of(context).disabledColor, + color: Theme.of(context).hoverColor, border: Border.all( color: Theme.of(context).colorScheme.tertiaryContainer, ), ), child: Table( - border: TableBorder.all(), + // border: TableBorder.all(), columnWidths: const { 1: FlexColumnWidth(), 2: FlexColumnWidth(), @@ -475,14 +475,14 @@ class _SimpleFoodDetailState extends State { TextSpan( text: '$title\n', style: TextStyle( - // color: Theme.of(context).primaryColor, + color: Theme.of(context).primaryColor, fontSize: CusFontSizes.itemContent, ), ), TextSpan( text: value, style: TextStyle( - // color: Theme.of(context).primaryColor, + color: Theme.of(context).primaryColor, fontSize: CusFontSizes.itemTitle, fontWeight: FontWeight.bold, ), @@ -601,6 +601,7 @@ class _SimpleFoodDetailState extends State { ), ], ), + SizedBox(height: 20.sp), ], ); } diff --git a/lib/views/dietary/records/ai_suggestion/ai_suggestion_page.dart b/lib/views/dietary/records/ai_suggestion/ai_suggestion_page.dart index f2b834b..4ec276f 100644 --- a/lib/views/dietary/records/ai_suggestion/ai_suggestion_page.dart +++ b/lib/views/dietary/records/ai_suggestion/ai_suggestion_page.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print, - import 'dart:convert'; import 'dart:io'; @@ -13,6 +11,7 @@ import 'package:uuid/uuid.dart'; import '../../../../apis/paid_llm_apis.dart'; import '../../../../common/components/dialog_widgets.dart'; import '../../../../common/global/constants.dart'; +import '../../../../common/utils/tool_widgets.dart'; import '../../../../models/cus_app_localizations.dart'; import '../../../../models/paid_llm/common_chat_completion_state.dart'; import '../../../../models/paid_llm/llm_chat.dart'; @@ -43,12 +42,8 @@ class _OneChatScreenState extends State { // AI是否在思考中(如果是,则不允许再次发送) bool isBotThinking = false; - /// 2024-06-11 默认使用流式请求,更快;但是同样的问题,流式使用的token会比非流式更多 - /// 2024-06-15 限时限量的可能都是收费的,本来就慢,所以默认就流式,不用切换 - /// 2024-06-20 流式使用的token太多了,还是默认更省的 - bool isStream = false; - // 默认进入对话页面应该就是啥都没有,然后根据这空来显示预设对话 + // 2024-12-03 不再需要占位的,是因为请求中时 http 客户端有加载中弹窗 List messages = [ // 预设第一个role为system,指定系统角色 ChatMessage( @@ -58,29 +53,19 @@ class _OneChatScreenState extends State { : "你是一名资深且优秀的营养学、健康学、养生学专家。", role: "system", dateTime: DateTime.now(), - isPlaceholder: false, ), ]; - // 等待AI响应时的占位的消息,在构建真实对话的list时要删除 - var placeholderMessage = ChatMessage( - messageId: "placeholderMessage", - content: box.read('language') == "en" - ? "thinking(longer wait,more replies) " - : "努力思考中(等待越久,回复内容越多) ", - role: "assistant", - dateTime: DateTime.now(), - isPlaceholder: true, - ); - // 如果是图片分析,还需要传入参数,图片base64 String? imageBase64String; // 图像理解就第一次需要传图片 bool? isFirstSendImage; - // 2024-07-12 因为等到AI响应是异步的,可能会出现等待中此页面被用户关闭,此时再调用setstate就会报错 - // 所以在dispose的时候设定标记,如果已经被销毁,则不执行setstate - bool _isDisposed = false; + // 2024-12-03 虽然暂时有这个设定,但没有切换的地方。所以总是流式响应 + bool isStream = true; + + // 当前正在响应的api返回流(放在全局为了可以手动取消) + StreamWithCancel respStream = StreamWithCancel.empty(); @override void initState() { @@ -92,12 +77,6 @@ class _OneChatScreenState extends State { }); } - @override - void dispose() { - _isDisposed = true; - super.dispose(); - } - // 2024-07-12 如果是餐次相册的图片分析,那么进入这个页面需要先处理图片数据 initSend() async { if (widget.imageUrl != null) { @@ -105,6 +84,8 @@ class _OneChatScreenState extends State { try { // 可能会出现不存在的图片路径,那边这里转base64就会报错,那么就返回上一页了 var tempBase64Str = base64Encode((await selectedImage.readAsBytes())); + + if (!mounted) return; setState(() { imageBase64String = "data:image/jpeg;base64,$tempBase64Str"; @@ -114,8 +95,6 @@ class _OneChatScreenState extends State { // 初始化提交之后,就不再发送图片了 isFirstSendImage = false; }); - - print(imageBase64String); } catch (e) { // 图片数据不能转base64,就弹窗提示,并返回上一页 if (!mounted) return; @@ -141,6 +120,7 @@ class _OneChatScreenState extends State { ); }, ).then((value) { + if (!mounted) return; Navigator.of(context).pop(); }); } @@ -149,73 +129,63 @@ class _OneChatScreenState extends State { } } - // 这个发送消息实际是将对话文本添加到对话列表中 - // 但是在用户发送消息之后,需要等到AI响应,成功响应之后将响应加入对话中 - _sendMessage(String text, {String role = "user", CCUsage? usage}) { - // 发送消息的逻辑,这里只是简单地将消息添加到列表中 - var temp = ChatMessage( - messageId: const Uuid().v4(), - content: text, - role: role, - dateTime: DateTime.now(), - promptTokens: usage?.promptTokens, // prompt 使用的token数(输入) - completionTokens: usage?.completionTokens, // 内容生成的token数(输出) - totalTokens: usage?.totalTokens, + // 在用户输入或者AI响应后,需要把对话列表滚动到最下面 + // 调用时放在状态改变函数中 + chatListScrollToBottom() { + // 每收到一点新的响应文本,就都滚动到ListView的底部 + // 注意:ai响应的消息卡片下方还有一行功能按钮,这里滚动了那个还没显示的话是看不到的 + // 所以滚动到最大还加一点高度(大于实际功能按钮高度也没问题) + _scrollController.animateTo( + _scrollController.position.maxScrollExtent + 80, + curve: Curves.easeOut, + // 注意:sse的间隔比较短,这个滚动也要快一点 + duration: const Duration(milliseconds: 50), ); + } - // 注意:如果在AI异步回复前,用户返回到其他页面,这里就不存在状态了,就会报错 - if (_isDisposed) return; + // 2024-12-02 改为仅用户可以发送消息,AI响应直接在响应函数中处理 + _sendMessage(String text, {CCUsage? usage}) { setState(() { - // AI思考和用户输入是相反的(如果角色是用户,那就是在等到机器回复了) - isBotThinking = (role == "user"); - - messages.add(temp); + messages.add(ChatMessage( + messageId: const Uuid().v4(), + content: text, + role: "user", + dateTime: DateTime.now(), + promptTokens: usage?.promptTokens, // prompt 使用的token数(输入) + completionTokens: usage?.completionTokens, // 内容生成的token数(输出) + totalTokens: usage?.totalTokens, + )); _userInputController.clear(); // 滚动到ListView的底部 - _scrollController.animateTo( - _scrollController.position.maxScrollExtent, - curve: Curves.easeOut, - duration: const Duration(milliseconds: 300), - ); + chatListScrollToBottom(); - // 如果是用户发送了消息,则开始等到AI响应(如果不是用户提问,则不会去调用接口) - if (role == "user") { - // 如果是用户输入时,在列表中添加一个占位的消息,以便思考时的装圈和已加载的消息可以放到同一个list进行滑动 - // 一定注意要记得AI响应后要删除此占位的消息 - placeholderMessage.dateTime = DateTime.now(); - messages.add(placeholderMessage); - - // 获取大模型应答 - _getLlmResponse(); - } + // 获取大模型应答 + _getLlmResponse(); }); } - // 根据不同的平台、选中的不同模型,调用对应的接口,得到回复 - // 虽然返回的响应通用了,但不同的平台和模型实际取值还是没有抽出来的 + // 得到模型响应 _getLlmResponse() async { - // 将已有的消息处理成Ernie支出的消息列表格式(构建查询条件时要删除占位的消息) + // 在调用前,不会设置响应状态 + if (isBotThinking) return; + setState(() { + isBotThinking = true; + }); + + // 将已有的消息处理成支持的消息列表格式(构建查询条件时要删除占位的消息) List msgs = messages - .where((e) => e.isPlaceholder != true) - .map((e) => CCMessage( - content: e.content, - role: e.role, - )) + .map((e) => CCMessage(content: e.content, role: e.role)) .toList(); - // 2024-07-12 如果有图片,content结构会不一样. - // 看多伦对话的示例,似乎只需要第一次时传图片数据,后面不必再传 + // 如果是图片,图片要单独处理下 if (imageBase64String != null) { - // yi-vision 暂不支持设置系统消息。 msgs = messages - .where((e) => e.isPlaceholder != true && e.role != "system") .map((e) => CCMessage( - content: (e.role == "assistant") + content: (e.role == "assistant" || e.role == "system") ? e.content : isFirstSendImage == true ? [ - // 2024-07-12 这里就不使用VisionContent,直接拼接json { "type": "image_url", "image_url": {"url": imageBase64String} @@ -230,59 +200,99 @@ class _OneChatScreenState extends State { .toList(); } - // 等待请求响应 - // 这里一定要确保存在模型名称,因为要作为http请求参数 - List temp; + // 流式响应处理 + StreamWithCancel stream; if (imageBase64String != null) { - temp = await getChatResp( + stream = await getChatRespStream( ApiPlatform.lingyiwanwu, msgs, model: ccmSpecList[CCM.YiVision]!.model, + stream: isStream, ); } else { - temp = await getChatResp( + stream = await getChatRespStream( ApiPlatform.lingyiwanwu, msgs, model: ccmSpecList[CCM.YiSpark]!.model, + stream: isStream, ); } - // 得到回复后要删除表示加载中的占位消息 - // 注意:如果在AI回复时,用户返回到其他页面,这里就不存在状态了,就会报错 - if (!_isDisposed) { - setState(() { - messages.removeWhere((e) => e.isPlaceholder == true); - }); - } - - // 得到AI回复之后,添加到列表中,也注明不是用户提问 - var tempText = temp.map((e) => e.customReplyText).join(); - if (temp.isNotEmpty && temp.first.error?.code != null) { - if (!mounted) return; - tempText = """${CusAL.of(context).apiErrorHint}: -\ncode: ${temp.first.error?.code} -\ntype: ${temp.first.error?.type} -\nmessage: ${temp.first.error?.message} -"""; - } + // 保存流以便可以取消 + if (!mounted) return; + setState(() { + respStream = stream; + }); - // 每次对话的结果流式返回,所以是个列表,就需要累加起来 - int inputTokens = 0; - int outputTokens = 0; - int totalTokens = 0; - for (var e in temp) { - inputTokens += e.usage?.promptTokens ?? 0; - outputTokens += e.usage?.completionTokens ?? 0; - totalTokens += e.usage?.totalTokens ?? 0; - } - // 里面的promptTokens和completionTokens是百度这个特立独行的,在上面拼到一起了 - var a = CCUsage( - promptTokens: inputTokens, - completionTokens: outputTokens, - totalTokens: totalTokens, + ChatMessage? csMsg = ChatMessage( + messageId: const Uuid().v4(), + role: "assistant", + content: "", + dateTime: DateTime.now(), ); - _sendMessage(tempText, role: "assistant", usage: a); + setState(() { + messages.add(csMsg!); + }); + + respStream.stream.listen( + (crb) { + // 如果返回了[DONE],则表示响应结束 + if ((crb.customReplyText ?? "").contains('[DONE]')) { + setState(() { + csMsg = null; + isBotThinking = false; + }); + } else { + // 为了每次有消息都能更新页面状态 + setState(() { + isBotThinking = true; + }); + + // 更新响应文本 + // 2024-11-04 讯飞星火,虽然成功返回,还是会有message栏位,其他的是出错了才有该栏位 + // 所以需要判断该errorMsg的值 + if ((crb.error != null)) { + csMsg?.content += """后台响应报错: + \n\n错误代码: ${crb.error?.code} + \n\n错误原因: ${crb.error?.message} + """; + + if (!mounted) return; + setState(() { + csMsg = null; + isBotThinking = false; + }); + } else { + csMsg?.content += crb.customReplyText ?? ""; + } + + // 更新token信息 + csMsg?.promptTokens = (crb.usage?.promptTokens ?? 0); + csMsg?.completionTokens = (crb.usage?.completionTokens ?? 0); + csMsg?.totalTokens = (crb.usage?.totalTokens ?? 0); + + chatListScrollToBottom(); + } + }, + onDone: () { + // 如果是流式响应,最后一条会带有[DNOE]关键字,所以在上面处理最后响应结束的操作 + // 如果不是流式,响应流就只有1条数据,那么就只有在这里才能得到流结束了,所以需要在这里完成后的操作 + // 但是如果是流式,还在这里处理结束操作的话会出问题(实测在数据还在推送的时候,这个ondone就触发了) + if (!isStream) { + if (!mounted) return; + // 流式响应结束了,就保存数据到db,并重置流式变量和aip响应标志 + setState(() { + csMsg = null; + isBotThinking = false; + }); + } + }, + onError: (error) { + if (!mounted) return; + commonExceptionDialog(context, "异常提示", error.toString()); + }, + ); } /// 最后一条大模型回复如果不满意,可以重新生成(中间的不行,因为后续的问题是关联上下文的) @@ -291,10 +301,15 @@ class _OneChatScreenState extends State { setState(() { // 将最后一条消息删除,并添加占位消息,重新发送 messages.removeLast(); - placeholderMessage.dateTime = DateTime.now(); - messages.add(placeholderMessage); - _getLlmResponse(); + // 2024-12-03 如果删除最后一条,消息列表只剩2条了(system和user), + // 那表明其实是初始化的提问,需要带上图片 + if (messages.length <= 2) { + messages.clear(); + initSend(); + } else { + _getLlmResponse(); + } }); } @@ -312,7 +327,7 @@ class _OneChatScreenState extends State { behavior: HitTestBehavior.translucent, onTap: () { // 点击空白处可以移除焦点,关闭键盘 - FocusScope.of(context).unfocus(); + unfocusHandle(); }, child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -355,23 +370,24 @@ class _OneChatScreenState extends State { padding: EdgeInsets.all(5.sp), child: Column( children: [ - // 如果是最后一个回复的文本,使用打字机特效 - // if (index == messages.length - 1) - // TypewriterText(text: messages[index].text), - // 如果是预设的system信息,则不显示 if (messages[index].role != "system") - MessageItem(message: messages[index]), + MessageItem( + message: messages[index], + // 只有最后一个才显示圈圈 + isBotThinking: + index == messages.length - 1 ? isBotThinking : false, + ), - // 如果是大模型回复,可以有一些功能按钮 - if (messages[index].role == "assistant") + // 如果是大模型回复且回复完了,可以有一些功能按钮 + if (messages[index].role == "assistant" && + isBotThinking != true) Row( mainAxisAlignment: MainAxisAlignment.end, children: [ // 其中,是大模型最后一条回复,则可以重新生成 // 注意,还要排除占位消息 - if ((index == messages.length - 1) && - messages[index].isPlaceholder != true) + if ((index == messages.length - 1)) TextButton( onPressed: () { regenerateLatestQuestion(); @@ -379,28 +395,26 @@ class _OneChatScreenState extends State { child: Text(CusAL.of(context).regeneration), ), // - // 如果不是等待响应才可以点击复制该条回复 - if (messages[index].isPlaceholder != true) - IconButton( - onPressed: () { - Clipboard.setData( - ClipboardData(text: messages[index].content), - ); - - EasyLoading.showToast( - CusAL.of(context).copiedHint, - duration: const Duration(seconds: 3), - toastPosition: EasyLoadingToastPosition.center, - ); - }, - icon: Icon(Icons.copy, size: 20.sp), - ), - // 如果不是等待响应才显示token数量 - if (messages[index].isPlaceholder != true) - Text( - "tokens 输入:${messages[index].promptTokens} 输出:${messages[index].completionTokens} 总计:${messages[index].totalTokens}", - style: TextStyle(fontSize: 10.sp), - ), + + IconButton( + onPressed: () { + Clipboard.setData( + ClipboardData(text: messages[index].content), + ); + + EasyLoading.showToast( + CusAL.of(context).copiedHint, + duration: const Duration(seconds: 3), + toastPosition: EasyLoadingToastPosition.center, + ); + }, + icon: Icon(Icons.copy, size: 20.sp), + ), + + Text( + "tokens 输入:${messages[index].promptTokens} 输出:${messages[index].completionTokens} 总计:${messages[index].totalTokens}", + style: TextStyle(fontSize: 10.sp), + ), SizedBox(width: 10.sp), ], ) @@ -437,24 +451,40 @@ class _OneChatScreenState extends State { }, ), ), - IconButton( - // 如果AI正在响应,或者输入框没有任何文字,不让点击发送 - onPressed: isBotThinking || userInput.isEmpty - ? null - : () { - // 在当前上下文中查找最近的 FocusScope 并使其失去焦点,从而收起键盘。 - FocusScope.of(context).unfocus(); - - // 用户发送消息 - _sendMessage(userInput); - - // 发送完要清空记录用户输的入变量 + + // 如果是API响应中,可以点击终止 + isBotThinking + ? IconButton( + onPressed: () async { + await respStream.cancel(); + if (!mounted) return; setState(() { - userInput = ""; + _userInputController.clear(); + chatListScrollToBottom(); + isBotThinking = false; }); }, - icon: const Icon(Icons.send), - ), + icon: const Icon(Icons.stop), + ) + : IconButton( + // 如果AI正在响应,或者输入框没有任何文字,不让点击发送 + onPressed: isBotThinking || userInput.isEmpty + ? null + : () { + // 失去焦点,从而收起键盘。 + unfocusHandle(); + + // 用户发送消息 + _sendMessage(userInput); + + // 发送完要清空记录用户输的入变量 + if (!mounted) return; + setState(() { + userInput = ""; + }); + }, + icon: const Icon(Icons.send), + ), ], ), ); diff --git a/lib/views/dietary/records/ai_suggestion/widgets/message_item.dart b/lib/views/dietary/records/ai_suggestion/widgets/message_item.dart index 1443295..582b921 100644 --- a/lib/views/dietary/records/ai_suggestion/widgets/message_item.dart +++ b/lib/views/dietary/records/ai_suggestion/widgets/message_item.dart @@ -8,8 +8,14 @@ import '../../../../../models/paid_llm/llm_chat.dart'; class MessageItem extends StatelessWidget { final ChatMessage message; + // 2024-08-12 流式响应时,数据是逐步增加的,如果还在响应中加个符号 + final bool? isBotThinking; - const MessageItem({super.key, required this.message}); + const MessageItem({ + super.key, + required this.message, + this.isBotThinking = false, + }); @override Widget build(BuildContext context) { @@ -51,57 +57,38 @@ class MessageItem extends StatelessWidget { style: TextStyle(fontSize: 12.sp, color: textColor), ), ), - // 如果是占位的消息,则显示装圈圈 - if (message.isPlaceholder == true) - Card( - elevation: 3, - child: Padding( - padding: EdgeInsets.all(5.sp), - child: Row( - crossAxisAlignment: crossAlignment, - children: [ - Text( - message.content, - style: const TextStyle(color: Colors.black), - ), - SizedBox( - height: 20.sp, - width: 20.sp, - child: const CircularProgressIndicator(), - ), - ], - ), - ), - ), - // 如果不是占位的消息,则正常显示 - if (message.isPlaceholder != true) - Card( - elevation: 3, - child: Padding( - padding: EdgeInsets.all(5.sp), + Card( + elevation: 3, + child: Padding( + padding: EdgeInsets.all(5.sp), - /// 这里考虑根据 格式等格式化显示内容 - child: SingleChildScrollView( - child: MarkdownBody( - data: message.content, - selectable: true, - // 设置Markdown文本全局样式 - styleSheet: MarkdownStyleSheet( - // 普通段落文本颜色(假定用户输入就是普通段落文本) - p: TextStyle(color: textColor), - // ... 其他级别的标题样式 - // 可以继续添加更多Markdown元素的样式 + /// 这里考虑根据 格式等格式化显示内容 + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + mainAxisSize: MainAxisSize.min, + children: [ + // 显示对话正文内容 + MarkdownBody( + data: message.content, + selectable: true, + styleSheet: MarkdownStyleSheet( + p: TextStyle(color: textColor), + ), ), - ), - // Text( - // message.text, - // // 根据来源设置不同颜色 - // style: TextStyle(color: textColor), - // ), + // 如果是流式加载中,显示一个加载圈 + if (message.role != "user" && isBotThinking == true) + SizedBox( + width: 16.sp, + height: 16.sp, + child: CircularProgressIndicator(strokeWidth: 2.sp), + ), + ], ), ), ), + ), ], ), ), diff --git a/lib/views/dietary/records/index.dart b/lib/views/dietary/records/index.dart index 30f36b6..8f8b066 100644 --- a/lib/views/dietary/records/index.dart +++ b/lib/views/dietary/records/index.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -99,6 +97,7 @@ class _DietaryRecordsState extends State { .where((e) => e.dayOfWeek == DateTime.now().weekday.toString()) .toList(); + if (!mounted) return; setState(() { // 如果有对应的星期几的摄入目标,则使用该值 if (dailyGoal.isNotEmpty) { @@ -124,6 +123,7 @@ class _DietaryRecordsState extends State { // 查询餐次照片数量 _queryMealPhotoNums(); + if (!mounted) return; setState(() { dfiwfsList = temp; @@ -147,6 +147,7 @@ class _DietaryRecordsState extends State { mealCategory: mealEnLabel, ); + if (!mounted) return; setState(() { // 2023-12-31 需要先清空之前的,否则即便没有也会展示旧的数据 // mealPhotoNums = { @@ -379,44 +380,43 @@ class _DietaryRecordsState extends State { // title: Text('其他选项功能区(暂留)'), // ), // ), + SizedBox(height: 20.sp), ], ), ), ), ], ), - floatingActionButton: FloatingActionButton( - onPressed: () { - if (dfiwfsList.isEmpty) { - commonExceptionDialog( - context, - "提示", - "本日暂无食物摄入信息,无须AI助手给出分析建议。", - ); - } else { - Navigator.of(context).push( - MaterialPageRoute( - builder: (context) => - OneChatScreen(intakeInfo: buildSuggestionString()), - ), - ); - } - }, - tooltip: box.read('language') == "en" ? "AI Assistant" : 'AI分析对话助手', - child: const Icon(Icons.chat), - // child: Text( - // box.read('language') == "en" ? "AIA" : "AI\n助手", - // style: TextStyle(fontSize: 12.sp), - // textAlign: TextAlign.center, - // ), - ), + floatingActionButton: dfiwfsList.isEmpty + ? null + : FloatingActionButton( + onPressed: () { + if (dfiwfsList.isEmpty) { + commonExceptionDialog( + context, + "提示", + "本日暂无食物摄入信息,无须AI助手给出分析建议。", + ); + } else { + Navigator.of(context).push( + MaterialPageRoute( + builder: (context) => + OneChatScreen(intakeInfo: buildSuggestionString()), + ), + ); + } + }, + tooltip: + box.read('language') == "en" ? "AI Assistant" : 'AI分析对话助手', + child: const Icon(Icons.chat), + ), ); } /// 最上面的每日概述卡片 Widget buildDailyOverviewCard() { return Card( - elevation: 4, + elevation: 5.sp, color: Theme.of(context).secondaryHeaderColor, child: GestureDetector( onTap: () { @@ -576,7 +576,7 @@ class _DietaryRecordsState extends State { bool showExpansionTile = dfiwfsMealItems.isNotEmpty; return Card( - elevation: 5, // 设置阴影的程度 + elevation: 2.sp, // 设置阴影的程度 shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.sp), // 设置圆角的大小 ), @@ -963,9 +963,9 @@ class _DietaryRecordsState extends State { /// 绘制营养素占比卡片区域 buildNutrientProportionCard() { return Card( - elevation: 10, + elevation: 2.sp, child: Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: SizedBox( height: 450.sp, child: Column( @@ -1037,7 +1037,7 @@ class _DietaryRecordsState extends State { padding: EdgeInsets.symmetric(vertical: 4.sp), child: Row( children: [ - Container(width: 14, height: 14, color: data.color), + Container(width: 14.sp, height: 14.sp, color: data.color), SizedBox(width: 8.sp), // 将百分比数据添加到标题后面 Expanded( @@ -1085,7 +1085,7 @@ class _DietaryRecordsState extends State { padding: EdgeInsets.symmetric(vertical: 4.sp), child: Row( children: [ - Container(width: 14, height: 14, color: data.color), + Container(width: 14.sp, height: 14.sp, color: data.color), SizedBox(width: 8.sp), // 将百分比数据添加到标题后面 Expanded( diff --git a/lib/views/dietary/records/report_calendar_summary.dart b/lib/views/dietary/records/report_calendar_summary.dart index 7229bd4..889d454 100644 --- a/lib/views/dietary/records/report_calendar_summary.dart +++ b/lib/views/dietary/records/report_calendar_summary.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:intl/intl.dart'; @@ -74,6 +72,7 @@ class _ReportCalendarSummaryState extends State { withDetail: true, ) as List); + if (!mounted) return; setState(() { dfiwfsList = temp; @@ -96,7 +95,7 @@ class _ReportCalendarSummaryState extends State { // 当某一天被选中,获取该天的数据 void _onDaySelected(DateTime selectedDay, DateTime focusedDay) { - print("某天被选中--------$selectedDay $focusedDay"); + debugPrint("某天被选中--------$selectedDay $focusedDay"); if (!isSameDay(_selectedDay, selectedDay)) { setState(() { @@ -126,11 +125,14 @@ class _ReportCalendarSummaryState extends State { SizedBox(height: 8.sp), /// 总计本月摄入量和平均到每天的摄入量 - _buildDailyAverageCount(), + SizedBox( + width: 1.sw, + child: _buildDailyAverageCount(), + ), SizedBox(height: 8.sp), - /// 日历某些操作改变后,显示对应的手记内容列表 + /// 日历某些操作改变后,显示选中那日的摄入信息 ValueListenableBuilder>( valueListenable: _selectedItems, // 当_selectedEvents有变化时,这个builder才会被调用 @@ -140,15 +142,19 @@ class _ReportCalendarSummaryState extends State { return Container(); } - return Card( - elevation: 5, - child: _buildSelectedDayListView( - value, - formatIntakeItemListForMarker(context, value), + return SizedBox( + width: 1.sw, + child: Card( + elevation: 2.sp, + child: _buildSelectedDayListView( + value, + formatIntakeItemListForMarker(context, value), + ), ), ); }, ), + SizedBox(height: 20.sp), ], ), ), @@ -261,6 +267,7 @@ class _ReportCalendarSummaryState extends State { var totalCho = tempList.firstWhere((e) => e.label == "cho").value; return Card( + elevation: 2.sp, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, @@ -364,13 +371,20 @@ class _ReportCalendarSummaryState extends State { scrollDirection: Axis.horizontal, child: _buildSummaryTable(formatList), ), - Text( - CusAL.of(context).dietaryCalendarLabels('2'), - style: TextStyle( - fontSize: CusFontSizes.flagMedium, - fontWeight: FontWeight.bold, - color: Colors.green, - ), + + /// 详细摄入输入每日摄入的子项,不应该是一样的标题样式,要小一号 + Row( + children: [ + SizedBox(width: 20.sp), + Text( + CusAL.of(context).dietaryCalendarLabels('2'), + style: TextStyle( + fontSize: CusFontSizes.flagSmall, + fontWeight: FontWeight.bold, + color: Colors.green, + ), + ) + ], ), ListView.builder( shrinkWrap: true, @@ -381,37 +395,19 @@ class _ReportCalendarSummaryState extends State { var intakeSize = value[index].dailyFoodItem.foodIntakeSize; var servingUnit = value[index].servingInfo.servingUnit; - // return Container( - // margin: const EdgeInsets.symmetric( - // horizontal: 12.0, - // vertical: 4.0, - // ), - // decoration: BoxDecoration( - // border: Border.all(), - // borderRadius: BorderRadius.circular(12.sp), - // ), - // child: ListTile( - // title: Text( - // '${CusAL.of(context).foodName}: ${food.product} (${food.brand})', - // style: TextStyle(fontSize: CusFontSizes.itemSubTitle), - // ), - // subtitle: Text( - // '${CusAL.of(context).eatableSize}: ${cusDoubleTryToIntString(intakeSize)} x $servingUnit', - // style: TextStyle(fontSize: CusFontSizes.itemSubTitle), - // ), - // ), - // ); - return Card( - elevation: 5.sp, - child: ListTile( - title: Text( - '${CusAL.of(context).foodName}: ${food.product} (${food.brand})', - style: TextStyle(fontSize: CusFontSizes.itemSubTitle), - ), - subtitle: Text( - '${CusAL.of(context).eatableSize}: ${cusDoubleTryToIntString(intakeSize)} x $servingUnit', - style: TextStyle(fontSize: CusFontSizes.itemSubTitle), - ), + return ListTile( + dense: true, + // 自定义下划线当个分割线 + shape: Border( + bottom: BorderSide(color: Colors.grey[300]!, width: 1.sp), + ), + title: Text( + '${CusAL.of(context).foodName}: ${food.product} (${food.brand})', + style: TextStyle(fontSize: CusFontSizes.itemSubTitle), + ), + subtitle: Text( + '${CusAL.of(context).eatableSize}: ${cusDoubleTryToIntString(intakeSize)} x $servingUnit', + style: TextStyle(fontSize: CusFontSizes.itemSubTitle), ), ); }, diff --git a/lib/views/dietary/records/save_meal_photo.dart b/lib/views/dietary/records/save_meal_photo.dart index 52a569a..ccff262 100644 --- a/lib/views/dietary/records/save_meal_photo.dart +++ b/lib/views/dietary/records/save_meal_photo.dart @@ -42,11 +42,17 @@ class _SaveMealPhotosState extends State { final _formKey = GlobalKey(); + // 传入的餐次条目不会改变,这个变量只是为了减少 widget.mealItems 的使用 late List items; - // 默认显示的图片列表 + // 2024-12-02 因为传入餐次的饮食记录和图片,在这里虽然不能改变餐次条目,但可以改变图片 + // 如果改过图片,再次修改,没有使用更新后的餐次记录,还是传入时的记录,数据就会出错 + late MealPhoto? inputPhotos; + + // 默认显示的图片列表(输入框展示的) List? initImages; + // 用于显示的图片 地址(和上面两者类型不一样) List imagesUrls = []; bool isLoading = false; @@ -57,20 +63,50 @@ class _SaveMealPhotosState extends State { @override void initState() { super.initState(); - setState(() { - items = widget.mealItems; - // 如果有照片,则先显示照片 - if (widget.mealPhoto != null) { - String paths = widget.mealPhoto!.photos; + items = widget.mealItems; + inputPhotos = widget.mealPhoto; + + getImageByPhotos(); + } + + getImageByPhotos() { + // 如果有照片,则先显示照片 + if (inputPhotos != null) { + String paths = inputPhotos!.photos; + + initImages = convertStringToPlatformFiles(paths); + // 先排除照片路径是空字符串,再分割 + if (paths.trim().isNotEmpty) { + imagesUrls = paths.trim().split(","); + } + } else { + initImages = []; + imagesUrls = []; + } + } + + // 2024-12-02 因为存在删除餐次图片的情况,所以删除之后再新增,图片编号就变了。 + // 删除之后、新增了,再修改,就要用新的编号了 + rebuildMealPhoto() async { + List temp = await _dietaryHelper.queryMealPhotoList( + CacheUser.userId, // userId是必传的 + startDate: widget.date, + endDate: widget.date, + mealCategory: widget.mealtime.enLabel, + ); - initImages = convertStringToPlatformFiles(paths); - // 先排除照片路径是空字符串,再分割 - if (paths.trim().isNotEmpty) { - imagesUrls = paths.trim().split(","); + if (!mounted) return; + setState(() { + inputPhotos = null; + for (var e in temp) { + if (e.mealCategory == widget.mealtime.enLabel) { + inputPhotos = e; } } }); + + getImageByPhotos(); } @override @@ -164,8 +200,8 @@ class _SaveMealPhotosState extends State { try { // 如果有照片,则是修改 - if (widget.mealPhoto != null) { - tempMp.mealPhotoId = widget.mealPhoto!.mealPhotoId!; + if (inputPhotos != null) { + tempMp.mealPhotoId = inputPhotos!.mealPhotoId!; // 如果有传照片,但现在没有照片了,就是删除该条记录;否则就是修改 if (photos.trim().isEmpty || photos.split(",").isEmpty) { @@ -180,13 +216,6 @@ class _SaveMealPhotosState extends State { await _dietaryHelper.insertMealPhoto(tempMp); } - if (!mounted) return; - setState(() { - isLoading = false; - isEditing = !isEditing; - imagesUrls = - photos.trim().isEmpty ? [] : photos.split(","); - }); // 父组件应该重新加载(传参到父组件中重新加载) // 强行返回前一页为了加载新数据,不返回的话这里轮播图是删除修改之前的 // Navigator.pop(context, true); @@ -198,14 +227,14 @@ class _SaveMealPhotosState extends State { CusAL.of(context).exceptionWarningTitle, e.toString(), ); - + } finally { setState(() { isLoading = false; isEditing = !isEditing; - imagesUrls = - photos.trim().isEmpty ? [] : photos.split(","); + + // 2024-12-02 新增或删除了餐次图片后,更新当前的餐次相关图片信息 + rebuildMealPhoto(); }); - return; } } }, @@ -218,7 +247,7 @@ class _SaveMealPhotosState extends State { SizedBox(height: 10.sp), if (imagesUrls.isNotEmpty && !isEditing) buildImageCarouselSlider(imagesUrls), - const SizedBox(height: 10), + SizedBox(height: 10.sp), // 上传活动示例图片(静态图或者gif) if (isEditing) FormBuilder( @@ -226,7 +255,7 @@ class _SaveMealPhotosState extends State { child: Column( children: [ Padding( - padding: EdgeInsets.all(20.sp), + padding: EdgeInsets.all(5.sp), child: FormBuilderFilePicker( name: 'images', initialValue: initImages, @@ -345,6 +374,7 @@ void handleImageAnalysis(BuildContext context, List imagesUrls) { ); }, ).then((value) { + if (!context.mounted) return; navigateToOneChatScreen(context, imagesUrls.first); }); } else { diff --git a/lib/views/dietary/reports/export/report_pdf_export.dart b/lib/views/dietary/reports/export/report_pdf_export.dart index a660488..c66af2f 100644 --- a/lib/views/dietary/reports/export/report_pdf_export.dart +++ b/lib/views/dietary/reports/export/report_pdf_export.dart @@ -128,7 +128,7 @@ _buildPdfPage( return pw.Page( // 两者不能同时存在 pageTheme: pw.PageTheme( - margin: pw.EdgeInsets.all(10.sp), + margin: pw.EdgeInsets.all(5.sp), ), // 页面展示横向显示 // pageFormat: PdfPageFormat.a4.landscape, @@ -272,8 +272,8 @@ _buildMealSubBodyTable( var tempSugar = 0.0; return pw.Table( - // 字数据可以不显示边框,更方便看? - // border: pw.TableBorder.all(color: PdfColors.black), + // 子数据可以不显示边框,更方便看? + border: pw.TableBorder.all(color: PdfColors.black), children: [ ...mealData.map((e) { var food = e.food; diff --git a/lib/views/dietary/reports/export/report_pdf_viewer.dart b/lib/views/dietary/reports/export/report_pdf_viewer.dart index 36e0a38..9e55df0 100644 --- a/lib/views/dietary/reports/export/report_pdf_viewer.dart +++ b/lib/views/dietary/reports/export/report_pdf_viewer.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:pdf/pdf.dart'; import 'package:printing/printing.dart'; @@ -62,11 +60,9 @@ class _ReportPdfViewerState extends State { withDetail: true, ) as List); - print("导出pdf查询到的饮食数据数量${temp.length}"); - + if (!mounted) return; setState(() { dfiwfsList = temp; - isLoading = false; }); } @@ -88,6 +84,9 @@ class _ReportPdfViewerState extends State { widget.endDate.split(" ")[0], lang: box.read('language'), ), + pdfFileName: box.read('language') == "en" + ? "DietaryLogExport_${DateTime.now().millisecondsSinceEpoch}" + : "饮食日志导出_${DateTime.now().millisecondsSinceEpoch}", ), ); } diff --git a/lib/views/dietary/reports/index.dart b/lib/views/dietary/reports/index.dart index 1bd316b..d0a77c8 100644 --- a/lib/views/dietary/reports/index.dart +++ b/lib/views/dietary/reports/index.dart @@ -53,9 +53,7 @@ class _DietaryReportsState extends State { void initState() { super.initState(); - setState(() { - _queryDailyFoodItemList(); - }); + _queryDailyFoodItemList(); } /// 通过下拉按钮获取统计的范围日期 @@ -127,6 +125,7 @@ class _DietaryReportsState extends State { .where((e) => e.dayOfWeek == DateTime.now().weekday.toString()) .toList(); + if (!mounted) return; setState(() { // 如果有对应的星期几的摄入目标,则使用该值 if (dailyGoal.isNotEmpty) { @@ -290,6 +289,8 @@ class _DietaryReportsState extends State { /// 食物摄入条目统计卡片(类型为name表示食物摄入次数) _buildDataTableCard(dfiwfsList, CusChartType.calory), + + SizedBox(height: 20.sp), ], ); } @@ -362,6 +363,8 @@ class _DietaryReportsState extends State { /// 食物摄入宏量统计卡片 _buildDataTableCard(dfiwfsList, CusChartType.macro), + + SizedBox(height: 20.sp), ], ); } @@ -383,24 +386,27 @@ class _DietaryReportsState extends State { } } - return DataTable( - columns: [ - DataColumn( - label: Text( - CusAL.of(context).dietaryReportTabs('2'), - style: const TextStyle(fontWeight: FontWeight.bold), + return Card( + elevation: 5.sp, + child: DataTable( + columns: [ + DataColumn( + label: Text( + CusAL.of(context).dietaryReportTabs('2'), + style: const TextStyle(fontWeight: FontWeight.bold), + ), ), - ), - DataColumn( - label: Text( - CusAL.of(context).eatableSize, - style: const TextStyle(fontWeight: FontWeight.bold), + DataColumn( + label: Text( + CusAL.of(context).eatableSize, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + numeric: true, ), - numeric: true, - ), - // DataColumn(label: Text('目标量'), numeric: true), - ], - rows: rows, + // DataColumn(label: Text('目标量'), numeric: true), + ], + rows: rows, + ), ); } @@ -428,7 +434,7 @@ class _DietaryReportsState extends State { /// 绘制卡路里摄入或宏量素摄入的【饼图卡片】(包含图例legend和图chart两部分) _buildPieChartCard(FoodNutrientTotals fntVO, CusChartType type) { return Card( - elevation: 10.sp, + elevation: 5.sp, child: SizedBox( height: 200.sp, child: Column( @@ -661,7 +667,7 @@ class _DietaryReportsState extends State { // 绘制整体柱状图表 return Card( - elevation: 10, + elevation: 5.sp, child: SizedBox( child: Column( children: [ @@ -787,7 +793,7 @@ class _DietaryReportsState extends State { )); return Card( - elevation: 10, + elevation: 5.sp, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -805,7 +811,7 @@ class _DietaryReportsState extends State { child: FittedBox( // 使用FittedBox来自动调整宽度 child: DataTable( - columnSpacing: 10.0, + columnSpacing: 10.sp, columns: type == CusChartType.calory ? [ DataColumn(label: Text(CusAL.of(context).foodName)), diff --git a/lib/views/dietary/reports/week_intake_bar.dart b/lib/views/dietary/reports/week_intake_bar.dart index acbc860..e7d7fa1 100644 --- a/lib/views/dietary/reports/week_intake_bar.dart +++ b/lib/views/dietary/reports/week_intake_bar.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; diff --git a/lib/views/me/backup_and_restore/index.dart b/lib/views/me/backup_and_restore/index.dart index de2738d..2a2ad22 100644 --- a/lib/views/me/backup_and_restore/index.dart +++ b/lib/views/me/backup_and_restore/index.dart @@ -1,8 +1,8 @@ -// ignore_for_file: avoid_print - import 'dart:convert'; import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:free_fitness/models/training_state.dart'; import 'package:path/path.dart' as p; import 'package:archive/archive_io.dart'; @@ -25,6 +25,9 @@ import '../../../models/user_state.dart'; /// /// 2023-12-26 备份恢复还可以优化,就暂时不做 /// +/// 2024-11-26 备份文件前缀 +const bakPrefix = "FreeFitness-FullBackup_"; + class BackupAndRestore extends StatefulWidget { const BackupAndRestore({super.key}); @@ -54,6 +57,8 @@ class _BackupAndRestoreState extends State { // 用户选择指定文件夹 String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); // 如果有选中文件夹,执行导出数据库的json文件,并添加到压缩档。 + + if (!mounted) return; if (selectedDirectory != null) { if (isLoading) return; @@ -67,8 +72,7 @@ class _BackupAndRestoreState extends State { var tempZipDir = await Directory(p.join(appDocDir.path, "temp_zip")).create(); // zip 文件的名称 - String zipName = - "free-fitness-full-bak-${DateTime.now().millisecondsSinceEpoch}.zip"; + String zipName = "$bakPrefix${DateTime.now().millisecondsSinceEpoch}.zip"; // 执行讲db数据导出到临时json路径和构建临时zip文件(???应该有错误检查) await backupDbData(zipName, tempZipDir.path); @@ -84,7 +88,9 @@ class _BackupAndRestoreState extends State { // 把文件从缓存的位置放到用户选择的位置 sourceFile.copySync(p.join(selectedDirectory, zipName)); - print('文件已成功复制到:${p.join(selectedDirectory, zipName)}'); + if (kDebugMode) { + print('文件已成功复制到:${p.join(selectedDirectory, zipName)}'); + } // 删除临时zip文件 if (sourceFile.existsSync()) { @@ -92,18 +98,20 @@ class _BackupAndRestoreState extends State { sourceFile.deleteSync(); } + if (!mounted) return; setState(() { isLoading = false; }); - if (!mounted) return; showSnackMessage( context, CusAL.of(context).bakSuccessNote(selectedDirectory), backgroundColor: Colors.green, ); } else { - print('保存操作已取消'); + if (kDebugMode) { + print('保存操作已取消'); + } return; } } @@ -173,25 +181,34 @@ class _BackupAndRestoreState extends State { outFile = await outFile.create(recursive: true); await outFile.writeAsBytes(file.content); - print("解压时的outFile$outFile"); + if (kDebugMode) { + print("解压时的outFile$outFile"); + } } else { Directory dir = Directory(filename); await dir.create(recursive: true); } } - print('解压完成'); + if (kDebugMode) { + print('解压完成'); + } return tempPath; } catch (e) { - print('解压失败: $e'); + if (kDebugMode) { + print('解压失败: $e'); + } throw Exception(e); } } // 2023-12-11 恢复的话,简单需要导出时同名的zip压缩包 Future restoreDataFromBackup() async { - FilePickerResult? result = - await FilePicker.platform.pickFiles(allowMultiple: false); + FilePickerResult? result = await FilePicker.platform.pickFiles( + allowMultiple: false, + type: FileType.custom, + allowedExtensions: ['zip', 'ZIP'], + ); if (result != null) { if (isLoading) return; @@ -202,14 +219,13 @@ class _BackupAndRestoreState extends State { // 不允许多选,理论就是第一个文件,且不为空 File file = File(result.files.first.path!); - print("获取的上传zip文件路径${p.basename(file.path)}"); - print("获取的上传zip文件路径 result $result"); + if (kDebugMode) { + print("获取的上传zip文件路径${p.basename(file.path)}"); + print("获取的上传zip文件路径 result $result"); + } // 这个判断虽然不准确,但先这样 - if (p - .basename(file.path) - .toLowerCase() - .startsWith('free-fitness-full-bak-') && + if (p.basename(file.path).startsWith(bakPrefix) && p.basename(file.path).toLowerCase().endsWith('.zip')) { try { // 等待解压完成 @@ -221,7 +237,9 @@ class _BackupAndRestoreState extends State { .map((entity) => entity as File) .toList(); - print("jsonFiles---$jsonFiles"); + if (kDebugMode) { + print("jsonFiles---$jsonFiles"); + } /// 删除前可以先备份一下到临时文件,避免出错后完成无法使用(最多确认恢复成功之后再删除就好了) @@ -232,7 +250,7 @@ class _BackupAndRestoreState extends State { await Directory(p.join(appDocDir.path, "temp_auto_zip")).create(); // zip 文件的名称 String zipName = - "free-fitness-full-bak-${DateTime.now().millisecondsSinceEpoch}.zip"; + "$bakPrefix${DateTime.now().millisecondsSinceEpoch}.zip"; // 执行讲db数据导出到临时json路径和构建临时zip文件(???应该有错误检查) await backupDbData(zipName, tempZipDir.path); @@ -253,11 +271,11 @@ class _BackupAndRestoreState extends State { sourceFile.deleteSync(); } + if (!mounted) return; setState(() { isLoading = false; }); - if (!mounted) return; showSnackMessage( context, CusAL.of(context).resSuccessNote, @@ -266,7 +284,6 @@ class _BackupAndRestoreState extends State { } catch (e) { // 弹出报错提示框 if (!mounted) return; - commonExceptionDialog( context, CusAL.of(context).importJsonError, @@ -279,9 +296,11 @@ class _BackupAndRestoreState extends State { // 中止操作 return; } + } else { + EasyLoading.showInfo("Not a backup file exported from the app"); } // 这个判断不准确,但先这样 - + if (!mounted) return; setState(() { isLoading = false; }); @@ -295,7 +314,9 @@ class _BackupAndRestoreState extends State { _saveJsonFileDataToDb(List jsonFiles) async { // 解压之后获取到所有的json文件,逐个添加到数据库,会先清空数据库的数据 for (File file in jsonFiles) { - print("_saveJsonFileDataToDb---${file.path}"); + if (kDebugMode) { + print("_saveJsonFileDataToDb---${file.path}"); + } String jsonData = await file.readAsString(); // db导出时json文件是列表 diff --git a/lib/views/me/index.dart b/lib/views/me/index.dart index 1090712..27acf66 100644 --- a/lib/views/me/index.dart +++ b/lib/views/me/index.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'dart:io'; import 'package:flutter/material.dart'; @@ -12,7 +10,6 @@ import '../../common/utils/db_user_helper.dart'; import '../../layout/themes/cus_font_size.dart'; import '../../models/cus_app_localizations.dart'; import '../../models/user_state.dart'; -// import '_feature_mock_data/index.dart'; import 'backup_and_restore/index.dart'; import 'intake_goals/intake_target.dart'; import 'more_settings/index.dart'; @@ -49,13 +46,11 @@ class _UserAndSettingsState extends State { void initState() { super.initState(); - setState(() { - currentUserId = CacheUser.userId; - }); - + currentUserId = CacheUser.userId; _queryLoginedUserInfo(); } + // 查询登录用户的信息 _queryLoginedUserInfo() async { if (isLoading) return; setState(() { @@ -65,6 +60,7 @@ class _UserAndSettingsState extends State { // 查询登录用户的信息一定会有的 var tempUser = (await _userHelper.queryUser(userId: currentUserId))!; + if (!mounted) return; setState(() { userInfo = tempUser; if (tempUser.avatar != null) { @@ -167,6 +163,7 @@ class _UserAndSettingsState extends State { Future _pickImage(ImageSource source) async { final picker = ImagePicker(); final pickedFile = await picker.pickImage(source: source); + if (!mounted) return; if (pickedFile != null) { setState(() { _avatarPath = pickedFile.path; @@ -180,38 +177,12 @@ class _UserAndSettingsState extends State { @override Widget build(BuildContext context) { - // 计算屏幕剩余的高度 - // 设备屏幕的总高度 - // - 屏幕顶部的安全区域高度,即状态栏的高度 - // - 屏幕底部的安全区域高度,即导航栏的高度或者虚拟按键的高度 - // - 应用程序顶部的工具栏(如 AppBar)的高度 - // - 应用程序底部的导航栏的高度 - // - 组件的边框间隔(不一定就是2) - double screenBodyHeight = MediaQuery.of(context).size.height - - MediaQuery.of(context).padding.top - - MediaQuery.of(context).padding.bottom - - kToolbarHeight - - kBottomNavigationBarHeight; - - print("screenBodyHeight--------$screenBodyHeight"); - return Scaffold( appBar: AppBar( title: Text( CusAL.of(context).moduleTitles('3'), ), actions: [ - // IconButton( - // onPressed: () { - // Navigator.push( - // context, - // MaterialPageRoute( - // builder: (context) => const FeatureMockDemo(), - // ), - // ); - // }, - // icon: const Icon(Icons.bug_report), - // ), // 切换用户(切换后缓存的用户编号也得修改) IconButton( onPressed: _switchUser, @@ -233,31 +204,21 @@ class _UserAndSettingsState extends State { ), body: isLoading ? buildLoader(isLoading) - : ListView( + : Column( + // 从listview改为column后需要纵向主轴为stretch切换头像等图标才不会跑偏 + crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - /// 用户基本信息展示区域(固定高度10+120+120=250) + /// 用户基本信息展示区域(固定高度) ..._buildBaseUserInfoArea(userInfo), - /// 功能区,参看别的app大概留几个 - /// 功能区的占位就是除去状态栏、标题、底部按钮、头像区域个人信息外的高度进行等分 - /// 底部还预留20sp - // 基本信息和体重趋势 - SizedBox( - height: (screenBodyHeight - 250 - 20) / 3, - child: _buildInfoAndWeightChangeRow(), - ), + /// 用户基本信息和体重趋势按钮 + Expanded(child: _buildInfoAndWeightChangeRow()), - // 摄入目标和运动设置 - SizedBox( - height: (screenBodyHeight - 250 - 20) / 3, - child: _buildIntakeGoalAndRestTimeRow(), - ), + /// 摄入目标和运动设置按钮 + Expanded(child: _buildIntakeGoalAndRestTimeRow()), - // 备份还原和更多设置 - SizedBox( - height: (screenBodyHeight - 250 - 20) / 3, - child: _buildBakAndRestoreAndMoreSettingRow(), - ), + /// 备份还原和更多设置按钮 + Expanded(child: _buildBakAndRestoreAndMoreSettingRow()), ], ), ); @@ -267,16 +228,19 @@ class _UserAndSettingsState extends State { _buildBaseUserInfoArea(User userInfo) { return [ SizedBox(height: 10.sp), + + /// 头像相关 Stack( alignment: Alignment.center, children: [ + /// 头像图片 // 没有修改头像,就用默认的 if (_avatarPath.isEmpty) CircleAvatar( maxRadius: 60.sp, backgroundColor: Colors.transparent, backgroundImage: const AssetImage(defaultAvatarImageUrl), - // y圆形头像的边框线 + // 圆形头像的边框线 child: Container( decoration: BoxDecoration( shape: BoxShape.circle, @@ -317,6 +281,8 @@ class _UserAndSettingsState extends State { backgroundImage: FileImage(File(_avatarPath)), ), ), + + /// 性别图标 Positioned( top: 90.sp, right: 0.5.sw - 70.sp, @@ -333,11 +299,13 @@ class _UserAndSettingsState extends State { color: Colors.green, ) : Icon( - Icons.circle_outlined, + Icons.bolt, size: CusIconSizes.iconNormal, color: Theme.of(context).disabledColor, ), ), + + /// 修改头像按钮 Positioned( top: 0.sp, right: 0.sp, @@ -382,8 +350,10 @@ class _UserAndSettingsState extends State { ), ], ), + + /// 个人简介 SizedBox( - height: 120.sp, + height: 130.sp, child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, @@ -411,17 +381,22 @@ class _UserAndSettingsState extends State { ), // 用户简介 description - Padding( - padding: EdgeInsets.symmetric(horizontal: 18.sp), - child: Text( - "${userInfo.description ?? 'no description'} ", - textAlign: TextAlign.center, - softWrap: true, - maxLines: 3, - overflow: TextOverflow.ellipsis, - style: TextStyle(fontSize: CusFontSizes.pageContent), + Expanded( + child: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.symmetric(horizontal: 18.sp), + child: Text( + "${userInfo.description ?? 'no description'} ", + textAlign: TextAlign.center, + // softWrap: true, + // maxLines: 3, + // overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: CusFontSizes.pageContent), + ), + ), ), ), + SizedBox(height: 10.sp), ], ), ), @@ -436,14 +411,12 @@ class _UserAndSettingsState extends State { leadingIcon: Icons.account_circle_outlined, title: CusAL.of(context).settingLabels('0'), onTap: () { - // 处理相应的点击事件 Navigator.push( context, MaterialPageRoute( builder: (context) => const UserInfo(), ), ).then((value) { - // 确认新增成功后重新加载当前日期的条目数据 _queryLoginedUserInfo(); }); }, @@ -454,14 +427,12 @@ class _UserAndSettingsState extends State { leadingIcon: Icons.table_chart_outlined, title: CusAL.of(context).settingLabels('1'), onTap: () { - // 处理相应的点击事件 Navigator.push( context, MaterialPageRoute( builder: (context) => WeightChangeRecord(userInfo: userInfo), ), ).then((value) { - // 确认新增成功后重新加载当前日期的条目数据 if (value != null && value == true) { _queryLoginedUserInfo(); } @@ -481,14 +452,12 @@ class _UserAndSettingsState extends State { leadingIcon: Icons.flag_circle_outlined, title: CusAL.of(context).settingLabels('2'), onTap: () { - // 处理相应的点击事件 Navigator.push( context, MaterialPageRoute( builder: (context) => IntakeTargetPage(userInfo: userInfo), ), ).then((value) { - // 确认新增成功后重新加载当前日期的条目数据 _queryLoginedUserInfo(); }); }, @@ -499,14 +468,12 @@ class _UserAndSettingsState extends State { leadingIcon: Icons.run_circle_outlined, title: CusAL.of(context).settingLabels('3'), onTap: () { - // 处理相应的点击事件 Navigator.push( context, MaterialPageRoute( builder: (context) => TrainingSetting(userInfo: userInfo), ), ).then((value) { - // 确认新增成功后重新加载当前日期的条目数据 _queryLoginedUserInfo(); }); }, @@ -524,8 +491,6 @@ class _UserAndSettingsState extends State { leadingIcon: Icons.backup_outlined, title: CusAL.of(context).settingLabels('4'), onTap: () { - // 处理相应的点击事件 - Navigator.push( context, MaterialPageRoute( @@ -540,8 +505,6 @@ class _UserAndSettingsState extends State { leadingIcon: Icons.more_horiz_outlined, title: CusAL.of(context).settingLabels('5'), onTap: () { - // 处理相应的点击事件 - Navigator.push( context, MaterialPageRoute( @@ -580,14 +543,15 @@ class NewCusSettingCard extends StatelessWidget { @override Widget build(BuildContext context) { - return Card( - elevation: 5, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(10.sp), - ), - child: Container( - height: 150.sp, - padding: EdgeInsets.all(2.sp), + // 这里套一层容器宽高过小会生效不好看,但过大会在使用处的expanded限制住 + return InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(10.sp), + child: Card( + elevation: 2.sp, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10.sp), + ), child: Center( child: ListTile( leading: Icon(leadingIcon), @@ -599,7 +563,6 @@ class NewCusSettingCard extends StatelessWidget { color: Theme.of(context).primaryColor, ), ), - onTap: onTap, ), ), ), diff --git a/lib/views/me/intake_goals/intake_target.dart b/lib/views/me/intake_goals/intake_target.dart index 96fb045..6028e36 100644 --- a/lib/views/me/intake_goals/intake_target.dart +++ b/lib/views/me/intake_goals/intake_target.dart @@ -31,7 +31,7 @@ class _IntakeTargetPageState extends State { // 整体卡路里宏量素表单全局key,用于验证表单 final _macrosFormKey = GlobalKey(); Map initialMacrosMap = {}; - // 能量卡里里等效千焦数 + // 能量卡路里等效千焦数 String equivalentKJdata = ''; // 是否在修改每日卡路里和宏量素 @@ -61,19 +61,18 @@ class _IntakeTargetPageState extends State { // 初始化整体卡路里和营养素目标 user = widget.userInfo; - setState(() { - // 给整体营养素目标设置初始值 - // (注意key要和表单中name一致。因为是两个不同的表单,所以和每日营养素目标表单同名了也不影响) - initialMacrosMap = { - "calory": (user.rdaGoal ?? 0).toString(), - "carbs": cusDoubleTryToIntString(user.choGoal ?? 0), - "fat": cusDoubleTryToIntString(user.fatGoal ?? 0), - "protein": cusDoubleTryToIntString(user.proteinGoal ?? 0), - }; - equivalentKJdata = caloryToKjStr(user.rdaGoal ?? 0); - _macrosFormKey.currentState?.patchValue(initialMacrosMap); - }); + // 给整体营养素目标设置初始值 + // (注意key要和表单中name一致。因为是两个不同的表单,所以和每日营养素目标表单同名了也不影响) + initialMacrosMap = { + "calory": (user.rdaGoal ?? 0).toString(), + "carbs": cusDoubleTryToIntString(user.choGoal ?? 0), + "fat": cusDoubleTryToIntString(user.fatGoal ?? 0), + "protein": cusDoubleTryToIntString(user.proteinGoal ?? 0), + }; + + equivalentKJdata = caloryToKjStr(user.rdaGoal ?? 0); + _macrosFormKey.currentState?.patchValue(initialMacrosMap); // 格式化处理每日卡路里和营养素目标 formatDailyIntakeMap(); @@ -113,6 +112,7 @@ class _IntakeTargetPageState extends State { ); } + if (!mounted) return; setState(() { intakeData = tempIntakes; }); @@ -161,9 +161,9 @@ class _IntakeTargetPageState extends State { buildWeekMacrosBarChartCard() { return Card( - elevation: 10, + elevation: 5.sp, child: Padding( - padding: EdgeInsets.all(16.sp), + padding: EdgeInsets.all(5.sp), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, @@ -217,9 +217,9 @@ class _IntakeTargetPageState extends State { /// 构建修改整体宏量素目标的卡片 buildEditMacrosCard() { return Card( - elevation: 10, + elevation: 5.sp, child: Padding( - padding: EdgeInsets.all(16.sp), + padding: EdgeInsets.all(5.sp), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, @@ -242,7 +242,7 @@ class _IntakeTargetPageState extends State { Expanded( flex: 2, child: TextButton( - onPressed: () async { + onPressed: () { setState(() { _isEditing = !_isEditing; }); @@ -272,6 +272,7 @@ class _IntakeTargetPageState extends State { await _userHelper.updateUser(user); // 平均营养素目标修改后,也更新下方图表的值 + if (!mounted) return; setState(() { formatDailyIntakeMap(); }); @@ -387,9 +388,9 @@ class _IntakeTargetPageState extends State { /// 构建修改每日卡路里和宏量素目标的卡片 buildEditWeekMacrosCard() { return Card( - elevation: 10, + elevation: 5.sp, child: Padding( - padding: EdgeInsets.all(16.sp), + padding: EdgeInsets.all(5.sp), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, @@ -475,7 +476,7 @@ class _IntakeTargetPageState extends State { Expanded( flex: 2, child: TextButton( - onPressed: () async { + onPressed: () { setState(() { _isWeekdayEditing = !_isWeekdayEditing; }); @@ -562,6 +563,7 @@ class _IntakeTargetPageState extends State { await _userHelper.updateIntakeDailyGoalByUser([temp]); // 修改了数据库,也修改对应显示内容 + if (!mounted) return; setState(() { intakeData[selectedDay] = newData; diff --git a/lib/views/me/intake_goals/week_intake_bar_chart.dart b/lib/views/me/intake_goals/week_intake_bar_chart.dart index 82d03e5..5208502 100644 --- a/lib/views/me/intake_goals/week_intake_bar_chart.dart +++ b/lib/views/me/intake_goals/week_intake_bar_chart.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -41,7 +39,7 @@ class WeekIntakeBarChartState extends State { touchTooltipData: BarTouchTooltipData( getTooltipColor: (_) => Colors.blueGrey, tooltipHorizontalAlignment: FLHorizontalAlignment.center, - tooltipPadding: EdgeInsets.symmetric(horizontal: 5.sp, vertical: 8), + tooltipPadding: EdgeInsets.all(5.sp), // 提示框的最大宽度(默认120) maxContentWidth: 0.5.sw, // 提示框举例条状图顶部的距离(正数就是往上空,负数就是向下移动) @@ -80,7 +78,7 @@ class WeekIntakeBarChartState extends State { // 构建气泡框显示的内容 return BarTooltipItem( '$weekDay\n', - TextStyle(fontSize: CusFontSizes.flagTiny), + TextStyle(fontSize: CusFontSizes.flagTiny, color: Colors.white), textAlign: TextAlign.left, children: [ TextSpan(text: "$choStr\n"), @@ -98,14 +96,14 @@ class WeekIntakeBarChartState extends State { bottomTitles: AxisTitles( sideTitles: SideTitles( showTitles: true, - reservedSize: 28, + reservedSize: 28.sp, getTitlesWidget: _bottomTitles, ), ), leftTitles: AxisTitles( sideTitles: SideTitles( showTitles: true, - reservedSize: 50, // 左侧刻度标签的宽度 + reservedSize: 50.sp, // 左侧刻度标签的宽度 getTitlesWidget: _leftTitles, ), ), diff --git a/lib/views/me/more_settings/index.dart b/lib/views/me/more_settings/index.dart index 8285f86..ec8b2a7 100644 --- a/lib/views/me/more_settings/index.dart +++ b/lib/views/me/more_settings/index.dart @@ -92,7 +92,14 @@ class _MoreSettingsState extends State { mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded(flex: 1, child: Text("Author")), - Expanded(flex: 3, child: Text("SanotSu")), + Expanded(flex: 2, child: Text("SanotSu")), + ], + ), + const Row( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Expanded(flex: 1, child: Text("Wechat")), + Expanded(flex: 2, child: Text("SanotSu")), ], ), Row( diff --git a/lib/views/me/training_setting/index.dart b/lib/views/me/training_setting/index.dart index 476785f..c3c5fb4 100644 --- a/lib/views/me/training_setting/index.dart +++ b/lib/views/me/training_setting/index.dart @@ -50,7 +50,7 @@ class _TrainingSettingState extends State { Widget _buildListItem(String title, dynamic value, VoidCallback onTap) { return Card( - elevation: 5, + elevation: 2.sp, child: ListTile( title: Text(title), subtitle: Text(value.toString()), diff --git a/lib/views/me/user_info/index.dart b/lib/views/me/user_info/index.dart index 0549276..0d072a5 100644 --- a/lib/views/me/user_info/index.dart +++ b/lib/views/me/user_info/index.dart @@ -41,7 +41,7 @@ class _UserInfoState extends State { // 查询登录用户的信息一定会有的 var tempUser = (await _userHelper.queryUser(userId: CacheUser.userId))!; - + if (!mounted) return; setState(() { user = tempUser; if (tempUser.avatar != null) { @@ -57,23 +57,6 @@ class _UserInfoState extends State { appBar: AppBar( title: Text(CusAL.of(context).settingLabels("0")), actions: [ - // TextButton( - // onPressed: () { - // Navigator.push( - // context, - // MaterialPageRoute( - // builder: (context) => ModifyUserPage(user: user), - // ), - // ).then((value) { - // // 确认新增成功后重新加载当前日期的条目数据 - // _queryLoginedUserInfo(); - // }); - // }, - // child: Text( - // CusAL.of(context).eidtLabel(""), - // style: const TextStyle(color: Colors.white), - // ), - // ), IconButton( onPressed: () { Navigator.push( @@ -82,7 +65,6 @@ class _UserInfoState extends State { builder: (context) => ModifyUserPage(user: user), ), ).then((value) { - // 确认新增成功后重新加载当前日期的条目数据 _queryLoginedUserInfo(); }); }, diff --git a/lib/views/me/user_info/modify_user/index.dart b/lib/views/me/user_info/modify_user/index.dart index 6dee71d..42fc89f 100644 --- a/lib/views/me/user_info/modify_user/index.dart +++ b/lib/views/me/user_info/modify_user/index.dart @@ -13,7 +13,7 @@ import '../../../../models/cus_app_localizations.dart'; import '../../../../models/user_state.dart'; class ModifyUserPage extends StatefulWidget { - // 修改的时候可能会传用户信息 + // 修改的时候可能会传用户信息,“我的”首页新增用户时就没有用户信息 final User? user; const ModifyUserPage({super.key, this.user}); @@ -38,7 +38,7 @@ class _ModifyUserPageState extends State { setState(() { _formKey.currentState?.patchValue(widget.user!.toStringMap()); }); - } else {} + } }); } @@ -107,14 +107,6 @@ class _ModifyUserPageState extends State { : CusAL.of(context).eidtLabel(CusAL.of(context).userInfo), ), actions: [ - // TextButton( - // onPressed: _saveUser, - // child: Text( - // CusAL.of(context).saveLabel, - // style: const TextStyle(color: Colors.white), - // ), - // ), - // 2023-12-30 appbar 的action都优先iconbutton IconButton( onPressed: _saveUser, icon: const Icon(Icons.save), @@ -125,7 +117,7 @@ class _ModifyUserPageState extends State { child: Column( children: [ Padding( - padding: EdgeInsets.all(20.sp), + padding: EdgeInsets.all(5.sp), child: FormBuilder( key: _formKey, child: Column( @@ -171,7 +163,6 @@ class _ModifyUserPageState extends State { filled: true, fillColor: Colors.transparent, ), - // 2023-12-21 enableSuggestions 设为 true后键盘类型为text(默认就是)就正常了。 enableSuggestions: true, ), FormBuilderDropdown( @@ -225,14 +216,27 @@ class _ModifyUserPageState extends State { 'height', CusAL.of(context).userInfoLabels("4"), CusAL.of(context).unitLabels("4"), + validator: FormBuilderValidators.compose([ + FormBuilderValidators.numeric(), + FormBuilderValidators.min(30), + FormBuilderValidators.max(240), + ]), ), ), - SizedBox(width: 10.sp), + ], + ), + Row( + children: [ Expanded( child: _buildDoubleTextField( 'current_weight', CusAL.of(context).userInfoLabels("5"), CusAL.of(context).unitLabels("5"), + validator: FormBuilderValidators.compose([ + FormBuilderValidators.numeric(), + FormBuilderValidators.min(5), + FormBuilderValidators.max(300), + ]), ), ), ], @@ -264,14 +268,18 @@ class _ModifyUserPageState extends State { filled: true, fillColor: Colors.transparent, ), - // 2023-12-21 enableSuggestions 设为 true后键盘类型为multitext(默认是text)就正常了。 enableSuggestions: true, keyboardType: TextInputType.multiline, ), ]; } - _buildDoubleTextField(String name, String labelText, String suffixText) { + _buildDoubleTextField( + String name, + String labelText, + String suffixText, { + String? Function(String?)? validator, + }) { // 这里的只读就用全局的isEditing了,不作为参数传递了 return FormBuilderTextField( name: name, @@ -287,6 +295,7 @@ class _ModifyUserPageState extends State { FilteringTextInputFormatter.allow(RegExp(r'^\d*\.?\d*$')) ], keyboardType: TextInputType.number, + validator: validator, ); } } diff --git a/lib/views/me/weight_change_record/index.dart b/lib/views/me/weight_change_record/index.dart index e542afc..b32c80f 100644 --- a/lib/views/me/weight_change_record/index.dart +++ b/lib/views/me/weight_change_record/index.dart @@ -33,13 +33,38 @@ class _WeightChangeRecordState extends State { // 查询数据的时候不显示图表 bool isLoading = false; + // 用于强制更新体重趋势图组件 + Key _lineChartKey = UniqueKey(); + @override void initState() { super.initState(); + + user = widget.userInfo; + _currentWeight = user.currentWeight ?? 70; + _currentHeight = user.height ?? 170; + } + + // 刷新用户信息,以便能重新加载最新的当前体重身高 + Future _refreshUser() async { + setState(() { + isLoading = true; + }); + + var tempUser = (await _userHelper.queryUser( + userId: CacheUser.userId, + ))!; + + if (!mounted) return; setState(() { - user = widget.userInfo; + user = tempUser; + _currentWeight = user.currentWeight ?? 70; _currentHeight = user.height ?? 170; + isLoading = false; + + // 强制更新体重趋势图组件 + _lineChartKey = UniqueKey(); }); } @@ -49,171 +74,128 @@ class _WeightChangeRecordState extends State { appBar: AppBar( title: Text(CusAL.of(context).settingLabels('1')), ), - body: ListView( - children: [ - /// 体重趋势折线图区域 - /// 修改成功之后应该要重新刷新数据??? + body: SingleChildScrollView( + child: Padding( + padding: EdgeInsets.all(5.sp), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + /// 体重趋势折线图区域 + ...buildWeghtLineArea(), - Card( - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - CusAL.of(context).weightLabel(''), - style: TextStyle( - fontSize: CusFontSizes.flagMedium, - fontWeight: FontWeight.bold, - color: Theme.of(context).primaryColor, - ), - ), - Row( - children: [ - ElevatedButton( - onPressed: () { - // 这里只显示修改体重 - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => - WeightRecordManage(user: user), - ), - ).then( - (value) async { - // 强制重新加载体重变化图表 - setState(() { - isLoading = true; - }); - var tempUser = (await _userHelper.queryUser( - userId: CacheUser.userId, - ))!; + /// BMI区域 + ...buildBmiArea(), - setState(() { - user = tempUser; - _currentWeight = user.currentWeight ?? 70; - _currentHeight = user.height ?? 170; - isLoading = false; - }); - }, - ); - }, - child: Text(CusAL.of(context).manageLabel), - ), - SizedBox(width: 10.sp), - ElevatedButton( - onPressed: () { - // 这里只显示修改体重 - _buildModifyWeightOrBmiDialog(onlyWeight: true) - .then( - (value) async { - // 强制重新加载体重变化图表 - setState(() { - isLoading = true; - }); - var tempUser = (await _userHelper.queryUser( - userId: CacheUser.userId, - ))!; + SizedBox(height: 20.sp), + ], + ), + ), + ), + ); + } - setState(() { - user = tempUser; - _currentWeight = user.currentWeight ?? 70; - _currentHeight = user.height ?? 170; - isLoading = false; - }); - }, - ); - }, - child: Text(CusAL.of(context).recordLabel), - ), - ], - ) - ], - ), - if (!isLoading) WeightChangeLineChart(user: user), - ], + List buildWeghtLineArea() { + return [ + // 体重区块的标题和按钮 + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + CusAL.of(context).weightLabel(''), + style: TextStyle( + fontSize: CusFontSizes.flagMedium, + fontWeight: FontWeight.bold, + color: Theme.of(context).primaryColor, ), ), + Row( + children: [ + ElevatedButton( + onPressed: () { + // 这里只显示修改体重 + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => WeightRecordManage(user: user), + ), + ).then( + (value) async { + await _refreshUser(); + }, + ); + }, + child: Text(CusAL.of(context).manageLabel), + ), + SizedBox(width: 10.sp), + ElevatedButton( + onPressed: () { + // 这里只显示修改体重 + _buildModifyWeightOrBmiDialog(onlyWeight: true).then( + (value) async { + // 强制重新加载体重变化图表 + await _refreshUser(); + }, + ); + }, + child: Text(CusAL.of(context).recordLabel), + ), + ], + ) + ], + ), + // 显示体重趋势图 + isLoading + ? buildLoader(isLoading) + : WeightChangeLineChart(key: _lineChartKey, user: user), + ]; + } - /// BMI区域 - Center( - child: Card( - child: Column( - children: [ - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - RichText( - textAlign: TextAlign.left, - text: TextSpan( - children: [ - TextSpan( - text: "BMI", - style: TextStyle( - fontSize: CusFontSizes.flagMedium, - fontWeight: FontWeight.bold, - color: Theme.of(context).primaryColor, - ), - ), - const TextSpan( - text: " (15 ~ 40)", - style: TextStyle(color: Colors.green), - ), - ], - ), - ), - ElevatedButton( - onPressed: () { - // 这里要显示修改身高和体重 - _buildModifyWeightOrBmiDialog(onlyWeight: false).then( - (value) async { - // 强制重新加载体重变化图表 - setState(() { - isLoading = true; - }); - var tempUser = (await _userHelper.queryUser( - userId: CacheUser.userId, - ))!; - - setState(() { - user = tempUser; - _currentWeight = user.currentWeight ?? 70; - _currentHeight = user.height ?? 170; - isLoading = false; - }); - }, - ); - }, - child: Text(CusAL.of(context).recordLabel), - ), - ], + List buildBmiArea() { + return [ + // BMI标题和按钮行 + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + RichText( + textAlign: TextAlign.left, + text: TextSpan( + children: [ + TextSpan( + text: "BMI", + style: TextStyle( + fontSize: CusFontSizes.flagMedium, + fontWeight: FontWeight.bold, + color: Theme.of(context).primaryColor, ), - _buildBmiArea(context), - ], - ), + ), + const TextSpan( + text: " (15 ~ 40)", + style: TextStyle(color: Colors.green), + ), + ], ), ), - - /// 占位的 - // SizedBox( - // height: 30, - // child: Row( - // children: [ - // Expanded(child: Container(color: Colors.grey)), - // Expanded(child: Container(color: Colors.green)), - // Expanded(child: Container(color: Colors.blue)), - // Expanded(child: Container(color: Colors.yellow)), - // Expanded(child: Container(color: Colors.red)), - // ], - // ), - // ), - SizedBox(height: 20.sp), + ElevatedButton( + onPressed: () { + // 这里要显示修改身高和体重 + _buildModifyWeightOrBmiDialog(onlyWeight: false).then( + (value) async { + // 强制重新加载体重变化图表 + await _refreshUser(); + }, + ); + }, + child: Text(CusAL.of(context).recordLabel), + ), ], ), - ); + // BMI分段区间容器 + Center(child: _buildBmiRangeContainer(context)), + ]; } - _buildBmiArea(BuildContext context) { + // 构建bmi色块容器 + SizedBox _buildBmiRangeContainer(BuildContext context) { // 存的是kg var tempWeight = user.currentWeight ?? 0; // 存的是cm,所以要/100 @@ -340,6 +322,7 @@ class _WeightChangeRecordState extends State { ); } + // 输入体重或bmi值的弹窗 Future _buildModifyWeightOrBmiDialog({bool onlyWeight = true}) async { await showModalBottomSheet( isScrollControlled: true, @@ -363,7 +346,7 @@ class _WeightChangeRecordState extends State { ), DecimalNumberPicker( value: _currentWeight, - minValue: 10, + minValue: 5, maxValue: 300, decimalPlaces: 1, itemHeight: 40, @@ -383,7 +366,7 @@ class _WeightChangeRecordState extends State { ), DecimalNumberPicker( value: _currentHeight, - minValue: 50, + minValue: 30, maxValue: 240, decimalPlaces: 1, itemHeight: 40, @@ -444,6 +427,7 @@ class _WeightChangeRecordState extends State { } } +// 构建bmi文字 buildWeightBmiText(double bmi, BuildContext context) { if (bmi < 18.4) { return Text( diff --git a/lib/views/me/weight_change_record/weight_change_line_chart.dart b/lib/views/me/weight_change_record/weight_change_line_chart.dart index c0fa405..03e5ac3 100644 --- a/lib/views/me/weight_change_record/weight_change_line_chart.dart +++ b/lib/views/me/weight_change_record/weight_change_line_chart.dart @@ -1,15 +1,13 @@ -// ignore_for_file: avoid_print - import 'dart:io'; import 'dart:ui' as ui; -import 'package:device_info_plus/device_info_plus.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; +import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import 'package:image_gallery_saver/image_gallery_saver.dart'; +import 'package:screenshot/screenshot.dart'; import '../../../common/utils/db_user_helper.dart'; import '../../../common/utils/tools.dart'; @@ -51,16 +49,13 @@ class _WeightChangeLineChartState extends State { // 保存折线图图表为图片时需要 final GlobalKey _chartKey = GlobalKey(); -// 是否显示保存的按钮(Android9及其以下是无法保存的,组件已经不支持了) - bool isShowSaveButton = true; + ScreenshotController screenshotController = ScreenshotController(); @override void initState() { super.initState(); - setState(() { - getWeightData(); - getDeviceInfo(); - }); + + getWeightData(); } getWeightData({String? startDate, String? endDate}) async { @@ -76,6 +71,7 @@ class _WeightChangeLineChartState extends State { endDate: endDate, ); + if (!mounted) return; setState(() { weightTrends = tempList; allSpots.clear(); @@ -172,35 +168,56 @@ class _WeightChangeLineChartState extends State { ); } - // 找了很多问题,是Android9及之下,无法保存。 - // 权限什么的都已经给了的,还是存不了,有时间找个Android10及其之上的设备试一下 + // 将折线图保存到本地图片 saveChartImage() async { - RenderRepaintBoundary boundary = - _chartKey.currentContext!.findRenderObject() as RenderRepaintBoundary; - ui.Image image = await boundary.toImage(pixelRatio: 2.sp); - - ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png); + try { + // 2024-11-18 直接保存文件到指定位置 + var dir = Directory('/storage/emulated/0/free-fitness/images'); - if (byteData != null) { - final result = await ImageGallerySaver.saveImage( - byteData.buffer.asUint8List(), - name: "${getCurrentDateTime()}图表", + if (!await dir.exists()) { + await dir.create(recursive: true); + } + // 传入的前缀有强制带上下划线 + final file = File( + '${dir.path}/体重趋势图_${DateTime.now().millisecondsSinceEpoch}.png', ); - print(result); - } - } - // 获取设备信息,判断是否显示保存按钮 - getDeviceInfo() async { - if (Platform.isAndroid) { - final deviceInfoPlugin = DeviceInfoPlugin(); - final deviceInfo = await deviceInfoPlugin.androidInfo; - final sdkInt = deviceInfo.version.sdkInt; + /// 方法1 使用 RenderRepaintBoundary + RenderRepaintBoundary boundary = + _chartKey.currentContext!.findRenderObject() as RenderRepaintBoundary; + ui.Image image = await boundary.toImage(pixelRatio: 2.sp); + + ByteData? byteData = await image.toByteData( + format: ui.ImageByteFormat.png, + ); - // Android9对应sdk是28,<=28就不显示保存按钮 - if (sdkInt <= 28) { - isShowSaveButton = false; + if (byteData != null) { + await file.writeAsBytes(byteData.buffer.asUint8List()); + EasyLoading.showToast("图片已保存在手机下/${file.path.split("/0/").last}"); } + + /// 方法2 使用 ScreenShot 库 (两者图片效果是一样的) + // screenshotController.capture().then((Uint8List? imageData) async { + // try { + // if (imageData != null) { + // // 将 PNG 图片转换为 JPG 图片 + // // Uint8List? jpgBytes = await FlutterImageCompress.compressWithList( + // // imageData, + // // format: CompressFormat.jpeg, + // // quality: 90, + // // ); + + // await file.writeAsBytes(imageData); + // EasyLoading.showToast("图片已保存在手机下/${file.path.split("/0/").last}"); + // } + // } catch (e) { + // print(e); + // } + // }).catchError((onError) { + // print(onError); + // }); + } catch (e) { + debugPrint(e.toString()); } } @@ -243,15 +260,13 @@ class _WeightChangeLineChartState extends State { Row( mainAxisAlignment: MainAxisAlignment.end, children: [ - // 2023-12-30 还没有优化,暂时不支持下载 - // if (isShowSaveButton) - // IconButton( - // onPressed: saveChartImage, - // icon: Icon( - // Icons.download, - // color: Theme.of(context).primaryColor, - // ), - // ), + IconButton( + onPressed: saveChartImage, + icon: Icon( + Icons.download, + color: Theme.of(context).primaryColor, + ), + ), IconButton( onPressed: () { setState(() { @@ -310,7 +325,7 @@ class _WeightChangeLineChartState extends State { // 是否曲线平滑 // isCurved: true, // 线宽 - barWidth: 2, + barWidth: 2.sp, // 设置线加上阴影 // shadow: Shadow(blurRadius: 3.sp), @@ -347,159 +362,163 @@ class _WeightChangeLineChartState extends State { return SingleChildScrollView( scrollDirection: Axis.horizontal, - child: Container( - // 四周留点边框方便标题显示完整(上面右边多留点为了数据点提示工具框显示完整) - padding: EdgeInsets.fromLTRB(10.sp, 50.sp, 30.sp, 10.sp), - // 表格的宽度可以根据数量来(这每个sport的宽度可以根据x轴坐标的标题长度来定) - // width: allSpots.length * 60.sp, - - // 要考虑上面padding左右边框和适当的图表最小宽度 - width: (allSpots.length * spotWidth) + 80.sp, - height: 300.sp, + child: Screenshot( + controller: screenshotController, child: RepaintBoundary( key: _chartKey, - child: LineChart( - // 折线图的数据 - LineChartData( - // 显示工具提示框的设置 - showingTooltipIndicators: showingTooltipOnSpots.map((index) { - return ShowingTooltipIndicators([ - LineBarSpot( - tooltipsOnBar, - lineBarsData.indexOf(tooltipsOnBar), - tooltipsOnBar.spots[index], - ), - ]); - }).toList(), - // 折线图触摸的时候的数据 - lineTouchData: LineTouchData( - // 启用触摸反馈 - enabled: true, - // 内置触摸处理 - handleBuiltInTouches: false, - // 这个触摸反馈是:点击某个点,显示该点的值;再点击就取消显示 - touchCallback: - (FlTouchEvent event, LineTouchResponse? response) { - if (response == null || response.lineBarSpots == null) { - return; - } - if (event is FlTapUpEvent) { - final spotIndex = response.lineBarSpots!.first.spotIndex; - // 点击某个数据点,如果已经展示了工具提示框就从工具提示框点列表移除;没有,则加入 - setState(() { - if (showingTooltipOnSpots.contains(spotIndex)) { - showingTooltipOnSpots.remove(spotIndex); - } else { - showingTooltipOnSpots.add(spotIndex); - } - }); - } - }, - // 鼠标解析器(注释了在安卓上好像没影响) - // mouseCursorResolver: - // (FlTouchEvent event, LineTouchResponse? response) { - // if (response == null || response.lineBarSpots == null) { - // return SystemMouseCursors.basic; - // } - // return SystemMouseCursors.click; - // }, - - /// 获取触摸点的工具提示框(就是上面触摸反馈时,展示的内容工具提示框的样式) - getTouchedSpotIndicator: - (LineChartBarData barData, List spotIndexes) { - return spotIndexes.map((index) { - return TouchedSpotIndicatorData( - const FlLine(color: Colors.pink), - FlDotData( - show: true, - getDotPainter: (spot, percent, barData, index) => - FlDotCirclePainter( - // 被选中展示了工具提示框的数据点的半径 - radius: 5, - color: lerpGradient( - barData.gradient!.colors, - barData.gradient!.stops!, - percent / 100, + child: Container( + // 四周留点边框方便标题显示完整(上面右边多留点为了数据点提示工具框显示完整) + padding: EdgeInsets.fromLTRB(10.sp, 50.sp, 30.sp, 10.sp), + // 表格的宽度可以根据数量来(这每个spot的宽度可以根据x轴坐标的标题长度来定) + // width: allSpots.length * 60.sp, + + // 要考虑上面padding左右边框和适当的图表最小宽度 + width: (allSpots.length * spotWidth) + 80.sp, + height: 300.sp, + + child: LineChart( + // 折线图的数据 + LineChartData( + // 显示工具提示框的设置 + showingTooltipIndicators: showingTooltipOnSpots.map((index) { + return ShowingTooltipIndicators([ + LineBarSpot( + tooltipsOnBar, + lineBarsData.indexOf(tooltipsOnBar), + tooltipsOnBar.spots[index], + ), + ]); + }).toList(), + // 折线图触摸的时候的数据 + lineTouchData: LineTouchData( + // 启用触摸反馈 + enabled: true, + // 内置触摸处理 + handleBuiltInTouches: false, + // 这个触摸反馈是:点击某个点,显示该点的值;再点击就取消显示 + touchCallback: + (FlTouchEvent event, LineTouchResponse? response) { + if (response == null || response.lineBarSpots == null) { + return; + } + if (event is FlTapUpEvent) { + final spotIndex = response.lineBarSpots!.first.spotIndex; + // 点击某个数据点,如果已经展示了工具提示框就从工具提示框点列表移除;没有,则加入 + setState(() { + if (showingTooltipOnSpots.contains(spotIndex)) { + showingTooltipOnSpots.remove(spotIndex); + } else { + showingTooltipOnSpots.add(spotIndex); + } + }); + } + }, + // 鼠标解析器(注释了在安卓上好像没影响) + // mouseCursorResolver: + // (FlTouchEvent event, LineTouchResponse? response) { + // if (response == null || response.lineBarSpots == null) { + // return SystemMouseCursors.basic; + // } + // return SystemMouseCursors.click; + // }, + + /// 获取触摸点的工具提示框(就是上面触摸反馈时,展示的内容工具提示框的样式) + getTouchedSpotIndicator: + (LineChartBarData barData, List spotIndexes) { + return spotIndexes.map((index) { + return TouchedSpotIndicatorData( + const FlLine(color: Colors.pink), + FlDotData( + show: true, + getDotPainter: (spot, percent, barData, index) => + FlDotCirclePainter( + // 被选中展示了工具提示框的数据点的半径 + radius: 5.sp, + color: lerpGradient( + barData.gradient!.colors, + barData.gradient!.stops!, + percent / 100, + ), + // 折线上数据点的颜色,如果不那么较真跟着折线的渐变色显示,都统一纯色就好,简单。 + // color: Colors.black, + strokeWidth: 2.sp, + strokeColor: Colors.grey, ), - // 折线上数据点的颜色,如果不那么较真跟着折线的渐变色显示,都统一纯色就好,简单。 - // color: Colors.black, - strokeWidth: 2, - strokeColor: Colors.grey, - ), - ), - ); - }).toList(); - }, - touchTooltipData: LineTouchTooltipData( - getTooltipColor: (_) => Colors.pink, - tooltipRoundedRadius: 8, - getTooltipItems: (List lineBarsSpot) { - return lineBarsSpot.map((lineBarSpot) { - return LineTooltipItem( - // 工具提示框中的数据可能太长,只取两位小数 - lineBarSpot.y.toStringAsFixed(2), - TextStyle( - fontSize: CusFontSizes.itemSubContent, - color: Colors.white, - fontWeight: FontWeight.bold, ), ); }).toList(); }, - ), - ), - // 折线图的条数据 - lineBarsData: lineBarsData, - // y轴最小值 - // minY: 0, // ???如果是体重的话,传入的数据的最小值减个三五千克,然后间隔单位小一点 - minY: (weightTrends - .reduce((currentWT, nextWT) => - currentWT.weight < nextWT.weight - ? currentWT - : nextWT) - .weight) - .floor() - - 3, // 最后的-3是避免最小的值就显示在最下面了,还是留点空隙 - // 标题数据 - titlesData: FlTitlesData( - // 左侧标题 - leftTitles: AxisTitles( - // axisNameWidget: Text('体重(kg)'), - // axisNameSize: 24, - // sideTitles: SideTitles(showTitles: false, reservedSize: 0), - sideTitles: SideTitles( - showTitles: true, - // interval: 2, // ???间隔可以根据数量多少来,不设置就自动来 - // interval: (maxWeight - minWeight) / 5, - getTitlesWidget: _leftTitles, - // 标题所需的最大空间(所有标题都将使用此值进行扩展) - reservedSize: 50, + touchTooltipData: LineTouchTooltipData( + getTooltipColor: (_) => Colors.pink, + tooltipRoundedRadius: 8.sp, + getTooltipItems: (List lineBarsSpot) { + return lineBarsSpot.map((lineBarSpot) { + return LineTooltipItem( + // 工具提示框中的数据可能太长,只取两位小数 + lineBarSpot.y.toStringAsFixed(2), + TextStyle( + fontSize: CusFontSizes.itemSubContent, + color: Colors.white, + fontWeight: FontWeight.bold, + ), + ); + }).toList(); + }, ), ), - // 底部标题(日期) - bottomTitles: AxisTitles( - sideTitles: SideTitles( - showTitles: true, - interval: 1, // ???间隔可以根据数量多少来 - getTitlesWidget: bottomTitleWidgets, - reservedSize: 40, + // 折线图的条数据 + lineBarsData: lineBarsData, + // y轴最小值 + // minY: 0, // ???如果是体重的话,传入的数据的最小值减个三五千克,然后间隔单位小一点 + minY: (weightTrends + .reduce((currentWT, nextWT) => + currentWT.weight < nextWT.weight + ? currentWT + : nextWT) + .weight) + .floor() - + 3, // 最后的-3是避免最小的值就显示在最下面了,还是留点空隙 + // 标题数据 + titlesData: FlTitlesData( + // 左侧标题 + leftTitles: AxisTitles( + // axisNameWidget: Text('体重(kg)'), + // axisNameSize: 24, + // sideTitles: SideTitles(showTitles: false, reservedSize: 0), + sideTitles: SideTitles( + showTitles: true, + // interval: 2, // ???间隔可以根据数量多少来,不设置就自动来 + // interval: (maxWeight - minWeight) / 5, + getTitlesWidget: _leftTitles, + // 标题所需的最大空间(所有标题都将使用此值进行扩展) + reservedSize: 50.sp, + ), + ), + // 底部标题(日期) + bottomTitles: AxisTitles( + sideTitles: SideTitles( + showTitles: true, + interval: 1, // ???间隔可以根据数量多少来 + getTitlesWidget: bottomTitleWidgets, + reservedSize: 40.sp, + ), + ), + // 不显示内容也要设定,否则就是默认的样式 + topTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), + ), + rightTitles: const AxisTitles( + sideTitles: SideTitles(showTitles: false), ), ), - // 不显示内容也要设定,否则就是默认的样式 - topTitles: const AxisTitles( - sideTitles: SideTitles(showTitles: false), - ), - rightTitles: const AxisTitles( - sideTitles: SideTitles(showTitles: false), + // 是否显示辅助线(默认是true) + gridData: const FlGridData(show: true), + // 图表的边框 + borderData: FlBorderData( + show: true, + border: Border.all(color: Colors.grey), ), ), - // 是否显示辅助线(默认是true) - gridData: const FlGridData(show: true), - // 图表的边框 - borderData: FlBorderData( - show: true, - border: Border.all(color: Colors.grey), - ), ), ), ), diff --git a/lib/views/me/weight_change_record/weight_record_manage.dart b/lib/views/me/weight_change_record/weight_record_manage.dart index c34a413..b2008fb 100644 --- a/lib/views/me/weight_change_record/weight_record_manage.dart +++ b/lib/views/me/weight_change_record/weight_record_manage.dart @@ -57,6 +57,7 @@ class _WeightRecordManageState extends State { gmtCreateSort: 'DESC', ); + if (!mounted) return; setState(() { weightTrends.clear(); weightTrends.addAll(tempList); @@ -77,6 +78,7 @@ class _WeightRecordManageState extends State { ), ); + if (!mounted) return; if (picked != null) { setState(() { _startDate = picked.start; @@ -176,6 +178,7 @@ class _WeightRecordManageState extends State { // ???应该有成功的判断 await _userHelper.deleteWeightTrendList(toDeletedWT); + if (!mounted) return; setState(() { // 从列表中移除 // 倒序遍历需要移除的索引列表,以避免索引变化导致的问题 diff --git a/lib/views/training/exercise/exercise_detail.dart b/lib/views/training/exercise/exercise_detail.dart index 3f71e1e..aa44cd9 100644 --- a/lib/views/training/exercise/exercise_detail.dart +++ b/lib/views/training/exercise/exercise_detail.dart @@ -54,7 +54,7 @@ class _ExerciseDetailDialogState extends State { return PopScope( canPop: false, - onPopInvoked: (didPop) async { + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) return; Navigator.pop(context, modifiedFlag); }, @@ -64,15 +64,18 @@ class _ExerciseDetailDialogState extends State { mainAxisSize: MainAxisSize.min, // 从上到下依次为关闭按钮、图片、动作名称及其技术要点、详情和修改按钮、翻页按钮 children: [ + /// 关闭按钮 // ???关闭按钮考虑和下面的修改和详情放一起,但3个按钮怎么排都显示很奇怪 // _buildCloseButton(), SizedBox( - height: 40.sp, - child: buildCloseButton( - context, - popValue: modifiedFlag, - )), + height: 40.sp, + child: buildCloseButton(context, popValue: modifiedFlag), + ), + + /// 图片 Expanded(flex: 2, child: _buildExerciseImageArea(_currentItem)), + + /// 动作名称及其技术要点、详情和修改按钮 Expanded( flex: 3, child: buildTitleAndDescription( @@ -80,7 +83,8 @@ class _ExerciseDetailDialogState extends State { _currentItem.instructions ?? "", ), ), - // 固定高度更好看 + + /// 翻页按钮(固定高度更好看) SizedBox(height: 60.sp, child: _buildPageButton()) ], ), @@ -105,17 +109,17 @@ class _ExerciseDetailDialogState extends State { child: Row( children: [ Expanded( - flex: 10, + flex: 4, child: Text( '${_currentIndex + 1} ${_currentItem.exerciseName}', - // 限制只显示一行,多的用省略号 + // 限制只显示两行,多的用省略号 overflow: TextOverflow.ellipsis, maxLines: 2, style: TextStyle(fontSize: CusFontSizes.itemTitle), ), ), Expanded( - flex: 3, + flex: 1, child: TextButton( child: Text( CusAL.of(context).detailLabel, @@ -137,7 +141,7 @@ class _ExerciseDetailDialogState extends State { ), ), Expanded( - flex: 2, + flex: 1, child: TextButton( child: Text( CusAL.of(context).eidtLabel(""), @@ -159,6 +163,7 @@ class _ExerciseDetailDialogState extends State { _currentItem.exerciseId!, ); + if (!mounted) return; setState(() { modifiedFlag = result; _currentItem = exercise; diff --git a/lib/views/training/exercise/exercise_detail_more.dart b/lib/views/training/exercise/exercise_detail_more.dart index 35e0660..5aacbd5 100644 --- a/lib/views/training/exercise/exercise_detail_more.dart +++ b/lib/views/training/exercise/exercise_detail_more.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -86,7 +84,7 @@ class _ExerciseDetailMoreState extends State { ), ), Padding( - padding: EdgeInsets.all(16.0.sp), + padding: EdgeInsets.all(10.sp), child: Text( CusAL.of(context).moreDetail, style: TextStyle(fontSize: CusFontSizes.itemTitle), @@ -103,14 +101,14 @@ class _ExerciseDetailMoreState extends State { buildTableData() { return [ Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: Table( // 设置表格边框 border: TableBorder.all(color: Theme.of(context).primaryColor), // 设置每列的宽度占比 - columnWidths: const { - 0: FlexColumnWidth(1), - 1: FlexColumnWidth(2), + columnWidths: { + 0: FixedColumnWidth(110.sp), + 1: const FlexColumnWidth(1), }, defaultVerticalAlignment: TableCellVerticalAlignment.middle, children: [ @@ -187,7 +185,7 @@ class _ExerciseDetailMoreState extends State { return TableRow( children: [ Padding( - padding: EdgeInsets.symmetric(horizontal: 10.sp), + padding: EdgeInsets.symmetric(horizontal: 5.sp), child: Text( label, style: TextStyle( @@ -197,11 +195,11 @@ class _ExerciseDetailMoreState extends State { ), ), Padding( - padding: EdgeInsets.symmetric(horizontal: 10.sp), + padding: EdgeInsets.symmetric(horizontal: 5.sp), child: Text( value, style: TextStyle( - fontSize: CusFontSizes.pageSubContent, + fontSize: CusFontSizes.pageContent, color: Theme.of(context).disabledColor, ), textAlign: TextAlign.left, diff --git a/lib/views/training/exercise/exercise_json_import.dart b/lib/views/training/exercise/exercise_json_import.dart index 931e410..b1c9083 100644 --- a/lib/views/training/exercise/exercise_json_import.dart +++ b/lib/views/training/exercise/exercise_json_import.dart @@ -1,7 +1,4 @@ -// ignore_for_file: avoid_print - import 'dart:convert'; -import 'dart:developer'; import 'dart:io'; import 'package:flutter/material.dart'; @@ -17,6 +14,11 @@ import '../../../models/cus_app_localizations.dart'; import '../../../models/custom_exercise.dart'; import '../../../models/training_state.dart'; +/// +/// 2024-11-14 +/// 为了减少干扰信息,只支持单个(其实也可以多个)json导入,选中图片文件夹 +/// 不再处理json文件夹的导入 +/// class ExerciseJsonImport extends StatefulWidget { const ExerciseJsonImport({super.key}); @@ -29,8 +31,7 @@ class _ExerciseJsonImportState extends State { // 是否在解析json中或导入数据库中 bool isLoading = false; - // 上传的json文件列表 - List jsons = []; + // 解析后的动作列表(文件和动作都不支持移除) List cusExercises = []; // 如果用户没有在这里选择图片的文件夹,就使用预设要求用户放置的位置 @@ -44,58 +45,47 @@ class _ExerciseJsonImportState extends State { List exerciseSelectedList = [false]; var importNote = """ -json文件的images栏位只指定相对文件路径, -再指定一个公共文件夹存放所有的图片。 +**json文件的 images 栏位指定图片相对路径,**\n +**需要再指定一个存放所有图片的公共文件夹。** 比如一个实际的图片位于设备的: +```sh .../DCIM/exercise-images/3_4_Sit-Up/0.jpg; .../DCIM/exercise-images/Ab_Roller/0.jpg; - +``` 那么对应json文件的 `images` 栏位可以如下填写: +``` 3_4_Sit-Up.json: - "images": ["3_4_Sit-Up/0.jpg","3_4_Sit-Up/1.jpg"], +"images": ["3_4_Sit-Up/0.jpg","3_4_Sit-Up/1.jpg"], Ab_Roller.json: - "images": ["Ab_Roller/0.jpg","Ab_Roller/1.jpg"], +"images": ["Ab_Roller/0.jpg","Ab_Roller/1.jpg"], +``` 同时选择公共文件夹位置 -> 点击文件夹图标、选择公共文件夹: +``` .../DCIM/exercise-images/ +``` -这样保存的地址就是完整的 "公共文件夹/json文件images栏位" - -比如 -/storage/emulated/0/DCIM/exercise-images/3_4_Sit-Up/0.jpg -/storage/emulated/0/DCIM/exercise-images/Ab_Roller/0.jpg - -不指定公共文件夹,则默认json文件中存放的是完整的绝对路径。 -找不到图片则需要在动作库模块对指定动作重新上传图片。 - -超过50条数据,就不用表格展示了,太耗费性能。 +**如果 json 文件中的 images 栏位是完整的本地图片地址,则无需选择图片公共文件夹。** """; - /// ???可以考虑在打开文件夹或者文件时,删除已选择的文件夹或文件(现在是追加,不会去重) - // 上传指定文件夹,处理里面所有指定格式的json - Future _openFileExplorer() async { - // 用户选择指定文件夹 - String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); - // 如果有选中文件夹,遍历出里面所有json结尾的文件 - if (selectedDirectory != null) { - setState(() { - isLoading = true; - }); - - Directory directory = Directory(selectedDirectory); - List jsonFiles = directory - .listSync() - .where((entity) => entity.path.toLowerCase().endsWith('.json')) - .map((entity) => File(entity.path)) - .toList(); + // 用户可以选择多个json文件 + Future _openJsonFiles() async { + FilePickerResult? result = await FilePicker.platform.pickFiles( + type: FileType.custom, + allowedExtensions: ['json', 'JSON'], + allowMultiple: true, + ); + if (!mounted) return; + if (result != null) { setState(() { - jsons.addAll(jsonFiles); + isLoading = true; }); - for (File file in jsonFiles) { + // 一个json文件和多个json文件都是一个列表 + for (File file in result.files.map((file) => File(file.path!))) { try { String jsonData = await file.readAsString(); @@ -109,6 +99,7 @@ Ab_Roller.json: .map((e) => CustomExercise.fromJson(e)) .toList(); + if (!mounted) return; setState(() { cusExercises.addAll(temp); // 更新需要构建的表格的长度和每条数据的可选中状态 @@ -126,6 +117,7 @@ Ab_Roller.json: CusAL.of(context).importJsonErrorText(file.path, e.toString()), ); + if (!mounted) return; setState(() { isLoading = false; }); @@ -133,67 +125,7 @@ Ab_Roller.json: return; } } - setState(() { - isLoading = false; - }); - } else { - // User canceled the picker - return; - } - } - - // 用户可以选择多个json文件 - Future _openJsonFiles() async { - FilePickerResult? result = - await FilePicker.platform.pickFiles(allowMultiple: true); - - if (result != null) { - setState(() { - isLoading = true; - }); - - for (File file in result.files.map((file) => File(file.path!))) { - if (file.path.toLowerCase().endsWith('.json')) { - try { - String jsonData = await file.readAsString(); - - // 如果一个json文件只是一个动作,那就加上中括号;如果本身就是带了中括号的多个,就不再加 - List cusExerciseMapList = - jsonData.trim().startsWith("[") && jsonData.trim().endsWith("]") - ? json.decode(jsonData) - : json.decode("[$jsonData]"); - - log("${cusExerciseMapList.length}"); - - var temp = cusExerciseMapList.map((e) { - return CustomExercise.fromJson(e); - }).toList(); - - setState(() { - cusExercises.addAll(temp); - // 更新需要构建的表格的长度和每条数据的可选中状态 - exerciseItemsNum = cusExercises.length; - exerciseSelectedList = - List.generate(exerciseItemsNum, (int index) => false); - }); - } catch (e) { - // 弹出报错提示框 - if (!mounted) return; - - commonExceptionDialog( - context, - CusAL.of(context).importJsonError, - CusAL.of(context).importJsonErrorText(file.path, e.toString()), - ); - - setState(() { - isLoading = false; - }); - // 中止操作 - return; - } - } - } + if (!mounted) return; setState(() { isLoading = false; }); @@ -208,9 +140,8 @@ Ab_Roller.json: // 用户选择指定文件夹 String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); - log("selectedDirectory------------$selectedDirectory"); - // 如果有选中文件夹,遍历出里面所有json结尾的文件 + if (!mounted) return; if (selectedDirectory != null) { setState(() { // 注意,这里的文件夹地址尾巴没有/,预设的是有的,所以带上 @@ -265,13 +196,12 @@ Ab_Roller.json: } on Exception catch (e) { // 将错误信息展示给用户 if (!mounted) return; - // ???可以抽公共的错误处理和提示弹窗 - commonExceptionDialog( context, CusAL.of(context).exceptionWarningTitle, e.toString(), ); + if (!mounted) return; setState(() { isLoading = false; }); @@ -280,8 +210,8 @@ Ab_Roller.json: } } // 保存完了,情况数据,并弹窗提示。 + if (!mounted) return; setState(() { - jsons = []; cusExercises = []; // 更新需要构建的表格的长度和每条数据的可选中状态 exerciseItemsNum = 0; @@ -327,22 +257,16 @@ Ab_Roller.json: : Theme.of(context).disabledColor, ), ), - // TextButton.icon( - // onPressed: cusExercises.isNotEmpty ? _saveToDb : null, - // icon: Icon( - // Icons.save, - // color: cusExercises.isNotEmpty - // ? null - // : Theme.of(context).disabledColor, - // ), - // label: Text( - // CusAL.of(context).saveLabel, - // style: TextStyle( - // color: cusExercises.isNotEmpty - // ? null - // : Theme.of(context).disabledColor, - // ), - // ), + // IconButton( + // onPressed: () { + // commonMDHintModalBottomSheet( + // context, + // "使用说明", + // importNote, + // msgFontSize: 15.sp, + // ); + // }, + // icon: const Icon(Icons.info_outline), // ), ], ), @@ -355,9 +279,6 @@ Ab_Roller.json: /// 最上方的功能按钮区域 _buildButtonsArea(), - /// json文件列表不为空才显示对应区域 - // if (jsons.isNotEmpty) ...buildJsonFileInfoArea(), - /// 动作列表不为空且待上传数量超过50显示简单文本(太大了用表格会巨卡) if (cusExercises.isNotEmpty && cusExercises.length > 50) ..._buildExerciseListArea(), @@ -374,49 +295,36 @@ Ab_Roller.json: /// 上方的功能按钮区域 _buildButtonsArea() { return Card( - elevation: 5, + elevation: 5.sp, child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Expanded( - child: IconButton( - onPressed: _openFileExplorer, - icon: Icon( - Icons.drive_folder_upload, - size: CusIconSizes.iconMedium, - color: Theme.of(context).primaryColor, - ), - ), - ), - Expanded( - child: IconButton( + child: TextButton( onPressed: _openJsonFiles, - icon: Icon( - Icons.file_upload, - size: CusIconSizes.iconMedium, - color: Theme.of(context).primaryColor, + child: Text( + CusAL.of(context).importJsonButtons('0'), + style: TextStyle(fontSize: CusFontSizes.flagSmall), ), ), ), Expanded( - child: IconButton( - onPressed: () { - setState(() { - jsons = []; - cusExercises = []; - cusExerciseImagePerfix = ""; - exerciseItemsNum = 0; - exerciseSelectedList = [false]; - }); - }, - icon: Icon( - Icons.clear, - size: CusIconSizes.iconMedium, - color: cusExercises.isNotEmpty - ? Theme.of(context).primaryColor - : Theme.of(context).disabledColor, + child: TextButton( + onPressed: cusExercises.isNotEmpty + ? () { + setState(() { + cusExercises = []; + cusExerciseImagePerfix = ""; + exerciseItemsNum = 0; + exerciseSelectedList = [false]; + }); + } + : null, + child: Text( + CusAL.of(context).importJsonButtons('1'), + style: TextStyle(fontSize: CusFontSizes.flagSmall), ), ), ), @@ -451,85 +359,67 @@ Ab_Roller.json: return IconButton( icon: const Icon(Icons.help_outline, color: Colors.lightGreen), onPressed: () { - // 简单的自定义对话框(默认的弹窗有宽高限制) - showGeneralDialog( - context: context, - // 背景色 - barrierColor: Colors.white.withOpacity(1), - - barrierDismissible: false, - barrierLabel: 'Dialog', - transitionDuration: const Duration(milliseconds: 400), - pageBuilder: (BuildContext context, Animation animation, - Animation secondaryAnimation) { - return Scaffold( - body: Padding( - padding: EdgeInsets.symmetric(horizontal: 5.sp), - child: Column( - children: [ - Expanded( - flex: 2, - child: Center( - child: Text( - '导入动作关联图片事宜', - style: TextStyle(fontSize: CusFontSizes.pageTitle), - ), - ), - ), - Expanded( - flex: 8, - child: SingleChildScrollView( - child: Text( - importNote, - style: TextStyle(fontSize: CusFontSizes.itemContent), - ), - ), - ), - Expanded( - flex: 1, - child: TextButton( - child: Text(CusAL.of(context).closeLabel), - onPressed: () { - Navigator.of(context).pop(); - }, - ), - ), - ], - ), - ), - ); - }, + // 底部弹窗 + commonMDHintModalBottomSheet( + context, + "使用说明", + importNote, + msgFontSize: 15.sp, ); + + /// 简单的自定义对话框(默认的弹窗有宽高限制) + // showGeneralDialog( + // context: context, + // // 背景色 + // barrierColor: Colors.white.withOpacity(1), + + // barrierDismissible: false, + // barrierLabel: 'Dialog', + // transitionDuration: const Duration(milliseconds: 400), + // pageBuilder: (BuildContext context, Animation animation, + // Animation secondaryAnimation) { + // return Scaffold( + // body: Padding( + // padding: EdgeInsets.symmetric(horizontal: 5.sp), + // child: Column( + // children: [ + // Expanded( + // flex: 2, + // child: Center( + // child: Text( + // '导入动作关联图片事宜', + // style: TextStyle(fontSize: CusFontSizes.pageTitle), + // ), + // ), + // ), + // Expanded( + // flex: 8, + // child: SingleChildScrollView( + // child: Text( + // importNote, + // style: TextStyle(fontSize: CusFontSizes.itemTitle), + // ), + // ), + // ), + // Expanded( + // flex: 1, + // child: TextButton( + // child: Text(CusAL.of(context).closeLabel), + // onPressed: () { + // Navigator.of(context).pop(); + // }, + // ), + // ), + // ], + // ), + // ), + // ); + // }, + // ); }, ); } - buildJsonFileInfoArea() { - /// json文件列表不为空才显示对应区域 - /// 2023-11-30 数据用表格显示的话,就暂时不显示文件了,不好看 - return [ - Text( - CusAL.of(context).jsonFiles, - style: TextStyle(fontSize: CusFontSizes.itemSubTitle), - textAlign: TextAlign.start, - ), - SizedBox( - height: 100.sp, - child: ListView.builder( - shrinkWrap: true, - itemCount: jsons.length, - itemBuilder: (context, index) { - return Text( - jsons[index].path, - style: TextStyle(fontSize: CusFontSizes.itemContent), - textAlign: TextAlign.start, - ); - }, - ), - ), - ]; - } - // 构建上传文件或文件夹时显示锻炼的数据概要和文件列表信息 _buildExerciseListArea() { return [ @@ -563,40 +453,33 @@ Ab_Roller.json: verticalDirection: VerticalDirection.up, children: [ Expanded( - child: RichText( - textAlign: TextAlign.start, - text: TextSpan( - children: [ - TextSpan( - text: '${index + 1} ', - style: TextStyle( - fontSize: CusFontSizes.itemContent, - color: Colors.green, - ), - ), - TextSpan( - text: "${cusExercises[index].id} ", - style: TextStyle( - fontSize: CusFontSizes.itemContent, - color: Colors.grey, - ), - ), - TextSpan( - text: "${cusExercises[index].name} ", - style: TextStyle( - fontSize: CusFontSizes.itemContent, - color: Colors.red, - ), - ), - TextSpan( - text: "${cusExercises[index].level}", - style: TextStyle( - fontSize: CusFontSizes.itemContent, - color: Colors.lightBlue, - ), - ), - ], - ), + child: buildRichTextItem( + '${index + 1}', + Colors.green, + textAlign: TextAlign.center, + ), + ), + Expanded( + flex: 3, + child: buildRichTextItem( + "${cusExercises[index].id}", + Colors.grey, + ), + ), + SizedBox(width: 2.sp), + Expanded( + flex: 3, + child: buildRichTextItem( + "${cusExercises[index].name}", + Colors.red, + ), + ), + SizedBox(width: 2.sp), + Expanded( + flex: 2, + child: buildRichTextItem( + "${cusExercises[index].level}", + Colors.lightBlue, ), ), ], diff --git a/lib/views/training/exercise/exercise_modify.dart b/lib/views/training/exercise/exercise_modify.dart index 2e6d9e1..21749f4 100644 --- a/lib/views/training/exercise/exercise_modify.dart +++ b/lib/views/training/exercise/exercise_modify.dart @@ -13,8 +13,9 @@ import '../../../layout/themes/cus_font_size.dart'; import '../../../models/cus_app_localizations.dart'; import '../../../models/training_state.dart'; -/// 基础活动变更表单(希望新增、修改可通用) +/// 基础活动变更表单 class ExerciseModify extends StatefulWidget { + // 有传数据是修改,没有则是新增 final Exercise? item; const ExerciseModify({super.key, this.item}); @@ -45,27 +46,25 @@ class _ExerciseModifyState extends State { void initState() { super.initState(); - setState(() { - if (widget.item != null) { - updateTarget = widget.item; - // 有图片地址,显示图片 - if (updateTarget?.images != null && updateTarget?.images != "") { - exerciseImages = convertStringToPlatformFiles(updateTarget!.images!); - } - // 有主要肌肉,显示主要肌肉 - if (updateTarget?.primaryMuscles != null && - updateTarget?.primaryMuscles != "") { - selectedPrimaryMuscles = - _genSelectedMuscleOptions(updateTarget?.primaryMuscles); - } - // 有次要肌肉,显示次要肌肉 - if (updateTarget?.secondaryMuscles != null && - updateTarget?.secondaryMuscles != "") { - selectedSecondaryMuscles = - _genSelectedMuscleOptions(updateTarget?.secondaryMuscles); - } + if (widget.item != null) { + updateTarget = widget.item; + // 有图片地址,显示图片 + if (updateTarget?.images != null && updateTarget?.images != "") { + exerciseImages = convertStringToPlatformFiles(updateTarget!.images!); + } + // 有主要肌肉,显示主要肌肉 + if (updateTarget?.primaryMuscles != null && + updateTarget?.primaryMuscles != "") { + selectedPrimaryMuscles = + _genSelectedMuscleOptions(updateTarget?.primaryMuscles); } - }); + // 有次要肌肉,显示次要肌肉 + if (updateTarget?.secondaryMuscles != null && + updateTarget?.secondaryMuscles != "") { + selectedSecondaryMuscles = + _genSelectedMuscleOptions(updateTarget?.secondaryMuscles); + } + } } // 根据数据库拼接的字符串值转回对应选项 @@ -107,7 +106,7 @@ class _ExerciseModifyState extends State { equipment: temp?.fields['equipment']?.value, countingMode: temp?.fields['counting_mode']?.value, standardDuration: - int.tryParse(temp?.fields['standard_duration']?.value) ?? 1, + int.tryParse(temp?.fields['standard_duration']?.value ?? "1") ?? 1, instructions: temp?.fields['instructions']?.value, ttsNotes: temp?.fields['tts_notes']?.value, category: temp?.fields['category']?.value, @@ -168,35 +167,21 @@ class _ExerciseModifyState extends State { @override Widget build(BuildContext context) { - // 只能接收一个子组件滚动组件 return Scaffold( appBar: AppBar( title: Text( "${updateTarget != null ? CusAL.of(context).eidtLabel('') : CusAL.of(context).addLabel('')}${CusAL.of(context).exerciseLabel}", style: TextStyle(fontSize: CusFontSizes.pageTitle), ), - elevation: 0, actions: [ IconButton(onPressed: _saveNewExercise, icon: const Icon(Icons.save)) - // TextButton( - // onPressed: _saveNewExercise, - // child: Text( - // CusAL.of(context).saveLabel, - // style: TextStyle( - // color: Theme.of(context).primaryColor, - // ), - // ), - // ) ], ), - body: Card( - elevation: 10.sp, - child: Padding( - padding: EdgeInsets.all(10.sp), - child: SingleChildScrollView( - // 创建表单 - child: _buildFormBuilder(), - ), + body: Padding( + padding: EdgeInsets.symmetric(vertical: 10.sp), + child: SingleChildScrollView( + // 创建表单 + child: _buildFormBuilder(), ), ), ); diff --git a/lib/views/training/exercise/exercise_query_form.dart b/lib/views/training/exercise/exercise_query_form.dart index 21b7bbd..6da998b 100644 --- a/lib/views/training/exercise/exercise_query_form.dart +++ b/lib/views/training/exercise/exercise_query_form.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -54,130 +52,140 @@ class _ExerciseQueryFormState extends State { return Card( elevation: 5.sp, child: Padding( - padding: EdgeInsets.all(5.sp), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center, + padding: EdgeInsets.fromLTRB(0, 5.sp, 0, 0), + child: Column( children: [ - Expanded( - flex: 6, - // FormBuilderDropdown需要指定外部容器大小,或者放在类似expanded中自动扩展 - child: cusFormBuilerDropdown( - "primary_muscles", - musclesOptions, - labelText: CusAL.of(context).exerciseQuerys("0"), - hintStyle: TextStyle(fontSize: CusFontSizes.searchInputMedium), - isOutline: true, - ), - ), - Expanded( - flex: 1, - child: IconButton( - onPressed: _showHintDialog, - icon: Icon( - Icons.warning, - size: CusIconSizes.iconSmall, - color: Theme.of(context).primaryColor, + Row( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + flex: 3, + // FormBuilderDropdown需要指定外部容器大小,或者放在类似expanded中自动扩展 + child: cusFormBuilerDropdown( + "primary_muscles", + musclesOptions, + labelText: CusAL.of(context).exerciseQuerys("0"), + hintStyle: TextStyle( + fontSize: CusFontSizes.searchInputLarge, + ), + isOutline: true, + optionFontSize: CusFontSizes.searchInputLarge, + ), ), - ), - ), - Expanded( - flex: 1, - child: IconButton( - onPressed: () { - setState(() { - _showAdvancedOptions = !_showAdvancedOptions; - }); - }, - icon: Icon( - _showAdvancedOptions ? Icons.expand_less : Icons.expand_more, - size: CusIconSizes.iconSmall, - color: Theme.of(context).primaryColor, + Expanded( + child: Padding( + // 因为下拉框两侧有空10,所以整体的row左侧有空10,所以右侧填充一个10 + padding: EdgeInsets.only(right: 10.sp), + child: SizedBox( + // height: 48.sp, + child: ElevatedButton( + onPressed: _submitForm, + child: const Icon(Icons.search), + ), + ), + ), ), - ), - - // TextButton( - // onPressed: () { - // setState(() { - // _showAdvancedOptions = !_showAdvancedOptions; - // }); - // }, - // child: Text( - // _showAdvancedOptions - // ? CusAL.of(context).lessLabel - // : CusAL.of(context).moreLabel, - // style: TextStyle(fontSize: 12.sp), - // ), - // ), + ], ), - Expanded( - flex: 2, - child: - // IconButton( - // onPressed: () { - // // todo 如果有高级查询条件被选择,但是被折叠了,点击重置是不会清除的。 - // setState(() { - // _formKey.currentState!.reset(); - // // 2023-12-12 不知道为什么,reset对下拉选中的没有效,所以手动清除 - // _formKey.currentState?.fields['primary_muscles'] - // ?.didChange(null); - // _formKey.currentState?.fields['level']?.didChange(null); - // _formKey.currentState?.fields['mechanic']?.didChange(null); - // _formKey.currentState?.fields['category']?.didChange(null); - // _formKey.currentState?.fields['equipment']?.didChange(null); - // }); - - // // 失去焦点 - // FocusScope.of(context).requestFocus(FocusNode()); - // }, - // icon: Icon(Icons.settings_backup_restore, size: 16.sp), - // ), - - TextButton( - onPressed: () { - // todo 如果有高级查询条件被选择,但是被折叠了,点击重置是不会清除的。 - setState(() { - _formKey.currentState!.reset(); - // 2023-12-12 不知道为什么,reset对下拉选中的没有效,所以手动清除 - _formKey.currentState?.fields['primary_muscles'] - ?.didChange(null); - _formKey.currentState?.fields['level']?.didChange(null); - _formKey.currentState?.fields['mechanic']?.didChange(null); - _formKey.currentState?.fields['category']?.didChange(null); - _formKey.currentState?.fields['equipment']?.didChange(null); - }); + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + TextButton( + onPressed: _showHintDialog, + child: Text( + CusAL.of(context).noteLabel, + style: TextStyle(fontSize: CusFontSizes.pageAppendix), + ), + ), + TextButton( + onPressed: () { + setState(() { + _showAdvancedOptions = !_showAdvancedOptions; + }); + }, + child: Text( + _showAdvancedOptions + ? CusAL.of(context).lessLabel + : CusAL.of(context).moreLabel, + style: TextStyle(fontSize: CusFontSizes.pageAppendix), + ), + ), + TextButton( + onPressed: () { + // todo 如果有高级查询条件被选择,但是被折叠了,点击重置是不会清除的。 + setState(() { + _formKey.currentState!.reset(); + // 2023-12-12 不知道为什么,reset对下拉选中的没有效,所以手动清除 + _formKey.currentState?.fields['primary_muscles'] + ?.didChange(null); + _formKey.currentState?.fields['level']?.didChange(null); + _formKey.currentState?.fields['mechanic'] + ?.didChange(null); + _formKey.currentState?.fields['category'] + ?.didChange(null); + _formKey.currentState?.fields['equipment'] + ?.didChange(null); + }); - // 失去焦点 - FocusScope.of(context).requestFocus(FocusNode()); - }, - child: Text( - CusAL.of(context).resetLabel, - style: TextStyle( - fontSize: CusFontSizes.itemContent, - color: Theme.of(context).primaryColor, + // 失去焦点 + unfocusHandle(); + }, + child: Text( + CusAL.of(context).resetLabel, + style: TextStyle( + fontSize: CusFontSizes.itemContent, + color: Theme.of(context).primaryColor, + ), ), ), - ), - ), - Expanded( - flex: 2, - child: ElevatedButton( - onPressed: _submitForm, - child: const Icon(Icons.search), - ), - // IconButton( - // onPressed: _submitForm, - // icon: Icon( - // Icons.search, - // size: 32.sp, - // color: Theme.of(context).primaryColor, - // ), - // ), - // ElevatedButton( - // onPressed: _submitForm, - // child: Text(CusAL.of(context).queryLabel), - // ), + // IconButton( + // onPressed: _showHintDialog, + // icon: Icon( + // Icons.warning_amber_rounded, + // size: CusIconSizes.iconMedium, + // ), + // ), + // IconButton( + // onPressed: () { + // setState(() { + // _showAdvancedOptions = !_showAdvancedOptions; + // }); + // }, + // icon: Icon( + // _showAdvancedOptions + // ? Icons.expand_less + // : Icons.expand_more, + // size: CusIconSizes.iconMedium, + // ), + // ), + // IconButton( + // onPressed: () { + // // todo 如果有高级查询条件被选择,但是被折叠了,点击重置是不会清除的。 + // setState(() { + // _formKey.currentState!.reset(); + // // 2023-12-12 不知道为什么,reset对下拉选中的没有效,所以手动清除 + // _formKey.currentState?.fields['primary_muscles'] + // ?.didChange(null); + // _formKey.currentState?.fields['level']?.didChange(null); + // _formKey.currentState?.fields['mechanic'] + // ?.didChange(null); + // _formKey.currentState?.fields['category'] + // ?.didChange(null); + // _formKey.currentState?.fields['equipment'] + // ?.didChange(null); + // }); + + // // 失去焦点 + // unfocusHandle(); + // }, + // icon: Icon( + // Icons.refresh, + // size: CusIconSizes.iconMedium, + // ), + // ), + ], ), ], ), @@ -194,7 +202,7 @@ class _ExerciseQueryFormState extends State { return Card( elevation: 5.sp, child: Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: Column( children: [ // 更多查询条件 diff --git a/lib/views/training/exercise/index.dart b/lib/views/training/exercise/index.dart index 6e2ba1e..8004b17 100644 --- a/lib/views/training/exercise/index.dart +++ b/lib/views/training/exercise/index.dart @@ -1,13 +1,8 @@ -// ignore_for_file: avoid_print - -import 'dart:io'; - import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:free_fitness/models/cus_app_localizations.dart'; import 'package:free_fitness/models/training_state.dart'; -import 'package:path_provider/path_provider.dart'; import '../../../common/components/dialog_widgets.dart'; import '../../../common/global/constants.dart'; @@ -43,8 +38,6 @@ class _TrainingExerciseState extends State { // 查询条件 Map? queryConditon; - late File file; - @override void initState() { super.initState(); @@ -95,10 +88,6 @@ class _TrainingExerciseState extends State { CusDataResult temp = await _searchExercise(); List newData = temp.data as List; - print("[[基础动作的洗洗脑]]---$newData"); - - print((await getExternalStorageDirectory())); - // 如果没有更多数据,则在底部显示 if (newData.isEmpty) { // 如果没有更多数据就回弹一下 @@ -154,11 +143,7 @@ class _TrainingExerciseState extends State { // 定义查询表单点击确认的回调函数,参数为查询条件的值 _handleQuery(Map query) { - // 处理查询条件的值 - print(query); // 示例:打印查询条件的值 - - // 失焦 - FocusScope.of(context).requestFocus(FocusNode()); + unfocusHandle(); // 有变动查询条件,则重新开始查询 setState(() { @@ -211,9 +196,7 @@ class _TrainingExerciseState extends State { children: [ TextSpan( text: '${CusAL.of(context).exercise}\n', - style: TextStyle( - fontSize: CusFontSizes.pageTitle, - ), + style: TextStyle(fontSize: CusFontSizes.pageTitle), ), TextSpan( text: CusAL.of(context).itemCount(itemsCount), @@ -265,7 +248,7 @@ class _TrainingExerciseState extends State { itemCount: exerciseItems.length + 1, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1, - childAspectRatio: 3, // 主轴和纵轴的比例 + childAspectRatio: 3.6, // 主轴和纵轴的比例 ), controller: scrollController, itemBuilder: (context, index) { @@ -366,6 +349,7 @@ class _TrainingExerciseState extends State { : []; return Card( + elevation: 2.sp, child: InkWell( onTap: () { // 点击卡片,弹窗显示基础活动的基本信息 @@ -392,13 +376,12 @@ class _TrainingExerciseState extends State { crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ - SizedBox( - width: 0.4.sw, - height: 0.3.sh, + Expanded( + flex: 3, child: buildImageCarouselSlider(imageList), ), Expanded( - flex: 3, + flex: 5, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -409,7 +392,7 @@ class _TrainingExerciseState extends State { overflow: TextOverflow.ellipsis, maxLines: 1, style: TextStyle( - fontSize: CusFontSizes.itemTitle, + fontSize: CusFontSizes.itemSmallTitle, fontWeight: FontWeight.bold, color: Theme.of(context).primaryColor, ), diff --git a/lib/views/training/index.dart b/lib/views/training/index.dart index 8140a91..0fc10d9 100644 --- a/lib/views/training/index.dart +++ b/lib/views/training/index.dart @@ -1,7 +1,4 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; -import 'package:flutter_screenutil/flutter_screenutil.dart'; import '../../common/components/cus_cards.dart'; import '../../common/global/constants.dart'; @@ -11,6 +8,19 @@ import 'plans/index.dart'; import 'reports/index.dart'; import 'workouts/index.dart'; +/// +/// 2024-11-15 +/// 几个概念说明,理论上: +/// 1 个 plan 有多个 group(workout) +/// 1 个 group(workout) 有多个 action +/// 1 个 action 对应 1 个增强的 exercise (会有更多的属性) +/// group 和 workout 的区别 (内核上没啥区别,代码中大部分都是group) +/// group 是针对 plan 来的,一个 plan 有多个 group +/// 但 group 的内容和 workout 是一样的,当 workout 被选中到某个 plan 中,就是该 plan 的一个 group +/// 从plan中 删除 group 不影响数据库中的 workout ,该 workout 还可以被其他 plan 选择 +/// 从数据库删除 workout,那就是永久删除了,其他plan就没得选 +/// 如果 workout 被某个 plan 使用中,那就无法删除,除非先删除 plan +/// class Training extends StatefulWidget { const Training({super.key}); @@ -19,99 +29,45 @@ class Training extends StatefulWidget { } class _TrainingState extends State { - @override - void initState() { - // 进入运动模块就获取存储授权(应该是启动app就需要这个请求) - // _requestPermission(); - super.initState(); - } - @override Widget build(BuildContext context) { - // 计算屏幕剩余的高度 - // 设备屏幕的总高度 - // - 屏幕顶部的安全区域高度,即状态栏的高度 - // - 屏幕底部的安全区域高度,即导航栏的高度或者虚拟按键的高度 - // - 应用程序顶部的工具栏(如 AppBar)的高度 - // - 应用程序底部的导航栏的高度 - // - 组件的边框间隔(不一定就是2) - double screenHeight = MediaQuery.of(context).size.height - - MediaQuery.of(context).padding.top - - MediaQuery.of(context).padding.bottom - - kToolbarHeight - - kBottomNavigationBarHeight - - 2 * 12.sp; // 减的越多,上下空隙越大 - return Scaffold( // 避免搜索时弹出键盘,让底部的minibar位置移动到tab顶部导致溢出的问题 resizeToAvoidBottomInset: false, - appBar: AppBar( - title: Text(CusAL.of(context).training), - ), - body: buildFixedBody(screenHeight), - ); - } - - // 可视页面固定等分居中、不可滚动的首页 - buildFixedBody(double screenHeight) { - return Center( - child: Column( + appBar: AppBar(title: Text(CusAL.of(context).training)), + body: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - // SizedBox( - // height: screenHeight / 4, - // child: buildSmallCoverCard( - // context, - // const TrainingReports(), - // CusAL.of(context).report, - // ), - // ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const TrainingReports(), - CusAL.of(context).trainingReports, - CusAL.of(context).trainingReportsSubtitle, - reportImageUrl, - ), + child: CusCoverCard( + targetPage: const TrainingReports(), + title: CusAL.of(context).trainingReports, + subtitle: CusAL.of(context).trainingReportsSubtitle, + imageUrl: reportImageUrl, ), ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const TrainingExercise(), - CusAL.of(context).exerciseLabel, - CusAL.of(context).exerciseSubtitle, - workoutWomanImageUrl, - ), + child: CusCoverCard( + targetPage: const TrainingExercise(), + title: CusAL.of(context).exerciseLabel, + subtitle: CusAL.of(context).exerciseSubtitle, + imageUrl: workoutWomanImageUrl, ), ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const TrainingWorkouts(), - CusAL.of(context).workout, - CusAL.of(context).workoutSubtitle, - workoutManImageUrl, - ), + child: CusCoverCard( + targetPage: const TrainingWorkouts(), + title: CusAL.of(context).workout, + subtitle: CusAL.of(context).workoutSubtitle, + imageUrl: workoutManImageUrl, ), ), Expanded( - child: SizedBox( - height: screenHeight / 4, - child: buildCoverCard( - context, - const TrainingPlans(), - CusAL.of(context).plan, - CusAL.of(context).planSubtitle, - workoutCalendarImageUrl, - ), + child: CusCoverCard( + targetPage: const TrainingPlans(), + title: CusAL.of(context).plan, + subtitle: CusAL.of(context).planSubtitle, + imageUrl: workoutCalendarImageUrl, ), ), ], diff --git a/lib/views/training/plans/group_list.dart b/lib/views/training/plans/group_list.dart index 663e503..a446a0a 100644 --- a/lib/views/training/plans/group_list.dart +++ b/lib/views/training/plans/group_list.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:free_fitness/views/training/workouts/action_list.dart'; @@ -20,8 +18,6 @@ import '../workouts/index.dart'; /// 在这个知道plan中新增训练,就需要跳转到后者列表去选择指定的训练,再带回来进行新增。 /// 这里删除某个训练只是从plan中移除某一个训练,后者删除某个训练就是直接从数据库删除了。 /// -/// -/// class GroupList extends StatefulWidget { // 从已存在的计划进入group list,会带上plan信息去查询已存在的group list final TrainingPlan planItem; @@ -55,10 +51,8 @@ class _GroupListState extends State { void initState() { super.initState(); - setState(() { - planItem = widget.planItem; - _getGroupListByPlanId(); - }); + planItem = widget.planItem; + _getGroupListByPlanId(); } // 查询指定训练中的动作列表 @@ -81,8 +75,7 @@ class _GroupListState extends State { var tempLog = await _dbHelper.queryLastTrainingDetailLogByPlanName(planItem); - print("动作组的跟练日志$tempLog"); - + if (!mounted) return; // 设置查询结果 setState(() { // 因为没有分页查询,所有这里直接替换已有的数组 @@ -121,6 +114,8 @@ class _GroupListState extends State { await _getGroupListByPlanId(); // 虽然更新了plan,则重新获取最新的plan var plans = await _dbHelper.queryTrainingPlanById(planItem.planId!); + + if (!mounted) return; if (plans.isNotEmpty) { setState(() { planItem = plans.first; @@ -165,12 +160,13 @@ class _GroupListState extends State { canPop: !_isEditing, // 处理pop操作。如果 didPop 为false,则pop被阻止,进行执行后面代码块的操作。 // 如果didPop为true,则直接返回。 - onPopInvoked: (didPop) async { + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) return; // (修改中点击返回按钮变为非修改中;非修改中点击返回则返回上一页) if (_isEditing) { // 取消时数据恢复原本的内容 await _getGroupListByPlanId(); + if (!mounted) return; setState(() { _isEditing = !_isEditing; }); @@ -202,6 +198,7 @@ class _GroupListState extends State { if (_isEditing) { // 取消时数据恢复原本的内容 await _getGroupListByPlanId(); + if (!mounted) return; setState(() { _isEditing = !_isEditing; }); @@ -213,25 +210,47 @@ class _GroupListState extends State { ), // 2023-12-04 因为有跟练日志之后再修改计划的内容可能会导致日志查不到对应的基础表数据 // 所以暂时有跟练的计划不让修改内容(理论上对应的action list也不允许再改了) - actions: (logMap.values.where((value) => value != null).isNotEmpty) - ? null - : [ - if (_isEditing) - IconButton( - icon: const Icon(Icons.cancel_outlined), - onPressed: () async { - // 取消时数据恢复原本的内容 - await _getGroupListByPlanId(); - setState(() { - _isEditing = !_isEditing; - }); - }, - ), - IconButton( - icon: Icon(_isEditing ? Icons.done : Icons.edit), - onPressed: _isEditing ? _onSavePressed : _onEditPressed, - ), - ], + actions: [ + // 没有训练日志的训练才可修改 + if (!(logMap.values + .where((value) => value != null) + .isNotEmpty)) ...[ + // 如果已经在修改中,显示取消修改按钮 + if (_isEditing) + IconButton( + icon: const Icon(Icons.cancel_outlined), + onPressed: () async { + // 取消时数据恢复原本的内容 + await _getGroupListByPlanId(); + if (!mounted) return; + setState(() { + _isEditing = !_isEditing; + }); + }, + ), + IconButton( + icon: Icon(_isEditing ? Icons.done : Icons.edit), + onPressed: _isEditing ? _onSavePressed : _onEditPressed, + ), + ], + IconButton( + icon: const Icon(Icons.info_outline), + onPressed: () { + var content = """ +- ${planItem.planCode} +- ${getCusLabelText(planItem.planCategory, categoryOptions)} +- ${getCusLabelText(planItem.planLevel, levelOptions)} +- ${CusAL.of(context).dayCount(planItem.planPeriod)} +- ${planItem.description} +"""; + commonMDHintModalBottomSheet( + context, + planItem.planName, + content, + ); + }, + ), + ], ), body: isLoading ? buildLoader(isLoading) @@ -245,7 +264,7 @@ class _GroupListState extends State { itemBuilder: (context, index) { return Card( key: Key('$index'), - elevation: 3, + elevation: 2.sp, child: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -274,11 +293,13 @@ class _GroupListState extends State { ), ), ).then((value) { - // 这里正常返回值的话,一定是一个GroupWithActions类型的 groupItem, - // 存入group列表尾部就好了 - setState(() { - groupList.add(value); - }); + // 这里正常返回值的话,一定是一个GroupWithActions类型的 groupItem, 存入group列表尾部就好了 + // 2024-11-15 注意,存在今日 workout 列表但是没有点选,直接返回的,value就为空 + if (value != null) { + setState(() { + groupList.add(value); + }); + } }); }, child: const Icon(Icons.add), @@ -292,7 +313,6 @@ class _GroupListState extends State { // 构建训练条目瓦片 _buildGroupItemListTile(List groupList, int index) { - // actionDetailItem GroupWithActions gwaItem = groupList[index]; TrainingGroup groupItem = gwaItem.group; diff --git a/lib/views/training/plans/index.dart b/lib/views/training/plans/index.dart index 6235ea1..e0f93a2 100644 --- a/lib/views/training/plans/index.dart +++ b/lib/views/training/plans/index.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -16,7 +14,8 @@ import 'group_list.dart'; /// /// 2023-11-22 和workout index 基本类似,几乎一模一样 -/// +/// 2024-11-14 +/// 但是类型、文字等不相同,本来想抽象类复用的,暂时没弄 /// class TrainingPlans extends StatefulWidget { const TrainingPlans({super.key}); @@ -51,9 +50,6 @@ class _TrainingPlansState extends State { // 如果已经在查询数据中,则忽略此次新的查询 if (isLoading) return; - print(DateTime.now()); - var a = DateTime.now().microsecondsSinceEpoch; - // 如果没在查询中,设置状态为查询中 setState(() { isLoading = true; @@ -78,10 +74,6 @@ class _TrainingPlansState extends State { planList = temp; // 重置状态为查询完成 isLoading = false; - - var b = DateTime.now().microsecondsSinceEpoch; - print(DateTime.now()); - print('【plan】查询耗时,微秒: ${b - a}'); }); } @@ -125,7 +117,15 @@ class _TrainingPlansState extends State { ), isLoading ? buildLoader(isLoading) - : Expanded(child: _buildPlanList()), + : Expanded( + child: ListView.builder( + itemCount: planList.length, + itemBuilder: (context, index) { + final planItem = planList[index]; + return _buildPlanCard(planItem); + }, + ), + ), ], ), ); @@ -220,132 +220,119 @@ class _TrainingPlansState extends State { ); } - // 数据列表区域 - _buildPlanList() { - return ListView.builder( - itemCount: planList.length, - itemBuilder: (context, index) { - final planItem = planList[index]; - - return Card( - elevation: 5.sp, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - ListTile( - leading: Icon(Icons.alarm_on, size: CusIconSizes.iconLarge), - title: Text( - planItem.plan.planName, - style: TextStyle( - fontSize: CusFontSizes.itemTitle, - fontWeight: FontWeight.w500, - ), + // 计划数据卡片(和action list几乎一模一样) + _buildPlanCard(PlanWithGroups planItem) { + return Card( + elevation: 2.sp, + child: ListTile( + leading: Icon(Icons.alarm_on, size: CusIconSizes.iconLarge), + title: Text( + planItem.plan.planName, + style: TextStyle( + fontSize: CusFontSizes.itemTitle, + color: Theme.of(context).primaryColor, + ), + ), + subtitle: RichText( + textAlign: TextAlign.left, + maxLines: 2, + softWrap: true, + overflow: TextOverflow.ellipsis, + text: TextSpan( + children: [ + TextSpan( + text: + '${planItem.groupDetailList.length} ${CusAL.of(context).workouts} ', + // 这里只是取text的默认颜色,避免浅主题时文字不显示(好像默认是白色,反正看不到) + style: TextStyle( + color: Theme.of(context).textTheme.bodyMedium?.color, ), - subtitle: RichText( - textAlign: TextAlign.left, - maxLines: 2, - softWrap: true, - overflow: TextOverflow.ellipsis, - text: TextSpan( - children: [ - TextSpan( - text: - '${planItem.groupDetailList.length} ${CusAL.of(context).workouts} ', - // 这里只是取text的默认颜色,避免浅主题时文字不显示(好像默认是白色,反正看不到) - style: TextStyle( - color: Theme.of(context).textTheme.bodyMedium?.color, - ), - ), - TextSpan( - text: - '${getCusLabelText(planItem.plan.planLevel, levelOptions)}', - style: TextStyle(color: Colors.green[500]), - ), - TextSpan( - // 可以不和exercise用同一个分类,但要单独列一个 - text: - ' ${getCusLabelText(planItem.plan.planCategory, categoryOptions)}', - style: TextStyle( - color: Theme.of(context).textTheme.bodyMedium?.color, - ), - ), - ], - ), + ), + TextSpan( + text: + '${getCusLabelText(planItem.plan.planLevel, levelOptions)}', + style: TextStyle(color: Colors.green[500]), + ), + TextSpan( + // 可以不和exercise用同一个分类,但要单独列一个 + text: + ' ${getCusLabelText(planItem.plan.planCategory, categoryOptions)}', + style: TextStyle( + color: Theme.of(context).textTheme.bodyMedium?.color, ), + ), + ], + ), + ), - trailing: SizedBox( - width: 30.sp, - child: IconButton( - icon: Icon( - Icons.edit, - size: CusIconSizes.iconNormal, - color: Theme.of(context).primaryColor, - ), + trailing: SizedBox( + width: 30.sp, + child: IconButton( + icon: Icon( + Icons.edit, + size: CusIconSizes.iconNormal, + color: Theme.of(context).primaryColor, + ), + onPressed: () { + _modifyPlanInfo(planItem: planItem.plan); + }, + ), + ), + onTap: () { + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => GroupList(planItem: planItem.plan), + ), + ).then((value) { + getPlanList(); + }); + }, + // 长按点击弹窗提示是否删除 + onLongPress: () async { + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text(CusAL.of(context).deleteConfirm), + content: Text( + CusAL.of(context).planDeleteAlert(planItem.plan.planName), + ), + actions: [ + TextButton( onPressed: () { - _modifyPlanInfo(planItem: planItem.plan); + Navigator.pop(context, false); }, + child: Text(CusAL.of(context).cancelLabel), ), - ), - onTap: () { - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => GroupList(planItem: planItem.plan), - ), - ).then((value) { - setState(() { - getPlanList(); - }); - }); - }, - // 长按点击弹窗提示是否删除 - onLongPress: () async { - showDialog( - context: context, - builder: (context) { - return AlertDialog( - title: Text(CusAL.of(context).deleteConfirm), - content: Text(CusAL.of(context) - .planDeleteAlert(planItem.plan.planName)), - actions: [ - TextButton( - onPressed: () { - Navigator.pop(context, false); - }, - child: Text(CusAL.of(context).cancelLabel), - ), - TextButton( - onPressed: () { - Navigator.pop(context, true); - }, - child: Text(CusAL.of(context).confirmLabel), - ), - ], - ); + TextButton( + onPressed: () { + Navigator.pop(context, true); }, - ).then((value) async { - if (value != null && value) { - try { - await _dbHelper.deletePlanById(planItem.plan.planId!); - - // 删除后重新查询 - getPlanList(); - } catch (e) { - if (!context.mounted) return; - commonExceptionDialog( - context, - CusAL.of(context).exceptionWarningTitle, - e.toString(), - ); - } - } - }); - }, - ), - ], - ), - ); - }, + child: Text(CusAL.of(context).confirmLabel), + ), + ], + ); + }, + ).then((value) async { + if (value != null && value) { + try { + await _dbHelper.deletePlanById(planItem.plan.planId!); + + // 删除后重新查询 + getPlanList(); + } catch (e) { + if (!mounted) return; + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + e.toString(), + ); + } + } + }); + }, + ), ); } @@ -356,9 +343,11 @@ class _TrainingPlansState extends State { context: context, builder: (BuildContext context) { return AlertDialog( - title: Text(planItem != null - ? CusAL.of(context).modifyPlanLabels('1') - : CusAL.of(context).modifyPlanLabels('0')), + title: Text( + planItem != null + ? CusAL.of(context).modifyPlanLabels('1') + : CusAL.of(context).modifyPlanLabels('0'), + ), content: _buildPlanModifyForm(planItem), actions: [ TextButton( @@ -448,16 +437,6 @@ class _TrainingPlansState extends State { // 获取表单数值 Map formData = _addFormKey.currentState!.value; - print("修改的计划表单数据-----$formData"); - // 对周期进行类型转换 - // var planPeriod = int.parse(formData['plan_period']); - // // 再放回去 - // // 深拷贝表单数据的Map,修改拷贝后的(原始的那个好像是不可修改的,会报错) - // var copiedFormData = Map.from(formData); - // copiedFormData["plan_period"] = planPeriod; - - // var temp = TrainingPlan.fromMap(copiedFormData); - // 2023-12-30 实际这个周期不需要用户手动输入,它就是该plan对应的group列表的长度 var temp = TrainingPlan.fromMap(formData); @@ -479,9 +458,7 @@ class _TrainingPlansState extends State { ).then((value) { // 新增plan基本信息后直接跳入训练列表,在其中完成新增训练操作之后该计划就会变; // 暂时返回这个页面时都重新加载最新的计划列表数据 - setState(() { - getPlanList(); - }); + getPlanList(); }); } else { // 如果是修改 @@ -491,9 +468,7 @@ class _TrainingPlansState extends State { // 如果是修改就返回训练组列表,而不是进入动作列表 if (!mounted) return; Navigator.of(context).pop(); - setState(() { - getPlanList(); - }); + getPlanList(); } } catch (e) { if (!mounted) return; diff --git a/lib/views/training/reports/export/report_pdf_export.dart b/lib/views/training/reports/export/report_pdf_export.dart index b43f355..2600b0d 100644 --- a/lib/views/training/reports/export/report_pdf_export.dart +++ b/lib/views/training/reports/export/report_pdf_export.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'dart:typed_data'; import 'package:flutter/services.dart' show rootBundle; @@ -104,7 +102,7 @@ _buildPdfPage( var trainedDate = DateTime.parse(date); return pw.Page( // theme和format两者不能同时存在 - pageTheme: pw.PageTheme(margin: pw.EdgeInsets.all(10.sp)), + pageTheme: pw.PageTheme(margin: pw.EdgeInsets.all(5.sp)), // 页面展示横向显示 // pageFormat: PdfPageFormat.a4.landscape, build: (context) { @@ -202,7 +200,7 @@ _buildBodyTable(List trainedData, String lang) { trainedData.fold(0, (prev, item) => prev + item.trainedDuration); return pw.Table( - // 字数据可以不显示边框,更方便看? + // 子数据可以不显示边框,更方便看? border: pw.TableBorder.all(color: PdfColors.black), children: [ ...trainedData.map((e) { diff --git a/lib/views/training/reports/export/report_pdf_viewer.dart b/lib/views/training/reports/export/report_pdf_viewer.dart index ee65ea9..3feaee9 100644 --- a/lib/views/training/reports/export/report_pdf_viewer.dart +++ b/lib/views/training/reports/export/report_pdf_viewer.dart @@ -60,6 +60,7 @@ class _TrainedReportPdfViewerState extends State { gmtCreateSort: "desc", ); + if (!mounted) return; setState(() { tdlList = temp; isLoading = false; @@ -83,6 +84,11 @@ class _TrainedReportPdfViewerState extends State { widget.endDate.split(" ")[0], lang: box.read('language'), ), + pdfFileName: box.read('language') == "en" + // ? "TrainedRecords_${widget.startDate}~${widget.endDate}" + // : "训练日志导出_${widget.startDate}~${widget.endDate}"), + ? "TrainingLogExport_${DateTime.now().millisecondsSinceEpoch}" + : "训练日志导出_${DateTime.now().millisecondsSinceEpoch}", ), ); } diff --git a/lib/views/training/reports/index.dart b/lib/views/training/reports/index.dart index 00b4e52..33b6667 100644 --- a/lib/views/training/reports/index.dart +++ b/lib/views/training/reports/index.dart @@ -1,9 +1,6 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:intl/intl.dart'; -import 'package:logger/logger.dart'; import 'package:table_calendar/table_calendar.dart'; import '../../../common/global/constants.dart'; @@ -23,9 +20,6 @@ class TrainingReports extends StatefulWidget { } class _TrainingReportsState extends State { - // 过长的字符串无法打印显示完,默认的developer库的log有时候没效果 - var log = Logger(); - // 数据是否加载中 bool isLoading = false; @@ -60,9 +54,7 @@ class _TrainingReportsState extends State { _getEventsForInitDay(); - setState(() { - initialIndex = 1; - }); + initialIndex = 1; } /// @@ -83,6 +75,7 @@ class _TrainingReportsState extends State { gmtCreateSort: "DESC", ); + if (!mounted) return; setState(() { tdlList = list; // 初始化时设定当前选中的日期就是聚焦的日期 @@ -106,13 +99,13 @@ class _TrainingReportsState extends State { // 当某一天被选中时的回调 _onDaySelected(DateTime selectedDay, DateTime focusedDay) { - print("某天被选中--------$selectedDay $focusedDay"); + debugPrint("某天被选中--------$selectedDay $focusedDay"); if (!isSameDay(_selectedDay, selectedDay)) { setState(() { _selectedDay = selectedDay; _focusedDay = focusedDay; - // 如果当前点击的日期就是已经被选中的日期,日期范围也得情况 + // 如果当前点击的日期就是已经被选中的日期,日期范围也得清空 _rangeStart = null; _rangeEnd = null; _rangeSelectionMode = RangeSelectionMode.toggledOff; @@ -124,13 +117,13 @@ class _TrainingReportsState extends State { // 当某个日期被长按 _onDayLongPressed(DateTime selectedDay, DateTime focusedDay) { - print("日期被长按了---$selectedDay --$focusedDay"); + debugPrint("日期被长按了---$selectedDay --$focusedDay"); // 长按某一天,可以新增备注??? } // 当日期范围被选中时 _onRangeSelected(DateTime? start, DateTime? end, DateTime focusedDay) { - print("日期被_onRangeSelected了---$start --$end $focusedDay"); + debugPrint("日期被_onRangeSelected了---$start --$end $focusedDay"); setState(() { _selectedDay = null; @@ -259,6 +252,9 @@ class _TrainingReportsState extends State { ); } + /// + /// 绘制训练统计的tab + /// buildReportsView() { // 统计的是所有的运动次数和总的运动时间 return FutureBuilder( @@ -283,7 +279,7 @@ class _TrainingReportsState extends State { ); } - // TrainedDetailLog-->tlwgb + // TrainedDetailLog-->tdl // 计算所有训练日志的累加时间 int totalRest = data.fold(0, (prevVal, tdl) => prevVal + tdl.totalRestTime); @@ -295,6 +291,7 @@ class _TrainingReportsState extends State { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + /// 总训练次数 SizedBox(height: 10.sp), Row( mainAxisAlignment: MainAxisAlignment.center, @@ -322,6 +319,8 @@ class _TrainingReportsState extends State { ), ], ), + + /// 总训练时长 SizedBox(height: 10.sp), Row( mainAxisAlignment: MainAxisAlignment.center, @@ -384,6 +383,8 @@ class _TrainingReportsState extends State { ), ], ), + + /// 上一次训练项目 SizedBox(height: 10.sp), Row( mainAxisAlignment: MainAxisAlignment.center, @@ -582,13 +583,8 @@ class _TrainingReportsState extends State { var log = value[index]; return Card( - elevation: 5, - margin: - EdgeInsets.symmetric(horizontal: 12.sp, vertical: 4.sp), - child: Padding( - padding: EdgeInsets.all(10.sp), - child: _buildTrainedDetailLogListTile(log), - ), + elevation: 2.sp, + child: _buildTrainedDetailLogListTile(log), ); }, ); @@ -658,9 +654,9 @@ class _TrainingReportsState extends State { ), ), Padding( - padding: EdgeInsets.fromLTRB(10.sp, 0, 10.sp, 10.sp), + padding: EdgeInsets.only(bottom: 10.sp), child: Card( - elevation: 5, + elevation: 5.sp, child: ListView.builder( // 和外层的滚动只保留一个 shrinkWrap: true, @@ -673,7 +669,7 @@ class _TrainingReportsState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ if (index != 0) - Divider(height: 5.sp, thickness: 3.sp), + Divider(height: 3.sp, thickness: 2.sp), _buildTrainedDetailLogListTile(log), ], ); diff --git a/lib/views/training/workouts/action_config_dialog.dart b/lib/views/training/workouts/action_config_dialog.dart index ed9360c..999706d 100644 --- a/lib/views/training/workouts/action_config_dialog.dart +++ b/lib/views/training/workouts/action_config_dialog.dart @@ -35,59 +35,23 @@ void showConfigDialog( // 其他需要输入的例如器械重量、action名称、描述之类的 final formKey = GlobalKey(); - // 底部的保存按钮区域(固定在底部靠上10) - Widget genBottomArea() { - return Center( - child: SizedBox( - width: 0.8.sw, - child: FloatingActionButton.extended( - onPressed: () { - // 点击保存按钮的逻辑 - if (formKey.currentState!.saveAndValidate()) { - // 输入的是0或者0.0或者0.000类似物,这里转换完都是0 - var tempWeight = double.tryParse( - formKey.currentState?.fields['equipment_weight']?.value, - ); - - // 是个对象,直接修改(直接复制的浅拷贝没意义) - ad.action.duration = timeInSeconds; - ad.action.frequency = count; - ad.action.equipmentWeight = - (tempWeight == 0 || tempWeight == 0.0) ? null : tempWeight; - - Navigator.pop(context); - - // 调用回调函数并传递数据 - onConfigurationDialogClosed(index, ad); - } - }, - label: Text( - CusAL.of(context).saveLabel, - style: TextStyle( - fontSize: CusFontSizes.buttonMedium, - // color: Theme.of(context).primaryColor, - ), - ), - ), - ), - ); - } - // 顶部的关闭按钮和重置按钮 List genTopArea() { - // 关闭按钮 return [ + // 弹窗标题 Positioned( - left: 20, - top: 10, + left: 20.sp, + top: 10.sp, child: Text( CusAL.of(context).actionConfigLabel('0'), style: TextStyle(fontSize: CusFontSizes.pageTitle), ), ), + + // 关闭按钮 Positioned( - right: 0, - top: 0, + right: 0.sp, + top: 0.sp, // 不要重置按钮了,就关闭再打开就好 child: IconButton( icon: Icon( @@ -186,7 +150,7 @@ void showConfigDialog( children: [ // 图片部分 SizedBox( - height: 200.0, + height: 200.sp, child: buildImageCarouselSlider(imageList), ), ], @@ -203,7 +167,7 @@ void showConfigDialog( SizedBox( height: 300.sp, child: Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: Container( padding: EdgeInsets.only(bottom: 20.sp), child: ListTile( @@ -220,7 +184,7 @@ void showConfigDialog( subtitle: SingleChildScrollView( scrollDirection: Axis.vertical, child: Text( - ad.exercise.instructions ?? "", + ad.exercise.instructions ?? '', overflow: TextOverflow.clip, // 设置文字溢出时的处理方式 ), ), @@ -229,7 +193,7 @@ void showConfigDialog( ), ), // 预留空白避免被下方的保存按钮挡住说明文字,显示不全 - SizedBox(height: 60.sp) + SizedBox(height: 120.sp) ], ), ], @@ -240,6 +204,44 @@ void showConfigDialog( ); } + // 底部的保存按钮区域(固定在底部靠上10) + Widget genBottomArea() { + return Center( + child: SizedBox( + width: 0.8.sw, + child: FloatingActionButton.extended( + onPressed: () { + // 点击保存按钮的逻辑 + if (formKey.currentState!.saveAndValidate()) { + // 输入的是0或者0.0或者0.000类似物,这里转换完都是0 + var tempWeight = double.tryParse( + formKey.currentState?.fields['equipment_weight']?.value, + ); + + // 是个对象,直接修改(直接复制的浅拷贝没意义) + ad.action.duration = timeInSeconds; + ad.action.frequency = count; + ad.action.equipmentWeight = + (tempWeight == 0 || tempWeight == 0.0) ? null : tempWeight; + + Navigator.pop(context); + + // 调用回调函数并传递数据 + onConfigurationDialogClosed(index, ad); + } + }, + label: Text( + CusAL.of(context).saveLabel, + style: TextStyle( + fontSize: CusFontSizes.buttonMedium, + // color: Theme.of(context).primaryColor, + ), + ), + ), + ), + ); + } + // 绘制弹窗 showModalBottomSheet( isScrollControlled: true, @@ -259,7 +261,7 @@ void showConfigDialog( Positioned( left: 0, right: 0, - top: 50, + top: 50.sp, child: genConfigBody(), ), diff --git a/lib/views/training/workouts/action_detail.dart b/lib/views/training/workouts/action_detail.dart index fa87b1f..8480ef8 100644 --- a/lib/views/training/workouts/action_detail.dart +++ b/lib/views/training/workouts/action_detail.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -150,27 +148,20 @@ class _ActionDetailDialogState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded( - child: Padding( - padding: EdgeInsets.only(right: 10.sp), - child: Text( - (_currentItem.exercise.countingMode == - countingOptions.first.value) - ? '${CusAL.of(context).actionDetailLabel('0')} ${_currentItem.action.duration}' - : '${CusAL.of(context).actionDetailLabel('1')} ${_currentItem.action.frequency}', - style: TextStyle(fontSize: CusFontSizes.flagMedium), - textAlign: TextAlign.end, - ), + child: Text( + (_currentItem.exercise.countingMode == countingOptions.first.value) + ? '${CusAL.of(context).actionDetailLabel('0')} ${_currentItem.action.duration}' + : '${CusAL.of(context).actionDetailLabel('1')} ${_currentItem.action.frequency}', + style: TextStyle(fontSize: CusFontSizes.flagMedium), + textAlign: TextAlign.center, ), ), if (_currentItem.action.equipmentWeight != null) Expanded( - child: Padding( - padding: EdgeInsets.only(left: 10.sp), - child: Text( - '${CusAL.of(context).actionDetailLabel('2')} ${cusDoubleTryToIntString(_currentItem.action.equipmentWeight!)}', - style: TextStyle(fontSize: CusFontSizes.flagMedium), - textAlign: TextAlign.start, - ), + child: Text( + '${CusAL.of(context).actionDetailLabel('2')} ${cusDoubleTryToIntString(_currentItem.action.equipmentWeight!)}', + style: TextStyle(fontSize: CusFontSizes.flagMedium), + textAlign: TextAlign.center, ), ), ], diff --git a/lib/views/training/workouts/action_follow_practice.dart b/lib/views/training/workouts/action_follow_practice.dart index c14c866..71b230e 100644 --- a/lib/views/training/workouts/action_follow_practice.dart +++ b/lib/views/training/workouts/action_follow_practice.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart' show kIsWeb; @@ -8,6 +6,7 @@ import 'package:flutter/material.dart'; import 'package:circular_countdown_timer/circular_countdown_timer.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_tts/flutter_tts.dart'; +import 'package:toastification/toastification.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import '../../../common/components/dialog_widgets.dart'; @@ -53,7 +52,7 @@ class _ActionFollowPracticeWithTTSState final _actionController = CountDownController(); // 休息时的倒计时组件控制器 final _restController = CountDownController(); - // 准备时的倒计时组件控制器 + // 预备时的倒计时组件控制器 final _prepareController = CountDownController(); /// 跟练的时候,可能是直接的某个训练;也可能是某个计划的某个训练日 @@ -67,7 +66,7 @@ class _ActionFollowPracticeWithTTSState // 当前的动作列表 late List actions; - // 设置动作开始索引为-1,这时不会匹配任何动作,只是为了有个准备的10秒倒计时 + // 设置动作开始索引为-1,这时不会匹配任何动作,只是为了有个预备的10秒倒计时 int _currentIndex = -1; // 预设的休息时间(从用户配置表读取的,是不变的。每次休息完成之后都要重置为这个时间) @@ -153,6 +152,7 @@ class _ActionFollowPracticeWithTTSState plan = widget.plan; dayNumber = widget.dayNumber; group = widget.group; + // 进入此跟练页面自动开始 startedMoment = DateTime.now(); }); @@ -171,9 +171,10 @@ class _ActionFollowPracticeWithTTSState /// /// 获取用户自定义的间隔耗时 /// - getUserConfig() async { + void getUserConfig() async { var tempUser = (await _userHelper.queryUser(userId: CacheUser.userId))!; + if (!mounted) return; setState(() { _defaultCusRestTime = tempUser.actionRestTime ?? 10; }); @@ -209,7 +210,7 @@ class _ActionFollowPracticeWithTTSState } /// 获取指定动作的次数或者持续时间(休息或者跟练的页面显示有用) - _getActionCountString(index) { + String _getActionCountString(index) { // currentActionDetail var curAd = actions[index]; // currentExercisecountingMode @@ -240,7 +241,7 @@ class _ActionFollowPracticeWithTTSState totalRestTimes = 0; _cusRestTime = _defaultCusRestTime; - // 修改索引为-1就直接到准备页面了 + // 修改索引为-1就直接到预备页面了 _currentIndex = -1; }); } @@ -254,7 +255,6 @@ class _ActionFollowPracticeWithTTSState /// /// TTS 相关的操作=============== /// - /// // 初始化tts服务 initTts() { @@ -269,42 +269,42 @@ class _ActionFollowPracticeWithTTSState flutterTts.setStartHandler(() { setState(() { - print("Playing"); + debugPrint("Playing"); ttsState = TtsState.playing; }); }); flutterTts.setCompletionHandler(() { setState(() { - print("Complete"); + debugPrint("Complete"); ttsState = TtsState.stopped; }); }); flutterTts.setCancelHandler(() { setState(() { - print("Cancel"); + debugPrint("Cancel"); ttsState = TtsState.stopped; }); }); flutterTts.setPauseHandler(() { setState(() { - print("Paused"); + debugPrint("Paused"); ttsState = TtsState.paused; }); }); flutterTts.setContinueHandler(() { setState(() { - print("Continued"); + debugPrint("Continued"); ttsState = TtsState.continued; }); }); flutterTts.setErrorHandler((msg) { setState(() { - print("error: $msg"); + debugPrint("【setErrorHandler】: $msg"); ttsState = TtsState.stopped; }); }); @@ -313,14 +313,24 @@ class _ActionFollowPracticeWithTTSState Future _getDefaultEngine() async { var engine = await flutterTts.getDefaultEngine; if (engine != null) { - print(engine); + } else { + if (!mounted) return; + // EasyLoading.showToast(CusAL.of(context).noTtsEngine); + toastification.show( + context: context, + type: ToastificationType.warning, + style: ToastificationStyle.fillColored, + alignment: Alignment.center, + title: Text(CusAL.of(context).noTtsEngine), + autoCloseDuration: const Duration(seconds: 5), + ); } } Future _getDefaultVoice() async { var voice = await flutterTts.getDefaultVoice; if (voice != null) { - print(voice); + debugPrint("【_getDefaultVoice】$voice"); } } @@ -337,52 +347,39 @@ class _ActionFollowPracticeWithTTSState Future _stop() async { var result = await flutterTts.stop(); + if (!mounted) return; if (result == 1) setState(() => ttsState = TtsState.stopped); } Future _pause() async { var result = await flutterTts.pause(); + if (!mounted) return; if (result == 1) setState(() => ttsState = TtsState.paused); } @override Widget build(BuildContext context) { - // 完成之后,这里页面点返回按钮,应该和弹窗中跳到报告页面一样。 - // ???或者正式的时候,弹窗就直接改为跳到报告页面即可 - // 跟练中点击返回按钮是暂停,然后询问用户是否确定退出,还是继续等等 + /// 跟练中点击返回按钮是暂停,然后询问用户是否确定退出,还是继续等等 return PopScope( // 跟练页面点击返回默认不返回,先暂停,然后弹窗提示是否退出;是就退出,否就继续 canPop: false, - onPopInvoked: (didPop) async { + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) return; + /// /// 点击了返回按钮,就先暂停,并弹窗询问是否退出跟练 - // 点击返回按钮时,可能处在准备、跟练、休息3种情况的任意一种。 - // 只要是已经开始或者继续的状态,就暂停 - // if (_actionController.isResumed || - // _actionController.isStarted || - // _actionController.isRestarted) { - // _actionController.pause(); - // } - // if (_restController.isResumed || - // _restController.isStarted || - // _restController.isRestarted) { - // _restController.pause(); - // } - // if (_prepareController.isResumed || - // _prepareController.isStarted || - // _prepareController.isRestarted) { - // _prepareController.pause(); - // } - - /// 2023-12-27 当前页面只会处于预备、跟练、休息中的某一个,切换后其他两个的anmation是dispose的 + /// - 点击返回按钮时,可能处在预备、跟练、休息3种情况的任意一种。 + /// - 只要是已经开始或者继续的状态,就暂停 + /// 2023-12-27 + /// 当前页面只会处于预备、跟练、休息中的某一个,切换后其他两个的anmation是dispose的 /// 所以还需要按照当前的页面是哪一个对应去暂停和继续,时机就和页面展示时一样 - // 预备页面的返回暂停 + /// + /// 预备页面的返回暂停 if (_currentIndex < 0) { - if (_prepareController.isResumed || - _prepareController.isStarted || - _prepareController.isRestarted) { + if (_prepareController.isResumed.value || + _prepareController.isStarted.value || + _prepareController.isRestarted.value) { _prepareController.pause(); } } @@ -390,21 +387,22 @@ class _ActionFollowPracticeWithTTSState if (!isRestTurn && _currentIndex >= 0 && _currentIndex <= actions.length - 1) { - if (_actionController.isResumed || - _actionController.isStarted || - _actionController.isRestarted) { + if (_actionController.isResumed.value || + _actionController.isStarted.value || + _actionController.isRestarted.value) { _actionController.pause(); } } // 休息页面的返回暂停 if (isRestTurn) { - if (_restController.isResumed || - _restController.isStarted || - _restController.isRestarted) { + if (_restController.isResumed.value || + _restController.isStarted.value || + _restController.isRestarted.value) { _restController.pause(); } } + if (!mounted) return; setState(() { pausedMoment = DateTime.now(); // 这个标志只是用于显示跟练画面的暂停和继续的文字, @@ -437,23 +435,14 @@ class _ActionFollowPracticeWithTTSState ).then((value) { // 确定确定退出跟练,就直接中断所有内容进行退出,没有任何记录;否则就是继续 if (value != null && value) { + if (!context.mounted) return; Navigator.pop(context); } else { - // 关闭弹窗,不是退出就继续跟练。如果这些控制器是暂停的状态,就恢复 - // if (_actionController.isPaused) { - // _actionController.resume(); - // } - // if (_restController.isPaused) { - // _restController.resume(); - // } - // if (_prepareController.isPaused) { - // _prepareController.resume(); - // } - + /// 关闭弹窗,不是退出就继续跟练。如果这些控制器是暂停的状态,就恢复 /// 2023-12-27 根据当前是哪个倒计时页面对应判断不同的倒计时控制器 - // 准备页面的暂停恢复 + // 预备页面的暂停恢复 if (_currentIndex < 0) { - if (_prepareController.isPaused) { + if (_prepareController.isPaused.value) { _prepareController.resume(); } } @@ -461,17 +450,18 @@ class _ActionFollowPracticeWithTTSState if (!isRestTurn && _currentIndex >= 0 && _currentIndex <= actions.length - 1) { - if (_actionController.isPaused) { + if (_actionController.isPaused.value) { _actionController.resume(); } } // 休息页面的暂停恢复 if (isRestTurn) { - if (_restController.isPaused) { + if (_restController.isPaused.value) { _restController.resume(); } } + if (!mounted) return; setState(() { // 点击继续时需要统计该次暂停的时间 totalPausedTimes += DateTime.now().millisecondsSinceEpoch - @@ -486,20 +476,20 @@ class _ActionFollowPracticeWithTTSState child: Scaffold( appBar: AppBar(title: Text(CusAL.of(context).workoutFollowLabel('0'))), body: Padding( - padding: EdgeInsets.all(10.sp), + padding: EdgeInsets.all(5.sp), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - // 专门的一个预备开始的倒计时(只有当前索引为-1的时候触发) + /// 专门的一个预备开始的倒计时(只有当前索引为-1的时候触发) if (_currentIndex < 0) ..._buildPrepareScreen(), - // 跟练的时候,动作不能调整倒计时 + /// 跟练的时候,动作不能调整倒计时 if (!isRestTurn && _currentIndex >= 0 && _currentIndex <= actions.length - 1) ..._buildFollowScreen(), - // 休息的时候,可以增加休息时间,或者跳过休息时间 + /// 休息的时候,可以增加休息时间,或者跳过休息时间 if (isRestTurn) ..._buildRestScreen(), ], ), @@ -589,6 +579,7 @@ class _ActionFollowPracticeWithTTSState _speak(prepareText); }, onComplete: () { + if (!mounted) return; setState(() { // 预备动作,下一个一定是跟练的第一个,所以设置索引加1(默认是-1开始的),非休息状态。 _currentIndex = 0; @@ -825,7 +816,7 @@ class _ActionFollowPracticeWithTTSState Expanded( flex: 1, child: Text( - '${_getActionCountString(_currentIndex)}', + _getActionCountString(_currentIndex), style: TextStyle( fontSize: CusFontSizes.flagSmall, color: Theme.of(context).disabledColor, @@ -1185,7 +1176,7 @@ class _ActionFollowPracticeWithTTSState Expanded( flex: 1, child: Text( - '${_getActionCountString(_currentIndex)}', + _getActionCountString(_currentIndex), style: TextStyle( fontSize: CusFontSizes.flagMedium, color: Theme.of(context).disabledColor, @@ -1268,13 +1259,13 @@ class _ActionFollowPracticeWithTTSState children: [ Text(CusAL.of(context).trainedDoneNote(totolTime)), Text( - ' ${CusAL.of(context).trainedCalendarLabels("3")}: $pausedTime ${CusAL.of(context).unitLabels("6")}', + '\t\t${CusAL.of(context).trainedCalendarLabels("3")}: $pausedTime ${CusAL.of(context).unitLabels("6")}', ), Text( - ' ${CusAL.of(context).trainedCalendarLabels("4")}: $totalRestTimes ${CusAL.of(context).unitLabels("6")}', + '\t\t${CusAL.of(context).trainedCalendarLabels("4")}: $totalRestTimes ${CusAL.of(context).unitLabels("6")}', ), Text( - ' ${CusAL.of(context).trainedCalendarLabels("2")}: $workoutTime ${CusAL.of(context).unitLabels("6")}', + '\t\t${CusAL.of(context).trainedCalendarLabels("2")}: $workoutTime ${CusAL.of(context).unitLabels("6")}', ), ], ), @@ -1314,6 +1305,7 @@ class _ActionFollowPracticeWithTTSState if (value == null || value == false) { // Navigator.pop(context); // 返回上一页还是直接到主页?跟练完之后没点击按钮直接返回主页更合理 + if (!mounted) return; Navigator.of(context).popUntil((route) => route.isFirst); } }); diff --git a/lib/views/training/workouts/action_list.dart b/lib/views/training/workouts/action_list.dart index 907da0c..8a83650 100644 --- a/lib/views/training/workouts/action_list.dart +++ b/lib/views/training/workouts/action_list.dart @@ -1,8 +1,5 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; -import 'package:logger/logger.dart'; import '../../../common/components/dialog_widgets.dart'; import '../../../common/global/constants.dart'; @@ -18,8 +15,8 @@ import 'action_follow_practice.dart'; import 'simple_exercise_list.dart'; class ActionList extends StatefulWidget { - // 从已存在的训练进入action list,会带上group信息去查询已存在的action list - // 2023-12-04 如果是从计划页面跳转过来,就需要带上计划的编号已经训练日信息 + // 从已存在的训练(workout)进入action list,会带上group信息去查询已存在的action list + // 2023-12-04 如果是从计划(plan)页面跳转过来,就还需要额外带上计划的编号以及训练日信息 final TrainingGroup groupItem; final TrainingPlan? planItem; final int? dayNumber; @@ -36,8 +33,6 @@ class ActionList extends StatefulWidget { } class _ActionListState extends State { - var log = Logger(); - final DBTrainingHelper _dbHelper = DBTrainingHelper(); // 这里不使用TrainingAction 是因为actionDetail有更多信息可以直接显示 @@ -72,6 +67,7 @@ class _ActionListState extends State { ); // 设置查询结果 + if (!mounted) return; setState(() { // ???因为没有分页查询,所有这里直接替换已有的数组 actionList = tempGWA.isNotEmpty ? tempGWA[0].actionDetailList : []; @@ -102,6 +98,7 @@ class _ActionListState extends State { // 点击了顶部保存按钮,把新的动作列表存入数据库,并更新动作列表页面 void _onSavePressed() async { await _saveActionList(); + if (!mounted) return; setState(() { _isEditing = false; }); @@ -148,13 +145,14 @@ class _ActionListState extends State { canPop: !_isEditing, // 处理pop操作。如果 didPop 为false,则pop被阻止,进行执行后面代码块的操作。 // 如果didPop为true,则直接返回。 - onPopInvoked: (didPop) async { + onPopInvokedWithResult: (bool didPop, Object? result) async { if (didPop) return; // ???这下面好像没生效,但返回上一层的逻辑又是正确的 - // (修改中点击返回按钮变为非修改中;非修改中点击返回则返回尚义页) + // (修改中点击返回按钮变为非修改中;非修改中点击返回则返回上一页) if (_isEditing) { // 取消时数据恢复原本的内容 await _getActionListByGroupId(); + if (!mounted) return; setState(() { _isEditing = !_isEditing; }); @@ -171,8 +169,9 @@ class _ActionListState extends State { text: TextSpan( children: [ TextSpan( - text: widget.groupItem.groupName, - style: TextStyle(fontSize: CusFontSizes.pageTitle)), + text: widget.groupItem.groupName, + style: TextStyle(fontSize: CusFontSizes.pageTitle), + ), TextSpan( text: "\n${CusAL.of(context).actionLabel('1')}: ${CusAL.of(context).itemCount(actionList.length)}", @@ -188,6 +187,7 @@ class _ActionListState extends State { if (_isEditing) { // 取消时数据恢复原本的内容 await _getActionListByGroupId(); + if (!mounted) return; setState(() { _isEditing = !_isEditing; }); @@ -207,6 +207,7 @@ class _ActionListState extends State { onPressed: () async { // 取消时数据恢复原本的内容 await _getActionListByGroupId(); + if (!mounted) return; setState(() { _isEditing = !_isEditing; }); @@ -222,9 +223,7 @@ class _ActionListState extends State { ? buildLoader(isLoading) : Column( children: [ - Expanded( - child: _buildReorderableList(), - ), + Expanded(child: _buildReorderableList()), // 避免修改时新增按钮遮住最后一条列表 if (_isEditing) SizedBox(height: 80.sp), ], @@ -261,6 +260,7 @@ class _ActionListState extends State { borderRadius: BorderRadius.circular(20.sp), // 设置圆角 ), backgroundColor: Colors.green, + // backgroundColor: Theme.of(context).primaryColor, ), child: Text( CusAL.of(context).startLabel, @@ -319,7 +319,7 @@ class _ActionListState extends State { : []; return Card( - elevation: 3, + elevation: 2.sp, key: Key('$index'), child: InkWell( onTap: () { @@ -421,6 +421,7 @@ class _ActionListState extends State { ); // 索引从0开始,所以新增的时候就从 actionList.length 开始 + if (!mounted) return; showConfigDialog(context, temp, actionList.length, onConfiguClosed); } }); diff --git a/lib/views/training/workouts/index.dart b/lib/views/training/workouts/index.dart index 603b072..c01fd1e 100644 --- a/lib/views/training/workouts/index.dart +++ b/lib/views/training/workouts/index.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -17,7 +15,7 @@ import 'action_list.dart'; class TrainingWorkouts extends StatefulWidget { // 2023-11-15 这个页面复用,直接看【训练】模块不会传东西, // 但在【计划】模块,指定计划的训练列表中新增时,则传一个标志过来。 - // 当检测到这个标志时,点击指定行数据后就把这行数据返回到计划的新增页面去。 + // 当检测到这个标志时,点击指定行数据后就把这行数据返回到计划的新增页面去。 // 不是指定计划的新增,则使用正常逻辑。 final bool? isPlanAdd; const TrainingWorkouts({super.key, this.isPlanAdd}); @@ -31,7 +29,7 @@ class _TrainingWorkoutsState extends State { // 查询表单的key final _queryFormKey = GlobalKey(); // 新增表单的key - final _groupFormKey = GlobalKey(); + final _addFormKey = GlobalKey(); // 展示训练列表(训练列表一次性查询所有,应该不会太多) List groupList = []; @@ -47,11 +45,9 @@ class _TrainingWorkoutsState extends State { void initState() { super.initState(); - setState(() { - getGroupList(); - // 如果没有传这个标志,则不是计划新增训练调过来的;如果有传,取其bool值 - isPlanAddGroup = (widget.isPlanAdd == null) ? false : widget.isPlanAdd!; - }); + getGroupList(); + // 如果没有传这个标志,则不是计划新增训练调过来的;如果有传,取其bool值 + isPlanAddGroup = (widget.isPlanAdd == null) ? false : widget.isPlanAdd!; } // 查询已有的训练 @@ -59,9 +55,6 @@ class _TrainingWorkoutsState extends State { // 如果已经在查询数据中,则忽略此次新的查询 if (isLoading) return; - print(DateTime.now()); - var a = DateTime.now().microsecondsSinceEpoch; - // 如果没在查询中,设置状态为查询中 setState(() { isLoading = true; @@ -87,17 +80,12 @@ class _TrainingWorkoutsState extends State { groupList = temp; // 重置状态为查询完成 isLoading = false; - - var b = DateTime.now().microsecondsSinceEpoch; - print(DateTime.now()); - print('训练查询耗时,微秒: ${b - a}'); }); } @override Widget build(BuildContext context) { return Scaffold( - resizeToAvoidBottomInset: true, // 打开键盘不重置按钮布局 appBar: AppBar( title: RichText( text: TextSpan( @@ -138,7 +126,16 @@ class _TrainingWorkoutsState extends State { ), ), ), - isLoading ? buildLoader(isLoading) : Expanded(child: _buildList()), + isLoading + ? buildLoader(isLoading) + : Expanded( + child: ListView.builder( + itemCount: groupList.length, + itemBuilder: (context, index) { + final groupItem = groupList[index]; + return _buildGroupCard(groupItem); + }, + )), ], ), ); @@ -173,11 +170,12 @@ class _TrainingWorkoutsState extends State { ?.didChange(null); _queryFormKey.currentState?.fields['group_level'] ?.didChange(null); + conditionMap = {}; getGroupList(); }); // 如果有键盘就收起键盘 - FocusScope.of(context).focusedChild?.unfocus(); + unfocusHandle(); }, child: Text( CusAL.of(context).resetLabel, @@ -225,7 +223,7 @@ class _TrainingWorkoutsState extends State { }); } // 如果有键盘就收起键盘 - FocusScope.of(context).focusedChild?.unfocus(); + unfocusHandle(); }, ), ) @@ -233,154 +231,145 @@ class _TrainingWorkoutsState extends State { ); } - // 数据列表区域 - _buildList() { - return ListView.builder( - itemCount: groupList.length, - itemBuilder: (context, index) { - final groupItem = groupList[index]; - - return Card( - elevation: 5.sp, - child: ListTile( - leading: Icon(Icons.alarm_on, size: CusIconSizes.iconLarge), - title: Text( - groupItem.group.groupName, - style: TextStyle( - fontSize: CusFontSizes.itemTitle, - color: Theme.of(context).primaryColor, + // 训练组数据卡片 + _buildGroupCard(GroupWithActions groupItem) { + return Card( + elevation: 2.sp, + child: ListTile( + leading: Icon(Icons.alarm_on, size: CusIconSizes.iconLarge), + title: Text( + groupItem.group.groupName, + style: TextStyle( + fontSize: CusFontSizes.itemTitle, + color: Theme.of(context).primaryColor, + ), + ), + subtitle: RichText( + textAlign: TextAlign.left, + maxLines: 2, + softWrap: true, + overflow: TextOverflow.ellipsis, + text: TextSpan( + children: [ + TextSpan( + text: + '${groupItem.actionDetailList.length} ${CusAL.of(context).exercise}', + // 这里只是取text的默认颜色,避免浅主题时文字不显示(好像默认是白色,反正看不到) + style: TextStyle( + color: Theme.of(context).textTheme.bodyMedium?.color, + ), ), - ), - subtitle: RichText( - textAlign: TextAlign.left, - maxLines: 2, - softWrap: true, - overflow: TextOverflow.ellipsis, - text: TextSpan( - children: [ - TextSpan( - text: - '${groupItem.actionDetailList.length} ${CusAL.of(context).exercise}', - // 这里只是取text的默认颜色,避免浅主题时文字不显示(好像默认是白色,反正看不到) - style: TextStyle( - color: Theme.of(context).textTheme.bodyMedium?.color, - ), - ), - TextSpan( - text: - ' ${getCusLabelText(groupItem.group.groupLevel, levelOptions)} ', - style: TextStyle(color: Colors.green[500]), - ), - TextSpan( - text: - '${getCusLabelText(groupItem.group.groupCategory, categoryOptions)}', - style: TextStyle( - color: Theme.of(context).textTheme.bodyMedium?.color, - ), + TextSpan( + text: + ' ${getCusLabelText(groupItem.group.groupLevel, levelOptions)} ', + style: TextStyle(color: Colors.green[500]), + ), + TextSpan( + text: + '${getCusLabelText(groupItem.group.groupCategory, categoryOptions)}', + style: TextStyle( + color: Theme.of(context).textTheme.bodyMedium?.color, + ), + ), + ], + ), + ), + + // 2023-11-23 如果是计划新增训练跳转来的,则不允许修改已有的训练或者新增训练,还是严格各自模块去完成各自的内容。 + // 如果说需要计划新增训练时可以再新增训练或者修改指定训练,则不做下面这个限制 + trailing: isPlanAddGroup + ? null + : SizedBox( + width: 30.sp, + child: IconButton( + icon: Icon( + Icons.edit, + size: CusIconSizes.iconNormal, + color: Theme.of(context).primaryColor, ), - ], + onPressed: () { + _modifyGroupInfo(groupItem: groupItem.group); + }, + ), ), - ), + onTap: () { + // 如果是计划新增训练跳转过来的,点击条目直接带值返回 + // (类型要一致,是GroupWithActions就好) + if (isPlanAddGroup) { + Navigator.pop(context, groupItem); + } else { + // 不传 GroupWithActions 类数据给 action list是因为: + // 1 新增训练时,还没有group;2 而且进入action list页面后,还是会不时修改其实。 + // 所以还是直接传TrainingGroup,主要给子组件group id即可 + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ActionList( + groupItem: groupItem.group, + ), + ), + ).then((value) { + // ???暂时返回这个页面时都重新加载最新的训练列表数据 + getGroupList(); + }); + } + }, + // 长按点击弹窗提示是否删除 + onLongPress: () async { + // 如果该训练有被使用,则不允许直接删除 + var list = await _dbHelper.isGroupUsed(groupItem.group.groupId!); - // 2023-11-23 如果是计划新增训练跳转来的,则不允许修改已有的训练或者新增训练,还是严格各自模块去完成各自的内容。 - // 如果说需要计划新增训练时可以再新增训练或者修改指定训练,则不做下面这个限制 - trailing: isPlanAddGroup - ? null - : SizedBox( - width: 30.sp, - child: IconButton( - icon: Icon( - Icons.edit, - size: CusIconSizes.iconNormal, - color: Theme.of(context).primaryColor, - ), + if (!mounted) return; + if (list.isNotEmpty) { + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + CusAL.of(context).groupInUse(groupItem.group.groupName), + ); + } else { + showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text(CusAL.of(context).deleteConfirm), + content: Text(CusAL.of(context) + .groupDeleteAlert(groupItem.group.groupName)), + actions: [ + TextButton( onPressed: () { - _modifyGroupInfo(groupItem: groupItem.group); + Navigator.pop(context, false); }, + child: Text(CusAL.of(context).cancelLabel), ), - ), - onTap: () { - // 如果是计划新增训练跳转过来的,点击条目直接带值返回 - // (类型要一致,是GroupWithActions就好) - if (isPlanAddGroup) { - Navigator.pop(context, groupItem); - } else { - // 不传 GroupWithActions 类数据给 action list是因为: - // 1 新增训练时,还没有group;2 而且进入action list页面后,还是会不时修改其实。 - // 所以还是直接传TrainingGroup,主要给子组件group id即可 - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => ActionList( - groupItem: groupItem.group, + TextButton( + onPressed: () { + Navigator.pop(context, true); + }, + child: Text(CusAL.of(context).confirmLabel), ), - ), - ).then((value) { - // ???暂时返回这个页面时都重新加载最新的训练列表数据 - setState(() { - getGroupList(); - }); - }); - } - }, - // 长按点击弹窗提示是否删除 - onLongPress: () async { - // 如果该训练有被使用,则不允许直接删除 - var list = await _dbHelper.isGroupUsed(groupItem.group.groupId!); - - if (!context.mounted) return; - if (list.isNotEmpty) { - commonExceptionDialog( - context, - CusAL.of(context).exceptionWarningTitle, - CusAL.of(context).groupInUse(groupItem.group.groupName), + ], ); - } else { - showDialog( - context: context, - builder: (context) { - return AlertDialog( - title: Text(CusAL.of(context).deleteConfirm), - content: Text(CusAL.of(context) - .groupDeleteAlert(groupItem.group.groupName)), - actions: [ - TextButton( - onPressed: () { - Navigator.pop(context, false); - }, - child: Text(CusAL.of(context).cancelLabel), - ), - TextButton( - onPressed: () { - Navigator.pop(context, true); - }, - child: Text(CusAL.of(context).confirmLabel), - ), - ], - ); - }, - ).then((value) async { - if (value != null && value) { - try { - await _dbHelper.deleteGroupById(groupItem.group.groupId!); + }, + ).then((value) async { + if (value != null && value) { + try { + await _dbHelper.deleteGroupById(groupItem.group.groupId!); - // 删除后重新查询 - getGroupList(); - } catch (e) { - if (!context.mounted) return; - commonExceptionDialog( - context, - CusAL.of(context).exceptionWarningTitle, - e.toString(), - ); - } - } - }); + // 删除后重新查询 + getGroupList(); + } catch (e) { + if (!mounted) return; + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + e.toString(), + ); + } } - }, - ), - ); - }, + }); + } + }, + ), ); } @@ -395,35 +384,7 @@ class _TrainingWorkoutsState extends State { ? CusAL.of(context).modifyGroupLabels('1') : CusAL.of(context).modifyGroupLabels('0'), ), - content: FormBuilder( - key: _groupFormKey, - initialValue: groupItem != null ? groupItem.toMap() : {}, - // autovalidateMode: AutovalidateMode.always, - child: SingleChildScrollView( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - cusFormBuilerTextField( - "group_name", - labelText: '*${CusAL.of(context).workoutQuerys('0')}', - validator: FormBuilderValidators.required(), - ), - cusFormBuilerDropdown( - "group_category", - categoryOptions, - labelText: '*${CusAL.of(context).workoutQuerys('1')}', - validator: FormBuilderValidators.required(), - ), - cusFormBuilerDropdown( - "group_level", - levelOptions, - labelText: '*${CusAL.of(context).workoutQuerys('2')}', - validator: FormBuilderValidators.required(), - ), - ], - ), - ), - ), + content: _buildGroupModifyForm(groupItem), actions: [ TextButton( child: Text(CusAL.of(context).cancelLabel), @@ -432,55 +393,96 @@ class _TrainingWorkoutsState extends State { }, ), TextButton( - child: Text(CusAL.of(context).confirmLabel), - onPressed: () async { - if (_groupFormKey.currentState!.saveAndValidate()) { - // 获取表单数值 - Map formData = - _groupFormKey.currentState!.value; - // 处理数据提交逻辑 - var temp = TrainingGroup.fromMap(formData); - - // 如果是新增 - if (groupItem == null) { - // ???这里应该验证是否新增成功 - var groupId = await _dbHelper.insertTrainingGroup(temp); - temp.groupId = groupId; - - if (!context.mounted) return; - Navigator.of(context).pop(); - Navigator.push( - context, - MaterialPageRoute( - builder: (context) => ActionList(groupItem: temp), - ), - ).then((value) { - setState(() { - getGroupList(); - }); - }); - } else { - // 如果是修改 - // ???这里应该验证是否修成功 - temp.groupId = groupItem.groupId!; - await _dbHelper.updateTrainingGroup( - groupItem.groupId!, - temp, - ); - - // 如果是修改就返回训练组列表,而不是进入动作列表 - if (!context.mounted) return; - Navigator.of(context).pop(); - setState(() { - getGroupList(); - }); - } - } + onPressed: () { + _clickGroupModifyButton(groupItem); }, + child: Text(CusAL.of(context).confirmLabel), ), ], ); }, ); } + + // 构建训练做主修改表单 + _buildGroupModifyForm(TrainingGroup? groupItem) { + return FormBuilder( + key: _addFormKey, + initialValue: groupItem != null ? groupItem.toMap() : {}, + // autovalidateMode: AutovalidateMode.always, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + cusFormBuilerTextField( + "group_name", + labelText: '*${CusAL.of(context).workoutQuerys('0')}', + validator: FormBuilderValidators.required(), + ), + cusFormBuilerDropdown( + "group_category", + categoryOptions, + labelText: '*${CusAL.of(context).workoutQuerys('1')}', + validator: FormBuilderValidators.required(), + ), + cusFormBuilerDropdown( + "group_level", + levelOptions, + labelText: '*${CusAL.of(context).workoutQuerys('2')}', + validator: FormBuilderValidators.required(), + ), + ], + ), + ), + ); + } + + // 构建确认编辑的回调 + _clickGroupModifyButton(TrainingGroup? groupItem) async { + if (_addFormKey.currentState!.saveAndValidate()) { + // 获取表单数值 + Map formData = _addFormKey.currentState!.value; + // 处理数据提交逻辑 + var temp = TrainingGroup.fromMap(formData); + try { + // 如果是新增 + if (groupItem == null) { + // ???这里应该验证是否新增成功 + var groupId = await _dbHelper.insertTrainingGroup(temp); + temp.groupId = groupId; + + if (!mounted) return; + Navigator.of(context).pop(); + Navigator.push( + context, + MaterialPageRoute( + builder: (context) => ActionList(groupItem: temp), + ), + ).then((value) { + getGroupList(); + }); + } else { + // 如果是修改 + // ???这里应该验证是否修成功 + temp.groupId = groupItem.groupId!; + await _dbHelper.updateTrainingGroup( + groupItem.groupId!, + temp, + ); + + // 如果是修改就返回训练组列表,而不是进入动作列表 + if (!mounted) return; + Navigator.of(context).pop(); + getGroupList(); + } + } catch (e) { + if (!mounted) return; + commonExceptionDialog( + context, + CusAL.of(context).exceptionWarningTitle, + e.toString(), + ); + } + } + } } diff --git a/lib/views/training/workouts/simple_exercise_list.dart b/lib/views/training/workouts/simple_exercise_list.dart index 822fa1f..7f73d53 100644 --- a/lib/views/training/workouts/simple_exercise_list.dart +++ b/lib/views/training/workouts/simple_exercise_list.dart @@ -1,5 +1,3 @@ -// ignore_for_file: avoid_print - import 'package:flutter/material.dart'; import 'package:flutter_form_builder/flutter_form_builder.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; @@ -79,8 +77,6 @@ class _SimpleExerciseListState extends State { isLoading = true; }); - print("查询数据中的条件$conditionMap"); - // 查询结果是个动态的list和该表的总数据,使用list要转型 CusDataResult temp; if (conditionMap.isEmpty) { @@ -104,8 +100,8 @@ class _SimpleExerciseListState extends State { List newData = temp.data as List; // 如果没有更多数据,则在底部显示回弹一下 + if (!mounted) return; if (newData.isEmpty) { - if (!mounted) return; scrollController.animateTo( scrollController.position.pixels, // 回弹的距离 duration: const Duration(milliseconds: 1000), // 动画持续300毫秒 @@ -197,7 +193,7 @@ class _SimpleExerciseListState extends State { _loadData(); }); // 如果有键盘就收起键盘 - FocusScope.of(context).focusedChild?.unfocus(); + unfocusHandle(); }, child: Text( CusAL.of(context).resetLabel, @@ -250,7 +246,7 @@ class _SimpleExerciseListState extends State { }); } // 如果有键盘就收起键盘 - FocusScope.of(context).focusedChild?.unfocus(); + unfocusHandle(); }, ), ) @@ -274,55 +270,55 @@ class _SimpleExerciseListState extends State { : []; return Card( - elevation: 10, + elevation: 2.sp, child: GestureDetector( onTap: () { // 在这里添加你想要执行的点击事件逻辑 Navigator.pop(context, exerciseItem); }, - child: Row( - children: [ - Expanded( - flex: 2, - child: Icon( - Icons.add_circle_outline, - color: Theme.of(context).primaryColor, + child: SizedBox( + height: 80.sp, + child: Row( + children: [ + Expanded( + flex: 2, + child: Icon( + Icons.add_circle_outline, + color: Theme.of(context).primaryColor, + ), ), - ), - Expanded( - flex: 9, - child: ListTile( - title: Text( - "${index + 1}-${exerciseItem.exerciseName}", - overflow: TextOverflow.ellipsis, - maxLines: 2, - style: TextStyle( - fontSize: CusFontSizes.itemTitle, - fontWeight: FontWeight.bold, + Expanded( + flex: 9, + child: ListTile( + title: Text( + "${index + 1}-${exerciseItem.exerciseName}", + overflow: TextOverflow.ellipsis, + maxLines: 2, + style: TextStyle( + fontSize: CusFontSizes.itemTitle, + fontWeight: FontWeight.bold, + ), + ), + subtitle: Text( + '${getCusLabelText( + exerciseItem.countingMode, + countingOptions, + )} ${getCusLabelText( + exerciseItem.level ?? '', + levelOptions, + )}', ), - ), - subtitle: Text( - '${getCusLabelText( - exerciseItem.countingMode, - countingOptions, - )} ${getCusLabelText( - exerciseItem.level ?? '', - levelOptions, - )}', ), ), - ), - Expanded( - flex: 6, - child: SizedBox( - height: 80.sp, + Expanded( + flex: 6, child: Padding( padding: EdgeInsets.all(5.sp), child: buildImageCarouselSlider(imageList), ), ), - ), - ], + ], + ), ), ), ); diff --git a/linux/.gitignore b/linux/.gitignore deleted file mode 100644 index d3896c9..0000000 --- a/linux/.gitignore +++ /dev/null @@ -1 +0,0 @@ -flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt deleted file mode 100644 index db5796b..0000000 --- a/linux/CMakeLists.txt +++ /dev/null @@ -1,139 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.10) -project(runner LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "free_fitness") -# The unique GTK application identifier for this application. See: -# https://wiki.gnome.org/HowDoI/ChooseApplicationID -set(APPLICATION_ID "com.swm.free_fitness") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Load bundled libraries from the lib/ directory relative to the binary. -set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") - -# Root filesystem for cross-building. -if(FLUTTER_TARGET_PLATFORM_SYSROOT) - set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) - set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) - set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) - set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) -endif() - -# Define build configuration options. -if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") -endif() - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_14) - target_compile_options(${TARGET} PRIVATE -Wall -Werror) - target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") - target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) - -add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") - -# Define the application target. To change its name, change BINARY_NAME above, -# not the value here, or `flutter run` will no longer work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} - "main.cc" - "my_application.cc" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add dependency libraries. Add any application-specific dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter) -target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) - -# Only the install-generated bundle's copy of the executable will launch -# correctly, since the resources must in the right relative locations. To avoid -# people trying to run the unbundled copy, put it in a subdirectory instead of -# the default top-level location. -set_target_properties(${BINARY_NAME} - PROPERTIES - RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" -) - - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# By default, "installing" just makes a relocatable bundle in the build -# directory. -set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -# Start with a clean build bundle directory every time. -install(CODE " - file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") - " COMPONENT Runtime) - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) - install(FILES "${bundled_library}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endforeach(bundled_library) - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") - install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt deleted file mode 100644 index d5bd016..0000000 --- a/linux/flutter/CMakeLists.txt +++ /dev/null @@ -1,88 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.10) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. - -# Serves the same purpose as list(TRANSFORM ... PREPEND ...), -# which isn't available in 3.10. -function(list_prepend LIST_NAME PREFIX) - set(NEW_LIST "") - foreach(element ${${LIST_NAME}}) - list(APPEND NEW_LIST "${PREFIX}${element}") - endforeach(element) - set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) -endfunction() - -# === Flutter Library === -# System-level dependencies. -find_package(PkgConfig REQUIRED) -pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) -pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) -pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) - -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "fl_basic_message_channel.h" - "fl_binary_codec.h" - "fl_binary_messenger.h" - "fl_dart_project.h" - "fl_engine.h" - "fl_json_message_codec.h" - "fl_json_method_codec.h" - "fl_message_codec.h" - "fl_method_call.h" - "fl_method_channel.h" - "fl_method_codec.h" - "fl_method_response.h" - "fl_plugin_registrar.h" - "fl_plugin_registry.h" - "fl_standard_message_codec.h" - "fl_standard_method_codec.h" - "fl_string_codec.h" - "fl_value.h" - "fl_view.h" - "flutter_linux.h" -) -list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") -target_link_libraries(flutter INTERFACE - PkgConfig::GTK - PkgConfig::GLIB - PkgConfig::GIO -) -add_dependencies(flutter flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CMAKE_CURRENT_BINARY_DIR}/_phony_ - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" - ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} -) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc deleted file mode 100644 index 7dd20b8..0000000 --- a/linux/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,31 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include -#include -#include -#include -#include - -void fl_register_plugins(FlPluginRegistry* registry) { - g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); - file_selector_plugin_register_with_registrar(file_selector_linux_registrar); - g_autoptr(FlPluginRegistrar) irondash_engine_context_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "IrondashEngineContextPlugin"); - irondash_engine_context_plugin_register_with_registrar(irondash_engine_context_registrar); - g_autoptr(FlPluginRegistrar) printing_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "PrintingPlugin"); - printing_plugin_register_with_registrar(printing_registrar); - g_autoptr(FlPluginRegistrar) super_native_extensions_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "SuperNativeExtensionsPlugin"); - super_native_extensions_plugin_register_with_registrar(super_native_extensions_registrar); - g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = - fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); - url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); -} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h deleted file mode 100644 index e0f0a47..0000000 --- a/linux/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void fl_register_plugins(FlPluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake deleted file mode 100644 index b2fc94a..0000000 --- a/linux/flutter/generated_plugins.cmake +++ /dev/null @@ -1,28 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - file_selector_linux - irondash_engine_context - printing - super_native_extensions - url_launcher_linux -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/linux/main.cc b/linux/main.cc deleted file mode 100644 index e7c5c54..0000000 --- a/linux/main.cc +++ /dev/null @@ -1,6 +0,0 @@ -#include "my_application.h" - -int main(int argc, char** argv) { - g_autoptr(MyApplication) app = my_application_new(); - return g_application_run(G_APPLICATION(app), argc, argv); -} diff --git a/linux/my_application.cc b/linux/my_application.cc deleted file mode 100644 index a55468a..0000000 --- a/linux/my_application.cc +++ /dev/null @@ -1,104 +0,0 @@ -#include "my_application.h" - -#include -#ifdef GDK_WINDOWING_X11 -#include -#endif - -#include "flutter/generated_plugin_registrant.h" - -struct _MyApplication { - GtkApplication parent_instance; - char** dart_entrypoint_arguments; -}; - -G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) - -// Implements GApplication::activate. -static void my_application_activate(GApplication* application) { - MyApplication* self = MY_APPLICATION(application); - GtkWindow* window = - GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); - - // Use a header bar when running in GNOME as this is the common style used - // by applications and is the setup most users will be using (e.g. Ubuntu - // desktop). - // If running on X and not using GNOME then just use a traditional title bar - // in case the window manager does more exotic layout, e.g. tiling. - // If running on Wayland assume the header bar will work (may need changing - // if future cases occur). - gboolean use_header_bar = TRUE; -#ifdef GDK_WINDOWING_X11 - GdkScreen* screen = gtk_window_get_screen(window); - if (GDK_IS_X11_SCREEN(screen)) { - const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); - if (g_strcmp0(wm_name, "GNOME Shell") != 0) { - use_header_bar = FALSE; - } - } -#endif - if (use_header_bar) { - GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); - gtk_widget_show(GTK_WIDGET(header_bar)); - gtk_header_bar_set_title(header_bar, "free_fitness"); - gtk_header_bar_set_show_close_button(header_bar, TRUE); - gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); - } else { - gtk_window_set_title(window, "free_fitness"); - } - - gtk_window_set_default_size(window, 1280, 720); - gtk_widget_show(GTK_WIDGET(window)); - - g_autoptr(FlDartProject) project = fl_dart_project_new(); - fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); - - FlView* view = fl_view_new(project); - gtk_widget_show(GTK_WIDGET(view)); - gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); - - fl_register_plugins(FL_PLUGIN_REGISTRY(view)); - - gtk_widget_grab_focus(GTK_WIDGET(view)); -} - -// Implements GApplication::local_command_line. -static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { - MyApplication* self = MY_APPLICATION(application); - // Strip out the first argument as it is the binary name. - self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); - - g_autoptr(GError) error = nullptr; - if (!g_application_register(application, nullptr, &error)) { - g_warning("Failed to register: %s", error->message); - *exit_status = 1; - return TRUE; - } - - g_application_activate(application); - *exit_status = 0; - - return TRUE; -} - -// Implements GObject::dispose. -static void my_application_dispose(GObject* object) { - MyApplication* self = MY_APPLICATION(object); - g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); - G_OBJECT_CLASS(my_application_parent_class)->dispose(object); -} - -static void my_application_class_init(MyApplicationClass* klass) { - G_APPLICATION_CLASS(klass)->activate = my_application_activate; - G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; - G_OBJECT_CLASS(klass)->dispose = my_application_dispose; -} - -static void my_application_init(MyApplication* self) {} - -MyApplication* my_application_new() { - return MY_APPLICATION(g_object_new(my_application_get_type(), - "application-id", APPLICATION_ID, - "flags", G_APPLICATION_NON_UNIQUE, - nullptr)); -} diff --git a/linux/my_application.h b/linux/my_application.h deleted file mode 100644 index 72271d5..0000000 --- a/linux/my_application.h +++ /dev/null @@ -1,18 +0,0 @@ -#ifndef FLUTTER_MY_APPLICATION_H_ -#define FLUTTER_MY_APPLICATION_H_ - -#include - -G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, - GtkApplication) - -/** - * my_application_new: - * - * Creates a new Flutter-based application. - * - * Returns: a new #MyApplication. - */ -MyApplication* my_application_new(); - -#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore deleted file mode 100644 index 746adbb..0000000 --- a/macos/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -# Flutter-related -**/Flutter/ephemeral/ -**/Pods/ - -# Xcode-related -**/dgph -**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig deleted file mode 100644 index c2efd0b..0000000 --- a/macos/Flutter/Flutter-Debug.xcconfig +++ /dev/null @@ -1 +0,0 @@ -#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig deleted file mode 100644 index c2efd0b..0000000 --- a/macos/Flutter/Flutter-Release.xcconfig +++ /dev/null @@ -1 +0,0 @@ -#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift deleted file mode 100644 index a08fdbc..0000000 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ /dev/null @@ -1,40 +0,0 @@ -// -// Generated file. Do not edit. -// - -import FlutterMacOS -import Foundation - -import connectivity_plus -import device_info_plus -import file_selector_macos -import flutter_inappwebview_macos -import flutter_tts -import gal -import irondash_engine_context -import package_info_plus -import path_provider_foundation -import printing -import sqflite -import super_native_extensions -import url_launcher_macos -import video_player_avfoundation -import wakelock_plus - -func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { - ConnectivityPlusPlugin.register(with: registry.registrar(forPlugin: "ConnectivityPlusPlugin")) - DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin")) - FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) - InAppWebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "InAppWebViewFlutterPlugin")) - FlutterTtsPlugin.register(with: registry.registrar(forPlugin: "FlutterTtsPlugin")) - GalPlugin.register(with: registry.registrar(forPlugin: "GalPlugin")) - IrondashEngineContextPlugin.register(with: registry.registrar(forPlugin: "IrondashEngineContextPlugin")) - FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) - PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) - PrintingPlugin.register(with: registry.registrar(forPlugin: "PrintingPlugin")) - SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) - SuperNativeExtensionsPlugin.register(with: registry.registrar(forPlugin: "SuperNativeExtensionsPlugin")) - UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) - FVPVideoPlayerPlugin.register(with: registry.registrar(forPlugin: "FVPVideoPlayerPlugin")) - WakelockPlusMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockPlusMacosPlugin")) -} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj deleted file mode 100644 index e6a0dd1..0000000 --- a/macos/Runner.xcodeproj/project.pbxproj +++ /dev/null @@ -1,695 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 54; - objects = { - -/* Begin PBXAggregateTarget section */ - 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { - isa = PBXAggregateTarget; - buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; - buildPhases = ( - 33CC111E2044C6BF0003C045 /* ShellScript */, - ); - dependencies = ( - ); - name = "Flutter Assemble"; - productName = FLX; - }; -/* End PBXAggregateTarget section */ - -/* Begin PBXBuildFile section */ - 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC10EC2044A3C60003C045; - remoteInfo = Runner; - }; - 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC111A2044C6BA0003C045; - remoteInfo = FLX; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXCopyFilesBuildPhase section */ - 33CC110E2044A8840003C045 /* Bundle Framework */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = ""; - dstSubfolderSpec = 10; - files = ( - ); - name = "Bundle Framework"; - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* free_fitness.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "free_fitness.app"; sourceTree = BUILT_PRODUCTS_DIR; }; - 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; - 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; - 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; - 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; - 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; - 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; - 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; - 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 331C80D2294CF70F00263BE5 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 33CC10EA2044A3C60003C045 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 331C80D6294CF71000263BE5 /* RunnerTests */ = { - isa = PBXGroup; - children = ( - 331C80D7294CF71000263BE5 /* RunnerTests.swift */, - ); - path = RunnerTests; - sourceTree = ""; - }; - 33BA886A226E78AF003329D5 /* Configs */ = { - isa = PBXGroup; - children = ( - 33E5194F232828860026EE4D /* AppInfo.xcconfig */, - 9740EEB21CF90195004384FC /* Debug.xcconfig */, - 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, - 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, - ); - path = Configs; - sourceTree = ""; - }; - 33CC10E42044A3C60003C045 = { - isa = PBXGroup; - children = ( - 33FAB671232836740065AC1E /* Runner */, - 33CEB47122A05771004F2AC0 /* Flutter */, - 331C80D6294CF71000263BE5 /* RunnerTests */, - 33CC10EE2044A3C60003C045 /* Products */, - D73912EC22F37F3D000D13A0 /* Frameworks */, - ); - sourceTree = ""; - }; - 33CC10EE2044A3C60003C045 /* Products */ = { - isa = PBXGroup; - children = ( - 33CC10ED2044A3C60003C045 /* free_fitness.app */, - 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, - ); - name = Products; - sourceTree = ""; - }; - 33CC11242044D66E0003C045 /* Resources */ = { - isa = PBXGroup; - children = ( - 33CC10F22044A3C60003C045 /* Assets.xcassets */, - 33CC10F42044A3C60003C045 /* MainMenu.xib */, - 33CC10F72044A3C60003C045 /* Info.plist */, - ); - name = Resources; - path = ..; - sourceTree = ""; - }; - 33CEB47122A05771004F2AC0 /* Flutter */ = { - isa = PBXGroup; - children = ( - 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, - 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, - 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, - 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, - ); - path = Flutter; - sourceTree = ""; - }; - 33FAB671232836740065AC1E /* Runner */ = { - isa = PBXGroup; - children = ( - 33CC10F02044A3C60003C045 /* AppDelegate.swift */, - 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, - 33E51913231747F40026EE4D /* DebugProfile.entitlements */, - 33E51914231749380026EE4D /* Release.entitlements */, - 33CC11242044D66E0003C045 /* Resources */, - 33BA886A226E78AF003329D5 /* Configs */, - ); - path = Runner; - sourceTree = ""; - }; - D73912EC22F37F3D000D13A0 /* Frameworks */ = { - isa = PBXGroup; - children = ( - ); - name = Frameworks; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - 331C80D4294CF70F00263BE5 /* RunnerTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; - buildPhases = ( - 331C80D1294CF70F00263BE5 /* Sources */, - 331C80D2294CF70F00263BE5 /* Frameworks */, - 331C80D3294CF70F00263BE5 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 331C80DA294CF71000263BE5 /* PBXTargetDependency */, - ); - name = RunnerTests; - productName = RunnerTests; - productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; - 33CC10EC2044A3C60003C045 /* Runner */ = { - isa = PBXNativeTarget; - buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; - buildPhases = ( - 33CC10E92044A3C60003C045 /* Sources */, - 33CC10EA2044A3C60003C045 /* Frameworks */, - 33CC10EB2044A3C60003C045 /* Resources */, - 33CC110E2044A8840003C045 /* Bundle Framework */, - 3399D490228B24CF009A79C7 /* ShellScript */, - ); - buildRules = ( - ); - dependencies = ( - 33CC11202044C79F0003C045 /* PBXTargetDependency */, - ); - name = Runner; - productName = Runner; - productReference = 33CC10ED2044A3C60003C045 /* free_fitness.app */; - productType = "com.apple.product-type.application"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - 33CC10E52044A3C60003C045 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1300; - ORGANIZATIONNAME = ""; - TargetAttributes = { - 331C80D4294CF70F00263BE5 = { - CreatedOnToolsVersion = 14.0; - TestTargetID = 33CC10EC2044A3C60003C045; - }; - 33CC10EC2044A3C60003C045 = { - CreatedOnToolsVersion = 9.2; - LastSwiftMigration = 1100; - ProvisioningStyle = Automatic; - SystemCapabilities = { - com.apple.Sandbox = { - enabled = 1; - }; - }; - }; - 33CC111A2044C6BA0003C045 = { - CreatedOnToolsVersion = 9.2; - ProvisioningStyle = Manual; - }; - }; - }; - buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; - compatibilityVersion = "Xcode 9.3"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = 33CC10E42044A3C60003C045; - productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 33CC10EC2044A3C60003C045 /* Runner */, - 331C80D4294CF70F00263BE5 /* RunnerTests */, - 33CC111A2044C6BA0003C045 /* Flutter Assemble */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 331C80D3294CF70F00263BE5 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 33CC10EB2044A3C60003C045 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, - 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXShellScriptBuildPhase section */ - 3399D490228B24CF009A79C7 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - ); - outputFileListPaths = ( - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; - }; - 33CC111E2044C6BF0003C045 /* ShellScript */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - Flutter/ephemeral/FlutterInputs.xcfilelist, - ); - inputPaths = ( - Flutter/ephemeral/tripwire, - ); - outputFileListPaths = ( - Flutter/ephemeral/FlutterOutputs.xcfilelist, - ); - outputPaths = ( - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; - }; -/* End PBXShellScriptBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 331C80D1294CF70F00263BE5 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 33CC10E92044A3C60003C045 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, - 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, - 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC10EC2044A3C60003C045 /* Runner */; - targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; - }; - 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; - targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin PBXVariantGroup section */ - 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { - isa = PBXVariantGroup; - children = ( - 33CC10F52044A3C60003C045 /* Base */, - ); - name = MainMenu.xib; - path = Runner; - sourceTree = ""; - }; -/* End PBXVariantGroup section */ - -/* Begin XCBuildConfiguration section */ - 331C80DB294CF71000263BE5 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.swm.free_fitness.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/free_fitness.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/free_fitness"; - }; - name = Debug; - }; - 331C80DC294CF71000263BE5 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.swm.free_fitness.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/free_fitness.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/free_fitness"; - }; - name = Release; - }; - 331C80DD294CF71000263BE5 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.swm.free_fitness.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/free_fitness.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/free_fitness"; - }; - name = Profile; - }; - 338D0CE9231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Profile; - }; - 338D0CEA231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Profile; - }; - 338D0CEB231458BD00FA5F75 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Profile; - }; - 33CC10F92044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; - MTL_ENABLE_DEBUG_INFO = YES; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - }; - name = Debug; - }; - 33CC10FA2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CODE_SIGN_IDENTITY = "-"; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; - MTL_ENABLE_DEBUG_INFO = NO; - SDKROOT = macosx; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - }; - name = Release; - }; - 33CC10FC2044A3C60003C045 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - }; - name = Debug; - }; - 33CC10FD2044A3C60003C045 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; - buildSettings = { - ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; - CLANG_ENABLE_MODULES = YES; - CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; - CODE_SIGN_STYLE = Automatic; - COMBINE_HIDPI_IMAGES = YES; - INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( - "$(inherited)", - "@executable_path/../Frameworks", - ); - PROVISIONING_PROFILE_SPECIFIER = ""; - SWIFT_VERSION = 5.0; - }; - name = Release; - }; - 33CC111C2044C6BA0003C045 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Manual; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Debug; - }; - 33CC111D2044C6BA0003C045 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - CODE_SIGN_STYLE = Automatic; - PRODUCT_NAME = "$(TARGET_NAME)"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 331C80DB294CF71000263BE5 /* Debug */, - 331C80DC294CF71000263BE5 /* Release */, - 331C80DD294CF71000263BE5 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10F92044A3C60003C045 /* Debug */, - 33CC10FA2044A3C60003C045 /* Release */, - 338D0CE9231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC10FC2044A3C60003C045 /* Debug */, - 33CC10FD2044A3C60003C045 /* Release */, - 338D0CEA231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 33CC111C2044C6BA0003C045 /* Debug */, - 33CC111D2044C6BA0003C045 /* Release */, - 338D0CEB231458BD00FA5F75 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = 33CC10E52044A3C60003C045 /* Project object */; -} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme deleted file mode 100644 index 2282a60..0000000 --- a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index 1d526a1..0000000 --- a/macos/Runner.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist deleted file mode 100644 index 18d9810..0000000 --- a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist +++ /dev/null @@ -1,8 +0,0 @@ - - - - - IDEDidComputeMac32BitWarning - - - diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift deleted file mode 100644 index d53ef64..0000000 --- a/macos/Runner/AppDelegate.swift +++ /dev/null @@ -1,9 +0,0 @@ -import Cocoa -import FlutterMacOS - -@NSApplicationMain -class AppDelegate: FlutterAppDelegate { - override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { - return true - } -} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json deleted file mode 100644 index a2ec33f..0000000 --- a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "images" : [ - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_16.png", - "scale" : "1x" - }, - { - "size" : "16x16", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "2x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_32.png", - "scale" : "1x" - }, - { - "size" : "32x32", - "idiom" : "mac", - "filename" : "app_icon_64.png", - "scale" : "2x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_128.png", - "scale" : "1x" - }, - { - "size" : "128x128", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "2x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_256.png", - "scale" : "1x" - }, - { - "size" : "256x256", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "2x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_512.png", - "scale" : "1x" - }, - { - "size" : "512x512", - "idiom" : "mac", - "filename" : "app_icon_1024.png", - "scale" : "2x" - } - ], - "info" : { - "version" : 1, - "author" : "xcode" - } -} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png deleted file mode 100644 index 82b6f9d..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png deleted file mode 100644 index 13b35eb..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png deleted file mode 100644 index 0a3f5fa..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png deleted file mode 100644 index bdb5722..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png deleted file mode 100644 index f083318..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png deleted file mode 100644 index 326c0e7..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png and /dev/null differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png deleted file mode 100644 index 2f1632c..0000000 Binary files a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png and /dev/null differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib deleted file mode 100644 index 80e867a..0000000 --- a/macos/Runner/Base.lproj/MainMenu.xib +++ /dev/null @@ -1,343 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig deleted file mode 100644 index 11665a3..0000000 --- a/macos/Runner/Configs/AppInfo.xcconfig +++ /dev/null @@ -1,14 +0,0 @@ -// Application-level settings for the Runner target. -// -// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the -// future. If not, the values below would default to using the project name when this becomes a -// 'flutter create' template. - -// The application's name. By default this is also the title of the Flutter window. -PRODUCT_NAME = free_fitness - -// The application's bundle identifier -PRODUCT_BUNDLE_IDENTIFIER = com.swm.free_fitness - -// The copyright displayed in application information -PRODUCT_COPYRIGHT = Copyright © 2023 com.swm. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig deleted file mode 100644 index 36b0fd9..0000000 --- a/macos/Runner/Configs/Debug.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "../../Flutter/Flutter-Debug.xcconfig" -#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig deleted file mode 100644 index dff4f49..0000000 --- a/macos/Runner/Configs/Release.xcconfig +++ /dev/null @@ -1,2 +0,0 @@ -#include "../../Flutter/Flutter-Release.xcconfig" -#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig deleted file mode 100644 index 42bcbf4..0000000 --- a/macos/Runner/Configs/Warnings.xcconfig +++ /dev/null @@ -1,13 +0,0 @@ -WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings -GCC_WARN_UNDECLARED_SELECTOR = YES -CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES -CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE -CLANG_WARN__DUPLICATE_METHOD_MATCH = YES -CLANG_WARN_PRAGMA_PACK = YES -CLANG_WARN_STRICT_PROTOTYPES = YES -CLANG_WARN_COMMA = YES -GCC_WARN_STRICT_SELECTOR_MATCH = YES -CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES -CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES -GCC_WARN_SHADOW = YES -CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements deleted file mode 100644 index dddb8a3..0000000 --- a/macos/Runner/DebugProfile.entitlements +++ /dev/null @@ -1,12 +0,0 @@ - - - - - com.apple.security.app-sandbox - - com.apple.security.cs.allow-jit - - com.apple.security.network.server - - - diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist deleted file mode 100644 index 4789daa..0000000 --- a/macos/Runner/Info.plist +++ /dev/null @@ -1,32 +0,0 @@ - - - - - CFBundleDevelopmentRegion - $(DEVELOPMENT_LANGUAGE) - CFBundleExecutable - $(EXECUTABLE_NAME) - CFBundleIconFile - - CFBundleIdentifier - $(PRODUCT_BUNDLE_IDENTIFIER) - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - $(PRODUCT_NAME) - CFBundlePackageType - APPL - CFBundleShortVersionString - $(FLUTTER_BUILD_NAME) - CFBundleVersion - $(FLUTTER_BUILD_NUMBER) - LSMinimumSystemVersion - $(MACOSX_DEPLOYMENT_TARGET) - NSHumanReadableCopyright - $(PRODUCT_COPYRIGHT) - NSMainNibFile - MainMenu - NSPrincipalClass - NSApplication - - diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift deleted file mode 100644 index 3cc05eb..0000000 --- a/macos/Runner/MainFlutterWindow.swift +++ /dev/null @@ -1,15 +0,0 @@ -import Cocoa -import FlutterMacOS - -class MainFlutterWindow: NSWindow { - override func awakeFromNib() { - let flutterViewController = FlutterViewController() - let windowFrame = self.frame - self.contentViewController = flutterViewController - self.setFrame(windowFrame, display: true) - - RegisterGeneratedPlugins(registry: flutterViewController) - - super.awakeFromNib() - } -} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements deleted file mode 100644 index 852fa1a..0000000 --- a/macos/Runner/Release.entitlements +++ /dev/null @@ -1,8 +0,0 @@ - - - - - com.apple.security.app-sandbox - - - diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift deleted file mode 100644 index 5418c9f..0000000 --- a/macos/RunnerTests/RunnerTests.swift +++ /dev/null @@ -1,12 +0,0 @@ -import FlutterMacOS -import Cocoa -import XCTest - -class RunnerTests: XCTestCase { - - func testExample() { - // If you add code to the Runner application, consider adding tests here. - // See https://developer.apple.com/documentation/xctest for more information about using XCTest. - } - -} diff --git a/pubspec.lock b/pubspec.lock index fe78287..6646de3 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -13,10 +13,10 @@ packages: dependency: transitive description: name: args - sha256: "7cf60b9f0cc88203c5a190b4cd62a99feea42759a7fa695010eb5de1c0b2252a" + sha256: bf9f5caeea8d8fe6721a9c358dd8a5c1947b27f1cfaa18b39c301273594919e6 url: "https://pub.dev" source: hosted - version: "2.5.0" + version: "2.6.0" async: dependency: transitive description: @@ -37,10 +37,10 @@ packages: dependency: transitive description: name: bidi - sha256: "1a7d0c696324b2089f72e7671fd1f1f64fef44c980f3cebc84e803967c597b63" + sha256: "9a712c7ddf708f7c41b1923aa83648a3ed44cfd75b04f72d598c45e5be287f9d" url: "https://pub.dev" source: hosted - version: "2.0.10" + version: "2.0.12" boolean_selector: dependency: transitive description: @@ -53,10 +53,10 @@ packages: dependency: "direct main" description: name: carousel_slider - sha256: "9c695cc963bf1d04a47bd6021f68befce8970bcd61d24938e1fb0918cf5d9c42" + sha256: "7b006ec356205054af5beaef62e2221160ea36b90fb70a35e4deacd49d0349ae" url: "https://pub.dev" source: hosted - version: "4.2.1" + version: "5.0.0" characters: dependency: transitive description: @@ -77,10 +77,10 @@ packages: dependency: "direct main" description: name: circular_countdown_timer - sha256: "9ba5fbc076cedbcbf6190ed86762e679f43d7c67cdd903ea34df059dabdc08d4" + sha256: "608d166c8c659af5740ffec8859e1429a4849b706675a529dc381ef40784697b" url: "https://pub.dev" source: hosted - version: "0.2.3" + version: "0.2.4" clock: dependency: transitive description: @@ -109,42 +109,42 @@ packages: dependency: "direct main" description: name: connectivity_plus - sha256: db7a4e143dc72cc3cb2044ef9b052a7ebfe729513e6a82943bc3526f784365b8 + sha256: "876849631b0c7dc20f8b471a2a03142841b482438e3b707955464f5ffca3e4c3" url: "https://pub.dev" source: hosted - version: "6.0.3" + version: "6.1.0" connectivity_plus_platform_interface: dependency: transitive description: name: connectivity_plus_platform_interface - sha256: b6a56efe1e6675be240de39107281d4034b64ac23438026355b4234042a35adb + sha256: "42657c1715d48b167930d5f34d00222ac100475f73d10162ddf43e714932f204" url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "2.0.1" cross_file: dependency: transitive description: name: cross_file - sha256: "55d7b444feb71301ef6b8838dbc1ae02e63dd48c8773f3810ff53bb1e2945b32" + sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670" url: "https://pub.dev" source: hosted - version: "0.3.4+1" + version: "0.3.4+2" crypto: dependency: transitive description: name: crypto - sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.0.6" csslib: dependency: transitive description: name: csslib - sha256: "706b5707578e0c1b4b7550f64078f0a0f19dec3f50a178ffae7006b0a9ca58fb" + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" url: "https://pub.dev" source: hosted - version: "1.0.0" + version: "1.0.2" cupertino_icons: dependency: "direct main" description: @@ -157,10 +157,10 @@ packages: dependency: transitive description: name: dart_quill_delta - sha256: "9799e35933d526cfe22c16b8d800c8a709f2d0688b87715b0f13a3f86ce1b656" + sha256: "2962476fb9471439a959b68b0e032febee76475e934f2d65d8d86dd0d5bff7a6" url: "https://pub.dev" source: hosted - version: "9.5.6" + version: "10.8.2" dbus: dependency: transitive description: @@ -173,18 +173,18 @@ packages: dependency: "direct main" description: name: device_info_plus - sha256: eead12d1a1ed83d8283ab4c2f3fca23ac4082f29f25f29dff0f758f57d06ec91 + sha256: a7fd703482b391a87d60b6061d04dfdeab07826b96f9abd8f5ed98068acc0074 url: "https://pub.dev" source: hosted - version: "10.1.0" + version: "10.1.2" device_info_plus_platform_interface: dependency: transitive description: name: device_info_plus_platform_interface - sha256: d3b01d5868b50ae571cd1dc6e502fc94d956b665756180f7b16ead09e836fd64 + sha256: "282d3cf731045a2feb66abfe61bbc40870ae50a3ed10a4d3d217556c35c8c2ba" url: "https://pub.dev" source: hosted - version: "7.0.0" + version: "7.0.1" diff_match_patch: dependency: transitive description: @@ -197,18 +197,18 @@ packages: dependency: "direct main" description: name: dio - sha256: e17f6b3097b8c51b72c74c9f071a605c47bcc8893839bd66732457a5ebe73714 + sha256: "5598aa796bbf4699afd5c67c0f5f6e2ed542afc956884b9cd58c306966efc260" url: "https://pub.dev" source: hosted - version: "5.5.0+1" + version: "5.7.0" dio_web_adapter: dependency: transitive description: name: dio_web_adapter - sha256: "36c5b2d79eb17cdae41e974b7a8284fec631651d2a6f39a8a2ff22327e90aeac" + sha256: "33259a9276d6cea88774a0000cfae0d861003497755969c92faa223108620dc8" url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "2.0.0" equatable: dependency: transitive description: @@ -229,42 +229,42 @@ packages: dependency: transitive description: name: ffi - sha256: "493f37e7df1804778ff3a53bd691d8692ddf69702cf4c1c1096a2e41b4779e21" + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" url: "https://pub.dev" source: hosted - version: "2.1.2" + version: "2.1.3" file: dependency: transitive description: name: file - sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 url: "https://pub.dev" source: hosted - version: "7.0.0" + version: "7.0.1" file_picker: dependency: "direct main" description: name: file_picker - sha256: be325344c1f3070354a1d84a231a1ba75ea85d413774ec4bdf444c023342e030 + sha256: aac85f20436608e01a6ffd1fdd4e746a7f33c93a2c83752e626bdfaea139b877 url: "https://pub.dev" source: hosted - version: "5.5.0" + version: "8.1.3" file_selector_linux: dependency: transitive description: name: file_selector_linux - sha256: "045d372bf19b02aeb69cacf8b4009555fb5f6f0b7ad8016e5f46dd1387ddd492" + sha256: "712ce7fab537ba532c8febdb1a8f167b32441e74acd68c3ccb2e36dcb52c4ab2" url: "https://pub.dev" source: hosted - version: "0.9.2+1" + version: "0.9.3" file_selector_macos: dependency: transitive description: name: file_selector_macos - sha256: f42eacb83b318e183b1ae24eead1373ab1334084404c8c16e0354f9a3e55d385 + sha256: "271ab9986df0c135d45c3cdb6bd0faa5db6f4976d3e4b437cf7d0f258d941bfc" url: "https://pub.dev" source: hosted - version: "0.9.4" + version: "0.9.4+2" file_selector_platform_interface: dependency: transitive description: @@ -277,42 +277,42 @@ packages: dependency: transitive description: name: file_selector_windows - sha256: d3547240c20cabf205c7c7f01a50ecdbc413755814d6677f3cb366f04abcead0 + sha256: "8f5d2f6590d51ecd9179ba39c64f722edc15226cc93dcc8698466ad36a4a85a4" url: "https://pub.dev" source: hosted - version: "0.9.3+1" + version: "0.9.3+3" fixnum: dependency: transitive description: name: fixnum - sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be url: "https://pub.dev" source: hosted - version: "1.1.0" + version: "1.1.1" fl_chart: dependency: "direct main" description: name: fl_chart - sha256: d0f0d49112f2f4b192481c16d05b6418bd7820e021e265a3c22db98acf7ed7fb + sha256: "94307bef3a324a0d329d3ab77b2f0c6e5ed739185ffc029ed28c0f9b019ea7ef" url: "https://pub.dev" source: hosted - version: "0.68.0" + version: "0.69.0" flex_color_scheme: dependency: "direct main" description: name: flex_color_scheme - sha256: "32914024a4f404d90ff449f58d279191675b28e7c08824046baf06826e99d984" + sha256: "03fd5e68eff346a042026577f54be0cd4507e565cd86390b12c0aca1c5d6cb0b" url: "https://pub.dev" source: hosted - version: "7.3.1" + version: "8.0.0" flex_seed_scheme: dependency: transitive description: name: flex_seed_scheme - sha256: "4cee2f1d07259f77e8b36f4ec5f35499d19e74e17c7dce5b819554914082bc01" + sha256: "7639d2c86268eff84a909026eb169f008064af0fb3696a651b24b0fa24a40334" url: "https://pub.dev" source: hosted - version: "1.5.0" + version: "3.4.1" flutter: dependency: "direct main" description: flutter @@ -338,74 +338,58 @@ packages: dependency: "direct main" description: name: flutter_form_builder - sha256: "447f8808f68070f7df968e8063aada3c9d2e90e789b5b70f3b44e4b315212656" - url: "https://pub.dev" - source: hosted - version: "9.3.0" - flutter_inappwebview: - dependency: transitive - description: - name: flutter_inappwebview - sha256: "3e9a443a18ecef966fb930c3a76ca5ab6a7aafc0c7b5e14a4a850cf107b09959" - url: "https://pub.dev" - source: hosted - version: "6.0.0" - flutter_inappwebview_android: - dependency: transitive - description: - name: flutter_inappwebview_android - sha256: d247f6ed417f1f8c364612fa05a2ecba7f775c8d0c044c1d3b9ee33a6515c421 + sha256: c278ef69b08957d484f83413f0e77b656a39b7a7bb4eb8a295da3a820ecc6545 url: "https://pub.dev" source: hosted - version: "1.0.13" - flutter_inappwebview_internal_annotations: - dependency: transitive + version: "9.5.0" + flutter_image_compress: + dependency: "direct main" description: - name: flutter_inappwebview_internal_annotations - sha256: "5f80fd30e208ddded7dbbcd0d569e7995f9f63d45ea3f548d8dd4c0b473fb4c8" + name: flutter_image_compress + sha256: "45a3071868092a61b11044c70422b04d39d4d9f2ef536f3c5b11fb65a1e7dd90" url: "https://pub.dev" source: hosted - version: "1.1.1" - flutter_inappwebview_ios: + version: "2.3.0" + flutter_image_compress_common: dependency: transitive description: - name: flutter_inappwebview_ios - sha256: f363577208b97b10b319cd0c428555cd8493e88b468019a8c5635a0e4312bd0f + name: flutter_image_compress_common + sha256: "7f79bc6c8a363063620b4e372fa86bc691e1cb28e58048cd38e030692fbd99ee" url: "https://pub.dev" source: hosted - version: "1.0.13" - flutter_inappwebview_macos: + version: "1.0.5" + flutter_image_compress_macos: dependency: transitive description: - name: flutter_inappwebview_macos - sha256: b55b9e506c549ce88e26580351d2c71d54f4825901666bd6cfa4be9415bb2636 + name: flutter_image_compress_macos + sha256: "26df6385512e92b3789dc76b613b54b55c457a7f1532e59078b04bf189782d47" url: "https://pub.dev" source: hosted - version: "1.0.11" - flutter_inappwebview_platform_interface: + version: "1.0.2" + flutter_image_compress_ohos: dependency: transitive description: - name: flutter_inappwebview_platform_interface - sha256: "545fd4c25a07d2775f7d5af05a979b2cac4fbf79393b0a7f5d33ba39ba4f6187" + name: flutter_image_compress_ohos + sha256: e76b92bbc830ee08f5b05962fc78a532011fcd2041f620b5400a593e96da3f51 url: "https://pub.dev" source: hosted - version: "1.0.10" - flutter_inappwebview_web: + version: "0.0.3" + flutter_image_compress_platform_interface: dependency: transitive description: - name: flutter_inappwebview_web - sha256: d8c680abfb6fec71609a700199635d38a744df0febd5544c5a020bd73de8ee07 + name: flutter_image_compress_platform_interface + sha256: "579cb3947fd4309103afe6442a01ca01e1e6f93dc53bb4cbd090e8ce34a41889" url: "https://pub.dev" source: hosted - version: "1.0.8" - flutter_keyboard_visibility: + version: "1.0.5" + flutter_image_compress_web: dependency: transitive description: - name: flutter_keyboard_visibility - sha256: "98664be7be0e3ffca00de50f7f6a287ab62c763fc8c762e0a21584584a3ff4f8" + name: flutter_image_compress_web + sha256: f02fe352b17f82b72f481de45add240db062a2585850bea1667e82cc4cd6c311 url: "https://pub.dev" source: hosted - version: "6.0.0" + version: "0.1.4+1" flutter_keyboard_visibility_linux: dependency: transitive description: @@ -430,14 +414,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" - flutter_keyboard_visibility_web: + flutter_keyboard_visibility_temp_fork: dependency: transitive description: - name: flutter_keyboard_visibility_web - sha256: d3771a2e752880c79203f8d80658401d0c998e4183edca05a149f5098ce6e3d1 + name: flutter_keyboard_visibility_temp_fork + sha256: "2d94acecfc170d244157821cc67e784f60972677aac94a6672626a5d6b2dc537" url: "https://pub.dev" source: hosted - version: "2.0.0" + version: "0.1.3" flutter_keyboard_visibility_windows: dependency: transitive description: @@ -463,34 +447,42 @@ packages: dependency: "direct main" description: name: flutter_markdown - sha256: "2e8a801b1ded5ea001a4529c97b1f213dcb11c6b20668e081cafb23468593514" + sha256: f0e599ba89c9946c8e051780f0ec99aba4ba15895e0380a7ab68f420046fc44e url: "https://pub.dev" source: hosted - version: "0.7.3" + version: "0.7.4+1" flutter_plugin_android_lifecycle: dependency: transitive description: name: flutter_plugin_android_lifecycle - sha256: c6b0b4c05c458e1c01ad9bcc14041dd7b1f6783d487be4386f793f47a8a4d03e + sha256: "9b78450b89f059e96c9ebb355fa6b3df1d6b330436e0b885fb49594c41721398" url: "https://pub.dev" source: hosted - version: "2.0.20" + version: "2.0.23" flutter_quill: dependency: "direct main" description: name: flutter_quill - sha256: d6cb535e7c4c269a69a981d376ac51502f3f1e0ba636ecc5ea2c2a31d9af143c + sha256: "6274834823e61291c0cedee9dd7f73fc7836ea07a12596de8f5fa08598b5eb74" + url: "https://pub.dev" + source: hosted + version: "10.8.5" + flutter_quill_delta_from_html: + dependency: transitive + description: + name: flutter_quill_delta_from_html + sha256: "288f879bd11f9b6857868e7b198e69918530bd63d196ead6d8a9ee780b4b44d2" url: "https://pub.dev" source: hosted - version: "9.5.6" + version: "1.4.2" flutter_quill_extensions: dependency: "direct main" description: name: flutter_quill_extensions - sha256: d543b274e03c8e1ed710f9d88ed722098e27f2fb9b6d91c563fe68ef983ddf4a + sha256: e8ff79c2bbdbf57d3248ec07055ec54ef0c35e270659d6058efd42a0e0ae1286 url: "https://pub.dev" source: hosted - version: "9.5.6" + version: "10.8.5" flutter_screenutil: dependency: "direct main" description: @@ -529,26 +521,26 @@ packages: dependency: "direct main" description: name: form_builder_file_picker - sha256: "4d115d0c2d7754576866d7a4d4e364bd095bf368297c40a66209ac70bd2e3d0f" + sha256: "8bd5fca63a13bb5446c272e9d6968d114b3600496b291e34e76160a1b9219115" url: "https://pub.dev" source: hosted - version: "4.1.0" + version: "4.2.0" form_builder_validators: dependency: "direct main" description: name: form_builder_validators - sha256: "475853a177bfc832ec12551f752fd0001278358a6d42d2364681ff15f48f67cf" + sha256: c61ed7b1deecf0e1ebe49e2fa79e3283937c5a21c7e48e3ed9856a4a14e1191a url: "https://pub.dev" source: hosted - version: "10.0.1" + version: "11.0.0" freezed_annotation: dependency: transitive description: name: freezed_annotation - sha256: f54946fdb1fa7b01f780841937b1a80783a20b393485f3f6cdf336fd6f4705f2 + sha256: c2e2d632dd9b8a2b7751117abcfc2b4888ecfe181bd9fca7170d9ef02e595fe2 url: "https://pub.dev" source: hosted - version: "2.4.2" + version: "2.4.4" gal: dependency: transitive description: @@ -561,10 +553,10 @@ packages: dependency: transitive description: name: gal_linux - sha256: cbff918888aaa7b86d5a992764ad94d217347d63912e008e8449605b1cc0b38a + sha256: "0040d61843134cc5a93e4597080a86f2ba073217957e28b2a684b4d8b050873c" url: "https://pub.dev" source: hosted - version: "0.1.0" + version: "0.1.2" get: dependency: transitive description: @@ -585,26 +577,18 @@ packages: dependency: transitive description: name: html - sha256: "3a7812d5bcd2894edf53dfaf8cd640876cf6cef50a8f238745c8b8120ea74d3a" + sha256: "1fc58edeaec4307368c60d59b7e15b9d658b57d7f3125098b6294153c75337ec" url: "https://pub.dev" source: hosted - version: "0.15.4" - html2md: - dependency: transitive - description: - name: html2md - sha256: "465cf8ffa1b510fe0e97941579bf5b22e2d575f2cecb500a9c0254efe33a8036" - url: "https://pub.dev" - source: hosted - version: "1.3.2" + version: "0.15.5" http: dependency: transitive description: name: http - sha256: "761a297c042deedc1ffbb156d6e2af13886bb305c2a343a4d972504cd67dd938" + sha256: b9c29a161230ee03d3ccf545097fccd9b87a5264228c5d348202e0f0c28f9010 url: "https://pub.dev" source: hosted - version: "1.2.1" + version: "1.2.2" http_parser: dependency: transitive description: @@ -613,22 +597,22 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.2" - image: + iconsax_flutter: dependency: transitive description: - name: image - sha256: "2237616a36c0d69aef7549ab439b833fb7f9fb9fc861af2cc9ac3eedddd69ca8" + name: iconsax_flutter + sha256: "95b65699da8ea98f87c5d232f06b0debaaf1ec1332b697e4d90969ec9a93037d" url: "https://pub.dev" source: hosted - version: "4.2.0" - image_gallery_saver: - dependency: "direct main" + version: "1.0.0" + image: + dependency: transitive description: - name: image_gallery_saver - sha256: "0aba74216a4d9b0561510cb968015d56b701ba1bd94aace26aacdd8ae5761816" + name: image + sha256: f31d52537dc417fdcde36088fdf11d191026fd5e4fae742491ebd40e5a8bea7d url: "https://pub.dev" source: hosted - version: "2.0.3" + version: "4.3.0" image_picker: dependency: "direct main" description: @@ -641,26 +625,26 @@ packages: dependency: transitive description: name: image_picker_android - sha256: "4161e1f843d8480d2e9025ee22411778c3c9eb7e40076dcf2da23d8242b7b51c" + sha256: "8faba09ba361d4b246dc0a17cb4289b3324c2b9f6db7b3d457ee69106a86bd32" url: "https://pub.dev" source: hosted - version: "0.8.12+3" + version: "0.8.12+17" image_picker_for_web: dependency: transitive description: name: image_picker_for_web - sha256: "5d6eb13048cd47b60dbf1a5495424dea226c5faf3950e20bf8120a58efb5b5f3" + sha256: "717eb042ab08c40767684327be06a5d8dbb341fe791d514e4b92c7bbe1b7bb83" url: "https://pub.dev" source: hosted - version: "3.0.4" + version: "3.0.6" image_picker_ios: dependency: transitive description: name: image_picker_ios - sha256: "6703696ad49f5c3c8356d576d7ace84d1faf459afb07accbb0fae780753ff447" + sha256: "4f0568120c6fcc0aaa04511cb9f9f4d29fc3d0139884b1d06be88dcec7641d6b" url: "https://pub.dev" source: hosted - version: "0.8.12" + version: "0.8.12+1" image_picker_linux: dependency: transitive description: @@ -729,10 +713,10 @@ packages: dependency: transitive description: name: js - sha256: f2c445dce49627136094980615a031419f7f3eb393237e4ecd97ac15dea343f3 + sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf url: "https://pub.dev" source: hosted - version: "0.6.7" + version: "0.7.1" json_annotation: dependency: transitive description: @@ -745,18 +729,18 @@ packages: dependency: transitive description: name: leak_tracker - sha256: "7f0df31977cb2c0b88585095d168e689669a2cc9b97c309665e3386f3e9d341a" + sha256: "3f87a60e8c63aecc975dda1ceedbc8f24de75f09e4856ea27daf8958f2f0ce05" url: "https://pub.dev" source: hosted - version: "10.0.4" + version: "10.0.5" leak_tracker_flutter_testing: dependency: transitive description: name: leak_tracker_flutter_testing - sha256: "06e98f569d004c1315b991ded39924b21af84cf14cc94791b8aea337d25b57f8" + sha256: "932549fb305594d82d7183ecd9fa93463e9914e1b67cacc34bc40906594a1806" url: "https://pub.dev" source: hosted - version: "3.0.3" + version: "3.0.5" leak_tracker_testing: dependency: transitive description: @@ -773,14 +757,30 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.0" + lists: + dependency: transitive + description: + name: lists + sha256: "4ca5c19ae4350de036a7e996cdd1ee39c93ac0a2b840f4915459b7d0a7d4ab27" + url: "https://pub.dev" + source: hosted + version: "1.0.1" logger: dependency: "direct main" description: name: logger - sha256: af05cc8714f356fd1f3888fb6741cbe9fbe25cdb6eedbab80e1a6db21047d4a4 + sha256: "697d067c60c20999686a0add96cf6aba723b3aa1f83ecf806a8097231529ec32" url: "https://pub.dev" source: hosted - version: "2.3.0" + version: "2.4.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" markdown: dependency: transitive description: @@ -801,26 +801,26 @@ packages: dependency: transitive description: name: material_color_utilities - sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec url: "https://pub.dev" source: hosted - version: "0.8.0" + version: "0.11.1" meta: dependency: transitive description: name: meta - sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 url: "https://pub.dev" source: hosted - version: "1.12.0" + version: "1.15.0" mime: dependency: transitive description: name: mime - sha256: "2e123074287cc9fd6c09de8336dae606d1ddb88d9ac47358826db698c176a1f2" + sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6" url: "https://pub.dev" source: hosted - version: "1.0.5" + version: "2.0.0" multi_select_flutter: dependency: "direct main" description: @@ -849,18 +849,18 @@ packages: dependency: transitive description: name: package_info_plus - sha256: b93d8b4d624b4ea19b0a5a208b2d6eff06004bc3ce74c06040b120eeadd00ce0 + sha256: da8d9ac8c4b1df253d1a328b7bf01ae77ef132833479ab40763334db13b91cce url: "https://pub.dev" source: hosted - version: "8.0.0" + version: "8.1.1" package_info_plus_platform_interface: dependency: transitive description: name: package_info_plus_platform_interface - sha256: f49918f3433a3146047372f9d4f1f847511f2acd5cd030e1f44fe5a50036b70e + sha256: ac1f4a4847f1ade8e6a87d1f39f5d7c67490738642e2542f559ec38c37489a66 url: "https://pub.dev" source: hosted - version: "3.0.0" + version: "3.0.1" path: dependency: "direct main" description: @@ -873,26 +873,26 @@ packages: dependency: transitive description: name: path_parsing - sha256: e3e67b1629e6f7e8100b367d3db6ba6af4b1f0bb80f64db18ef1fbabd2fa9ccf + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" url: "https://pub.dev" source: hosted - version: "1.0.1" + version: "1.1.0" path_provider: dependency: "direct main" description: name: path_provider - sha256: c9e7d3a4cd1410877472158bee69963a4579f78b68c65a2b7d40d1a7a88bb161 + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" url: "https://pub.dev" source: hosted - version: "2.1.3" + version: "2.1.5" path_provider_android: dependency: transitive description: name: path_provider_android - sha256: bca87b0165ffd7cdb9cad8edd22d18d2201e886d9a9f19b4fb3452ea7df3a72a + sha256: c464428172cb986b758c6d1724c603097febb8fb855aa265aeecc9280c294d4a url: "https://pub.dev" source: hosted - version: "2.2.6" + version: "2.2.12" path_provider_foundation: dependency: transitive description: @@ -921,18 +921,26 @@ packages: dependency: transitive description: name: path_provider_windows - sha256: "8bc9f22eee8690981c22aa7fc602f5c85b497a6fb2ceb35ee5a5e5ed85ad8170" + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 url: "https://pub.dev" source: hosted - version: "2.2.1" + version: "2.3.0" + pausable_timer: + dependency: transitive + description: + name: pausable_timer + sha256: "6ef1a95441ec3439de6fb63f39a011b67e693198e7dae14e20675c3c00e86074" + url: "https://pub.dev" + source: hosted + version: "3.1.0+3" pdf: dependency: "direct main" description: name: pdf - sha256: "81d5522bddc1ef5c28e8f0ee40b71708761753c163e0c93a40df56fd515ea0f0" + sha256: "05df53f8791587402493ac97b9869d3824eccbc77d97855f4545cf72df3cae07" url: "https://pub.dev" source: hosted - version: "3.11.0" + version: "3.11.1" pdf_widget_wrapper: dependency: transitive description: @@ -953,10 +961,10 @@ packages: dependency: transitive description: name: permission_handler_android - sha256: b29a799ca03be9f999aa6c39f7de5209482d638e6f857f6b93b0875c618b7e54 + sha256: "71bbecfee799e65aff7c744761a57e817e73b738fedf62ab7afd5593da21f9f1" url: "https://pub.dev" source: hosted - version: "12.0.7" + version: "12.0.13" permission_handler_apple: dependency: transitive description: @@ -969,18 +977,18 @@ packages: dependency: transitive description: name: permission_handler_html - sha256: "54bf176b90f6eddd4ece307e2c06cf977fb3973719c35a93b85cc7093eb6070d" + sha256: af26edbbb1f2674af65a8f4b56e1a6f526156bc273d0e65dd8075fab51c78851 url: "https://pub.dev" source: hosted - version: "0.1.1" + version: "0.1.3+2" permission_handler_platform_interface: dependency: transitive description: name: permission_handler_platform_interface - sha256: "48d4fcf201a1dad93ee869ab0d4101d084f49136ec82a8a06ed9cfeacab9fd20" + sha256: e9c8eadee926c4532d0305dff94b85bf961f16759c3af791486613152af4b4f9 url: "https://pub.dev" source: hosted - version: "4.2.1" + version: "4.2.3" permission_handler_windows: dependency: transitive description: @@ -1017,10 +1025,10 @@ packages: dependency: transitive description: name: platform - sha256: "9b71283fc13df574056616011fb138fd3b793ea47cc509c189a6c3fa5f8a1a65" + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" url: "https://pub.dev" source: hosted - version: "3.1.5" + version: "3.1.6" plugin_platform_interface: dependency: transitive description: @@ -1033,34 +1041,106 @@ packages: dependency: "direct main" description: name: pretty_dio_logger - sha256: "00b80053063935cf9a6190da344c5373b9d0e92da4c944c878ff2fbef0ef6dc2" + sha256: "36f2101299786d567869493e2f5731de61ce130faa14679473b26905a92b6407" url: "https://pub.dev" source: hosted - version: "1.3.1" + version: "1.4.0" printing: dependency: "direct main" description: name: printing - sha256: cc4b256a5a89d5345488e3318897b595867f5181b8c5ed6fc63bfa5f2044aec3 + sha256: b535d177fc6e8f8908e19b0ff5c1d4a87e3c4d0bf675e05aa2562af1b7853906 url: "https://pub.dev" source: hosted - version: "5.13.1" + version: "5.13.4" qr: dependency: transitive description: name: qr - sha256: "64957a3930367bf97cc211a5af99551d630f2f4625e38af10edd6b19131b64b3" + sha256: "5a1d2586170e172b8a8c8470bbbffd5eb0cd38a66c0d77155ea138d3af3a4445" url: "https://pub.dev" source: hosted - version: "3.0.1" + version: "3.0.2" + quill_native_bridge: + dependency: transitive + description: + name: quill_native_bridge + sha256: "5ccf1930fe52db91846754bd56391d251071524ec594eb4c8509b3095f7f9e28" + url: "https://pub.dev" + source: hosted + version: "10.7.9" + quill_native_bridge_android: + dependency: transitive + description: + name: quill_native_bridge_android + sha256: "4e787041ad4ab99421dfed0199cb5a6f136b5f6a9e68d20b199064d85d4161d8" + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.4" + quill_native_bridge_ios: + dependency: transitive + description: + name: quill_native_bridge_ios + sha256: "16dd18a56bdc60f396eb873a0786141d8e3281cc0cb6ad7af24c2286abec43d8" + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.4" + quill_native_bridge_linux: + dependency: transitive + description: + name: quill_native_bridge_linux + sha256: a0d8aa775b36a7b8ac7ace5bd6ba05b21fed6c9b04a9f328f95489254ae0f7a3 + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.3" + quill_native_bridge_macos: + dependency: transitive + description: + name: quill_native_bridge_macos + sha256: "76d441a905181af04c51b9cf71a13e04c3dd51ed482dcb543a01e14d78ad3fc0" + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.2" + quill_native_bridge_platform_interface: + dependency: transitive + description: + name: quill_native_bridge_platform_interface + sha256: "5ad4a9cdb6fadd6575bca29c277f83daa324539c97f58cf45cff6195135defb9" + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.4" + quill_native_bridge_web: + dependency: transitive + description: + name: quill_native_bridge_web + sha256: bb3ab017fdb9b60a29cac0bce3acfd48396d13c1bd0499c97af112c84937b4d1 + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.5" + quill_native_bridge_windows: + dependency: transitive + description: + name: quill_native_bridge_windows + sha256: "78bc40cc4a23387ed79a309fc04f7a95a0b6da9ebce67f739dd08b0fd0523641" + url: "https://pub.dev" + source: hosted + version: "0.0.1-dev.3" quiver: dependency: transitive description: name: quiver - sha256: b1c1ac5ce6688d77f65f3375a9abb9319b3cb32486bdc7a1e0fdf004d7ba4e47 + sha256: ea0b925899e64ecdfbf9c7becb60d5b50e706ade44a85b2363be2a22d88117d2 url: "https://pub.dev" source: hosted - version: "3.2.1" + version: "3.2.2" + screenshot: + dependency: "direct main" + description: + name: screenshot + sha256: "63817697a7835e6ce82add4228e15d233b74d42975c143ad8cfe07009fab866b" + url: "https://pub.dev" + source: hosted + version: "3.0.0" simple_gesture_detector: dependency: transitive description: @@ -1094,18 +1174,42 @@ packages: dependency: "direct main" description: name: sqflite - sha256: a43e5a27235518c03ca238e7b4732cf35eabe863a369ceba6cbefa537a66f16d + sha256: "2d7299468485dca85efeeadf5d38986909c5eb0cd71fd3db2c2f000e6c9454bb" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sqflite_android: + dependency: transitive + description: + name: sqflite_android + sha256: "78f489aab276260cdd26676d2169446c7ecd3484bbd5fead4ca14f3ed4dd9ee3" url: "https://pub.dev" source: hosted - version: "2.3.3+1" + version: "2.4.0" sqflite_common: dependency: transitive description: name: sqflite_common - sha256: "3da423ce7baf868be70e2c0976c28a1bb2f73644268b7ffa7d2e08eab71f16a4" + sha256: "4468b24876d673418a7b7147e5a08a715b4998a7ae69227acafaab762e0e5490" + url: "https://pub.dev" + source: hosted + version: "2.5.4+5" + sqflite_darwin: + dependency: transitive + description: + name: sqflite_darwin + sha256: "96a698e2bc82bd770a4d6aab00b42396a7c63d9e33513a56945cbccb594c2474" url: "https://pub.dev" source: hosted - version: "2.5.4" + version: "2.4.1" + sqflite_platform_interface: + dependency: transitive + description: + name: sqflite_platform_interface + sha256: "8dd4515c7bdcae0a785b0062859336de775e8c65db81ae33dd5445f35be61920" + url: "https://pub.dev" + source: hosted + version: "2.4.0" stack_trace: dependency: transitive description: @@ -1134,26 +1238,26 @@ packages: dependency: transitive description: name: super_clipboard - sha256: cdab725bac26655ebd189f4d202d694a8cbc1c21e0f0478ccd7829c71716f09b + sha256: "4a6ae6dfaa282ec1f2bff750976f535517ed8ca842d5deae13985eb11c00ac1f" url: "https://pub.dev" source: hosted - version: "0.8.17" + version: "0.8.24" super_native_extensions: dependency: transitive description: name: super_native_extensions - sha256: fa55d452d34b7112453afbb9fa4d13c0527ff201630d10d86546497179030544 + sha256: a433bba8186cd6b707560c42535bf284804665231c00bca86faf1aa4968b7637 url: "https://pub.dev" source: hosted - version: "0.8.17" + version: "0.8.24" synchronized: dependency: transitive description: name: synchronized - sha256: "539ef412b170d65ecdafd780f924e5be3f60032a1128df156adad6c5b373d558" + sha256: "69fe30f3a8b04a0be0c15ae6490fc859a78ef4c43ae2dd5e8a623d45bfcf9225" url: "https://pub.dev" source: hosted - version: "3.1.0+1" + version: "3.3.0+3" table_calendar: dependency: "direct main" description: @@ -1174,10 +1278,10 @@ packages: dependency: transitive description: name: test_api - sha256: "9955ae474176f7ac8ee4e989dadfb411a58c30415bcfb648fa04b2b8a03afa7f" + sha256: "5b8a98dafc4d5c4c9c72d8b31ab2b23fc13422348d2997120294d3bac86b4ddb" url: "https://pub.dev" source: hosted - version: "0.7.0" + version: "0.7.2" timeline_tile: dependency: "direct main" description: @@ -1186,14 +1290,30 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.0" + toastification: + dependency: "direct main" + description: + name: toastification + sha256: "4d97fbfa463dfe83691044cba9f37cb185a79bb9205cfecb655fa1f6be126a13" + url: "https://pub.dev" + source: hosted + version: "2.3.0" typed_data: dependency: transitive description: name: typed_data - sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 url: "https://pub.dev" source: hosted - version: "1.3.2" + version: "1.4.0" + unicode: + dependency: transitive + description: + name: unicode + sha256: "0f69e46593d65245774d4f17125c6084d2c20b4e473a983f6e21b7d7762218f1" + url: "https://pub.dev" + source: hosted + version: "0.3.1" universal_html: dependency: transitive description: @@ -1214,42 +1334,42 @@ packages: dependency: transitive description: name: url_launcher - sha256: "21b704ce5fa560ea9f3b525b43601c678728ba46725bab9b01187b4831377ed3" + sha256: "9d06212b1362abc2f0f0d78e6f09f726608c74e3b9462e8368bb03314aa8d603" url: "https://pub.dev" source: hosted - version: "6.3.0" + version: "6.3.1" url_launcher_android: dependency: transitive description: name: url_launcher_android - sha256: ceb2625f0c24ade6ef6778d1de0b2e44f2db71fded235eb52295247feba8c5cf + sha256: "6fc2f56536ee873eeb867ad176ae15f304ccccc357848b351f6f0d8d4a40d193" url: "https://pub.dev" source: hosted - version: "6.3.3" + version: "6.3.14" url_launcher_ios: dependency: transitive description: name: url_launcher_ios - sha256: "7068716403343f6ba4969b4173cbf3b84fc768042124bc2c011e5d782b24fe89" + sha256: e43b677296fadce447e987a2f519dcf5f6d1e527dc35d01ffab4fff5b8a7063e url: "https://pub.dev" source: hosted - version: "6.3.0" + version: "6.3.1" url_launcher_linux: dependency: transitive description: name: url_launcher_linux - sha256: ab360eb661f8879369acac07b6bb3ff09d9471155357da8443fd5d3cf7363811 + sha256: e2b9622b4007f97f504cd64c0128309dfb978ae66adbe944125ed9e1750f06af url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.2.0" url_launcher_macos: dependency: transitive description: name: url_launcher_macos - sha256: "9a1a42d5d2d95400c795b2914c36fdcb525870c752569438e4ebb09a2b5d90de" + sha256: "769549c999acdb42b8bcfa7c43d72bf79a382ca7441ab18a808e101149daf672" url: "https://pub.dev" source: hosted - version: "3.2.0" + version: "3.2.1" url_launcher_platform_interface: dependency: transitive description: @@ -1262,26 +1382,26 @@ packages: dependency: transitive description: name: url_launcher_web - sha256: "8d9e750d8c9338601e709cd0885f95825086bd8b642547f26bda435aade95d8a" + sha256: "772638d3b34c779ede05ba3d38af34657a05ac55b06279ea6edd409e323dca8e" url: "https://pub.dev" source: hosted - version: "2.3.1" + version: "2.3.3" url_launcher_windows: dependency: transitive description: name: url_launcher_windows - sha256: ecf9725510600aa2bb6d7ddabe16357691b6d2805f66216a97d1b881e21beff7 + sha256: "44cf3aabcedde30f2dba119a9dea3b0f2672fbe6fa96e85536251d678216b3c4" url: "https://pub.dev" source: hosted - version: "3.1.1" + version: "3.1.3" uuid: dependency: "direct main" description: name: uuid - sha256: "814e9e88f21a176ae1359149021870e87f7cddaf633ab678a5d2b0bff7fd1ba8" + sha256: a5be9ef6618a7ac1e964353ef476418026db906c4facdedaa299b7a2e71690ff url: "https://pub.dev" source: hosted - version: "4.4.0" + version: "4.5.1" vector_math: dependency: transitive description: @@ -1294,58 +1414,58 @@ packages: dependency: transitive description: name: video_player - sha256: e30df0d226c4ef82e2c150ebf6834b3522cf3f654d8e2f9419d376cdc071425d + sha256: "4a8c3492d734f7c39c2588a3206707a05ee80cef52e8c7f3b2078d430c84bc17" url: "https://pub.dev" source: hosted - version: "2.9.1" + version: "2.9.2" video_player_android: dependency: transitive description: name: video_player_android - sha256: fdc0331ce9f808cc2714014cb8126bd6369943affefd54f8fdab0ea0bb617b7f + sha256: "391e092ba4abe2f93b3e625bd6b6a6ec7d7414279462c1c0ee42b5ab8d0a0898" url: "https://pub.dev" source: hosted - version: "2.5.2" + version: "2.7.16" video_player_avfoundation: dependency: transitive description: name: video_player_avfoundation - sha256: d1e9a824f2b324000dc8fb2dcb2a3285b6c1c7c487521c63306cc5b394f68a7c + sha256: cd5ab8a8bc0eab65ab0cea40304097edc46da574c8c1ecdee96f28cd8ef3792f url: "https://pub.dev" source: hosted - version: "2.6.1" + version: "2.6.2" video_player_platform_interface: dependency: transitive description: name: video_player_platform_interface - sha256: "236454725fafcacf98f0f39af0d7c7ab2ce84762e3b63f2cbb3ef9a7e0550bc6" + sha256: "229d7642ccd9f3dc4aba169609dd6b5f3f443bb4cc15b82f7785fcada5af9bbb" url: "https://pub.dev" source: hosted - version: "6.2.2" + version: "6.2.3" video_player_web: dependency: transitive description: name: video_player_web - sha256: ff4d69a6614b03f055397c27a71c9d3ddea2b2a23d71b2ba0164f59ca32b8fe2 + sha256: "881b375a934d8ebf868c7fb1423b2bfaa393a0a265fa3f733079a86536064a10" url: "https://pub.dev" source: hosted - version: "2.3.1" + version: "2.3.3" vm_service: dependency: transitive description: name: vm_service - sha256: "3923c89304b715fb1eb6423f017651664a03bf5f4b29983627c4da791f74a4ec" + sha256: "5c5f338a667b4c644744b661f309fb8080bb94b18a7e91ef1dbd343bed00ed6d" url: "https://pub.dev" source: hosted - version: "14.2.1" + version: "14.2.5" wakelock_plus: dependency: "direct main" description: name: wakelock_plus - sha256: "14758533319a462ffb5aa3b7ddb198e59b29ac3b02da14173a1715d65d4e6e68" + sha256: bf4ee6f17a2fa373ed3753ad0e602b7603f8c75af006d5b9bdade263928c0484 url: "https://pub.dev" source: hosted - version: "1.2.5" + version: "1.2.8" wakelock_plus_platform_interface: dependency: transitive description: @@ -1358,34 +1478,34 @@ packages: dependency: transitive description: name: web - sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" + sha256: cd3543bd5798f6ad290ea73d210f423502e71900302dde696f8bff84bf89a1cb url: "https://pub.dev" source: hosted - version: "0.5.1" + version: "1.1.0" win32: dependency: transitive description: name: win32 - sha256: a79dbe579cb51ecd6d30b17e0cae4e0ea15e2c0e66f69ad4198f22a6789e94f4 + sha256: "84ba388638ed7a8cb3445a320c8273136ab2631cd5f2c57888335504ddab1bc2" url: "https://pub.dev" source: hosted - version: "5.5.1" + version: "5.8.0" win32_registry: dependency: transitive description: name: win32_registry - sha256: "10589e0d7f4e053f2c61023a31c9ce01146656a70b7b7f0828c0b46d7da2a9bb" + sha256: "21ec76dfc731550fd3e2ce7a33a9ea90b828fdf19a5c3bcf556fa992cfa99852" url: "https://pub.dev" source: hosted - version: "1.1.3" + version: "1.1.5" xdg_directories: dependency: transitive description: name: xdg_directories - sha256: faea9dee56b520b55a566385b84f2e8de55e7496104adada9962e0bd11bcff1d + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" url: "https://pub.dev" source: hosted - version: "1.0.4" + version: "1.1.0" xml: dependency: transitive description: @@ -1398,18 +1518,10 @@ packages: dependency: transitive description: name: youtube_explode_dart - sha256: "26c9671d638f3396a1bfb2666f586988ee7b0ba3469e478b22a4c1a168bcf6ee" - url: "https://pub.dev" - source: hosted - version: "2.2.1" - youtube_player_flutter: - dependency: transitive - description: - name: youtube_player_flutter - sha256: "899f1fd15e924eb41150c78c5e2adfd7310100c26b2e1996c148d79e42737d72" + sha256: "6d5f9a0a55d02743e59ca495887432814bddb6b11400b08ee0eeaf69c83d0089" url: "https://pub.dev" source: hosted - version: "9.0.1" + version: "2.3.5" sdks: - dart: ">=3.4.0 <4.0.0" - flutter: ">=3.22.0" + dart: ">=3.5.4 <4.0.0" + flutter: ">=3.24.0" diff --git a/pubspec.yaml b/pubspec.yaml index 678f372..4544bd4 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,10 +16,10 @@ publish_to: "none" # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 0.2.0-beta.1 +version: 0.2.1-beta.1 environment: - sdk: ">=3.0.1 <4.0.0" + sdk: ^3.5.4 # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions @@ -34,77 +34,81 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.2 - flutter_screenutil: ^5.9.0 + flutter_screenutil: ^5.9.3 intl: ^0.19.0 flutter_localizations: sdk: flutter - sqflite: ^2.3.0 - path_provider: ^2.1.1 + sqflite: ^2.4.1 + path_provider: ^2.1.5 # 表单创建和验证 - flutter_form_builder: ^9.1.1 - form_builder_validators: ^10.0.1 + flutter_form_builder: ^9.5.0 + form_builder_validators: ^11.0.0 # 带文件的表单 - form_builder_file_picker: ^4.1.0 + form_builder_file_picker: ^4.2.0 # 下拉多选 multi_select_flutter: ^4.1.3 # 图表 - fl_chart: ^0.68.0 + fl_chart: ^0.69.0 # 日志工具 - logger: ^2.0.2+1 + logger: ^2.4.0 # 文件选择 - file_picker: ^5.5.0 + file_picker: ^8.1.3 # 圆形倒计时部件 - circular_countdown_timer: ^0.2.3 + circular_countdown_timer: ^0.2.4 # 富文本编辑 - flutter_quill: ^9.5.6 + flutter_quill: ^10.8.5 # 富文本编辑扩展(插入图片之类的) - flutter_quill_extensions: ^9.5.6 + flutter_quill_extensions: ^10.8.5 # 表格日历 - table_calendar: ^3.0.9 + table_calendar: ^3.1.2 # 时间线列表 timeline_tile: ^2.0.0 # 文本转语音 flutter_tts: ^4.0.2 # 权限处理 - permission_handler: ^11.1.0 + permission_handler: ^11.3.1 # 轮播组件 - carousel_slider: ^4.2.1 + carousel_slider: ^5.0.0 # 控制屏幕保持亮屏 - wakelock_plus: ^1.1.4 + wakelock_plus: ^1.2.8 # 数字选择器 numberpicker: ^2.1.2 - # 保存图片(Android9及其以下可能保存不了) - image_gallery_saver: ^2.0.3 - # 获取设备信息 - device_info_plus: ^10.1.0 + # 获取设备信息(和flutter_quill_extensions有冲突,所以没有使用到最新版本) + device_info_plus: ^10.1.2 # 创建和预览pdf - pdf: ^3.10.7 + pdf: ^3.11.1 # 允许 Flutter 应用程序生成文档并将其打印到 android 或 ios 兼容打印机 - printing: ^5.11.1 + printing: ^5.13.4 # 简单的键值对存储,可以用来存用户基本信息:支持存储的类型 String, int, double, Map and List # 不使用shared_preferences 是因为它不能保证一定存储到硬盘 get_storage: ^2.1.1 # 从相册选择图片或者拍照片 - image_picker: ^1.0.4 - # 一个全面的、跨平台的 Dart 路径操作库(2023-12-11安装1.9.0会报错)。 - path: ^1.8.3 + image_picker: ^1.1.2 + # 一个全面的、跨平台的 Dart 路径操作库 + path: ^1.9.0 # 压缩文件 - archive: ^3.4.9 + archive: ^3.6.1 # 一个颜色主题插件 - flex_color_scheme: ^7.3.1 + flex_color_scheme: ^8.0.0 # 可以按照手势缩放图片进行预览 photo_view: ^0.15.0 # http client - dio: ^5.5.0+1 + dio: ^5.7.0 # 美化dio请求的日志 - pretty_dio_logger: ^1.3.1 + pretty_dio_logger: ^1.4.0 # 提示框 flutter_easyloading: ^3.0.5 + toastification: ^2.3.0 # 查看网络状态 - connectivity_plus: ^6.0.3 - flutter_markdown: ^0.7.3 - uuid: ^4.4.0 - collection: ^1.18.0 # 集合的一些工具方法 + connectivity_plus: ^6.1.0 + flutter_markdown: ^0.7.4+1 + uuid: ^4.5.1 + # 集合的一些工具方法 + collection: ^1.18.0 + # 将部件内容保存为截图(透明的png) + screenshot: ^3.0.0 + # 压缩图片(比如把透明png压成白底jpg) + flutter_image_compress: ^2.3.0 dev_dependencies: flutter_test: diff --git a/web/favicon.png b/web/favicon.png deleted file mode 100644 index 8aaa46a..0000000 Binary files a/web/favicon.png and /dev/null differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png deleted file mode 100644 index b749bfe..0000000 Binary files a/web/icons/Icon-192.png and /dev/null differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png deleted file mode 100644 index 88cfd48..0000000 Binary files a/web/icons/Icon-512.png and /dev/null differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png deleted file mode 100644 index eb9b4d7..0000000 Binary files a/web/icons/Icon-maskable-192.png and /dev/null differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png deleted file mode 100644 index d69c566..0000000 Binary files a/web/icons/Icon-maskable-512.png and /dev/null differ diff --git a/web/index.html b/web/index.html deleted file mode 100644 index 3b94445..0000000 --- a/web/index.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - free_fitness - - - - - - - - - - diff --git a/web/manifest.json b/web/manifest.json deleted file mode 100644 index 60e6215..0000000 --- a/web/manifest.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "free_fitness", - "short_name": "free_fitness", - "start_url": ".", - "display": "standalone", - "background_color": "#0175C2", - "theme_color": "#0175C2", - "description": "A new Flutter project.", - "orientation": "portrait-primary", - "prefer_related_applications": false, - "icons": [ - { - "src": "icons/Icon-192.png", - "sizes": "192x192", - "type": "image/png" - }, - { - "src": "icons/Icon-512.png", - "sizes": "512x512", - "type": "image/png" - }, - { - "src": "icons/Icon-maskable-192.png", - "sizes": "192x192", - "type": "image/png", - "purpose": "maskable" - }, - { - "src": "icons/Icon-maskable-512.png", - "sizes": "512x512", - "type": "image/png", - "purpose": "maskable" - } - ] -} diff --git a/windows/.gitignore b/windows/.gitignore deleted file mode 100644 index d492d0d..0000000 --- a/windows/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -flutter/ephemeral/ - -# Visual Studio user-specific files. -*.suo -*.user -*.userosscache -*.sln.docstates - -# Visual Studio build-related files. -x64/ -x86/ - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt deleted file mode 100644 index 47ffbe8..0000000 --- a/windows/CMakeLists.txt +++ /dev/null @@ -1,102 +0,0 @@ -# Project-level configuration. -cmake_minimum_required(VERSION 3.14) -project(free_fitness LANGUAGES CXX) - -# The name of the executable created for the application. Change this to change -# the on-disk name of your application. -set(BINARY_NAME "free_fitness") - -# Explicitly opt in to modern CMake behaviors to avoid warnings with recent -# versions of CMake. -cmake_policy(SET CMP0063 NEW) - -# Define build configuration option. -get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) -if(IS_MULTICONFIG) - set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" - CACHE STRING "" FORCE) -else() - if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) - set(CMAKE_BUILD_TYPE "Debug" CACHE - STRING "Flutter build mode" FORCE) - set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS - "Debug" "Profile" "Release") - endif() -endif() -# Define settings for the Profile build mode. -set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") -set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") -set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") -set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") - -# Use Unicode for all projects. -add_definitions(-DUNICODE -D_UNICODE) - -# Compilation settings that should be applied to most targets. -# -# Be cautious about adding new options here, as plugins use this function by -# default. In most cases, you should add new options to specific targets instead -# of modifying this function. -function(APPLY_STANDARD_SETTINGS TARGET) - target_compile_features(${TARGET} PUBLIC cxx_std_17) - target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") - target_compile_options(${TARGET} PRIVATE /EHsc) - target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") - target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") -endfunction() - -# Flutter library and tool build rules. -set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") -add_subdirectory(${FLUTTER_MANAGED_DIR}) - -# Application build; see runner/CMakeLists.txt. -add_subdirectory("runner") - - -# Generated plugin build rules, which manage building the plugins and adding -# them to the application. -include(flutter/generated_plugins.cmake) - - -# === Installation === -# Support files are copied into place next to the executable, so that it can -# run in place. This is done instead of making a separate bundle (as on Linux) -# so that building and running from within Visual Studio will work. -set(BUILD_BUNDLE_DIR "$") -# Make the "install" step default, as it's required to run. -set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) -if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) -endif() - -set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") -set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") - -install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - COMPONENT Runtime) - -install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) - -if(PLUGIN_BUNDLED_LIBRARIES) - install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" - DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" - COMPONENT Runtime) -endif() - -# Fully re-copy the assets directory on each build to avoid having stale files -# from a previous install. -set(FLUTTER_ASSET_DIR_NAME "flutter_assets") -install(CODE " - file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") - " COMPONENT Runtime) -install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" - DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) - -# Install the AOT library on non-Debug builds only. -install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" - CONFIGURATIONS Profile;Release - COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt deleted file mode 100644 index 930d207..0000000 --- a/windows/flutter/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -# This file controls Flutter-level build steps. It should not be edited. -cmake_minimum_required(VERSION 3.14) - -set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") - -# Configuration provided via flutter tool. -include(${EPHEMERAL_DIR}/generated_config.cmake) - -# TODO: Move the rest of this into files in ephemeral. See -# https://github.com/flutter/flutter/issues/57146. -set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") - -# === Flutter Library === -set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") - -# Published to parent scope for install step. -set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) -set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) -set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) -set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) - -list(APPEND FLUTTER_LIBRARY_HEADERS - "flutter_export.h" - "flutter_windows.h" - "flutter_messenger.h" - "flutter_plugin_registrar.h" - "flutter_texture_registrar.h" -) -list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") -add_library(flutter INTERFACE) -target_include_directories(flutter INTERFACE - "${EPHEMERAL_DIR}" -) -target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") -add_dependencies(flutter flutter_assemble) - -# === Wrapper === -list(APPEND CPP_WRAPPER_SOURCES_CORE - "core_implementations.cc" - "standard_codec.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_PLUGIN - "plugin_registrar.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") -list(APPEND CPP_WRAPPER_SOURCES_APP - "flutter_engine.cc" - "flutter_view_controller.cc" -) -list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") - -# Wrapper sources needed for a plugin. -add_library(flutter_wrapper_plugin STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} -) -apply_standard_settings(flutter_wrapper_plugin) -set_target_properties(flutter_wrapper_plugin PROPERTIES - POSITION_INDEPENDENT_CODE ON) -set_target_properties(flutter_wrapper_plugin PROPERTIES - CXX_VISIBILITY_PRESET hidden) -target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) -target_include_directories(flutter_wrapper_plugin PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_plugin flutter_assemble) - -# Wrapper sources needed for the runner. -add_library(flutter_wrapper_app STATIC - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_APP} -) -apply_standard_settings(flutter_wrapper_app) -target_link_libraries(flutter_wrapper_app PUBLIC flutter) -target_include_directories(flutter_wrapper_app PUBLIC - "${WRAPPER_ROOT}/include" -) -add_dependencies(flutter_wrapper_app flutter_assemble) - -# === Flutter tool backend === -# _phony_ is a non-existent file to force this command to run every time, -# since currently there's no way to get a full input/output list from the -# flutter tool. -set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") -set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) -add_custom_command( - OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} - ${PHONY_OUTPUT} - COMMAND ${CMAKE_COMMAND} -E env - ${FLUTTER_TOOL_ENVIRONMENT} - "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" - windows-x64 $ - VERBATIM -) -add_custom_target(flutter_assemble DEPENDS - "${FLUTTER_LIBRARY}" - ${FLUTTER_LIBRARY_HEADERS} - ${CPP_WRAPPER_SOURCES_CORE} - ${CPP_WRAPPER_SOURCES_PLUGIN} - ${CPP_WRAPPER_SOURCES_APP} -) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc deleted file mode 100644 index a7476e3..0000000 --- a/windows/flutter/generated_plugin_registrant.cc +++ /dev/null @@ -1,38 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#include "generated_plugin_registrant.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void RegisterPlugins(flutter::PluginRegistry* registry) { - ConnectivityPlusWindowsPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("ConnectivityPlusWindowsPlugin")); - FileSelectorWindowsRegisterWithRegistrar( - registry->GetRegistrarForPlugin("FileSelectorWindows")); - FlutterTtsPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("FlutterTtsPlugin")); - GalPluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("GalPluginCApi")); - IrondashEngineContextPluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("IrondashEngineContextPluginCApi")); - PermissionHandlerWindowsPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin")); - PrintingPluginRegisterWithRegistrar( - registry->GetRegistrarForPlugin("PrintingPlugin")); - SuperNativeExtensionsPluginCApiRegisterWithRegistrar( - registry->GetRegistrarForPlugin("SuperNativeExtensionsPluginCApi")); - UrlLauncherWindowsRegisterWithRegistrar( - registry->GetRegistrarForPlugin("UrlLauncherWindows")); -} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h deleted file mode 100644 index dc139d8..0000000 --- a/windows/flutter/generated_plugin_registrant.h +++ /dev/null @@ -1,15 +0,0 @@ -// -// Generated file. Do not edit. -// - -// clang-format off - -#ifndef GENERATED_PLUGIN_REGISTRANT_ -#define GENERATED_PLUGIN_REGISTRANT_ - -#include - -// Registers Flutter plugins. -void RegisterPlugins(flutter::PluginRegistry* registry); - -#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake deleted file mode 100644 index fd3a184..0000000 --- a/windows/flutter/generated_plugins.cmake +++ /dev/null @@ -1,32 +0,0 @@ -# -# Generated file, do not edit. -# - -list(APPEND FLUTTER_PLUGIN_LIST - connectivity_plus - file_selector_windows - flutter_tts - gal - irondash_engine_context - permission_handler_windows - printing - super_native_extensions - url_launcher_windows -) - -list(APPEND FLUTTER_FFI_PLUGIN_LIST -) - -set(PLUGIN_BUNDLED_LIBRARIES) - -foreach(plugin ${FLUTTER_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) - target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) - list(APPEND PLUGIN_BUNDLED_LIBRARIES $) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) -endforeach(plugin) - -foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) - add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) - list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) -endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt deleted file mode 100644 index 394917c..0000000 --- a/windows/runner/CMakeLists.txt +++ /dev/null @@ -1,40 +0,0 @@ -cmake_minimum_required(VERSION 3.14) -project(runner LANGUAGES CXX) - -# Define the application target. To change its name, change BINARY_NAME in the -# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer -# work. -# -# Any new source files that you add to the application should be added here. -add_executable(${BINARY_NAME} WIN32 - "flutter_window.cpp" - "main.cpp" - "utils.cpp" - "win32_window.cpp" - "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" - "Runner.rc" - "runner.exe.manifest" -) - -# Apply the standard set of build settings. This can be removed for applications -# that need different build settings. -apply_standard_settings(${BINARY_NAME}) - -# Add preprocessor definitions for the build version. -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") -target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") - -# Disable Windows macros that collide with C++ standard library functions. -target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") - -# Add dependency libraries and include directories. Add any application-specific -# dependencies here. -target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) -target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") -target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") - -# Run the Flutter tool portions of the build. This must not be removed. -add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc deleted file mode 100644 index 92c6a02..0000000 --- a/windows/runner/Runner.rc +++ /dev/null @@ -1,121 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#pragma code_page(65001) -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Icon -// - -// Icon with lowest ID value placed first to ensure application icon -// remains consistent on all systems. -IDI_APP_ICON ICON "resources\\app_icon.ico" - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) -#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD -#else -#define VERSION_AS_NUMBER 1,0,0,0 -#endif - -#if defined(FLUTTER_VERSION) -#define VERSION_AS_STRING FLUTTER_VERSION -#else -#define VERSION_AS_STRING "1.0.0" -#endif - -VS_VERSION_INFO VERSIONINFO - FILEVERSION VERSION_AS_NUMBER - PRODUCTVERSION VERSION_AS_NUMBER - FILEFLAGSMASK VS_FFI_FILEFLAGSMASK -#ifdef _DEBUG - FILEFLAGS VS_FF_DEBUG -#else - FILEFLAGS 0x0L -#endif - FILEOS VOS__WINDOWS32 - FILETYPE VFT_APP - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040904e4" - BEGIN - VALUE "CompanyName", "com.swm" "\0" - VALUE "FileDescription", "free_fitness" "\0" - VALUE "FileVersion", VERSION_AS_STRING "\0" - VALUE "InternalName", "free_fitness" "\0" - VALUE "LegalCopyright", "Copyright (C) 2023 com.swm. All rights reserved." "\0" - VALUE "OriginalFilename", "free_fitness.exe" "\0" - VALUE "ProductName", "free_fitness" "\0" - VALUE "ProductVersion", VERSION_AS_STRING "\0" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x409, 1252 - END -END - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp deleted file mode 100644 index b25e363..0000000 --- a/windows/runner/flutter_window.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include "flutter_window.h" - -#include - -#include "flutter/generated_plugin_registrant.h" - -FlutterWindow::FlutterWindow(const flutter::DartProject& project) - : project_(project) {} - -FlutterWindow::~FlutterWindow() {} - -bool FlutterWindow::OnCreate() { - if (!Win32Window::OnCreate()) { - return false; - } - - RECT frame = GetClientArea(); - - // The size here must match the window dimensions to avoid unnecessary surface - // creation / destruction in the startup path. - flutter_controller_ = std::make_unique( - frame.right - frame.left, frame.bottom - frame.top, project_); - // Ensure that basic setup of the controller was successful. - if (!flutter_controller_->engine() || !flutter_controller_->view()) { - return false; - } - RegisterPlugins(flutter_controller_->engine()); - SetChildContent(flutter_controller_->view()->GetNativeWindow()); - - flutter_controller_->engine()->SetNextFrameCallback([&]() { - this->Show(); - }); - - return true; -} - -void FlutterWindow::OnDestroy() { - if (flutter_controller_) { - flutter_controller_ = nullptr; - } - - Win32Window::OnDestroy(); -} - -LRESULT -FlutterWindow::MessageHandler(HWND hwnd, UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - // Give Flutter, including plugins, an opportunity to handle window messages. - if (flutter_controller_) { - std::optional result = - flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, - lparam); - if (result) { - return *result; - } - } - - switch (message) { - case WM_FONTCHANGE: - flutter_controller_->engine()->ReloadSystemFonts(); - break; - } - - return Win32Window::MessageHandler(hwnd, message, wparam, lparam); -} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h deleted file mode 100644 index 6da0652..0000000 --- a/windows/runner/flutter_window.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef RUNNER_FLUTTER_WINDOW_H_ -#define RUNNER_FLUTTER_WINDOW_H_ - -#include -#include - -#include - -#include "win32_window.h" - -// A window that does nothing but host a Flutter view. -class FlutterWindow : public Win32Window { - public: - // Creates a new FlutterWindow hosting a Flutter view running |project|. - explicit FlutterWindow(const flutter::DartProject& project); - virtual ~FlutterWindow(); - - protected: - // Win32Window: - bool OnCreate() override; - void OnDestroy() override; - LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, - LPARAM const lparam) noexcept override; - - private: - // The project to run. - flutter::DartProject project_; - - // The Flutter instance hosted by this window. - std::unique_ptr flutter_controller_; -}; - -#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp deleted file mode 100644 index e5e513c..0000000 --- a/windows/runner/main.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include -#include -#include - -#include "flutter_window.h" -#include "utils.h" - -int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, - _In_ wchar_t *command_line, _In_ int show_command) { - // Attach to console when present (e.g., 'flutter run') or create a - // new console when running with a debugger. - if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { - CreateAndAttachConsole(); - } - - // Initialize COM, so that it is available for use in the library and/or - // plugins. - ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); - - flutter::DartProject project(L"data"); - - std::vector command_line_arguments = - GetCommandLineArguments(); - - project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); - - FlutterWindow window(project); - Win32Window::Point origin(10, 10); - Win32Window::Size size(1280, 720); - if (!window.Create(L"free_fitness", origin, size)) { - return EXIT_FAILURE; - } - window.SetQuitOnClose(true); - - ::MSG msg; - while (::GetMessage(&msg, nullptr, 0, 0)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - } - - ::CoUninitialize(); - return EXIT_SUCCESS; -} diff --git a/windows/runner/resource.h b/windows/runner/resource.h deleted file mode 100644 index 66a65d1..0000000 --- a/windows/runner/resource.h +++ /dev/null @@ -1,16 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by Runner.rc -// -#define IDI_APP_ICON 101 - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 102 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico deleted file mode 100644 index c04e20c..0000000 Binary files a/windows/runner/resources/app_icon.ico and /dev/null differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest deleted file mode 100644 index a42ea76..0000000 --- a/windows/runner/runner.exe.manifest +++ /dev/null @@ -1,20 +0,0 @@ - - - - - PerMonitorV2 - - - - - - - - - - - - - - - diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp deleted file mode 100644 index b2b0873..0000000 --- a/windows/runner/utils.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include "utils.h" - -#include -#include -#include -#include - -#include - -void CreateAndAttachConsole() { - if (::AllocConsole()) { - FILE *unused; - if (freopen_s(&unused, "CONOUT$", "w", stdout)) { - _dup2(_fileno(stdout), 1); - } - if (freopen_s(&unused, "CONOUT$", "w", stderr)) { - _dup2(_fileno(stdout), 2); - } - std::ios::sync_with_stdio(); - FlutterDesktopResyncOutputStreams(); - } -} - -std::vector GetCommandLineArguments() { - // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. - int argc; - wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); - if (argv == nullptr) { - return std::vector(); - } - - std::vector command_line_arguments; - - // Skip the first argument as it's the binary name. - for (int i = 1; i < argc; i++) { - command_line_arguments.push_back(Utf8FromUtf16(argv[i])); - } - - ::LocalFree(argv); - - return command_line_arguments; -} - -std::string Utf8FromUtf16(const wchar_t* utf16_string) { - if (utf16_string == nullptr) { - return std::string(); - } - int target_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - -1, nullptr, 0, nullptr, nullptr) - -1; // remove the trailing null character - int input_length = (int)wcslen(utf16_string); - std::string utf8_string; - if (target_length <= 0 || target_length > utf8_string.max_size()) { - return utf8_string; - } - utf8_string.resize(target_length); - int converted_length = ::WideCharToMultiByte( - CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, - input_length, utf8_string.data(), target_length, nullptr, nullptr); - if (converted_length == 0) { - return std::string(); - } - return utf8_string; -} diff --git a/windows/runner/utils.h b/windows/runner/utils.h deleted file mode 100644 index 3879d54..0000000 --- a/windows/runner/utils.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef RUNNER_UTILS_H_ -#define RUNNER_UTILS_H_ - -#include -#include - -// Creates a console for the process, and redirects stdout and stderr to -// it for both the runner and the Flutter library. -void CreateAndAttachConsole(); - -// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string -// encoded in UTF-8. Returns an empty std::string on failure. -std::string Utf8FromUtf16(const wchar_t* utf16_string); - -// Gets the command line arguments passed in as a std::vector, -// encoded in UTF-8. Returns an empty std::vector on failure. -std::vector GetCommandLineArguments(); - -#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp deleted file mode 100644 index 60608d0..0000000 --- a/windows/runner/win32_window.cpp +++ /dev/null @@ -1,288 +0,0 @@ -#include "win32_window.h" - -#include -#include - -#include "resource.h" - -namespace { - -/// Window attribute that enables dark mode window decorations. -/// -/// Redefined in case the developer's machine has a Windows SDK older than -/// version 10.0.22000.0. -/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute -#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE -#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 -#endif - -constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; - -/// Registry key for app theme preference. -/// -/// A value of 0 indicates apps should use dark mode. A non-zero or missing -/// value indicates apps should use light mode. -constexpr const wchar_t kGetPreferredBrightnessRegKey[] = - L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; -constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; - -// The number of Win32Window objects that currently exist. -static int g_active_window_count = 0; - -using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); - -// Scale helper to convert logical scaler values to physical using passed in -// scale factor -int Scale(int source, double scale_factor) { - return static_cast(source * scale_factor); -} - -// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. -// This API is only needed for PerMonitor V1 awareness mode. -void EnableFullDpiSupportIfAvailable(HWND hwnd) { - HMODULE user32_module = LoadLibraryA("User32.dll"); - if (!user32_module) { - return; - } - auto enable_non_client_dpi_scaling = - reinterpret_cast( - GetProcAddress(user32_module, "EnableNonClientDpiScaling")); - if (enable_non_client_dpi_scaling != nullptr) { - enable_non_client_dpi_scaling(hwnd); - } - FreeLibrary(user32_module); -} - -} // namespace - -// Manages the Win32Window's window class registration. -class WindowClassRegistrar { - public: - ~WindowClassRegistrar() = default; - - // Returns the singleton registrar instance. - static WindowClassRegistrar* GetInstance() { - if (!instance_) { - instance_ = new WindowClassRegistrar(); - } - return instance_; - } - - // Returns the name of the window class, registering the class if it hasn't - // previously been registered. - const wchar_t* GetWindowClass(); - - // Unregisters the window class. Should only be called if there are no - // instances of the window. - void UnregisterWindowClass(); - - private: - WindowClassRegistrar() = default; - - static WindowClassRegistrar* instance_; - - bool class_registered_ = false; -}; - -WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; - -const wchar_t* WindowClassRegistrar::GetWindowClass() { - if (!class_registered_) { - WNDCLASS window_class{}; - window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); - window_class.lpszClassName = kWindowClassName; - window_class.style = CS_HREDRAW | CS_VREDRAW; - window_class.cbClsExtra = 0; - window_class.cbWndExtra = 0; - window_class.hInstance = GetModuleHandle(nullptr); - window_class.hIcon = - LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); - window_class.hbrBackground = 0; - window_class.lpszMenuName = nullptr; - window_class.lpfnWndProc = Win32Window::WndProc; - RegisterClass(&window_class); - class_registered_ = true; - } - return kWindowClassName; -} - -void WindowClassRegistrar::UnregisterWindowClass() { - UnregisterClass(kWindowClassName, nullptr); - class_registered_ = false; -} - -Win32Window::Win32Window() { - ++g_active_window_count; -} - -Win32Window::~Win32Window() { - --g_active_window_count; - Destroy(); -} - -bool Win32Window::Create(const std::wstring& title, - const Point& origin, - const Size& size) { - Destroy(); - - const wchar_t* window_class = - WindowClassRegistrar::GetInstance()->GetWindowClass(); - - const POINT target_point = {static_cast(origin.x), - static_cast(origin.y)}; - HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); - UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); - double scale_factor = dpi / 96.0; - - HWND window = CreateWindow( - window_class, title.c_str(), WS_OVERLAPPEDWINDOW, - Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), - Scale(size.width, scale_factor), Scale(size.height, scale_factor), - nullptr, nullptr, GetModuleHandle(nullptr), this); - - if (!window) { - return false; - } - - UpdateTheme(window); - - return OnCreate(); -} - -bool Win32Window::Show() { - return ShowWindow(window_handle_, SW_SHOWNORMAL); -} - -// static -LRESULT CALLBACK Win32Window::WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - if (message == WM_NCCREATE) { - auto window_struct = reinterpret_cast(lparam); - SetWindowLongPtr(window, GWLP_USERDATA, - reinterpret_cast(window_struct->lpCreateParams)); - - auto that = static_cast(window_struct->lpCreateParams); - EnableFullDpiSupportIfAvailable(window); - that->window_handle_ = window; - } else if (Win32Window* that = GetThisFromHandle(window)) { - return that->MessageHandler(window, message, wparam, lparam); - } - - return DefWindowProc(window, message, wparam, lparam); -} - -LRESULT -Win32Window::MessageHandler(HWND hwnd, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept { - switch (message) { - case WM_DESTROY: - window_handle_ = nullptr; - Destroy(); - if (quit_on_close_) { - PostQuitMessage(0); - } - return 0; - - case WM_DPICHANGED: { - auto newRectSize = reinterpret_cast(lparam); - LONG newWidth = newRectSize->right - newRectSize->left; - LONG newHeight = newRectSize->bottom - newRectSize->top; - - SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, - newHeight, SWP_NOZORDER | SWP_NOACTIVATE); - - return 0; - } - case WM_SIZE: { - RECT rect = GetClientArea(); - if (child_content_ != nullptr) { - // Size and position the child window. - MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, - rect.bottom - rect.top, TRUE); - } - return 0; - } - - case WM_ACTIVATE: - if (child_content_ != nullptr) { - SetFocus(child_content_); - } - return 0; - - case WM_DWMCOLORIZATIONCOLORCHANGED: - UpdateTheme(hwnd); - return 0; - } - - return DefWindowProc(window_handle_, message, wparam, lparam); -} - -void Win32Window::Destroy() { - OnDestroy(); - - if (window_handle_) { - DestroyWindow(window_handle_); - window_handle_ = nullptr; - } - if (g_active_window_count == 0) { - WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); - } -} - -Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { - return reinterpret_cast( - GetWindowLongPtr(window, GWLP_USERDATA)); -} - -void Win32Window::SetChildContent(HWND content) { - child_content_ = content; - SetParent(content, window_handle_); - RECT frame = GetClientArea(); - - MoveWindow(content, frame.left, frame.top, frame.right - frame.left, - frame.bottom - frame.top, true); - - SetFocus(child_content_); -} - -RECT Win32Window::GetClientArea() { - RECT frame; - GetClientRect(window_handle_, &frame); - return frame; -} - -HWND Win32Window::GetHandle() { - return window_handle_; -} - -void Win32Window::SetQuitOnClose(bool quit_on_close) { - quit_on_close_ = quit_on_close; -} - -bool Win32Window::OnCreate() { - // No-op; provided for subclasses. - return true; -} - -void Win32Window::OnDestroy() { - // No-op; provided for subclasses. -} - -void Win32Window::UpdateTheme(HWND const window) { - DWORD light_mode; - DWORD light_mode_size = sizeof(light_mode); - LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, - kGetPreferredBrightnessRegValue, - RRF_RT_REG_DWORD, nullptr, &light_mode, - &light_mode_size); - - if (result == ERROR_SUCCESS) { - BOOL enable_dark_mode = light_mode == 0; - DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, - &enable_dark_mode, sizeof(enable_dark_mode)); - } -} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h deleted file mode 100644 index e901dde..0000000 --- a/windows/runner/win32_window.h +++ /dev/null @@ -1,102 +0,0 @@ -#ifndef RUNNER_WIN32_WINDOW_H_ -#define RUNNER_WIN32_WINDOW_H_ - -#include - -#include -#include -#include - -// A class abstraction for a high DPI-aware Win32 Window. Intended to be -// inherited from by classes that wish to specialize with custom -// rendering and input handling -class Win32Window { - public: - struct Point { - unsigned int x; - unsigned int y; - Point(unsigned int x, unsigned int y) : x(x), y(y) {} - }; - - struct Size { - unsigned int width; - unsigned int height; - Size(unsigned int width, unsigned int height) - : width(width), height(height) {} - }; - - Win32Window(); - virtual ~Win32Window(); - - // Creates a win32 window with |title| that is positioned and sized using - // |origin| and |size|. New windows are created on the default monitor. Window - // sizes are specified to the OS in physical pixels, hence to ensure a - // consistent size this function will scale the inputted width and height as - // as appropriate for the default monitor. The window is invisible until - // |Show| is called. Returns true if the window was created successfully. - bool Create(const std::wstring& title, const Point& origin, const Size& size); - - // Show the current window. Returns true if the window was successfully shown. - bool Show(); - - // Release OS resources associated with window. - void Destroy(); - - // Inserts |content| into the window tree. - void SetChildContent(HWND content); - - // Returns the backing Window handle to enable clients to set icon and other - // window properties. Returns nullptr if the window has been destroyed. - HWND GetHandle(); - - // If true, closing this window will quit the application. - void SetQuitOnClose(bool quit_on_close); - - // Return a RECT representing the bounds of the current client area. - RECT GetClientArea(); - - protected: - // Processes and route salient window messages for mouse handling, - // size change and DPI. Delegates handling of these to member overloads that - // inheriting classes can handle. - virtual LRESULT MessageHandler(HWND window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Called when CreateAndShow is called, allowing subclass window-related - // setup. Subclasses should return false if setup fails. - virtual bool OnCreate(); - - // Called when Destroy is called. - virtual void OnDestroy(); - - private: - friend class WindowClassRegistrar; - - // OS callback called by message pump. Handles the WM_NCCREATE message which - // is passed when the non-client area is being created and enables automatic - // non-client DPI scaling so that the non-client area automatically - // responds to changes in DPI. All other messages are handled by - // MessageHandler. - static LRESULT CALLBACK WndProc(HWND const window, - UINT const message, - WPARAM const wparam, - LPARAM const lparam) noexcept; - - // Retrieves a class instance pointer for |window| - static Win32Window* GetThisFromHandle(HWND const window) noexcept; - - // Update the window frame's theme to match the system theme. - static void UpdateTheme(HWND const window); - - bool quit_on_close_ = false; - - // window handle for top level window. - HWND window_handle_ = nullptr; - - // window handle for hosted content. - HWND child_content_ = nullptr; -}; - -#endif // RUNNER_WIN32_WINDOW_H_