From 045a2d6e68f4d8c1a26f6160ffba7fa1bfc5d87c Mon Sep 17 00:00:00 2001 From: Sandy <15143015732@163.com> Date: Fri, 4 Mar 2022 15:42:26 +0800 Subject: [PATCH] Merge remote-tracking branch 'origin/null-safe' into 2.2.x (#102) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Null safe (#13) * remove useless comments * remove useless dependencies * adapt brn_expandable_text.dart null-safe * upgrade dependencies:collection to stable * migrate constants to null safety * migrate brn_multi_click_util to null safety * migrate font util to null safety * migrate brn_text_style to null safety * migrate brn picker constants to null safety * migrate brn appBar theme to null safety * optimize bruno theme's import (#16) * ♻️ [NNBD] Part 1. Migrate configs (#28) * ♻️ [NNBD] Part 2. Migrate utils (#30) * ♻️ Migrate utils to NNBD * 🎨 Improve the color getter * :art: BrnSearchText (#36) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null (#40) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 🎨 utils-EventBus添加null-safe (#23) * 🎨 utils-EventBus添加null-safe * 🎨 修改theme配置功能及utils/brn_tools工具函数 null-safe * 🎨 EventBus添加null-safe(其他提交请忽略,输入回退) Co-authored-by: 大脸儿 * refactor brn_toast (#33) * refactor brn_toast * refactor brn_toast * 优化修复 EventBus * 优化 EventBus 单例实现 (#43) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * brn_toast time change to seconds (#45) * migrate brn_loading to null safety (#32) * migrate brn_loading to null safety * mv loading content to brnString constants * optimization brn_theme_configurator instance constructor (#47) * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * Migrate BrnStateTag、BrnTagCustom、BrnSelectTag、BrnDeleteTag to null-safe (#46) * [null-safe]: BrnStateTag、BrnTagCustom、BrnSelectTag、BrnDeleteTag 空安全适配 * perf: BrnDeleteTag null-safe * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * reset and migrated package [rating] to null-safety. (#42) * 迁移example ,优化常量命名,增加export (#51) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * 空安全报错修改 (#55) * 空安全报错修改 * 优化sketch教程为视频教程 * Migrated package [selectcity] to null-safety (#56) * reset and migrated package [rating] to null-safety. * Migrated package [selectcity] to null-safety * 修改ISuspensionBean抽象类相关子类的空字段问题。 * Migrated package [noticebar] to null-safety * migrate card_title to null safety (#59) * migrate card_title to null-safety * [fix] brn_action_card_title: _sub widget is not null * [optimize] empty widget use SizedBox instead of Container * replace empty widget SizedBox to SizedBox.shrink * Migrated package [radio] to null-safety (#62) * reset and migrated package [rating] to null-safety. * Migrated package [selectcity] to null-safety * 修改ISuspensionBean抽象类相关子类的空字段问题。 * Migrated package [noticebar] to null-safety * 1.Migrated package [radio] to null-safety; 2.Modified not-need-nullable param in brn_single_select_city_page.dart; * Migrated tabbar to null-safety * Migrated package [guide] to null-safety (#65) * reset and migrated package [rating] to null-safety. * Migrated package [selectcity] to null-safety * 修改ISuspensionBean抽象类相关子类的空字段问题。 * Migrated package [noticebar] to null-safety * 1.Migrated package [radio] to null-safety; 2.Modified not-need-nullable param in brn_single_select_city_page.dart; * Migrated package [guide] to null-safety * 🚀 Use the latest Podfile for the example (#68) * Null safe calendar (#64) * migrate calendar widget to null safety * brn_calendar_view fix _currentStartSelectedDate is not null * brn_calendar_view: simplify borderRadius usage * calendar widget late _displayMode * calendar widget add two constructors with date change * Card Components Null safe adapter (#53) * feat: support fvm * feat: Card components null-safey adpater * refactor: make code simple and clean * refactor: make code simple and clean * Migrated scroll_anchor to null-safety * fix #71 (#77) * fix content_card themeData is not null (#79) * Null safe of all buttons (#20) * icon button 增加null safe * null safe for normal button * null safe for normal button * null safe for button * null safe for all button * merge * rebase * rebase * merge * optimization * GlobalKey is not null * optimization * reset popup window * showButtonPanelPopList Co-authored-by: foreturn * Migrated package [navbar][input] to null-safety (#75) * reset and migrated package [rating] to null-safety. * Migrated package [selectcity] to null-safety * 修改ISuspensionBean抽象类相关子类的空字段问题。 * Migrated package [noticebar] to null-safety * 1.Migrated package [radio] to null-safety; 2.Modified not-need-nullable param in brn_single_select_city_page.dart; * Migrated package [guide] to null-safety * Migrated package [navbar][input] to null-safety * Optimized codes in brn_appbar.dart * Restore partial modification * fix:修复迁移tabar问题 * Migrated tabbar & scroll_anchor to null-safety (#66) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * Migrated tabbar to null-safety * Migrated scroll_anchor to null-safety * fix:修复迁移tabar问题 * Migrate Selection to null-safe (#54) * [null-safe]: BrnStateTag、BrnTagCustom、BrnSelectTag、BrnDeleteTag 空安全适配 * perf: BrnDeleteTag null-safe * Migrate Selection to null-safe * Migrate Selection to null-safe * perf: ItemEntity name 字段的初始化 * Migrate Selection to null-safe * migrate form to null safety * fix:修复tabbar报错及selection警告信息 * Migrated package [dialog] to null-safety (#81) * reset and migrated package [rating] to null-safety. * Migrated package [selectcity] to null-safety * 修改ISuspensionBean抽象类相关子类的空字段问题。 * Migrated package [noticebar] to null-safety * 1.Migrated package [radio] to null-safety; 2.Modified not-need-nullable param in brn_single_select_city_page.dart; * Migrated package [guide] to null-safety * Migrated package [navbar][input] to null-safety * Optimized codes in brn_appbar.dart * Restore partial modification * Migrated package [dialog] to null-safety * Modified some params's default value or nullable type * migrate brn_horizontal_steps、brn_step_line to null safety (#89) * migrate charts to null safety (#80) * migrate DoughuntChart to null safety * migrate progress bar chart to null safety * update progress bar chart document * migrate progress chart to null safety * migrate radar chart to null safety * migrate funnel chart to null safety * migrate broken line chart to null safety * fix progress bar chart some value is required * fix progress bar chart some value is required * fix brn_line_paint _path is not null * fix brn_funnel_chart properties is not null * fix brn_radar_chart properties is not null * fix brn_line_painter not null values * fix brn_progress_bar_chart error * brn_broken_line some properties is not null value * replace empty Container to SizedBox.shrink * update progress_bar_chart null safety value by hand * update broken_line null safety values by hand * update funnel_chart null safety value by hand * make LineCanvasModel immutable * migrate actionsheet into null-safe (#73) * migrate actionsheet into null-safe * sheet: code review Co-authored-by: yuanjunliang * fix:修复迁移问题 * fix:优化迁移部分问题key和style非空问题 * migrate form to null safety (#86) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * Migrated tabbar to null-safety * Migrated scroll_anchor to null-safety * fix:修复迁移tabar问题 * migrate form to null safety * fix:修复tabbar报错及selection警告信息 * fix:修复迁移问题 * fix:优化迁移部分问题key和style非空问题 * migrate picker to null safety * migrate popup to null safety (#69) * migrate popup to null safety * fix MeasureSize null safe problems * fix popup migrate to null-safety review problems * migrate gallery to null safety (#90) * migrate gallery to null safety * change the type error * remove @ * change String? to String * fix:修复picker空安全迁移问题 * migrate appraise dir to null safety (#84) * migrate appraise dir to null safety * fix appraise migrate to null-safety review problems * fix:修复list没指定泛型及if判断错误问题 * fix:migrate dashed line to null safty * migrate picker to null safety (#91) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * Migrated tabbar to null-safety * Migrated scroll_anchor to null-safety * fix:修复迁移tabar问题 * migrate form to null safety * fix:修复tabbar报错及selection警告信息 * fix:修复迁移问题 * fix:优化迁移部分问题key和style非空问题 * migrate picker to null safety * fix:修复picker空安全迁移问题 * fix:修复list没指定泛型及if判断错误问题 * fix:migrate dashed line to null safty * migrate example to null safty * fix:修复部分example warning * fix:修复demo报错问题 * fix:追加未跟踪修复 * fix:优化部分接口可空参数为非空 * Perf:Button Null safe (#93) * perf: Migrate Button Null-Safe * perf:优化 HorizontalStep Null-Safe * fix: null exception when parse json to entity * perf Button Null-Safe, fix NullException perf more layer icon color when item selected * migrate example to null safety (#94) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * Migrated tabbar to null-safety * Migrated scroll_anchor to null-safety * fix:修复迁移tabar问题 * migrate form to null safety * fix:修复tabbar报错及selection警告信息 * fix:修复迁移问题 * fix:优化迁移部分问题key和style非空问题 * migrate picker to null safety * fix:修复picker空安全迁移问题 * fix:修复list没指定泛型及if判断错误问题 * fix:migrate dashed line to null safty * migrate example to null safty * fix:修复部分example warning * fix:修复demo报错问题 * fix:追加未跟踪修复 * fix:优化部分接口可空参数为非空 Co-authored-by: violinday * fix:修复tabar showmore overflow 问题 #98 以及 tabbar 标签颜色默认设置倒置问题 * Fix #98 问题及优化部分代码 (#99) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * Migrated tabbar to null-safety * Migrated scroll_anchor to null-safety * fix:修复迁移tabar问题 * migrate form to null safety * fix:修复tabbar报错及selection警告信息 * fix:修复迁移问题 * fix:优化迁移部分问题key和style非空问题 * migrate picker to null safety * fix:修复picker空安全迁移问题 * fix:修复list没指定泛型及if判断错误问题 * fix:migrate dashed line to null safty * migrate example to null safty * fix:修复部分example warning * fix:修复demo报错问题 * fix:追加未跟踪修复 * fix:优化部分接口可空参数为非空 * fix:修复tabar showmore overflow 问题 #98 以及 tabbar 标签颜色默认设置倒置问题 Co-authored-by: violinday * refactor:优化 BrnInputItemType 常量命名 * refactor:优化枚举值命名 * fix:修改docs目录下form相关常量命名及所有枚举命名 * 优化 BrnInputItemType 常量命名 (#100) * Theme: 优化单例实现,初步优化 BrnAllThemeConfig 属性获取不为 null * refactor:优化theme,暴露非null引用 * theme:去除无用信息及优化部分代码 * theme:增加属性类型 * 优化修复 EventBus * 迁移example ,优化常量命名,增加export * migrate brn_empty_status.dart * 删除 BrnThemeImg * fix:tagConfig merge方法增加判空处理 * fix:revert tagConfig * fix:BrnAbnormalStateWidget空处理 * Migrated tabbar to null-safety * Migrated scroll_anchor to null-safety * fix:修复迁移tabar问题 * migrate form to null safety * fix:修复tabbar报错及selection警告信息 * fix:修复迁移问题 * fix:优化迁移部分问题key和style非空问题 * migrate picker to null safety * fix:修复picker空安全迁移问题 * fix:修复list没指定泛型及if判断错误问题 * fix:migrate dashed line to null safty * migrate example to null safty * fix:修复部分example warning * fix:修复demo报错问题 * fix:追加未跟踪修复 * fix:优化部分接口可空参数为非空 * fix:修复tabar showmore overflow 问题 #98 以及 tabbar 标签颜色默认设置倒置问题 * refactor:优化 BrnInputItemType 常量命名 * refactor:优化枚举值命名 * fix:修改docs目录下form相关常量命名及所有枚举命名 Co-authored-by: violinday * refactor: 更新 changelog * refactor:BrnBubbleText 增加属性 bgColor、textStyle,修复demo actionSheet、gallery、selection、picker错误 * fix:修复changelog 错误,brn_gallery_summary_page.dart 中标题空处理 * fix:修复部分问题 * fix:修复部分问题 Co-authored-by: laiiihz Co-authored-by: LAIIIHZ <35956195+laiiihz@users.noreply.github.com> Co-authored-by: Alex Li Co-authored-by: kalifun <37646342+kalifun@users.noreply.github.com> Co-authored-by: kkkman22 <2594387207@qq.com> Co-authored-by: 大脸儿 Co-authored-by: leftcoding <137387869@qq.com> Co-authored-by: violinday Co-authored-by: jojinshallar Co-authored-by: HappyImp Co-authored-by: Kenneth Co-authored-by: donywan Co-authored-by: foreturn Co-authored-by: Junl <17602153700@163.com> Co-authored-by: yuanjunliang Co-authored-by: Nayuta403 <40540394+Nayuta403@users.noreply.github.com> --- .gitignore | 3 + CHANGELOG.md | 44 +- assets/icons/icon_uparrow.png | Bin 452 -> 0 bytes .../BrnAbnormalStateWidget.md | 2 +- .../form/BrnAddLabel/BrnAddLabel.md | 2 +- .../BrnExpandFormGroup/BrnExpandFormGroup.md | 2 +- .../BrnMultiChoiceInputFormItem.md | 8 +- .../BrnMultiChoicePortraitInputFormItem.md | 14 +- .../BrnNormalFormGroup/BrnNormalFormGroup.md | 2 +- .../BrnRadioInputFormItem.md | 19 +- .../BrnRadioPortraitInputFormItem.md | 14 +- .../BrnRangeInputFormItem.md | 33 +- .../BrnRatioInputFormItem.md | 6 +- .../form/BrnStarsFormItem/BrnStarsFormItem.md | 6 +- .../BrnStepInputFormItem.md | 5 +- .../BrnTextBlockInputFormItem.md | 42 +- .../BrnTextInputFormItem.md | 14 +- .../BrnTextQuickSelectFormItem.md | 8 +- .../BrnTextSelectFormItem.md | 18 +- .../form/BrnTitleFormItem/BrnTitleFormItem.md | 6 +- .../BrnTitleSelectInputFormItem.md | 32 +- .../BrnMultiColumnPicker.md | 6 +- .../BrnSelectionView/BrnSelectionView.md | 28 +- docs/sketch.md | 12 +- example/ios/Podfile | 79 +- example/lib/main.dart | 2 + .../actionsheet/actionsheet_entry_page.dart | 74 +- ...ionsheet_selected_list_custom_example.dart | 18 +- .../actionsheet_selected_list_example.dart | 25 +- .../components/appraise/appraise_example.dart | 11 +- .../bottom_tabbar/bottom_tabbar_example.dart | 12 +- .../button/common_collection_example.dart | 4 +- .../button/selection_collection_example.dart | 7 +- .../calendar/calendarview_example.dart | 53 +- .../components/card/brn_shadow_example.dart | 10 +- .../bubble/brn_expanded_bubble_example.dart | 4 +- .../card/bubble/bubble_entry_page.dart | 2 + .../card/bubble/common_bubble_example.dart | 2 + .../content/brn_two_rich_content_example.dart | 2 + .../content/brn_two_text_content_example.dart | 2 + .../keyvalue_align_content_example.dart | 16 +- .../keyvalue_close_content_example.dart | 8 +- .../card/content/number_item_example.dart | 8 +- .../card/content/text_content_entry_page.dart | 2 + .../content/text_value_arrow_example.dart | 6 +- .../card_title/brn_action_title_example.dart | 2 + .../card_title/brn_common_title_example.dart | 7 +- .../components/card_title/title_example.dart | 2 + .../charts/chart_entry_example.dart | 74 +- .../charts/doughnut_chart_example.dart | 8 +- .../charts/line/brn_broken_line_example.dart | 42 +- .../charts/line/db_data_node_model.dart | 31 +- .../charts/progress_bar_chart_example.dart | 2 + .../charts/progress_chart_entry_page.dart | 2 + .../components/dialog/dialog_entry_page.dart | 46 +- .../components/empty/abnormal_entry_page.dart | 2 + .../empty/abnormal_state_example.dart | 14 +- .../form/all_item_style_example.dart | 2 + .../form/form_item_entry_example.dart | 2 + .../components/form/form_page_example.dart | 19 +- .../expansion_group_example.dart | 2 + .../form/group_example/group_add_example.dart | 2 + .../group_example/normal_group_example.dart | 2 + .../items_example/base_title_example.dart | 2 + .../items_example/multi_choice_example.dart | 14 +- .../multi_choice_protrait_example.dart | 6 +- .../items_example/radio_input_example.dart | 8 +- .../items_example/radio_protrait_example.dart | 6 +- .../items_example/range_input_example.dart | 16 +- .../items_example/ratio_input_example.dart | 8 +- .../select_all_title_example.dart | 2 + .../form/items_example/star_example.dart | 6 +- .../items_example/step_input_example.dart | 8 +- .../text_block_input_example.dart | 8 +- .../items_example/text_input_example.dart | 8 +- .../text_quick_select_input_example.dart | 12 +- .../items_example/text_select_example.dart | 8 +- .../form/items_example/title_example.dart | 2 + .../items_example/title_select_example.dart | 16 +- .../photo_preview_page.dart | 69 -- .../gallery/gallery_detail_example.dart | 12 +- .../gallery_detail_page_theme_example.dart | 2 + .../components/gallery/gallery_example.dart | 4 +- .../components/guide/force_guide_example.dart | 6 +- .../components/guide/guide_entry_page.dart | 2 + .../components/guide/soft_intro_example.dart | 6 +- .../components/input/input_example.dart | 8 +- .../components/line/dashed_line_example.dart | 11 +- .../loading/loading_widget_example.dart | 2 + .../components/navbar/appbar_entry_page.dart | 2 + .../navbar/nav_bar_example_page.dart | 46 +- .../noticebar/brn_notice_bar_example.dart | 2 + .../noticebar/notice_bar_example.dart | 2 + .../notice_bar_with_button_example.dart | 2 + .../picker/cutomer_bottom_picker_example.dart | 2 + .../picker/date_picker_example.dart | 4 +- .../picker/multi_picker_example.dart | 10 +- .../components/picker/picker_entry_page.dart | 56 +- .../popup/overlay_window_example.dart | 10 +- .../components/popup/popwindow_example.dart | 43 +- .../components/rating/rating_example.dart | 8 +- .../scroll_actor_tab_example.dart | 2 + .../selectcity/selected_city_example.dart | 10 +- .../components/selection/filter_entity.dart | 20 +- .../flat_selection_five_tags_example.dart | 16 +- .../flat_selection_four_tags_example.dart | 14 +- .../flat_selection_three_tags_example.dart | 14 +- .../selection/selection_entry_page.dart | 20 +- .../selection/selection_flat_entry_page.dart | 8 +- ...ionview_custom_floating_layer_example.dart | 16 +- ...view_customhandle_filter_example_page.dart | 8 +- ...selectionview_customview_example_page.dart | 36 +- ...electionview_date_filter_example_page.dart | 4 +- ...selectionview_date_range_example_page.dart | 16 +- .../selectionview_interceptor_example.dart | 26 +- ...view_limit_max_selected_count_example.dart | 12 +- ...electionview_more_filter_example_page.dart | 6 +- ...selectionview_multi_list_example_page.dart | 8 +- ...electionview_multi_range_example_page.dart | 12 +- ...nview_simple_multi_check_example_page.dart | 6 +- ...nview_simple_single_list_example_page.dart | 6 +- .../step/brn_horizontal_step_example.dart | 172 +++- .../sample/components/step/step_example.dart | 2 + .../components/step/step_line_example.dart | 205 +++-- .../sugsearch/search_text_example.dart | 1 + .../components/switch/checkbox_example.dart | 2 + .../components/switch/radio_example.dart | 2 + .../tabbar/brn_switch_title_example.dart | 4 +- .../components/tabbar/brn_tab_example.dart | 30 +- .../tabbar/brn_tabbar_sticky_example.dart | 22 +- .../tabbar/sub_switch_title_example.dart | 4 +- .../components/tag/border_tag_example.dart | 2 + .../components/tag/custom_tag_example.dart | 2 + .../components/tag/delete_tag_example.dart | 45 +- .../components/tag/select_tag_example.dart | 7 +- .../components/tag/state_tag_example.dart | 2 + .../sample/components/tag/tag_example.dart | 2 + .../components/tag/tag_row_example.dart | 2 + .../components/toast/toast_example.dart | 116 ++- example/lib/sample/home/card_data_config.dart | 28 +- .../home/expandable_container_widget.dart | 57 +- example/lib/sample/home/group_card.dart | 37 +- example/lib/sample/home/home.dart | 4 +- example/lib/sample/home/list_item.dart | 18 +- .../lib/sample/theme/config_test_utils.dart | 12 +- example/pubspec.yaml | 6 +- lib/bruno.dart | 11 +- .../actionsheet/brn_common_action_sheet.dart | 74 +- .../brn_selected_list_action_sheet.dart | 153 ++-- .../actionsheet/brn_share_action_sheet.dart | 52 +- lib/src/components/appraise/brn_appraise.dart | 218 ++--- .../appraise/brn_appraise_bottom_picker.dart | 19 +- .../appraise/brn_appraise_config.dart | 97 ++ .../appraise/brn_appraise_emoji_item.dart | 36 +- .../brn_appraise_emoji_list_view.dart | 48 +- .../appraise/brn_appraise_header.dart | 42 +- .../appraise/brn_appraise_interface.dart | 19 + .../appraise/brn_appraise_star_list_view.dart | 19 +- .../appraise/brn_flutter_gif_image.dart | 58 +- .../appraise/brn_mulit_select_tags.dart | 56 +- .../button/brn_big_ghost_button.dart | 27 +- .../button/brn_big_main_button.dart | 27 +- .../button/brn_big_outline_button.dart | 30 +- .../components/button/brn_icon_button.dart | 80 +- .../components/button/brn_normal_button.dart | 153 ++-- .../button/brn_small_main_button.dart | 57 +- .../button/brn_small_outline_button.dart | 42 +- .../button/brn_vertical_icon_button.dart | 11 +- .../collection/brn_bottom_button_panel.dart | 60 +- .../button/collection/brn_button_panel.dart | 58 +- .../brn_multiple_bottom_button.dart | 97 +- .../collection/brn_text_button_panel.dart | 59 +- .../calendar/brn_calendar_view.dart | 205 +++-- .../card/bubble_card/brn_bubble_text.dart | 62 +- .../card/bubble_card/brn_insert_info.dart | 4 +- .../content_card/brn_enhance_number_card.dart | 76 +- .../content_card/brn_pair_info_rich_grid.dart | 76 +- .../content_card/brn_pair_info_table.dart | 219 +++-- .../card/shadow_card/brn_shadow_card.dart | 22 +- .../card_title/brn_action_card_title.dart | 36 +- .../card_title/brn_common_card_title.dart | 66 +- .../brn_doughnut_chart.dart | 35 +- .../brn_doughnut_chart_legend.dart | 15 +- .../brn_bar_chart_data.dart | 22 +- .../brn_progress_bar_chart.dart | 60 +- .../brn_progress_bar_chart_painter.dart | 145 ++- .../brn_progress_chart.dart | 16 +- .../brn_progress_chart_painter.dart | 2 + .../charts/broken_line/brn_base_painter.dart | 8 +- .../charts/broken_line/brn_broken_line.dart | 85 +- .../charts/broken_line/brn_line_data.dart | 29 +- .../charts/broken_line/brn_line_painter.dart | 297 +++---- .../broken_line/brn_line_y_painter.dart | 74 +- .../charts/broken_line/monotone_x.dart | 25 +- lib/src/components/charts/funnel_chart.dart | 161 ++-- lib/src/components/charts/radar_chart.dart | 99 +-- .../dialog/brn_content_export_dialog.dart | 38 +- lib/src/components/dialog/brn_dialog.dart | 335 +++---- .../components/dialog/brn_dialog_utils.dart | 4 +- .../dialog/brn_enhance_operation_dialog.dart | 46 +- .../dialog/brn_middle_input_diaolg.dart | 40 +- .../dialog/brn_multi_select_dialog.dart | 152 ++-- .../dialog/brn_scrollable_text_dialog.dart | 37 +- .../components/dialog/brn_share_dialog.dart | 52 +- .../components/dialog/brn_single_select.dart | 66 +- .../components/empty/brn_empty_status.dart | 106 +-- .../form/base/brn_form_item_type.dart | 78 +- .../form/base/input_item_interface.dart | 5 +- .../general/brn_multi_choice_input_item.dart | 111 +-- .../brn_multi_choice_portrait_input_item.dart | 113 +-- .../general/brn_quick_select_input_item.dart | 133 ++- .../items/general/brn_radio_input_item.dart | 125 ++- .../brn_radio_portrait_input_item.dart | 83 +- .../items/general/brn_range_input_item.dart | 101 +-- .../items/general/brn_ratio_input_item.dart | 60 +- .../items/general/brn_star_input_item.dart | 52 +- .../items/general/brn_step_input_item.dart | 136 ++- .../general/brn_text_block_input_item.dart | 76 +- .../items/general/brn_text_input_item.dart | 79 +- .../items/general/brn_text_select_item.dart | 82 +- .../general/brn_title_select_input_item.dart | 134 +-- .../group}/brn_expandable_group.dart | 48 +- ...=> brn_expandable_group_with_opreate.dart} | 44 +- .../form/items/group/brn_normal_group.dart | 62 +- .../group}/brn_portrait_radio_group.dart | 105 ++- .../items/group/element_expand_widget.dart | 53 +- .../form/items/misc/brn_add_label_item.dart | 24 +- .../form/items/misc/brn_title_item.dart | 50 +- .../form/items/title/brn_base_title_item.dart | 50 +- .../title/brn_select_all_title_item.dart | 67 +- .../components/form/utils/brn_form_util.dart | 158 ++-- .../config/brn_basic_gallery_config.dart | 22 +- .../gallery/config/brn_bottom_card.dart | 44 +- .../gallery/config/brn_controller.dart | 3 +- .../config/brn_photo_gallery_config.dart | 88 +- .../gallery/page/brn_gallery_detail_page.dart | 189 ++-- .../page/brn_gallery_summary_page.dart | 58 +- .../guide/brn_delay_rendered_widget.dart | 10 +- .../components/guide/brn_flutter_guide.dart | 74 +- .../components/guide/brn_pulse_widget.dart | 9 +- .../guide/brn_step_widget_builder.dart | 9 +- .../guide/brn_step_widget_params.dart | 20 +- lib/src/components/guide/brn_throttling.dart | 6 +- lib/src/components/guide/brn_tip_widget.dart | 58 +- lib/src/components/input/brn_input_text.dart | 36 +- lib/src/components/line/brn_dashed_line.dart | 96 +- lib/src/components/line/brn_line.dart | 11 +- lib/src/components/loading/brn_loading.dart | 22 +- lib/src/components/navbar/brn_appbar.dart | 137 +-- .../components/navbar/brn_appbar_theme.dart | 4 +- .../components/navbar/brn_empty_appbar.dart | 19 - lib/src/components/navbar/brn_search_bar.dart | 91 +- .../noticebar/brn_marquee_text.dart | 37 +- .../components/noticebar/brn_notice_bar.dart | 73 +- .../noticebar/brn_notice_bar_with_button.dart | 47 +- .../components/picker/base/brn_picker.dart | 73 +- .../picker/base/brn_picker_constants.dart | 24 +- .../picker/base/brn_picker_title.dart | 40 +- .../picker/base/brn_picker_title_config.dart | 10 +- .../components/picker/brn_bottom_picker.dart | 42 +- .../picker/brn_bottom_write_picker.dart | 50 +- .../picker/brn_mulit_select_tags_picker.dart | 77 +- .../components/picker/brn_multi_picker.dart | 103 ++- .../picker/brn_picker_cliprrect.dart | 7 +- .../brn_select_tags_with_input_picker.dart | 141 +-- .../picker/brn_tags_common_picker.dart | 33 +- .../picker/brn_tags_picker_config.dart | 24 +- .../bean/brn_multi_column_picker_entity.dart | 134 ++- .../brn_multi_column_converter.dart | 35 +- .../brn_multi_column_list.dart | 116 +-- .../brn_multi_column_picker.dart | 144 ++- .../brn_multi_column_picker_util.dart | 30 +- .../btn_multi_column_picker_item.dart | 40 +- .../brn_multi_select_data.dart | 2 + .../brn_multi_select_list_picker.dart | 42 +- .../brn_date_picker_constants.dart | 19 +- .../time_picker/brn_date_time_formatter.dart | 30 +- .../date_picker/brn_date_picker.dart | 89 +- .../date_picker/brn_date_widget.dart | 106 +-- .../date_picker/brn_datetime_widget.dart | 168 ++-- .../date_picker/brn_time_widget.dart | 118 +-- .../brn_date_range_picker.dart | 91 +- .../brn_date_range_side_widget.dart | 109 +-- .../brn_date_range_widget.dart | 88 +- .../brn_time_range_side_widget.dart | 137 +-- .../brn_time_range_widget.dart | 108 ++- .../components/popup/brn_measure_size.dart | 22 +- .../components/popup/brn_overlay_window.dart | 89 +- .../components/popup/brn_popup_window.dart | 280 +++--- lib/src/components/radio/brn_checkbox.dart | 38 +- .../components/radio/brn_radio_button.dart | 37 +- lib/src/components/radio/brn_radio_core.dart | 33 +- .../components/rating/brn_rating_star.dart | 20 +- .../scroll_anchor/brn_scroll_anchor_tab.dart | 127 ++- .../components/selectcity/brn_az_common.dart | 24 +- .../selectcity/brn_az_listview.dart | 53 +- .../selectcity/brn_base_azlistview_page.dart | 30 +- .../components/selectcity/brn_index_bar.dart | 49 +- .../selectcity/brn_select_city_model.dart | 22 +- .../brn_single_select_city_page.dart | 54 +- .../selectcity/brn_suspension_view.dart | 73 +- .../selection/bean/brn_filter_entity.dart | 15 +- .../bean/brn_selection_common_entity.dart | 440 +++++----- .../selection/brn_flat_selection.dart | 122 ++- .../selection/brn_more_selection.dart | 136 ++- .../selection/brn_selection_list_entity.dart | 10 +- .../selection/brn_selection_util.dart | 77 +- .../selection/brn_selection_view.dart | 147 ++-- .../selection/brn_simple_selection.dart | 73 +- .../brn_selection_view_controller.dart | 14 +- ...selection_view_date_picker_controller.dart | 11 +- .../converter/brn_selection_converter.dart | 61 +- .../widget/brn_flat_selection_item.dart | 266 +++--- .../widget/brn_layer_more_selection_page.dart | 267 +++--- .../widget/brn_selection_animate_widget.dart | 56 +- .../brn_selection_common_item_widget.dart | 49 +- .../brn_selection_date_range_item_widget.dart | 142 ++- ...n_selection_datepicker_animate_widget.dart | 28 +- .../widget/brn_selection_list_widget.dart | 241 +++-- .../brn_selection_menu_item_widget.dart | 24 +- .../widget/brn_selection_menu_widget.dart | 408 ++++----- .../brn_selection_more_item_widget.dart | 295 +++---- ...brn_selection_range_input_item_widget.dart | 80 +- .../brn_selection_range_tag_widget.dart | 75 +- .../widget/brn_selection_range_widget.dart | 343 +++----- .../brn_selection_single_list_widget.dart | 131 ++- .../components/step/brn_horizontal_steps.dart | 372 ++++---- lib/src/components/step/brn_step_line.dart | 88 +- .../components/sugsearch/brn_search_text.dart | 85 +- .../bottom/brn_bottom_tab_bar_item.dart | 17 +- .../bottom/brn_bottom_tab_bar_main.dart | 127 +-- .../indicator/brn_custom_width_indicator.dart | 20 +- .../brn_fixed_underline_decoration.dart | 18 +- .../indicator/brn_triangle_decoration.dart | 54 +- .../tabbar/normal/brn_sub_switch_title.dart | 24 +- .../tabbar/normal/brn_switch_title.dart | 36 +- .../components/tabbar/normal/brn_tab_bar.dart | 362 ++++---- .../tabbar/normal/brn_tabbar_controller.dart | 12 +- lib/src/components/tag/brn_state_tag.dart | 12 +- lib/src/components/tag/brn_tag_custom.dart | 61 +- .../tag/tagview/brn_delete_tag.dart | 110 ++- .../tag/tagview/brn_select_tag.dart | 79 +- .../components/text/brn_expandable_text.dart | 24 +- lib/src/components/toast/brn_toast.dart | 328 ++++--- lib/src/constants/brn_asset_constants.dart | 199 ++--- lib/src/constants/brn_constants.dart | 38 +- lib/src/constants/brn_fonts_constants.dart | 10 + lib/src/constants/brn_strings_constants.dart | 5 +- lib/src/theme/base/brn_base_config.dart | 49 +- .../theme/base/brn_default_config_utils.dart | 800 +++++++++-------- lib/src/theme/base/brn_text_style.dart | 84 +- lib/src/theme/brn_initializer.dart | 17 +- lib/src/theme/brn_theme.dart | 3 +- lib/src/theme/brn_theme_configurator.dart | 57 +- .../configs/brn_abnormal_state_config.dart | 245 ++++-- .../configs/brn_action_sheet_config.dart | 378 ++++---- lib/src/theme/configs/brn_all_config.dart | 303 +++++-- lib/src/theme/configs/brn_appbar_config.dart | 382 ++++---- lib/src/theme/configs/brn_button_config.dart | 144 +-- .../theme/configs/brn_card_title_config.dart | 278 +++--- lib/src/theme/configs/brn_common_config.dart | 827 +++++++++++------ lib/src/theme/configs/brn_dialog_config.dart | 666 ++++++++------ .../brn_enhance_number_card_config.dart | 126 +-- lib/src/theme/configs/brn_form_config.dart | 544 +++++++----- .../configs/brn_gallery_detail_config.dart | 479 +++++----- .../theme/configs/brn_pair_info_config.dart | 352 +++++--- lib/src/theme/configs/brn_picker_config.dart | 342 +++++--- .../theme/configs/brn_selection_config.dart | 829 +++++++++++------- lib/src/theme/configs/brn_tabbar_config.dart | 359 +++++--- lib/src/theme/configs/brn_tag_config.dart | 209 +++-- .../theme/img/brn_theme_default_utils.dart | 69 -- lib/src/theme/img/brn_theme_img_utils.dart | 17 - lib/src/utils/brn_event_bus.dart | 56 +- lib/src/utils/brn_multi_click_util.dart | 10 +- lib/src/utils/brn_rich_text.dart | 108 +-- lib/src/utils/brn_text_util.dart | 12 +- lib/src/utils/brn_tools.dart | 89 +- lib/src/utils/css/brn_core_funtion.dart | 130 +-- lib/src/utils/css/brn_css_2_text.dart | 38 +- lib/src/utils/css/brn_util.dart | 39 +- lib/src/utils/font/brn_font.dart | 13 - lib/src/utils/i18n/brn_date_picker_i18n.dart | 54 +- lib/src/utils/i18n/brn_strings_zh_cn.dart | 66 +- pubspec.yaml | 2 +- 384 files changed, 14113 insertions(+), 12763 deletions(-) delete mode 100644 assets/icons/icon_uparrow.png delete mode 100644 example/lib/sample/components/form/phote_picker_example/photo_preview_page.dart create mode 100644 lib/src/components/appraise/brn_appraise_config.dart create mode 100644 lib/src/components/appraise/brn_appraise_interface.dart rename lib/src/components/form/{undetermined => items/group}/brn_expandable_group.dart (88%) rename lib/src/components/form/items/group/{brn_expand_group.dart => brn_expandable_group_with_opreate.dart} (79%) rename lib/src/components/form/{undetermined => items/group}/brn_portrait_radio_group.dart (74%) delete mode 100644 lib/src/components/navbar/brn_empty_appbar.dart create mode 100644 lib/src/constants/brn_fonts_constants.dart delete mode 100644 lib/src/theme/img/brn_theme_default_utils.dart delete mode 100644 lib/src/theme/img/brn_theme_img_utils.dart delete mode 100644 lib/src/utils/font/brn_font.dart diff --git a/.gitignore b/.gitignore index 8c47502d..19f097df 100644 --- a/.gitignore +++ b/.gitignore @@ -75,3 +75,6 @@ build/ !**/ios/**/default.perspectivev3 !/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages pubspec.lock + +# FVM +.fvm diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b3e551d..70537f23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,4 +1,44 @@ -## [1.0.0] - first publish adapter flutter sdk 1.22.4 -## [2.0.0] - adapter flutter sdk 2.2.2 + +## [2.1.0-Beta] - 2022-2-15 +### Changed + +#### base + +- **Breaking change**: Sound null safety support, thanks to @leftcoding #39#33 @donywan #20 @laiiihz #80#64#59#32#14 @kalifun #36 @jojinshallar #81#75#65#62#56#42 @junlandroid #73 @Kenneth #53 @HappyImp #55 @kkkman22 #23 @AlexV525 #30 +- **Breaking change**: Refer to the dart language specification to optimized constant and enum naming. +- Replace DIN Font with Bebas Font . +- Add build test thank to **AlexV525**. + +#### components +- BrnCalendarView: add BrnCalendarView.single() and BrnCalendarView.range() constructor and had its argument startEndDateChange removed. +- BrnSelectionEntityListBean: fromMap is renamed to fromJson. +- BrnRadioButton: optimize click area [#31](https://github.com/LianjiaTech/bruno/pull/31) , thanks to **a1017480401** . +- BrnScrollableTextDialog: remove Navigator.pop(context) in onSubmit() and hand it over to external processing (user). +- BrnBubbleText: add attribute bgColor and textStyle + + + +### Fixed + +- Fix example error [#71](https://github.com/LianjiaTech/bruno/issues/71) thanks to **leftcoding** fixing this issue. +- Fix BrnPickerTitleConfig titleContent setting is invalid [#70](https://github.com/LianjiaTech/bruno/issues/70). +- Optimize BrnPopupWindow onItemClick logic [#57 ](https://github.com/LianjiaTech/bruno/issues/57) . +- Fix BrnDialog is obscured by keyboard [#7](https://github.com/LianjiaTech/bruno/issues/7) . + + + +Thanks again to **leftcoding**, **jojinshallar**, **laiiihz**, **donywan**, **kalifun**, **junlandroid**, **Kenneth**, **HappyImp**, **kkkman22** , **a1017480401** and **Alex**. + + + +## [2.0.0] - 2021-12-8 + +- Adapt flutter sdk 2.2.2 + +## [1.0.0] - 2021-12-7 + +- First publish adapt flutter sdk 1.22.4 + + diff --git a/assets/icons/icon_uparrow.png b/assets/icons/icon_uparrow.png deleted file mode 100644 index b1d4cbf3a9918c37fdba49da7c2e47f07a02a8a1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 452 zcmeAS@N?(olHy`uVBq!ia0vp^x**KK1|+Sd9?b$$jKx9jP7LeL$-D$|Tv8)E(|mmy zw18|52FCVG1{RPKAeI7R1_tH@j10^`nh_+nfC(=G?|Dm){R;N%5N({9_}y24<@x!?>=%|jbY*|R zAiIFMq=D}Oqm={uCYc$_Ubap8y6M5vZUr@|O**GbWsV=WIiD}G<)S#R0G~zTo%kDU ze`45o-A%Z^?d@I5?>E18%lj_yZ?K)AxkJi|`G!mkYb-+!mtLD6!*}VYb+wD5_lCGw zTeJ4`vhVu(#bGP^`wRQCI?U4zOZYa}Ychl}@5!i~!f-e#X3~uKlt1%$*Ltq&v~@b) zw9O-H;Y0NaE!%w3mX>nmPCa7Xa?8n>D_2qOP+RWWZBO+5{}vvYxMS|qf65}~G;j7< z^`2mMzj8n^(6p9=|L_MVM{A#~i|dy0Ka@I9cWLX_TDfa5KLR~G!Qum}fVx.MULTI_CHOICE_PORTRAIT_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.multiChoicePortraitInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发 onTip 回调。 | 否 | 备注中类型 3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为 null 时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL2. 展示加号图标:BrnPrefixIconType.TYPE_ADD3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal2. 展示加号图标:BrnPrefixIconType.add3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示\*图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑 false:禁用 | @@ -137,7 +137,7 @@ BrnMultiChoiceInputFormItem( ```dart BrnMultiChoiceInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", diff --git a/docs/components/form/BrnMultiChoicePortraitInputFormItem/BrnMultiChoicePortraitInputFormItem.md b/docs/components/form/BrnMultiChoicePortraitInputFormItem/BrnMultiChoicePortraitInputFormItem.md index c19f9515..9bb04350 100644 --- a/docs/components/form/BrnMultiChoicePortraitInputFormItem/BrnMultiChoicePortraitInputFormItem.md +++ b/docs/components/form/BrnMultiChoicePortraitInputFormItem/BrnMultiChoicePortraitInputFormItem.md @@ -48,7 +48,7 @@ BrnMultiChoicePortraitInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -73,11 +73,11 @@ this.themeData = BrnThemeConfigurator.instance | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.MULTI_CHOICE_PORTRAIT_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.multiChoicePortraitInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE\_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE\_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE\_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE\_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | @@ -94,9 +94,9 @@ this.themeData = BrnThemeConfigurator.instance ###### BrnPrefixIconType: ```dart class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` ## 四、代码演示 @@ -138,7 +138,7 @@ BrnMultiChoicePortraitInputFormItem( ```dart BrnMultiChoicePortraitInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", diff --git a/docs/components/form/BrnNormalFormGroup/BrnNormalFormGroup.md b/docs/components/form/BrnNormalFormGroup/BrnNormalFormGroup.md index afd9cc19..3a1d2905 100644 --- a/docs/components/form/BrnNormalFormGroup/BrnNormalFormGroup.md +++ b/docs/components/form/BrnNormalFormGroup/BrnNormalFormGroup.md @@ -60,7 +60,7 @@ BrnNormalFormGroup({ | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | String | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.NORMAL_GROUP_TYPE | 外部可用此字段判断表单类型 | +| type | String | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.normalGroupType | 外部可用此字段判断表单类型 | | title | String | 录入项标题 | 否 | 无 | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | null | 1. 若赋值为 空字符串("")时仅展示"问号"图标,2. 若赋值为非空字符串时 展示"问号图标&文案",3. 若不赋值或赋值为null时 不显示提示项 | diff --git a/docs/components/form/BrnRadioInputFormItem/BrnRadioInputFormItem.md b/docs/components/form/BrnRadioInputFormItem/BrnRadioInputFormItem.md index 83fb480e..c799bf46 100644 --- a/docs/components/form/BrnRadioInputFormItem/BrnRadioInputFormItem.md +++ b/docs/components/form/BrnRadioInputFormItem/BrnRadioInputFormItem.md @@ -51,7 +51,7 @@ BrnRadioInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -78,11 +78,10 @@ BrnRadioInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TYPE_NORMAL | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE_ADD3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示*图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | @@ -103,10 +102,10 @@ BrnRadioInputFormItem( ```dart -class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; +class BrnPrefixIconType { + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` ## 四、代码演示 @@ -142,7 +141,7 @@ BrnRadioInputFormItem( ![](./img/BrnRadioInputFormItemDemo2.png) ```dart BrnRadioInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", @@ -173,7 +172,7 @@ BrnRadioInputFormItem( ![](./img/BrnRadioInputFormItemDemo3.png) ```dart BrnRadioInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, title: "自然到访保护期", subTitle: "这里是副标题", @@ -203,7 +202,7 @@ BrnRadioInputFormItem( ![](./img/BrnRadioInputFormItemDemo4.png) ```dart BrnRadioInputFormItem.autoLayout( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, error: "必填项不能为空", title: "autoLayout", diff --git a/docs/components/form/BrnRadioPortraitInputFormItem/BrnRadioPortraitInputFormItem.md b/docs/components/form/BrnRadioPortraitInputFormItem/BrnRadioPortraitInputFormItem.md index b7f70a32..237dc555 100644 --- a/docs/components/form/BrnRadioPortraitInputFormItem/BrnRadioPortraitInputFormItem.md +++ b/docs/components/form/BrnRadioPortraitInputFormItem/BrnRadioPortraitInputFormItem.md @@ -46,7 +46,7 @@ BrnRadioPortraitInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -73,11 +73,11 @@ BrnRadioPortraitInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | -------------- | -------------------------- | ------------------------------------------------------------------ | ------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.RADIO_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.radioInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | 无 | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发 onTip 回调。 | 否 | 备注中类型 3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为 null 时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL2. 展示加号图标:BrnPrefixIconType.TYPE_ADD3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal2. 展示加号图标:BrnPrefixIconType.add3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | 无 | | | isRequire | bool | 录入项是否为必填项(展示\*图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑 false:禁用 | @@ -96,9 +96,9 @@ BrnRadioPortraitInputFormItem( ```dart class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` @@ -138,7 +138,7 @@ BrnRadioPortraitInputFormItem( ```dart BrnRadioPortraitInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", diff --git a/docs/components/form/BrnRangeInputFormItem/BrnRangeInputFormItem.md b/docs/components/form/BrnRangeInputFormItem/BrnRangeInputFormItem.md index 65f5e8c0..19abd429 100644 --- a/docs/components/form/BrnRangeInputFormItem/BrnRangeInputFormItem.md +++ b/docs/components/form/BrnRangeInputFormItem/BrnRangeInputFormItem.md @@ -46,7 +46,7 @@ BrnRangeInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -82,11 +82,10 @@ BrnRangeInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TYPE_NORMAL | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标),默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | @@ -114,25 +113,25 @@ BrnRangeInputFormItem( #### BrnPrefixIconType: ``` dart -class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; +class BrnPrefixIconType { + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` #### BrnInputType ``` dart class BrnInputType { - static const String TEXT = "text"; - static const String MULTI_LINE = "multiline"; - static const String NUMBER = "number"; - static const String DECIMAL = "decimal"; - static const String PHONE = "phone"; - static const String DATE = "datetime"; - static const String EMAIL = "emailAddress"; - static const String URL = "url"; - static const String PWD = "visiblePassword"; + static const String text = "text"; + static const String multiLine = "multiline"; + static const String number = "number"; + static const String decimal = "decimal"; + static const String phone = "phone"; + static const String date = "datetime"; + static const String email = "emailAddress"; + static const String url = "url"; + static const String pwd = "visiblePassword"; } ``` ## 四、代码演示 @@ -178,7 +177,7 @@ BrnRangeInputFormItem( BrnRangeInputFormItem( minController: TextEditingController()..text = "10", maxController: TextEditingController()..text = "100", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "保护期", diff --git a/docs/components/form/BrnRatioInputFormItem/BrnRatioInputFormItem.md b/docs/components/form/BrnRatioInputFormItem/BrnRatioInputFormItem.md index c8e6d691..a6548d3f 100644 --- a/docs/components/form/BrnRatioInputFormItem/BrnRatioInputFormItem.md +++ b/docs/components/form/BrnRatioInputFormItem/BrnRatioInputFormItem.md @@ -44,7 +44,7 @@ BrnRatioInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -72,11 +72,11 @@ BrnRatioInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TEXT_INPUT_RATIO_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.textInputRatioType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑,false:禁用 | diff --git a/docs/components/form/BrnStarsFormItem/BrnStarsFormItem.md b/docs/components/form/BrnStarsFormItem/BrnStarsFormItem.md index b6a280fb..d98d3e3d 100644 --- a/docs/components/form/BrnStarsFormItem/BrnStarsFormItem.md +++ b/docs/components/form/BrnStarsFormItem/BrnStarsFormItem.md @@ -41,7 +41,7 @@ BrnStarsFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -66,11 +66,11 @@ BrnStarsFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.STAR_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.starInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE\_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE\_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE\_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE\_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | diff --git a/docs/components/form/BrnStepInputFormItem/BrnStepInputFormItem.md b/docs/components/form/BrnStepInputFormItem/BrnStepInputFormItem.md index f388bbd6..b97f5f2d 100644 --- a/docs/components/form/BrnStepInputFormItem/BrnStepInputFormItem.md +++ b/docs/components/form/BrnStepInputFormItem/BrnStepInputFormItem.md @@ -42,7 +42,7 @@ BrnStepInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -69,11 +69,10 @@ BrnStepInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TYPE_NORMAL | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE\_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE\_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE\_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE\_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | diff --git a/docs/components/form/BrnTextBlockInputFormItem/BrnTextBlockInputFormItem.md b/docs/components/form/BrnTextBlockInputFormItem/BrnTextBlockInputFormItem.md index 5c764ac7..4c07ac49 100644 --- a/docs/components/form/BrnTextBlockInputFormItem/BrnTextBlockInputFormItem.md +++ b/docs/components/form/BrnTextBlockInputFormItem/BrnTextBlockInputFormItem.md @@ -43,11 +43,11 @@ group: BrnTextBlockInputFormItem( {Key key, this.label, - this.type: BrnInputItemType.TEXT_BLOCK_INPUT_TYPE, + this.type: BrnInputItemType.textBlockInputType, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -77,11 +77,11 @@ BrnTextBlockInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TEXT_BLOCK_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.textBlockInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE_ADD3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | @@ -106,26 +106,26 @@ BrnTextBlockInputFormItem( ```dart -class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; +class BrnPrefixIconType { + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` #### BrnInputType -```dart r +```dart class BrnInputType { - static const String TEXT = "text"; - static const String MULTI_LINE = "multiline"; - static const String NUMBER = "number"; - static const String DECIMAL = "decimal"; - static const String PHONE = "phone"; - static const String DATE = "datetime"; - static const String EMAIL = "emailAddress"; - static const String URL = "url"; - static const String PWD = "visiblePassword"; + static const String text = "text"; + static const String multiLine = "multiline"; + static const String number = "number"; + static const String decimal = "decimal"; + static const String phone = "phone"; + static const String date = "datetime"; + static const String email = "emailAddress"; + static const String url = "url"; + static const String pwd = "visiblePassword"; } ``` ## 四、代码演示 @@ -160,7 +160,7 @@ BrnTextBlockInputFormItem( ```dart BrnTextBlockInputFormItem( controller: TextEditingController()..text = "hello", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", @@ -189,7 +189,7 @@ BrnTextBlockInputFormItem( ```dart BrnTextBlockInputFormItem( controller: TextEditingController()..text = "hello", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, title: "备注", @@ -217,7 +217,7 @@ BrnTextBlockInputFormItem( ```dart BrnTextBlockInputFormItem( controller: TextEditingController()..text = "hello", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, isPrefixIconEnabled: true, diff --git a/docs/components/form/BrnTextInputFormItem/BrnTextInputFormItem.md b/docs/components/form/BrnTextInputFormItem/BrnTextInputFormItem.md index ca77d8f8..284cc1ba 100644 --- a/docs/components/form/BrnTextInputFormItem/BrnTextInputFormItem.md +++ b/docs/components/form/BrnTextInputFormItem/BrnTextInputFormItem.md @@ -43,11 +43,11 @@ group: BrnTextInputFormItem({ Key key, this.label, - this.type: BrnInputItemType.TEXT_INPUT_TYPE, + this.type: BrnInputItemType.textInputType, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -77,11 +77,11 @@ BrnTextInputFormItem({ | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TEXT_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.textInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE\_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE\_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | @@ -158,7 +158,7 @@ BrnTextInputFormItem( ```dart BrnTextInputFormItem( controller: TextEditingController()..text = "300", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", @@ -188,7 +188,7 @@ BrnTextInputFormItem( ```dart BrnTextInputFormItem( controller: TextEditingController()..text = "300", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, title: "房屋总价", @@ -217,7 +217,7 @@ BrnTextInputFormItem( ```dart BrnTextInputFormItem( controller: TextEditingController()..text = "300", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, isPrefixIconEnabled: true, diff --git a/docs/components/form/BrnTextQuickSelectFormItem/BrnTextQuickSelectFormItem.md b/docs/components/form/BrnTextQuickSelectFormItem/BrnTextQuickSelectFormItem.md index cbc675e5..b174a09a 100644 --- a/docs/components/form/BrnTextQuickSelectFormItem/BrnTextQuickSelectFormItem.md +++ b/docs/components/form/BrnTextQuickSelectFormItem/BrnTextQuickSelectFormItem.md @@ -39,7 +39,7 @@ BrnTextQuickSelectFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -69,14 +69,14 @@ BrnTextQuickSelectFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TEXT_QUICK_SELECT_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.textQuickSelectInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑false:禁用 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 BrnPrefixIconType 类 | 否 | BrnPrefixIconType.TYPE\_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE\_NORMAL2. 展示加号图标:BrnPrefixIconType.TYPE\_ADD3. 展示减号图标:BrnPrefixIconType.TYPE\_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 BrnPrefixIconType 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal2. 展示加号图标:BrnPrefixIconType.add3. 展示减号图标:BrnPrefixIconType.remove | | isBtnsScroll | bool | 快捷按钮是否可滑动 | 否 | 无 | true:可滚动false:不可滚动 | | btnsTxt | List | 按钮文案 | 否 | 无 | | | selectBtnList | List | 按钮是否默认选中 | 否 | 无 | true:选中false:未选中 | @@ -150,7 +150,7 @@ List options = ['选项1', '选项2', '选项3', '选项4']; List statusAllFunctionDemo = [false, false, false, false]; BrnTextQuickSelectFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, btnsTxt: options, selectBtnList: statusAllFunctionDemo, diff --git a/docs/components/form/BrnTextSelectFormItem/BrnTextSelectFormItem.md b/docs/components/form/BrnTextSelectFormItem/BrnTextSelectFormItem.md index bf41b71b..3cfee756 100644 --- a/docs/components/form/BrnTextSelectFormItem/BrnTextSelectFormItem.md +++ b/docs/components/form/BrnTextSelectFormItem/BrnTextSelectFormItem.md @@ -40,7 +40,7 @@ BrnTextSelectFormItem({ this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -68,7 +68,7 @@ BrnTextSelectFormItem({ | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.TEXT_SELECT_INPUT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.textSelectInputType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | @@ -92,10 +92,10 @@ BrnTextSelectFormItem({ #### BrnPrefixIconType: ```dart -class BrnPrefixIconType{ - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; +class BrnPrefixIconType { + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` ## 四、代码演示 @@ -125,7 +125,7 @@ BrnTextSelectFormItem( ![](./img/BrnTextSelectFormItemDemo2.png) ```dart BrnTextSelectFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "证件类型", @@ -151,7 +151,7 @@ BrnTextSelectFormItem( ```dart BrnTextSelectFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, title: "证件类型", subTitle: "这里是副标题", @@ -176,7 +176,7 @@ BrnTextSelectFormItem( ```dart BrnTextSelectFormItem.autoLayout( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "证件类型", diff --git a/docs/components/form/BrnTitleFormItem/BrnTitleFormItem.md b/docs/components/form/BrnTitleFormItem/BrnTitleFormItem.md index ac2f6d85..68776bf8 100644 --- a/docs/components/form/BrnTitleFormItem/BrnTitleFormItem.md +++ b/docs/components/form/BrnTitleFormItem/BrnTitleFormItem.md @@ -32,7 +32,7 @@ BrnTitleFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -53,11 +53,11 @@ BrnTitleFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.LABEL_TITLE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.labelTitle | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE\_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE\_NORMAL2. 展示加号图标:BrnPrefixIconType.TYPE\_ADD3. 展示减号图标:BrnPrefixIconType.TYPE\_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal2. 展示加号图标:BrnPrefixIconType.add3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标), 默认为 false 不必填 | 否 | false | | | isEdit | bool | 录入项 是否可编辑 | 否 | true | true:可编辑,false:禁用 | diff --git a/docs/components/form/BrnTitleSelectInputFormItem/BrnTitleSelectInputFormItem.md b/docs/components/form/BrnTitleSelectInputFormItem/BrnTitleSelectInputFormItem.md index fe8f77d6..810e1cd3 100644 --- a/docs/components/form/BrnTitleSelectInputFormItem/BrnTitleSelectInputFormItem.md +++ b/docs/components/form/BrnTitleSelectInputFormItem/BrnTitleSelectInputFormItem.md @@ -44,7 +44,7 @@ BrnTitleSelectInputFormItem( this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -76,11 +76,11 @@ BrnTitleSelectInputFormItem( | **参数名** | **参数类型** | **描述** | **是否必填** | **默认值** | **备注** | | --- | --- | --- | --- | --- | --- | | label | String | 录入项的唯一标识,主要用于录入类型页面框架中 | 否 | 无 | | -| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType
.TEXT_INPUT_TITLE_SELECT_TYPE | 外部可根据此字段判断表单项类型 | +| type | Stirng | 录入项类型,主要用于录入类型页面框架中 | 否 | BrnInputItemType.textInputTitleSelectType | 外部可根据此字段判断表单项类型 | | title | String | 录入项标题 | 否 | '' | | | subTitle | String | 录入项子标题 | 否 | 无 | | | tipLabel | String | 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 | 否 | 备注中类型3 | 1. 设置"空字符串"时展示问号图标 2. 设置"非空字符串"时展示问号图标&文案 3. 若不赋值或赋值为null时,不显示提示项 | -| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.TYPE_NORMAL | 1. 不展示图标:BrnPrefixIconType.TYPE_NORMAL 2. 展示加号图标:BrnPrefixIconType.TYPE_ADD 3. 展示减号图标:BrnPrefixIconType.TYPE_REMOVE | +| prefixIconType | String | 录入项前缀图标样式 "添加项" "删除项" 详见 **BrnPrefixIconType** 类 | 否 | BrnPrefixIconType.normal | 1. 不展示图标:BrnPrefixIconType.normal 2. 展示加号图标:BrnPrefixIconType.add 3. 展示减号图标:BrnPrefixIconType.remove | | error | String | 录入项错误提示 | 否 | '' | | | isRequire | bool | 录入项是否为必填项(展示`*`图标) 默认为 false 不必填 | 否 | false | | | isPrefixIconEnabled | bool | 录入项不可编辑时(isEdit: false) "+"、"-"号是否可点击,true: 可点击回调false: 不可点击回调 | 否 | false | | @@ -104,9 +104,9 @@ BrnTitleSelectInputFormItem( ```dart class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } ``` @@ -114,15 +114,15 @@ class BrnPrefixIconType { ```dart class BrnInputType { - static const String TEXT = "text"; - static const String MULTI_LINE = "multiline"; - static const String NUMBER = "number"; - static const String DECIMAL = "decimal"; - static const String PHONE = "phone"; - static const String DATE = "datetime"; - static const String EMAIL = "emailAddress"; - static const String URL = "url"; - static const String PWD = "visiblePassword"; + static const String text = "text"; + static const String multiLine = "multiline"; + static const String number = "number"; + static const String decimal = "decimal"; + static const String phone = "phone"; + static const String date = "datetime"; + static const String email = "emailAddress"; + static const String url = "url"; + static const String pwd = "visiblePassword"; } ``` @@ -174,7 +174,7 @@ _list.add('手机号'); _list.add('座机'); BrnTitleSelectInputFormItem( controller: TextEditingController()..text = "124", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, error: "必填项不能为空", diff --git a/docs/components/picker/BrnMultiColumnPicker/BrnMultiColumnPicker.md b/docs/components/picker/BrnMultiColumnPicker/BrnMultiColumnPicker.md index 23bba47b..0781a113 100644 --- a/docs/components/picker/BrnMultiColumnPicker/BrnMultiColumnPicker.md +++ b/docs/components/picker/BrnMultiColumnPicker/BrnMultiColumnPicker.md @@ -58,9 +58,9 @@ BrnMultiColumnPicker( ```dart enum PickerFilterType { - None, //未设置 - Radio, //单选项,对应 type 为 radio - Checkbox, //多选项,对应 type 为 checkbox + none, //未设置 + radio, //单选项,对应 type 为 radio + checkbox, //多选项,对应 type 为 checkbox } ``` diff --git a/docs/components/selection/BrnSelectionView/BrnSelectionView.md b/docs/components/selection/BrnSelectionView/BrnSelectionView.md index 3ce81f6d..8e84a036 100644 --- a/docs/components/selection/BrnSelectionView/BrnSelectionView.md +++ b/docs/components/selection/BrnSelectionView/BrnSelectionView.md @@ -107,40 +107,40 @@ BrnSelectionView( ```dart enum BrnSelectionFilterType { /// 未设置 - None, + none, /// 不限类型 - UnLimit, + unLimit, /// 单选列表、单选项 type 为 radio - Radio, + radio, /// 多选列表、多选项 type 为 checkbox - Checkbox, + checkbox, /// 一般的值范围自定义区间 type 为 range - Range, + range, /// 日期选择,普通筛选时使用 CalendarView 展示选择时间,更多情况下使用 DatePicker 选择时间 - Date, + date, /// 自定义选择日期区间, type 为 dateRange - DateRange, + dateRange, /// 自定义通过 Calendar 选择日期区间,type 为 dateRangeCalendar - DateRangeCalendar, + dateRangeCalendar, /// 标签筛选 type 为 customerTag - CustomHandle, + customHandle, /// 更多列表、多选项 无 type - More, + more, /// 去二级页面 - Layer, + layer, /// 去自定义二级页面 - CustomLayer, + customLayer, } ``` @@ -165,8 +165,8 @@ enum BrnSelectionFilterType { ```dart enum SelectionWindowType { - List, //列表类型筛选弹窗,使用列表展示。 - Range, //标签类型筛选弹窗,使用 Tag + Range 的方式展示 + list, //列表类型筛选弹窗,使用列表展示。 + range, //标签类型筛选弹窗,使用 Tag + Range 的方式展示 } ``` diff --git a/docs/sketch.md b/docs/sketch.md index 03d90a2f..81ef8b53 100644 --- a/docs/sketch.md +++ b/docs/sketch.md @@ -2,24 +2,24 @@ order: 4 --- -# Sketch 设计指南 +# Sketch 设计指引 阅读本章内容你将学到如何使用 Bruno 配套的 Sketch 文件快速设计页面,并通过定制化标注插件导出可识别组件的设计稿。 -在开始之前需要先从 Bruno 主页下载 [UI 资源文件](https://bruno.ke.com:3008/download/sketch),得到 Sketch 文件和定制标注插件。 +在开始之前需要先从 Bruno 主页下载 [UI 资源文件](https://bruno.ke.com/download/sketch),得到 Sketch 文件和定制标注插件。 ## 第一部分 安装插件&选取所需组件 - + ## 第二部分 关于组件的解绑与使用 - + ## 第三部分 配合 Sketch 插件导出设计稿 - + ## 第四部分 查看标注中引用的组件信息 - + diff --git a/example/ios/Podfile b/example/ios/Podfile index b30a428b..ff7ef5e8 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -10,81 +10,32 @@ project 'Runner', { 'Release' => :release, } -def parse_KV_file(file, separator='=') - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return []; +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end - generated_key_values = {} - skip_line_start_symbols = ["#", "/"] - File.foreach(file_abs_path) do |line| - next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } - plugin = line.split(pattern=separator) - if plugin.length == 2 - podname = plugin[0].strip() - path = plugin[1].strip() - podpath = File.expand_path("#{path}", file_abs_path) - generated_key_values[podname] = podpath - else - puts "Invalid plugin specification: #{line}" - end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches end - generated_key_values + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" end +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + target 'Runner' do use_frameworks! use_modular_headers! - - # Flutter Pod - copied_flutter_dir = File.join(__dir__, 'Flutter') - copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework') - copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec') - unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path) - # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet. - # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration. - # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist. - - generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig') - unless File.exist?(generated_xcode_build_settings_path) - raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path) - cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR']; - - unless File.exist?(copied_framework_path) - FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir) - end - unless File.exist?(copied_podspec_path) - FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir) - end - end - - # Keep pod path relative so it can be checked into Podfile.lock. - pod 'Flutter', :path => 'Flutter' - - # Plugin Pods - - # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock - # referring to absolute paths on developers' machines. - system('rm -rf .symlinks') - system('mkdir -p .symlinks/plugins') - plugin_pods = parse_KV_file('../.flutter-plugins') - plugin_pods.each do |name, path| - symlink = File.join('.symlinks', 'plugins', name) - File.symlink(path, symlink) - pod name, :path => File.join(symlink, 'ios') - end + flutter_install_all_ios_pods(File.dirname(File.realpath(__FILE__))) end -# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. -install! 'cocoapods', :disable_input_output_paths => true - post_install do |installer| installer.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['ENABLE_BITCODE'] = 'NO' - end + flutter_additional_ios_build_settings(target) end end diff --git a/example/lib/main.dart b/example/lib/main.dart index 202b0652..dff77517 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1,3 +1,5 @@ + + import 'package:example/sample/home/home.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/actionsheet/actionsheet_entry_page.dart b/example/lib/sample/components/actionsheet/actionsheet_entry_page.dart index c98f8c16..25b1c8c6 100644 --- a/example/lib/sample/components/actionsheet/actionsheet_entry_page.dart +++ b/example/lib/sample/components/actionsheet/actionsheet_entry_page.dart @@ -1,3 +1,5 @@ + + import 'dart:async'; import 'package:bruno/bruno.dart'; @@ -121,7 +123,7 @@ class _ActionSheetEntryPageState extends State { } void _showCommonStyle(BuildContext context) { - List actions = List(); + List actions = []; actions.add(BrnCommonActionSheetItem( '选项一(警示项)', desc: '辅助信息辅助信息辅助信息', @@ -156,7 +158,7 @@ class _ActionSheetEntryPageState extends State { } void _showCommonStylex(){ - List actions = List(); + List actions = []; // 构建标题+辅助信息的普通项 actions.add(BrnCommonActionSheetItem( '选项一(警示项)', @@ -191,7 +193,7 @@ class _ActionSheetEntryPageState extends State { } void _showCommonStyle1(BuildContext context) { - List actions = List(); + List actions = []; actions.add(BrnCommonActionSheetItem( '选项一(警示项)', actionStyle: BrnCommonActionSheetItemStyle.alert, @@ -224,7 +226,7 @@ class _ActionSheetEntryPageState extends State { } void _showCommonStyle2(BuildContext context) { - List actions = List(); + List actions = []; actions.add(BrnCommonActionSheetItem( '选项一: (010)1234567', actionStyle: BrnCommonActionSheetItemStyle.link, @@ -258,7 +260,7 @@ class _ActionSheetEntryPageState extends State { } void _showCommonCustomStyle(BuildContext context) { - List actions = List(); + List actions =[]; actions.add( BrnCommonActionSheetItem( '选项一: 自定义主标题样式', @@ -332,8 +334,8 @@ class _ActionSheetEntryPageState extends State { // 用于控制timer只加载一次 var started = false; // 计时器 - var periodTimer; - List actions = List(); + late Timer periodTimer; + List actions = []; actions.add(BrnCommonActionSheetItem( '倒计时:$countdown', actionStyle: BrnCommonActionSheetItemStyle.alert, @@ -367,7 +369,7 @@ class _ActionSheetEntryPageState extends State { actions[0].desc = '倒计时:$times'; }); } else if (countdown == 0) { - periodTimer.onCancel(); + periodTimer.cancel(); } }); } @@ -378,7 +380,7 @@ class _ActionSheetEntryPageState extends State { BrnCommonActionSheetItem actionEle, ) { // 点击后立即停止计时 - periodTimer.onCancel(); + periodTimer.cancel(); var title = actionEle.title; BrnToast.show("title: $title, index: $index", context); }, @@ -386,38 +388,38 @@ class _ActionSheetEntryPageState extends State { }); // then用来在pop折后停止timer,如果不需要在pop后进行操作,不需要使用then }).then((value) { - periodTimer.onCancel(); + periodTimer.cancel(); }); } void _showShareSevenStyle(BuildContext context) { - List firstRowList = List(); + List firstRowList = []; firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_WEIXIN, + BrnShareItemConstants.shareWeiXin, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_BROWSER, + BrnShareItemConstants.shareBrowser, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_COPY_LINK, + BrnShareItemConstants.shareCopyLink, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_FRIEND, + BrnShareItemConstants.shareFriend, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_LINK, + BrnShareItemConstants.shareLink, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_QQ, + BrnShareItemConstants.shareQQ, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_CUSTOM, + BrnShareItemConstants.shareCustom, customImage: BrunoTools.getAssetImage("images/icon_custom_share.png"), customTitle: "自定义", canClick: true, @@ -434,38 +436,38 @@ class _ActionSheetEntryPageState extends State { } void _showShareFourStyle(BuildContext context) { - List firstRowList = List(); - List secondRowList = List(); + List firstRowList = []; + List secondRowList = []; firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_QZONE, + BrnShareItemConstants.shareQZone, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_SAVE_IMAGE, + BrnShareItemConstants.shareSaveImage, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_SMS, + BrnShareItemConstants.shareSms, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_WEIBO, + BrnShareItemConstants.shareWeiBo, canClick: true, )); secondRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_QZONE, + BrnShareItemConstants.shareQZone, canClick: false, )); secondRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_SAVE_IMAGE, + BrnShareItemConstants.shareSaveImage, canClick: false, )); secondRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_SMS, + BrnShareItemConstants.shareSms, canClick: false, )); secondRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_WEIBO, + BrnShareItemConstants.shareWeiBo, canClick: false, )); BrnShareActionSheet actionSheet = new BrnShareActionSheet( @@ -488,18 +490,18 @@ class _ActionSheetEntryPageState extends State { } void _showShareThreeStyle(BuildContext context) { - List firstRowList = List(); - List secondRowList = List(); + List firstRowList = []; + List secondRowList =[]; firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_WEIXIN, + BrnShareItemConstants.shareWeiXin, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_FRIEND, + BrnShareItemConstants.shareFriend, canClick: true, )); secondRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_CUSTOM, + BrnShareItemConstants.shareCustom, customImage: BrunoTools.getAssetImage("images/icon_custom_share.png"), customTitle: "自定义", canClick: true, @@ -516,13 +518,13 @@ class _ActionSheetEntryPageState extends State { } void _showShareTwoStyle(BuildContext context) { - List firstRowList = List(); + List firstRowList = []; firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_WEIXIN, + BrnShareItemConstants.shareWeiXin, canClick: true, )); firstRowList.add(BrnShareItem( - BrnShareItemConstants.SHARE_FRIEND, + BrnShareItemConstants.shareFriend, canClick: true, )); BrnShareActionSheet actionSheet = new BrnShareActionSheet( diff --git a/example/lib/sample/components/actionsheet/actionsheet_selected_list_custom_example.dart b/example/lib/sample/components/actionsheet/actionsheet_selected_list_custom_example.dart index d018de8a..283dc591 100644 --- a/example/lib/sample/components/actionsheet/actionsheet_selected_list_custom_example.dart +++ b/example/lib/sample/components/actionsheet/actionsheet_selected_list_custom_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -9,10 +11,10 @@ class SelectedListActionSheetCustomExamplePage extends StatefulWidget { class SelectedListActionSheetCustomExamplePageState extends State { - BrnSelectedListActionSheetController controller; + late BrnSelectedListActionSheetController controller; var _bottomActionKey = GlobalKey(); - List _data; + List? _data; @override void initState() { @@ -51,18 +53,18 @@ class SelectedListActionSheetCustomExamplePageState key: _bottomActionKey, mainButtonName: 'BrnBottomButtonPanel', mainButtonOnTap: () { - BrnToast.show('确定!sheet 的数据源长度 ${_data.length}', context); + BrnToast.show('确定!sheet 的数据源长度 ${_data!.length}', context); }, iconButtonList: [ BrnVerticalIconButton( - name: '已选(${_data.length})', + name: '已选(${_data!.length})', iconWidget: BrunoTools.getAssetImage( 'icons/grey_place_holder.png'), onTap: () { if (!controller.isHidden) { controller.dismiss(); } else { - if (_data == null || _data.length <= 0) { + if (_data == null || _data!.length <= 0) { BrnToast.show('数据为空,弹窗不展示', context); return; } @@ -70,12 +72,12 @@ class SelectedListActionSheetCustomExamplePageState context: context, isClearButtonHidden: false, isDeleteButtonHidden: true, - items: _data, + items: _data!, bottomOffset: 82, maxHeight: 400, controller: controller, title: '自定义行视图例子', - itemTitleBuilder: (int index, String entity) { + itemTitleBuilder: (int index, String? entity) { return Material( child: BrnStepInputFormItem( title: 'BrnStepInputFormItemWidget', @@ -100,7 +102,7 @@ class SelectedListActionSheetCustomExamplePageState cancel: '取消', confirm: '确定', onConfirm: () { setState(() {}); - _data.clear(); + _data!.clear(); }, onCancel: () {}); }) .showWithTargetKey( diff --git a/example/lib/sample/components/actionsheet/actionsheet_selected_list_example.dart b/example/lib/sample/components/actionsheet/actionsheet_selected_list_example.dart index e4d14f88..9dd1c195 100644 --- a/example/lib/sample/components/actionsheet/actionsheet_selected_list_example.dart +++ b/example/lib/sample/components/actionsheet/actionsheet_selected_list_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -8,21 +10,18 @@ class SelectedListActionSheetExamplePage extends StatefulWidget { class SelectedListActionSheetExamplePageState extends State { - BrnSelectedListActionSheetController controller; - List _data; + late BrnSelectedListActionSheetController controller; + List _data = [ + '1. 可以只指定要显示的文案,后边的 delete icon 是组件自带', + '2. delete icon 可以控制全部显示或者隐藏,但不支持某一行独立控制', + '3. 每一行的视图支持完全自定义', + '4. 如果要刷新列表,请调用 controller 调用 reloadData() 方法 ', + '5. 该例子中,点击最后一行的删除图表,可以更新当前行的文案' + ]; @override void initState() { - _data = [ - '1. 可以只指定要显示的文案,后边的 delete icon 是组件自带', - '2. delete icon 可以控制全部显示或者隐藏,但不支持某一行独立控制', - '3. 每一行的视图支持完全自定义', - '4. 如果要刷新列表,请调用 controller 调用 reloadData() 方法 ', - '5. 该例子中,点击最后一行的删除图表,可以更新当前行的文案' - ]; - controller = BrnSelectedListActionSheetController(); - super.initState(); } @@ -65,7 +64,7 @@ class SelectedListActionSheetExamplePageState if (!controller.isHidden) { controller.dismiss(); } else { - if (_data == null || _data.length <= 0) { + if ( _data.length <= 0) { BrnToast.show('数据为空,弹窗不展示', context); return; } @@ -90,7 +89,7 @@ class SelectedListActionSheetExamplePageState ), ), ), - itemTitleBuilder: (int index, String entity) { + itemTitleBuilder: (int index, String? entity) { return entity; }, onClear: () { diff --git a/example/lib/sample/components/appraise/appraise_example.dart b/example/lib/sample/components/appraise/appraise_example.dart index c092d228..8cb7791d 100644 --- a/example/lib/sample/components/appraise/appraise_example.dart +++ b/example/lib/sample/components/appraise/appraise_example.dart @@ -67,7 +67,7 @@ class _AppraiseExampleState extends State { BrnAppraise( title: "这里是标题文字", headerType: BrnAppraiseHeaderType.center, - type: BrnAppraiseType.Star, + type: BrnAppraiseType.star, tags: tags, inputHintText: '这里是文本输入的组件', iconDescriptions: [ @@ -80,6 +80,7 @@ class _AppraiseExampleState extends State { config: BrnAppraiseConfig( showConfirmButton: false, starAppraiseHint: '星星未选择时的文案', + inputDefaultText: '这是一段默认文字', inputTextChangeCallback: (input) { BrnToast.show('输入的内容为' + input, context); }, @@ -171,7 +172,7 @@ class _AppraiseExampleState extends State { }, ///必须传入5个字符串,没有的位置传'' - type: BrnAppraiseType.Emoji, + type: BrnAppraiseType.emoji, iconDescriptions: ['很差', '', '可以', '', '非常好'], config: BrnAppraiseConfig( indexes: [0, 2, 4], titleMaxLines: 3), @@ -205,7 +206,7 @@ class _AppraiseExampleState extends State { showToast(index, list, input, context); Navigator.pop(context); }, - type: BrnAppraiseType.Star, + type: BrnAppraiseType.star, iconDescriptions: ['很差', '不行', '可以', '好'], config: BrnAppraiseConfig( showTextInput: false, @@ -228,10 +229,10 @@ class _AppraiseExampleState extends State { void showToast(int index, List selectedTags, String input, BuildContext context) { String str = '选中的评价为$index'; - if (selectedTags?.isNotEmpty ?? false) { + if (selectedTags.isNotEmpty) { str = str + ',选中的标签为:' + selectedTags.toString(); } - if (input?.isNotEmpty ?? false) { + if (input.isNotEmpty) { str = str + ',输入的内容为:' + input; } BrnToast.show(str, context); diff --git a/example/lib/sample/components/bottom_tabbar/bottom_tabbar_example.dart b/example/lib/sample/components/bottom_tabbar/bottom_tabbar_example.dart index c63100a0..5cadf9f9 100644 --- a/example/lib/sample/components/bottom_tabbar/bottom_tabbar_example.dart +++ b/example/lib/sample/components/bottom_tabbar/bottom_tabbar_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -23,7 +25,7 @@ class BottomTabbarExampleState extends State with SingleTic int _selectedIndexTest3 = 0; /// 未读消息数量 - String badgeNo1; + String badgeNo1 = '100'; /// title数组 var titles = ['One', 'Two', 'Three', 'Four', 'Five', 'Six']; @@ -38,14 +40,6 @@ class BottomTabbarExampleState extends State with SingleTic Icons.star ]; - @override - void initState() { - super.initState(); - - /// 初始化某个未读消息的数量 - badgeNo1 = '100'; - } - /// 选中状态时state设置 void _onItemSelected(int index) { setState(() { diff --git a/example/lib/sample/components/button/common_collection_example.dart b/example/lib/sample/components/button/common_collection_example.dart index 249d6bd0..da249615 100644 --- a/example/lib/sample/components/button/common_collection_example.dart +++ b/example/lib/sample/components/button/common_collection_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -250,7 +252,7 @@ class BrnCommonBottomExample extends StatelessWidget { ], ), Text( - '异常案例:按钮文本长为0', + '异常案例:按钮文本长为空串', style: TextStyle( color: Color(0xFF222222), fontSize: 28, diff --git a/example/lib/sample/components/button/selection_collection_example.dart b/example/lib/sample/components/button/selection_collection_example.dart index 40bcbe64..42723669 100644 --- a/example/lib/sample/components/button/selection_collection_example.dart +++ b/example/lib/sample/components/button/selection_collection_example.dart @@ -7,13 +7,8 @@ class BrnSelectionBottomButtonExample extends StatefulWidget { } class _BrnSelectionBottomButtonExampleState extends State { - BrnMultipleBottomController controller; - @override - void initState() { - super.initState(); - controller = BrnMultipleBottomController(); - } + BrnMultipleBottomController controller = BrnMultipleBottomController(); @override Widget build(BuildContext context) { diff --git a/example/lib/sample/components/calendar/calendarview_example.dart b/example/lib/sample/components/calendar/calendarview_example.dart index 26e4178e..25e9f568 100644 --- a/example/lib/sample/components/calendar/calendarview_example.dart +++ b/example/lib/sample/components/calendar/calendarview_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -56,69 +58,66 @@ class TagViewExamplePageState extends State { } Widget _calendarViewWeekNocontroll(context) { - return BrnCalendarView( - displayMode: DisplayMode.Week, - selectMode: SelectMode.SINGLE, + return BrnCalendarView.single( + displayMode: DisplayMode.week, showControllerBar: false, - startEndDateChange: (startDate, endDate) { - BrnToast.show('开始时间: $startDate , 结束时间:$endDate', context); + dateChange: (date) { + BrnToast.show('选中的时间: $date', context); }, ); } Widget _calendarViewWeekNocontrollCustomWeekName(context) { - return BrnCalendarView( - displayMode: DisplayMode.Week, - selectMode: SelectMode.SINGLE, + return BrnCalendarView.single( + displayMode: DisplayMode.week, showControllerBar: false, weekNames: ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'], - startEndDateChange: (startDate, endDate) { - BrnToast.show('开始时间: $startDate , 结束时间:$endDate', context); + dateChange: (date) { + BrnToast.show('选中的时间: $date', context); }, ); } Widget _calendarViewWeek(context) { - return BrnCalendarView( - displayMode: DisplayMode.Week, + return BrnCalendarView.single( + displayMode: DisplayMode.week, initDisplayDate: DateTime.parse('2020-06-01'), minDate: DateTime(2020), maxDate: DateTime(2021), - startEndDateChange: (startDate, endDate) { - BrnToast.show('开始时间: $startDate , 结束时间:$endDate', context); + dateChange: (date) { + BrnToast.show('选中的时间: $date', context); }, ); } Widget _calendarViewWeekRange(context) { - return BrnCalendarView( - displayMode: DisplayMode.Week, - selectMode: SelectMode.RANGE, - startEndDateChange: (startDate, endDate) { - BrnToast.show('开始时间: $startDate , 结束时间:$endDate', context); + return BrnCalendarView.range( + displayMode: DisplayMode.week, + rangeDateChange: (rangeDate) { + BrnToast.show( + '开始时间: ${rangeDate.start} , 结束时间:${rangeDate.end}', context); }, ); } Widget _calendarViewMonth(context) { - return BrnCalendarView( - selectMode: SelectMode.SINGLE, + return BrnCalendarView.single( initDisplayDate: DateTime.parse('2020-06-01'), minDate: DateTime(2020), maxDate: DateTime(2021), - startEndDateChange: (startDate, endDate) { - BrnToast.show('开始时间: $startDate , 结束时间:$endDate', context); + dateChange: (date) { + BrnToast.show('选中的时间: $date', context); }, ); } Widget _calendarViewMonthRange(context) { - return BrnCalendarView( - selectMode: SelectMode.RANGE, + return BrnCalendarView.range( minDate: DateTime(2020), maxDate: DateTime(2023), - startEndDateChange: (startDate, endDate) { - BrnToast.show('开始时间: $startDate , 结束时间:$endDate', context); + rangeDateChange: (rangeDate) { + BrnToast.show( + '开始时间: ${rangeDate.start} , 结束时间:${rangeDate.end}', context); }, ); } diff --git a/example/lib/sample/components/card/brn_shadow_example.dart b/example/lib/sample/components/card/brn_shadow_example.dart index 679166c7..8579a95a 100644 --- a/example/lib/sample/components/card/brn_shadow_example.dart +++ b/example/lib/sample/components/card/brn_shadow_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; @@ -9,14 +11,6 @@ class BrnShadowExample extends StatefulWidget { } class _BrnShadowExampleState extends State { - int count; - - @override - void initState() { - super.initState(); - count = 0; - } - @override Widget build(BuildContext context) { return Scaffold( diff --git a/example/lib/sample/components/card/bubble/brn_expanded_bubble_example.dart b/example/lib/sample/components/card/bubble/brn_expanded_bubble_example.dart index 1c8754c0..46b50a47 100644 --- a/example/lib/sample/components/card/bubble/brn_expanded_bubble_example.dart +++ b/example/lib/sample/components/card/bubble/brn_expanded_bubble_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -38,7 +40,7 @@ class BrnBubbleExample2 extends StatelessWidget { maxLines: 2, text: '推荐理由:“满五唯一”“临近地铁”“首付低”,多出折行显示,文字展开的样式文式文文字展开的样式文式文。问我', onExpanded: (isExpanded){ - String str = isExpanded?"展开了":"收起了"; + String str = isExpanded ? "展开了" : "收起了"; BrnToast.show("我$str", context); }, ), diff --git a/example/lib/sample/components/card/bubble/bubble_entry_page.dart b/example/lib/sample/components/card/bubble/bubble_entry_page.dart index 550304cc..66346dcd 100644 --- a/example/lib/sample/components/card/bubble/bubble_entry_page.dart +++ b/example/lib/sample/components/card/bubble/bubble_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/card/bubble/common_bubble_example.dart'; import 'package:example/sample/components/card/bubble/brn_expanded_bubble_example.dart'; diff --git a/example/lib/sample/components/card/bubble/common_bubble_example.dart b/example/lib/sample/components/card/bubble/common_bubble_example.dart index 86532787..0468c77a 100644 --- a/example/lib/sample/components/card/bubble/common_bubble_example.dart +++ b/example/lib/sample/components/card/bubble/common_bubble_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/card/content/brn_two_rich_content_example.dart b/example/lib/sample/components/card/content/brn_two_rich_content_example.dart index fc9c112d..36f082ef 100644 --- a/example/lib/sample/components/card/content/brn_two_rich_content_example.dart +++ b/example/lib/sample/components/card/content/brn_two_rich_content_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/card/content/brn_two_text_content_example.dart b/example/lib/sample/components/card/content/brn_two_text_content_example.dart index 3f011d6e..19ecbdff 100644 --- a/example/lib/sample/components/card/content/brn_two_text_content_example.dart +++ b/example/lib/sample/components/card/content/brn_two_text_content_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/card/content/keyvalue_align_content_example.dart b/example/lib/sample/components/card/content/keyvalue_align_content_example.dart index 57527374..d959c039 100644 --- a/example/lib/sample/components/card/content/keyvalue_align_content_example.dart +++ b/example/lib/sample/components/card/content/keyvalue_align_content_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; @@ -9,7 +11,7 @@ class TextContentExample extends StatefulWidget { } class _TextContentExampleState extends State { - List list; + late List list; @override void initState() { @@ -23,7 +25,7 @@ class _TextContentExampleState extends State { BrnInfoModal(keyPart: "名称名称名:", valuePart: "内容内容内容内容内容"), BrnInfoModal(keyPart: "名称名称名称名称:", valuePart: "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容"), BrnInfoModal.valueLastClickInfo("名称名:", '内容内容内容内容内容', '可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }) ]; } @@ -231,7 +233,7 @@ class _TextContentExampleState extends State { keyPart: "名称名称名称名称:", valuePart: "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容"), BrnInfoModal.valueLastClickInfo("名称名:", '11111111', '22222222', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), ], ), @@ -257,7 +259,7 @@ class _TextContentExampleState extends State { keyPart: "名称名称名称名称:", valuePart: "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容"), BrnInfoModal.valueLastClickInfo("名称名:", '内容内容内容内容内容', '可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), ], ), @@ -301,7 +303,7 @@ class _TextContentExampleState extends State { ), Transform.rotate( angle: pi, - child: BrunoTools.getAssetImage('icons/icon_uparrow.png')), + child: BrunoTools.getAssetImage('icons/icon_up_arrow.png')), ], ), decoration: BoxDecoration( @@ -381,7 +383,7 @@ class _TextContentExampleState extends State { BrnInfoModal(keyPart: "名称名称名:", valuePart: "内容内容内容内容内容"), BrnInfoModal.valueLastClickInfo("名称十分的长名称十分的长名称十分的长名称十分的长:", '内容内容内容内容内容', '可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), ], ), @@ -401,7 +403,7 @@ class _TextContentExampleState extends State { BrnInfoModal.valueLastClickInfo( "名称十分的长名称十分的长名称十分的长名称十分的长:", '内容内容内容内容内容', '可点击内容可点击内容可点击内容可点击内容可点击内容可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), ], ), diff --git a/example/lib/sample/components/card/content/keyvalue_close_content_example.dart b/example/lib/sample/components/card/content/keyvalue_close_content_example.dart index acf2022c..2d6d8053 100644 --- a/example/lib/sample/components/card/content/keyvalue_close_content_example.dart +++ b/example/lib/sample/components/card/content/keyvalue_close_content_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -62,7 +64,7 @@ class _KeyTextCloseContentExampleState extends State BrnInfoModal(keyPart: "名称名称名:", valuePart: "内容内容内容内容内容"), BrnInfoModal.valueLastClickInfo("名称名:", '内容内容内容内容内容', '可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), ], ), @@ -132,12 +134,12 @@ class _KeyTextCloseContentExampleState extends State "内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内"), BrnInfoModal.valueLastClickInfo("名称十分的长名:", '内容内容内容内容内容', '可点击内容可点击内容可点击内容可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), BrnInfoModal.valueLastClickInfo( "名称十分的长名:", '内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容', '可点击内容可点击内容可点击内容可点击内容', clickCallback: (text) { - BrnToast.show(text, context); + BrnToast.show(text!, context); }), ], ), diff --git a/example/lib/sample/components/card/content/number_item_example.dart b/example/lib/sample/components/card/content/number_item_example.dart index 552ee602..f1a4df94 100644 --- a/example/lib/sample/components/card/content/number_item_example.dart +++ b/example/lib/sample/components/card/content/number_item_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -60,7 +62,7 @@ class _NumberItemRowExampleState extends State { number: '3', preDesc: '前', lastDesc: '后', - numberInfoIcon: BrnNumberInfoIcon.ARROW, + numberInfoIcon: BrnNumberInfoIcon.arrow, iconTapCallBack: (data) {}), ], ), @@ -79,9 +81,9 @@ class _NumberItemRowExampleState extends State { number: '3', preDesc: '前', lastDesc: '后', - numberInfoIcon: BrnNumberInfoIcon.ARROW, + numberInfoIcon: BrnNumberInfoIcon.arrow, iconTapCallBack: (data) { - BrnToast.show(data.title, context); + BrnToast.show(data.title!, context); }), BrnNumberInfoItemModel( title: '数字信息数字信息数字信息数字信息数字信息数字信息', diff --git a/example/lib/sample/components/card/content/text_content_entry_page.dart b/example/lib/sample/components/card/content/text_content_entry_page.dart index 2a3dfe12..e16e0aec 100644 --- a/example/lib/sample/components/card/content/text_content_entry_page.dart +++ b/example/lib/sample/components/card/content/text_content_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/card/content/keyvalue_align_content_example.dart'; import 'package:example/sample/components/card/content/keyvalue_close_content_example.dart'; diff --git a/example/lib/sample/components/card/content/text_value_arrow_example.dart b/example/lib/sample/components/card/content/text_value_arrow_example.dart index 56d52af9..e902465a 100644 --- a/example/lib/sample/components/card/content/text_value_arrow_example.dart +++ b/example/lib/sample/components/card/content/text_value_arrow_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -66,7 +68,7 @@ class _TextValueArrowContentExampleState extends State { children: [ Text( '规则', - style: TextStyle(color: Color(0xFF222222), fontSize: 28, fontWeight: FontWeight.bold), + style: TextStyle( + color: Color(0xFF222222), + fontSize: 28, + fontWeight: FontWeight.bold), ), BrnBubbleText( maxLines: 4, diff --git a/example/lib/sample/components/card_title/title_example.dart b/example/lib/sample/components/card_title/title_example.dart index 66b73224..084cce7a 100644 --- a/example/lib/sample/components/card_title/title_example.dart +++ b/example/lib/sample/components/card_title/title_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/card_title/brn_action_title_example.dart'; import 'package:example/sample/components/card_title/brn_common_title_example.dart'; diff --git a/example/lib/sample/components/charts/chart_entry_example.dart b/example/lib/sample/components/charts/chart_entry_example.dart index d66f5f19..64dd6ea0 100644 --- a/example/lib/sample/components/charts/chart_entry_example.dart +++ b/example/lib/sample/components/charts/chart_entry_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; @@ -18,21 +20,21 @@ class FunnelChartExamplePage extends StatelessWidget { } class FunnelChartExample extends StatefulWidget { - FunnelChartExample({Key key}) : super(key: key); + FunnelChartExample({Key? key}) : super(key: key); @override _FunnelChartExampleState createState() => _FunnelChartExampleState(); } class _FunnelChartExampleState extends State { - double maxLayerWidth; - double minLayerWidth; - double layerMargin; - double layerHeight; - double offsetX; - double offsetY; - MarkerAlignment alignment; - FunnelShape shape; + late double maxLayerWidth; + late double minLayerWidth; + late double layerMargin; + late double layerHeight; + late double offsetX; + late double offsetY; + late MarkerAlignment alignment; + FunnelShape? shape; bool defaultStyle = false; @override @@ -53,7 +55,7 @@ class _FunnelChartExampleState extends State { child: Column( children: [ BrnFunnelChart( - shape: FunnelShape.LeftOrRight, + shape: FunnelShape.leftOrRight, alignment: MarkerAlignment.right, maxLayerWidth: maxLayerWidth, minLayerWidth: minLayerWidth, @@ -82,7 +84,7 @@ class _FunnelChartExampleState extends State { height: 10, ), BrnFunnelChart( - shape: FunnelShape.LeftAndRight, + shape: FunnelShape.leftAndRight, alignment: alignment, maxLayerWidth: maxLayerWidth, minLayerWidth: minLayerWidth, @@ -359,7 +361,7 @@ class _FunnelChartExampleState extends State { padding: EdgeInsets.only(left: 20), child: Text('标签位置'), ), - FlatButton( + TextButton( onPressed: () { setState(() { alignment = MarkerAlignment.left; @@ -367,7 +369,7 @@ class _FunnelChartExampleState extends State { }, child: Text('居左'), ), - FlatButton( + TextButton( onPressed: () { setState(() { alignment = MarkerAlignment.center; @@ -375,7 +377,7 @@ class _FunnelChartExampleState extends State { }, child: Text('居中'), ), - FlatButton( + TextButton( onPressed: () { setState(() { alignment = MarkerAlignment.right; @@ -413,16 +415,16 @@ class RadarChartExample extends StatefulWidget { } class _RadarChartExampleState extends State with SingleTickerProviderStateMixin { - double radius; - int sideCount; - double angle; - double padding; + late double radius; + int? sideCount; + double? angle; + late double padding; Map> dataList1 = Map(); Map> dataList2 = Map(); - AnimationController controller; - Animation animation; + late AnimationController controller; + late Animation animation; bool defaultStyle = false; @override @@ -433,8 +435,8 @@ class _RadarChartExampleState extends State with SingleTicker padding = 4; angle = 0; for (int i = 3; i <= 8; i++) { - List data1 = List(); - List data2 = List(); + List data1 = []; + List data2 = []; for (int j = 0; j < i; j++) { data1.add(Random().nextDouble() * 10); @@ -461,18 +463,18 @@ class _RadarChartExampleState extends State with SingleTicker radius: radius, sidesCount: 5, markerMargin: padding, - rotateAngle: angle * 2 * pi / 360, - data: [dataList1[sideCount.toString()], dataList2[sideCount.toString()]], + rotateAngle: angle! * 2 * pi / 360, + data: [dataList1[sideCount.toString()]!, dataList2[sideCount.toString()]!], tagNames: ['合作共赢诚实守信', '合作共赢诚实守信', '合作共赢诚实守信', '合作共赢诚实守信', '合作共赢诚实守信'], ); } else { return BrnRadarChart( radius: radius, provider: RadarProvider(sideCount, dataList1, dataList2), - sidesCount: sideCount, + sidesCount: sideCount!, markerMargin: padding, crossedAxisLine: true, - rotateAngle: angle * 2 * pi / 360, + rotateAngle: angle! * 2 * pi / 360, animateProgress: animation.value, builder: (index) { return Text( @@ -560,7 +562,7 @@ class _RadarChartExampleState extends State with SingleTicker ), Expanded( child: Slider( - value: sideCount.toDouble(), + value: sideCount!.toDouble(), divisions: 6, onChanged: (data) { if (data.toInt() != sideCount) { @@ -577,9 +579,9 @@ class _RadarChartExampleState extends State with SingleTicker onChangeEnd: (data) { debugPrint('end:$data'); }, - min: defaultStyle ? sideCount.toDouble() : 3, - max: defaultStyle ? sideCount.toDouble() : 8, - label: '${sideCount.toStringAsFixed(0)}', + min: defaultStyle ? sideCount!.toDouble() : 3, + max: defaultStyle ? sideCount!.toDouble() : 8, + label: '${sideCount!.toStringAsFixed(0)}', activeColor: Colors.green, inactiveColor: Colors.grey, semanticFormatterCallback: (double newValue) { @@ -597,7 +599,7 @@ class _RadarChartExampleState extends State with SingleTicker ), Expanded( child: Slider( - value: angle.toDouble(), + value: angle!.toDouble(), divisions: 360, onChanged: (data) { if (data.toDouble() != angle) { @@ -616,7 +618,7 @@ class _RadarChartExampleState extends State with SingleTicker }, min: 0, max: 360, - label: '${angle.toStringAsFixed(0)}', + label: '${angle!.toStringAsFixed(0)}', activeColor: Colors.green, inactiveColor: Colors.grey, semanticFormatterCallback: (double newValue) { @@ -645,7 +647,7 @@ class RadarProvider extends BrnRadarChartDataProvider { final Map> dataList2; - final int sideCount; + final int? sideCount; RadarProvider(this.sideCount, this.dataList1, this.dataList2); @@ -686,10 +688,10 @@ class RadarProvider extends BrnRadarChartDataProvider { List getRadarValues(int radarIndex) { switch (radarIndex) { case 0: - return dataList1[sideCount.toString()]; + return dataList1[sideCount.toString()]!; case 1: - return dataList2[sideCount.toString()]; + return dataList2[sideCount.toString()]!; } - return dataList1[sideCount.toString()]; + return dataList1[sideCount.toString()]!; } } diff --git a/example/lib/sample/components/charts/doughnut_chart_example.dart b/example/lib/sample/components/charts/doughnut_chart_example.dart index 49d6c6dd..b653326a 100644 --- a/example/lib/sample/components/charts/doughnut_chart_example.dart +++ b/example/lib/sample/components/charts/doughnut_chart_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; @@ -11,9 +13,9 @@ class DoughnutChartExample extends StatefulWidget { } class DoughnutChartExampleState extends State { - BrnDoughnutDataItem selectedItem; + BrnDoughnutDataItem? selectedItem; - List dataList = List(); + List dataList = []; List preinstallColors = [ Color(0xffFF862D), Color(0xff26BB7D), @@ -55,7 +57,7 @@ class DoughnutChartExampleState extends State { data: dataList, selectedItem: selectedItem, showTitleWhenSelected: true, - selectCallback: (BrnDoughnutDataItem selectedItem) { + selectCallback: (BrnDoughnutDataItem? selectedItem) { setState(() { this.selectedItem = selectedItem; }); diff --git a/example/lib/sample/components/charts/line/brn_broken_line_example.dart b/example/lib/sample/components/charts/line/brn_broken_line_example.dart index fe4b71b2..46cce542 100644 --- a/example/lib/sample/components/charts/line/brn_broken_line_example.dart +++ b/example/lib/sample/components/charts/line/brn_broken_line_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; @@ -98,7 +100,7 @@ class _BrokenLineExampleState extends State { .map((_) => BrnPointData( pointText: _.value, x: brokenData.indexOf(_).toDouble(), - y: double.parse(_.value), + y: double.parse(_.value!), lineTouchData: BrnLineTouchData( tipWindowSize: Size(60, 40), @@ -129,17 +131,17 @@ class _BrokenLineExampleState extends State { } double _getMinValueForExample1(List brokenData) { - double minValue = double.tryParse(brokenData[0]?.value) ?? 0; + double minValue = double.tryParse(brokenData[0].value!) ?? 0; for (DBDataNodeModel point in brokenData) { - minValue = min(double.tryParse(point.value) ?? 0, minValue); + minValue = min(double.tryParse(point.value!) ?? 0, minValue); } return minValue; } double _getMaxValueForExample1(List brokenData) { - double maxValue = double.tryParse(brokenData[0]?.value) ?? 0; + double maxValue = double.tryParse(brokenData[0].value!) ?? 0; for (DBDataNodeModel point in brokenData) { - maxValue = max(double.tryParse(point.value) ?? 0, maxValue); + maxValue = max(double.tryParse(point.value!) ?? 0, maxValue); } return maxValue; } @@ -190,7 +192,7 @@ class _BrokenLineExampleState extends State { List _linesForExample2() { BrnPointsLine _pointsLine; BrnPointsLine _pointsLine1; - List pointsLineList = List(); + List pointsLineList = []; _pointsLine = BrnPointsLine( isShowPointText: true, isShowXDial: true, @@ -420,7 +422,7 @@ class _BrokenLineExampleState extends State { List _getPointsLinesForExample3() { BrnPointsLine pointsLine, _pointsLine2; - List pointsLineList = List(); + List pointsLineList = []; pointsLine = BrnPointsLine( isShowXDial: true, lineWidth: 3, @@ -486,13 +488,13 @@ class _BrokenLineExampleState extends State { ], ), ); - })), + }, tipWindowSize:Size(60, 40) )), BrnPointData( pointText: '20', y: 20, x: 3, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return '20'; })), @@ -501,7 +503,7 @@ class _BrokenLineExampleState extends State { y: 67, x: 4, lineTouchData: BrnLineTouchData( - + tipWindowSize:Size(60, 40), onTouch: () { return '66'; })), @@ -661,7 +663,7 @@ class _BrokenLineExampleState extends State { y: 66, x: 8, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return '66'; })), @@ -790,7 +792,7 @@ class _BrokenLineExampleState extends State { List _getPointsLinesForExample4() { BrnPointsLine pointsLine, _pointsLine2; - List pointsLineList = List(); + List pointsLineList = []; pointsLine = BrnPointsLine( isShowXDial: true, lineWidth: 3, @@ -834,7 +836,7 @@ class _BrokenLineExampleState extends State { y: 80, x: 2, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return Container( padding: EdgeInsets.only(left: 10, right: 10, top: 8, bottom: 8), @@ -862,7 +864,7 @@ class _BrokenLineExampleState extends State { y: 20, x: 3, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return '20'; })), @@ -871,7 +873,7 @@ class _BrokenLineExampleState extends State { y: 67, x: 4, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return '66'; })), @@ -1031,7 +1033,7 @@ class _BrokenLineExampleState extends State { y: 66, x: 8, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return '66'; })), @@ -1193,7 +1195,7 @@ class _BrokenLineExampleState extends State { List _getPointsLineListWithShowPointText() { BrnPointsLine pointsLine, _pointsLine2; - List pointsLineList = List(); + List pointsLineList = []; pointsLine = BrnPointsLine( isShowXDial: true, lineWidth: 3, @@ -1247,7 +1249,7 @@ class _BrokenLineExampleState extends State { y: 80, x: 2, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return Container( padding: EdgeInsets.only(left: 10, right: 10, top: 8, bottom: 8), @@ -1285,7 +1287,7 @@ class _BrokenLineExampleState extends State { y: 67, x: 4, lineTouchData: BrnLineTouchData( - + tipWindowSize: Size(60, 40), onTouch: () { return '66'; })), @@ -1490,7 +1492,7 @@ class _BrokenLineExampleState extends State { } Widget _buildIdentificationList() { - List widgetList = List(); + List widgetList = []; for (BrnPointsLine bean in _getPointsLinesForExample3()) { Widget widget = Row(children: [ Container( diff --git a/example/lib/sample/components/charts/line/db_data_node_model.dart b/example/lib/sample/components/charts/line/db_data_node_model.dart index 7e0464e4..fc5928b8 100644 --- a/example/lib/sample/components/charts/line/db_data_node_model.dart +++ b/example/lib/sample/components/charts/line/db_data_node_model.dart @@ -1,34 +1,35 @@ /// @desc 看板卡片中用于描述数据指标的模型,也能用于数据块的定义,内部嵌套了一个itemList + + class DBDataNodeModel { - String key; - String name; - String value; - String unit; - String percent; - String order; + String? key; + String? name; + String? value; + String? unit; + String? percent; + String? order; /// If tip.isNullOrEmpty == false, a question icon will be displayed on right of the label. /// A tip pop window would be displayed when icon was clicked. - String tipTitle; + String? tipTitle; - List tipList; + List? tipList; /// 1: up direction, green label, green arrow /// 0: gray label, no arrow /// -1: down direction, red label, red arrow - int trend; + int? trend; - List itemList; + List? itemList; /// section data field - String url; - DBDataNodeModel total; - + String? url; + DBDataNodeModel? total; DBDataNodeModel(); - factory DBDataNodeModel.fromJson(Map json) { - if (json == null) return null; + factory DBDataNodeModel.fromJson(Map? json) { + if (json == null) return DBDataNodeModel(); DBDataNodeModel entity = DBDataNodeModel(); entity.name = json['name'] ?? ""; entity.key = json['key'] ?? ""; diff --git a/example/lib/sample/components/charts/progress_bar_chart_example.dart b/example/lib/sample/components/charts/progress_bar_chart_example.dart index 0b6c98c4..b0563676 100644 --- a/example/lib/sample/components/charts/progress_bar_chart_example.dart +++ b/example/lib/sample/components/charts/progress_bar_chart_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/charts/progress_chart_entry_page.dart b/example/lib/sample/components/charts/progress_chart_entry_page.dart index bb0b34c9..6d71c9dc 100644 --- a/example/lib/sample/components/charts/progress_chart_entry_page.dart +++ b/example/lib/sample/components/charts/progress_chart_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/dialog/dialog_entry_page.dart b/example/lib/sample/components/dialog/dialog_entry_page.dart index ff961be6..f53999bf 100644 --- a/example/lib/sample/components/dialog/dialog_entry_page.dart +++ b/example/lib/sample/components/dialog/dialog_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:flutter/material.dart'; @@ -299,7 +301,7 @@ class DialogEntryPage extends StatelessWidget { //光标圆角弧度 cursorRadius: Radius.circular(2.0), style: TextStyle(fontSize: 14, color: Color(0xFF222222)), - maxLengthEnforced: true, + maxLengthEnforcement: MaxLengthEnforcement.enforced, onChanged: (value) {}, decoration: InputDecoration( contentPadding: EdgeInsets.all(8.0), @@ -326,7 +328,7 @@ class DialogEntryPage extends StatelessWidget { state(() {}); }, onSubmitClick: (data) { - BrnToast.show(data, context); + BrnToast.show(data!, context); }); }, )); @@ -334,7 +336,7 @@ class DialogEntryPage extends StatelessWidget { ///多选弹框 void _showMiddleMultiSelectDialog(BuildContext context) { - List data = new List(); + List data = []; data.add(new MultiSelectItem("100", "感兴趣待跟进")); data.add(new MultiSelectItem("101", "感兴趣但对本商圈没兴趣", isChecked: true)); data.add(new MultiSelectItem("102", "接通后挂断/不感兴趣", isChecked: true)); @@ -361,7 +363,7 @@ class DialogEntryPage extends StatelessWidget { void _showMiddleMultiSelectWithMessageWidgetDialog(BuildContext context) { String hintText = "感兴趣待跟进"; - List data = new List(); + List data = []; data.add(new MultiSelectItem("100", "感兴趣待跟进")); data.add(new MultiSelectItem("101", "感兴趣但对本商圈没兴趣", isChecked: true)); data.add(new MultiSelectItem("102", "接通后挂断/不感兴趣", isChecked: true)); @@ -392,7 +394,7 @@ class DialogEntryPage extends StatelessWidget { //光标圆角弧度 cursorRadius: Radius.circular(2.0), style: TextStyle(fontSize: 14, color: Color(0xFF222222)), - maxLengthEnforced: true, + maxLengthEnforcement: MaxLengthEnforcement.enforced, onChanged: (value) {}, decoration: InputDecoration( contentPadding: EdgeInsets.all(8.0), @@ -413,7 +415,7 @@ class DialogEntryPage extends StatelessWidget { )), ), ), - onItemClick: (BuildContext contex, int index) { + onItemClick: (BuildContext context, int index) { hintText = data[index].content; state(() {}); }, @@ -430,7 +432,7 @@ class DialogEntryPage extends StatelessWidget { ///多选弹框 void _showMiddleMultiSelectWithMessageDialog(BuildContext context) { - List data = new List(); + List data = []; data.add(new MultiSelectItem("100", "感兴趣待跟进")); data.add(new MultiSelectItem("101", "感兴趣但对本商圈没兴趣", isChecked: true)); data.add(new MultiSelectItem("102", "接通后挂断/不感兴趣", isChecked: true)); @@ -467,7 +469,7 @@ class DialogEntryPage extends StatelessWidget { padding: const EdgeInsets.only(top: 6, left: 24, right: 24), child: BrnCSS2Text.toTextView( "这是一条增使用标签修改文字颜色的example\我是带颜色的文字," - "这是颜色标签后边的文字", linksCallback: (String text, String linkUrl) { + "这是颜色标签后边的文字", linksCallback: (String? text, String? linkUrl) { BrnToast.show('$text clicked! Url is $linkUrl', context); }), ), @@ -721,7 +723,7 @@ class DialogEntryPage extends StatelessWidget { ///对话框样式九:标准的对话框:有标题、双按钮、有警示文案和辅助信息 void _showStyle9_1Dialog(BuildContext context) { - bool status = false; + bool? status = false; BrnDialogManager.showConfirmDialog(context, title: "标题内容?", cancel: '取消', @@ -730,7 +732,7 @@ class DialogEntryPage extends StatelessWidget { return Row(children: [ Checkbox( value: status, - onChanged: (bool aaa) { + onChanged: (bool? aaa) { status = aaa; setState(() {}); }, @@ -762,9 +764,9 @@ class DialogEntryPage extends StatelessWidget { BrnShareDialog brnShareDialog = new BrnShareDialog( context: context, shareChannels: [ - BrnShareItemConstants.SHARE_WEIXIN, - BrnShareItemConstants.SHARE_LINK, - BrnShareItemConstants.SHARE_CUSTOM + BrnShareItemConstants.shareWeiXin, + BrnShareItemConstants.shareLink, + BrnShareItemConstants.shareCustom ], titleText: "测试标题", descText: "测试辅助信息测试辅助信息测试辅助信息测试辅助信息测试辅助信息", @@ -792,11 +794,11 @@ class DialogEntryPage extends StatelessWidget { BrnShareDialog brnShareDialog = new BrnShareDialog( context: context, shareChannels: [ - BrnShareItemConstants.SHARE_WEIXIN, - BrnShareItemConstants.SHARE_CUSTOM, - BrnShareItemConstants.SHARE_CUSTOM, - BrnShareItemConstants.SHARE_LINK, - BrnShareItemConstants.SHARE_CUSTOM + BrnShareItemConstants.shareWeiXin, + BrnShareItemConstants.shareCustom, + BrnShareItemConstants.shareCustom, + BrnShareItemConstants.shareLink, + BrnShareItemConstants.shareCustom ], titleText: "测试标题", descText: "测试辅助信息测试辅助信息测试辅助信息测试辅助信息测试辅助信息", @@ -831,7 +833,7 @@ class DialogEntryPage extends StatelessWidget { void _showBrnTwoVerticalButtonDialogDialog(BuildContext context) { BrnEnhanceOperationDialog brnShareDialog = new BrnEnhanceOperationDialog( context: context, - iconType: BrnDialogConstants.ICON_ALERT, + iconType: BrnDialogConstants.iconAlert, titleText: "强提示文案", descText: "这里是文案这里是文案这里是文案这里是文案这里是文案这里是文案这里是文案这里是文案", mainButtonText: "主要按钮", @@ -848,7 +850,7 @@ class DialogEntryPage extends StatelessWidget { void _showBrnOneVerticalButtonDialogDialog(BuildContext context) { BrnEnhanceOperationDialog brnShareDialog = new BrnEnhanceOperationDialog( - iconType: BrnDialogConstants.ICON_WARNING, + iconType: BrnDialogConstants.iconWarning, context: context, titleText: "强提示文案", descText: "这里是文案这里是文案这里是文案这里是文案这里是文案这里是文案这里是文案这里是文案", @@ -878,8 +880,8 @@ class DialogEntryPage extends StatelessWidget { "文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文" "呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表纯本文呢表", submitText: "提交", - linksCallback: (String text, String url) { - BrnToast.show(text, context); + linksCallback: (String? text, String? url) { + BrnToast.show(text!, context); }, onSubmitClick: () { BrnToast.show("点击了纯文本弹框", context); diff --git a/example/lib/sample/components/empty/abnormal_entry_page.dart b/example/lib/sample/components/empty/abnormal_entry_page.dart index a0fa3ffa..3cfddc66 100644 --- a/example/lib/sample/components/empty/abnormal_entry_page.dart +++ b/example/lib/sample/components/empty/abnormal_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/empty/abnormal_state_example.dart'; import 'package:example/sample/home/list_item.dart'; diff --git a/example/lib/sample/components/empty/abnormal_state_example.dart b/example/lib/sample/components/empty/abnormal_state_example.dart index 8fa335fc..9ec98bd5 100644 --- a/example/lib/sample/components/empty/abnormal_state_example.dart +++ b/example/lib/sample/components/empty/abnormal_state_example.dart @@ -1,8 +1,10 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class AbnomalStateExample extends StatelessWidget { - final int caseIndex; + final int? caseIndex; AbnomalStateExample({this.caseIndex}); @@ -15,8 +17,8 @@ class AbnomalStateExample extends StatelessWidget { body: _buildEmpty(caseIndex, context)); } - Widget _buildEmpty(int index, BuildContext context) { - Widget widget; + Widget? _buildEmpty(int? index, BuildContext context) { + Widget? widget; switch (index) { case 0: widget = BrnAbnormalStateWidget( @@ -27,7 +29,7 @@ class AbnomalStateExample extends StatelessWidget { isCenterVertical: true, title: BrnStrings.getDateFailed, operateTexts: [BrnStrings.clickPageRetry], - operateAreaType: OperateAreaType.TextButton, + operateAreaType: OperateAreaType.textButton, action: (index) { BrnToast.show(BrnStrings.getDateFailed, context); }, @@ -69,7 +71,7 @@ class AbnomalStateExample extends StatelessWidget { ), title: "这是副标题内容这是副标题内容这是副标", content: '您的门店暂无用户', - operateAreaType: OperateAreaType.SingleButton, + operateAreaType: OperateAreaType.singleButton, operateTexts: ["切换账号"], action: (_) { BrnToast.show("第$_个按钮被点击了", context); @@ -84,7 +86,7 @@ class AbnomalStateExample extends StatelessWidget { ), title: "暂无", content: '您还没有在维护的信息哦', - operateAreaType: OperateAreaType.DoubleButton, + operateAreaType: OperateAreaType.doubleButton, operateTexts: ['去添加', '去修改'], action: (_) { BrnToast.show("第$_个按钮被点击了", context); diff --git a/example/lib/sample/components/form/all_item_style_example.dart b/example/lib/sample/components/form/all_item_style_example.dart index ab695efd..6084e42f 100644 --- a/example/lib/sample/components/form/all_item_style_example.dart +++ b/example/lib/sample/components/form/all_item_style_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/form/group_example/expansion_group_example.dart'; import 'package:example/sample/components/form/group_example/group_add_example.dart'; diff --git a/example/lib/sample/components/form/form_item_entry_example.dart b/example/lib/sample/components/form/form_item_entry_example.dart index 25b63537..d655dda2 100644 --- a/example/lib/sample/components/form/form_item_entry_example.dart +++ b/example/lib/sample/components/form/form_item_entry_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/form/all_item_style_example.dart'; import 'package:example/sample/components/form/form_page_example.dart'; diff --git a/example/lib/sample/components/form/form_page_example.dart b/example/lib/sample/components/form/form_page_example.dart index aa46c4bb..b55967d0 100644 --- a/example/lib/sample/components/form/form_page_example.dart +++ b/example/lib/sample/components/form/form_page_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; /// 退回订单 页面展示 @@ -9,13 +11,14 @@ class FormPageExample extends StatefulWidget { } class _FormPageExampleState extends State { - List selectedOptions = List(); - String commentStr; - BrnPortraitRadioGroupOption selectedValue; + List selectedOptions = []; + String? commentStr; + late BrnPortraitRadioGroupOption selectedValue; @override void initState() { super.initState(); + selectedValue = BrnPortraitRadioGroupOption(); } @override @@ -43,10 +46,10 @@ class _FormPageExampleState extends State { '$index 不在我服务范围', '$index 其他' ], - selectedOption: selectedValue?.title, - onChanged: (BrnPortraitRadioGroupOption old, + selectedOption: selectedValue.title ?? '', + onChanged: (BrnPortraitRadioGroupOption? old, BrnPortraitRadioGroupOption newList) { - BrnToast.show(newList.title, context); + BrnToast.show(newList.title!, context); selectedValue = newList; commentStr = ''; setState(() {}); @@ -69,9 +72,9 @@ class _FormPageExampleState extends State { subTitle: 'subtitlesubtn你好 哈哈哈哈哈哈啊哈哈哈哈哈子标题哈哈哈 子标题子标题'); }), selectedOption: selectedValue, - onChanged: (BrnPortraitRadioGroupOption old, + onChanged: (BrnPortraitRadioGroupOption? old, BrnPortraitRadioGroupOption newList) { - BrnToast.show(newList.title, context); + BrnToast.show(newList.title!, context); selectedValue = newList; commentStr = ''; setState(() {}); diff --git a/example/lib/sample/components/form/group_example/expansion_group_example.dart b/example/lib/sample/components/form/group_example/expansion_group_example.dart index 248937bb..9d2f2d98 100644 --- a/example/lib/sample/components/form/group_example/expansion_group_example.dart +++ b/example/lib/sample/components/form/group_example/expansion_group_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/form/group_example/group_add_example.dart b/example/lib/sample/components/form/group_example/group_add_example.dart index 7516c930..2e810ecf 100644 --- a/example/lib/sample/components/form/group_example/group_add_example.dart +++ b/example/lib/sample/components/form/group_example/group_add_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/form/group_example/normal_group_example.dart b/example/lib/sample/components/form/group_example/normal_group_example.dart index 8edefddd..5b4b133a 100644 --- a/example/lib/sample/components/form/group_example/normal_group_example.dart +++ b/example/lib/sample/components/form/group_example/normal_group_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/form/items_example/base_title_example.dart b/example/lib/sample/components/form/items_example/base_title_example.dart index f251cb35..b2e8b9d7 100644 --- a/example/lib/sample/components/form/items_example/base_title_example.dart +++ b/example/lib/sample/components/form/items_example/base_title_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/form/items_example/multi_choice_example.dart b/example/lib/sample/components/form/items_example/multi_choice_example.dart index bae807bf..204e8f4b 100644 --- a/example/lib/sample/components/form/items_example/multi_choice_example.dart +++ b/example/lib/sample/components/form/items_example/multi_choice_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -40,9 +42,9 @@ class MultiChoiceInputExamplePage extends StatelessWidget { onRemoveTap: () { BrnToast.show("点击触发onRemoveTap回调", context); }, - onChanged: (List oldValue, List newValue) { + onChanged: (List oldValue, List? newValue) { BrnToast.show( - "点击触发onChanged回调${oldValue.length}_${newValue.length}_onChanged", context); + "点击触发onChanged回调${oldValue.length}_${newValue!.length}_onChanged", context); }, ), Container( @@ -56,7 +58,7 @@ class MultiChoiceInputExamplePage extends StatelessWidget { ), ), BrnMultiChoiceInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "自然", @@ -79,9 +81,9 @@ class MultiChoiceInputExamplePage extends StatelessWidget { onRemoveTap: () { BrnToast.show("点击触发onRemoveTap回调", context); }, - onChanged: (List oldValue, List newValue) { + onChanged: (List oldValue, List? newValue) { BrnToast.show( - "点击触发onChanged回调${oldValue.length}_${newValue.length}_onChanged", context); + "点击触发onChanged回调${oldValue.length}_${newValue!.length}_onChanged", context); }, ), Container( @@ -95,7 +97,7 @@ class MultiChoiceInputExamplePage extends StatelessWidget { ), ), BrnMultiChoiceInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, title: "自然到", subTitle: "这里是副标题", diff --git a/example/lib/sample/components/form/items_example/multi_choice_protrait_example.dart b/example/lib/sample/components/form/items_example/multi_choice_protrait_example.dart index 9621128e..e74e91aa 100644 --- a/example/lib/sample/components/form/items_example/multi_choice_protrait_example.dart +++ b/example/lib/sample/components/form/items_example/multi_choice_protrait_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -60,7 +62,7 @@ class MultiChoicePortraitInputExamplePage extends StatelessWidget { ), ), BrnMultiChoicePortraitInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", @@ -101,7 +103,7 @@ class MultiChoicePortraitInputExamplePage extends StatelessWidget { ), ), BrnMultiChoicePortraitInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, title: "自然到访保护期", subTitle: "这里是副标题", diff --git a/example/lib/sample/components/form/items_example/radio_input_example.dart b/example/lib/sample/components/form/items_example/radio_input_example.dart index cf2045dd..f05edb6e 100644 --- a/example/lib/sample/components/form/items_example/radio_input_example.dart +++ b/example/lib/sample/components/form/items_example/radio_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -55,7 +57,7 @@ class RadioInputExamplePage extends StatelessWidget { ), ), BrnRadioInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", @@ -90,7 +92,7 @@ class RadioInputExamplePage extends StatelessWidget { ), ), BrnRadioInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, title: "自然到访保护期", subTitle: "这里是副标题", @@ -124,7 +126,7 @@ class RadioInputExamplePage extends StatelessWidget { ), ), BrnRadioInputFormItem.autoLayout( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, error: "必填项不能为空", title: "autoLayout", diff --git a/example/lib/sample/components/form/items_example/radio_protrait_example.dart b/example/lib/sample/components/form/items_example/radio_protrait_example.dart index 27b60220..b4c3949d 100644 --- a/example/lib/sample/components/form/items_example/radio_protrait_example.dart +++ b/example/lib/sample/components/form/items_example/radio_protrait_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -56,7 +58,7 @@ class RadioPortraitInputExamplePage extends StatelessWidget { ), ), BrnRadioPortraitInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "自然到访保护期", @@ -93,7 +95,7 @@ class RadioPortraitInputExamplePage extends StatelessWidget { ), ), BrnRadioPortraitInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, title: "自然到访保护期", subTitle: "这里是副标题", diff --git a/example/lib/sample/components/form/items_example/range_input_example.dart b/example/lib/sample/components/form/items_example/range_input_example.dart index b04a42d9..0e207851 100644 --- a/example/lib/sample/components/form/items_example/range_input_example.dart +++ b/example/lib/sample/components/form/items_example/range_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -34,7 +36,7 @@ class RangeInputExamplePage extends StatelessWidget { maxUnit: "天", leftMaxCount: 1, rightMaxCount: 3, - inputType: BrnInputType.NUMBER, + inputType: BrnInputType.number, onTip: () { BrnToast.show("点击触发onTip回调", context); }, @@ -64,7 +66,7 @@ class RangeInputExamplePage extends StatelessWidget { BrnRangeInputFormItem( minController: TextEditingController()..text = "10", maxController: TextEditingController()..text = "100", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "保护期", @@ -77,7 +79,7 @@ class RangeInputExamplePage extends StatelessWidget { maxUnit: "天", leftMaxCount: 1, rightMaxCount: 3, - inputType: BrnInputType.NUMBER, + inputType: BrnInputType.number, onTip: () { BrnToast.show("点击触发onTip回调", context); }, @@ -107,7 +109,7 @@ class RangeInputExamplePage extends StatelessWidget { BrnRangeInputFormItem( minController: TextEditingController()..text = "10", maxController: TextEditingController()..text = "100", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, title: "保护期", subTitle: "这里是副标题", @@ -119,7 +121,7 @@ class RangeInputExamplePage extends StatelessWidget { maxUnit: "天", leftMaxCount: 2, rightMaxCount: 3, - inputType: BrnInputType.NUMBER, + inputType: BrnInputType.number, onTip: () { BrnToast.show("点击触发onTip回调", context); }, @@ -149,7 +151,7 @@ class RangeInputExamplePage extends StatelessWidget { BrnRangeInputFormItem( minController: TextEditingController()..text = "10", maxController: TextEditingController()..text = "100", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, title: "保护期", subTitle: "这里是副标题", @@ -162,7 +164,7 @@ class RangeInputExamplePage extends StatelessWidget { maxUnit: "天", leftMaxCount: 2, rightMaxCount: 3, - inputType: BrnInputType.NUMBER, + inputType: BrnInputType.number, onTip: () { BrnToast.show("点击触发onTip回调", context); }, diff --git a/example/lib/sample/components/form/items_example/ratio_input_example.dart b/example/lib/sample/components/form/items_example/ratio_input_example.dart index 72f19a93..5d374d59 100644 --- a/example/lib/sample/components/form/items_example/ratio_input_example.dart +++ b/example/lib/sample/components/form/items_example/ratio_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -52,7 +54,7 @@ class RatioInputExamplePage extends StatelessWidget { ), BrnRatioInputFormItem( controller: TextEditingController()..text = "1.6", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", @@ -84,7 +86,7 @@ class RatioInputExamplePage extends StatelessWidget { ), BrnRatioInputFormItem( controller: TextEditingController()..text = "1.6", - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, isEdit: true, title: "车位比", @@ -115,7 +117,7 @@ class RatioInputExamplePage extends StatelessWidget { ), BrnRatioInputFormItem( controller: TextEditingController()..text = "1.6", - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, isEdit: false, isPrefixIconEnabled: true, diff --git a/example/lib/sample/components/form/items_example/select_all_title_example.dart b/example/lib/sample/components/form/items_example/select_all_title_example.dart index 2b2d991d..78507285 100644 --- a/example/lib/sample/components/form/items_example/select_all_title_example.dart +++ b/example/lib/sample/components/form/items_example/select_all_title_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/form/items_example/star_example.dart b/example/lib/sample/components/form/items_example/star_example.dart index 484bc0a4..d9f2f43f 100644 --- a/example/lib/sample/components/form/items_example/star_example.dart +++ b/example/lib/sample/components/form/items_example/star_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -52,7 +54,7 @@ class StarInputExamplePage extends StatelessWidget { ), ), BrnStarsFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", @@ -85,7 +87,7 @@ class StarInputExamplePage extends StatelessWidget { ), ), BrnStarsFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, isEdit: true, title: "自然到访保护期", diff --git a/example/lib/sample/components/form/items_example/step_input_example.dart b/example/lib/sample/components/form/items_example/step_input_example.dart index ca1ea523..07a92d2f 100644 --- a/example/lib/sample/components/form/items_example/step_input_example.dart +++ b/example/lib/sample/components/form/items_example/step_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -54,14 +56,13 @@ class StepInputExamplePage extends StatelessWidget { ), ), BrnStepInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", title: "自然到访保护期", subTitle: "这里是副标题", tipLabel: "标签", - value: 0, maxLimit: 5, minLimit: 1, onTip: () { @@ -88,13 +89,12 @@ class StepInputExamplePage extends StatelessWidget { ), ), BrnStepInputFormItem( - prefixIconType: BrnPrefixIconType.TYPE_REMOVE, + prefixIconType: BrnPrefixIconType.remove, isRequire: true, isEdit: true, title: "自然到访保护期", subTitle: "这里是副标题", tipLabel: "标签", - value: 0, maxLimit: 5, minLimit: 1, onTip: () { diff --git a/example/lib/sample/components/form/items_example/text_block_input_example.dart b/example/lib/sample/components/form/items_example/text_block_input_example.dart index bd15cc0a..9d05ba9f 100644 --- a/example/lib/sample/components/form/items_example/text_block_input_example.dart +++ b/example/lib/sample/components/form/items_example/text_block_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -55,7 +57,7 @@ class TextBlockInputExamplePage extends StatelessWidget { ), BrnTextBlockInputFormItem( controller: TextEditingController()..text = "hello", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", @@ -88,7 +90,7 @@ class TextBlockInputExamplePage extends StatelessWidget { ), BrnTextBlockInputFormItem( controller: TextEditingController()..text = "hello", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, title: "备注", @@ -120,7 +122,7 @@ class TextBlockInputExamplePage extends StatelessWidget { ), BrnTextBlockInputFormItem( controller: TextEditingController()..text = "hello", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, isPrefixIconEnabled: true, diff --git a/example/lib/sample/components/form/items_example/text_input_example.dart b/example/lib/sample/components/form/items_example/text_input_example.dart index 401b42dc..2e3037d8 100644 --- a/example/lib/sample/components/form/items_example/text_input_example.dart +++ b/example/lib/sample/components/form/items_example/text_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -54,7 +56,7 @@ class TextInputExamplePage extends StatelessWidget { ), BrnTextInputFormItem( controller: TextEditingController()..text = "300", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, error: "必填项不能为空", @@ -88,7 +90,7 @@ class TextInputExamplePage extends StatelessWidget { ), BrnTextInputFormItem( controller: TextEditingController()..text = "300", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: true, title: "房屋总价", @@ -121,7 +123,7 @@ class TextInputExamplePage extends StatelessWidget { ), BrnTextInputFormItem( controller: TextEditingController()..text = "300", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, isPrefixIconEnabled: true, diff --git a/example/lib/sample/components/form/items_example/text_quick_select_input_example.dart b/example/lib/sample/components/form/items_example/text_quick_select_input_example.dart index 8703111f..28698733 100644 --- a/example/lib/sample/components/form/items_example/text_quick_select_input_example.dart +++ b/example/lib/sample/components/form/items_example/text_quick_select_input_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -19,8 +21,8 @@ class _TextQuickSelectInputExamplePageState String selectedStr = ''; String selectedStrAllFunctionExample = ''; List options = ['选项1', '选项2', '选项3', '选项4', '选项5', '选项6', '选项7']; - List status; - List statusAllFunctionExample; + late List status; + List? statusAllFunctionExample; _TextQuickSelectInputExamplePageState(this._title); @@ -92,7 +94,7 @@ class _TextQuickSelectInputExamplePageState ), ), BrnTextQuickSelectFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, btnsTxt: options, selectBtnList: statusAllFunctionExample, @@ -103,8 +105,8 @@ class _TextQuickSelectInputExamplePageState subTitle: "这里是副标题", tipLabel: "标签", onBtnSelectChanged: (index) { - statusAllFunctionExample[index] = !statusAllFunctionExample[index]; - if (statusAllFunctionExample[index]) { + statusAllFunctionExample![index] = !statusAllFunctionExample![index]; + if (statusAllFunctionExample![index]) { selectedStrAllFunctionExample += '${options[index]} '; } else if (selectedStrAllFunctionExample.contains(options[index])) { selectedStrAllFunctionExample = selectedStrAllFunctionExample.replaceFirst('${options[index]} ', ''); diff --git a/example/lib/sample/components/form/items_example/text_select_example.dart b/example/lib/sample/components/form/items_example/text_select_example.dart index 3e8de41a..7a689bbd 100644 --- a/example/lib/sample/components/form/items_example/text_select_example.dart +++ b/example/lib/sample/components/form/items_example/text_select_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -51,7 +53,7 @@ class TextSelectInputExamplePage extends StatelessWidget { ), ), BrnTextSelectFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "证件类型", @@ -81,7 +83,7 @@ class TextSelectInputExamplePage extends StatelessWidget { ), ), BrnTextSelectFormItem( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, title: "证件类型", subTitle: "这里是副标题", @@ -110,7 +112,7 @@ class TextSelectInputExamplePage extends StatelessWidget { ), ), BrnTextSelectFormItem.autoLayout( - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, error: "必填项不能为空", title: "证件类型", diff --git a/example/lib/sample/components/form/items_example/title_example.dart b/example/lib/sample/components/form/items_example/title_example.dart index 227cd61a..8bcd8bb2 100644 --- a/example/lib/sample/components/form/items_example/title_example.dart +++ b/example/lib/sample/components/form/items_example/title_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/form/items_example/title_select_example.dart b/example/lib/sample/components/form/items_example/title_select_example.dart index 698237bf..afaff9d7 100644 --- a/example/lib/sample/components/form/items_example/title_select_example.dart +++ b/example/lib/sample/components/form/items_example/title_select_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -14,13 +16,13 @@ class TitleSelectInputExamplePage extends StatefulWidget { } class TitleSelectInputState extends State { - List _list; + late List _list; TextEditingController controller = TextEditingController()..text = '123456'; @override void initState() { super.initState(); - _list = List(); + _list = []; _list.add('手机号'); _list.add('座机'); } @@ -47,7 +49,7 @@ class TitleSelectInputState extends State { title: _list[0], hint: "请输入", controller: controller, - inputFormatters: [FilteringTextInputFormatter(RegExp('[0-9"]'))], + inputFormatters: [FilteringTextInputFormatter.digitsOnly], selectedIndex: -1, selectList: _list, onTip: () { @@ -81,7 +83,7 @@ class TitleSelectInputState extends State { ), BrnTitleSelectInputFormItem( controller: TextEditingController()..text = "124", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, error: "必填项不能为空", @@ -119,7 +121,7 @@ class TitleSelectInputState extends State { ), BrnTitleSelectInputFormItem( controller: TextEditingController()..text = "124", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, subTitle: "这里是副标题", @@ -156,7 +158,7 @@ class TitleSelectInputState extends State { ), BrnTitleSelectInputFormItem( controller: TextEditingController()..text = "不可编辑时+ -号可点击", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, isPrefixIconEnabled: false, @@ -195,7 +197,7 @@ class TitleSelectInputState extends State { ), BrnTitleSelectInputFormItem( controller: TextEditingController()..text = "不可编辑时+ -号可点击", - prefixIconType: BrnPrefixIconType.TYPE_ADD, + prefixIconType: BrnPrefixIconType.add, isRequire: true, isEdit: false, isPrefixIconEnabled: true, diff --git a/example/lib/sample/components/form/phote_picker_example/photo_preview_page.dart b/example/lib/sample/components/form/phote_picker_example/photo_preview_page.dart deleted file mode 100644 index 5cd8fa5b..00000000 --- a/example/lib/sample/components/form/phote_picker_example/photo_preview_page.dart +++ /dev/null @@ -1,69 +0,0 @@ -import 'dart:io'; -import 'package:bruno/bruno.dart'; -import 'package:flutter/material.dart'; -import 'package:flutter_swiper/flutter_swiper.dart'; - -/// @des:图片预览页面 -/// - -// ignore: must_be_immutable -class PhotoPreviewPage extends StatefulWidget { - /// 图片地址 - List picUrl; - - /// 初始化角标 - int initialIndex; - - PhotoPreviewPage({@required this.picUrl, this.initialIndex: 0}); - - @override - _PhotoPreviewPageState createState() => _PhotoPreviewPageState(); -} - -class _PhotoPreviewPageState extends State { - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: _buildAppBar(context), - body: _buildBody(context), - ); - } - - /// - /// 标题栏 - /// - Widget _buildAppBar(BuildContext context) { - return BrnAppBar( - title: "图片详情", - backLeadCallback: () { - Navigator.pop(context); - }, - ); - } - - /// - /// 轮播图 - /// - Widget _buildBody(BuildContext context) { - return Swiper( - itemCount: widget.picUrl.length, - itemBuilder: (BuildContext context, int index) { - String picUrl = widget.picUrl[index]; - if (picUrl.startsWith("http") || picUrl.startsWith("https")) { - return FadeInImage.assetNetwork( - placeholder: "packages/bruno/assets/" + "images/icon_alert", - image: widget.picUrl[index], - fit: BoxFit.fill, - ); - } else { - File file = File(picUrl); - Image image = Image.file(file, fit: BoxFit.fill); - return image; - } - }, - index: widget.initialIndex, - control: new SwiperControl(), - loop: false, - ); - } -} diff --git a/example/lib/sample/components/gallery/gallery_detail_example.dart b/example/lib/sample/components/gallery/gallery_detail_example.dart index 9680766f..1219679d 100644 --- a/example/lib/sample/components/gallery/gallery_detail_example.dart +++ b/example/lib/sample/components/gallery/gallery_detail_example.dart @@ -1,10 +1,12 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; enum PhotoGalleryTheme { dark, light } class GalleryDetailExamplePage extends StatefulWidget { - final String title; + final String? title; final PhotoGalleryTheme photoGalleryTheme; GalleryDetailExamplePage({this.title, this.photoGalleryTheme = PhotoGalleryTheme.dark}); @@ -16,8 +18,8 @@ class GalleryDetailExamplePage extends StatefulWidget { } class GalleryDetailExamplePageState extends State { - List allConfig; - BrnGalleryController controller; + late List allConfig; + late BrnGalleryController controller; @override void initState() { @@ -171,8 +173,8 @@ class GalleryDetailExamplePageState extends State { BrnToast.show("点击了$i $j", context); // 移除第二组的最后一个配置,跳转到 第二组的第一张图 if (allConfig.length > 1) { - if (allConfig[1].configList.length > 0) { - allConfig[1].configList.removeLast(); + if (allConfig[1].configList!.length > 0) { + allConfig[1].configList!.removeLast(); controller.refresh(1, 0); } else { allConfig.removeAt(1); diff --git a/example/lib/sample/components/gallery/gallery_detail_page_theme_example.dart b/example/lib/sample/components/gallery/gallery_detail_page_theme_example.dart index b47d65c6..88ea69ac 100644 --- a/example/lib/sample/components/gallery/gallery_detail_page_theme_example.dart +++ b/example/lib/sample/components/gallery/gallery_detail_page_theme_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/gallery/gallery_detail_example.dart'; import 'package:example/sample/home/list_item.dart'; diff --git a/example/lib/sample/components/gallery/gallery_example.dart b/example/lib/sample/components/gallery/gallery_example.dart index 1df173bf..fe88e811 100644 --- a/example/lib/sample/components/gallery/gallery_example.dart +++ b/example/lib/sample/components/gallery/gallery_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/gallery/gallery_detail_page_theme_example.dart'; import 'package:example/sample/home/list_item.dart'; @@ -88,7 +90,7 @@ class GalleryExample extends StatelessWidget { Widget build(BuildContext context) { return Scaffold( appBar: BrnAppBar( - title: "步骤条示例", + title: "Gallery 图片", ),body: ListView(children: [ ListItem( title: "图片选择控件", diff --git a/example/lib/sample/components/guide/force_guide_example.dart b/example/lib/sample/components/guide/force_guide_example.dart index 0803c653..e3e6b3c5 100644 --- a/example/lib/sample/components/guide/force_guide_example.dart +++ b/example/lib/sample/components/guide/force_guide_example.dart @@ -1,17 +1,19 @@ + + import 'dart:async'; import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; /// @desc 强引导example class ForceGuideExample extends StatefulWidget { - ForceGuideExample({Key key}) : super(key: key); + ForceGuideExample({Key? key}) : super(key: key); @override _ForceGuideExampleState createState() => _ForceGuideExampleState(); } class _ForceGuideExampleState extends State { - BrnGuide intro; + late BrnGuide intro; _ForceGuideExampleState() { /// init Guide diff --git a/example/lib/sample/components/guide/guide_entry_page.dart b/example/lib/sample/components/guide/guide_entry_page.dart index a48c0515..f15dc4b7 100644 --- a/example/lib/sample/components/guide/guide_entry_page.dart +++ b/example/lib/sample/components/guide/guide_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/guide/force_guide_example.dart'; import 'package:example/sample/components/guide/soft_intro_example.dart'; diff --git a/example/lib/sample/components/guide/soft_intro_example.dart b/example/lib/sample/components/guide/soft_intro_example.dart index 2fed63f6..fcb0a12f 100644 --- a/example/lib/sample/components/guide/soft_intro_example.dart +++ b/example/lib/sample/components/guide/soft_intro_example.dart @@ -1,3 +1,5 @@ + + import 'dart:async'; import 'package:bruno/bruno.dart'; @@ -5,14 +7,14 @@ import 'package:flutter/material.dart'; /// @desc 弱引导example class SoftGuideExample extends StatefulWidget { - SoftGuideExample({Key key}) : super(key: key); + SoftGuideExample({Key? key}) : super(key: key); @override _SoftGuideExampleState createState() => _SoftGuideExampleState(); } class _SoftGuideExampleState extends State { - BrnGuide intro; + late BrnGuide intro; _SoftGuideExampleState() { /// init Guide diff --git a/example/lib/sample/components/input/input_example.dart b/example/lib/sample/components/input/input_example.dart index a6e654b9..0aceb62b 100644 --- a/example/lib/sample/components/input/input_example.dart +++ b/example/lib/sample/components/input/input_example.dart @@ -1,9 +1,11 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class TextModel { - String text; + String? text; } class BrnInputTextExample extends StatefulWidget { @@ -46,8 +48,8 @@ class _BrnInputTextExampleState extends State { minHeight: 30, minLines: 1, maxLength: 10, - bgColor: Colors.grey[200], - textString: model.text, + bgColor: Colors.grey[200]!, + textString: model.text ?? '', textInputAction: TextInputAction.newline, maxHintLines: 20, hint: 'input动态算高input动态算高input动态算高input动态算高input动态算高', diff --git a/example/lib/sample/components/line/dashed_line_example.dart b/example/lib/sample/components/line/dashed_line_example.dart index 8ffd30a6..08cf4ff7 100644 --- a/example/lib/sample/components/line/dashed_line_example.dart +++ b/example/lib/sample/components/line/dashed_line_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -33,7 +35,7 @@ class _DashedLineExampleState extends State { axis: Axis.vertical, color: Colors.red, dashedOffset: 20, - position: BrnDashedLinePosition.DashedLineLeading, + position: BrnDashedLinePosition.leading, contentWidget: Container( margin: EdgeInsets.only(left: 60, right: 20, top: 10, bottom: 10), child: @@ -54,7 +56,7 @@ class _DashedLineExampleState extends State { axis: Axis.horizontal, color: Colors.green, dashedOffset: 20, - position: BrnDashedLinePosition.DashedLineLeading, + position: BrnDashedLinePosition.leading, contentWidget: Container( width: 200, height: 100, @@ -75,7 +77,10 @@ class _DashedLineExampleState extends State { color: Colors.red, child: BrnDashedLine( axis: Axis.horizontal, - dashedOffset: 10, + dashedOffset: 10, contentWidget: Container( + width: 200, + height: 100, + ), ), ), ], diff --git a/example/lib/sample/components/loading/loading_widget_example.dart b/example/lib/sample/components/loading/loading_widget_example.dart index f1f64c84..53b9aa05 100644 --- a/example/lib/sample/components/loading/loading_widget_example.dart +++ b/example/lib/sample/components/loading/loading_widget_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/navbar/appbar_entry_page.dart b/example/lib/sample/components/navbar/appbar_entry_page.dart index 31f4f747..b800a595 100644 --- a/example/lib/sample/components/navbar/appbar_entry_page.dart +++ b/example/lib/sample/components/navbar/appbar_entry_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:example/sample/components/navbar/nav_bar_example_page.dart'; diff --git a/example/lib/sample/components/navbar/nav_bar_example_page.dart b/example/lib/sample/components/navbar/nav_bar_example_page.dart index fa51a1ef..d0870d2a 100644 --- a/example/lib/sample/components/navbar/nav_bar_example_page.dart +++ b/example/lib/sample/components/navbar/nav_bar_example_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; @@ -12,25 +14,25 @@ class NavBarPage extends StatefulWidget { } class _NavBarPageState extends State with TickerProviderStateMixin { - TextEditingController textEditingController; + TextEditingController? textEditingController; - TextStyle selectedHeiStyle; - TextStyle unSelectedHeiStyle; - TextStyle commonHeiStyle; + TextStyle? selectedHeiStyle; + TextStyle? unSelectedHeiStyle; + TextStyle? commonHeiStyle; - TextStyle selectedBaiStyle; - TextStyle unSelectedBaiStyle; - TextStyle commonBaiStyle; + TextStyle? selectedBaiStyle; + TextStyle? unSelectedBaiStyle; + TextStyle? commonBaiStyle; int currentIndex = 0; - ValueNotifier valueNotifier; - FocusNode focusNode; + late ValueNotifier valueNotifier; + FocusNode? focusNode; - TabController tabController; + TabController? tabController; - var keyleading = GlobalKey(); + GlobalKey keyLeading = GlobalKey(); - var actionKey = GlobalKey(); + GlobalKey actionKey = GlobalKey(); @override void initState() { @@ -52,8 +54,8 @@ class _NavBarPageState extends State with TickerProviderStateMixin { commonBaiStyle = TextStyle(fontSize: 18, fontWeight: FontWeight.w600, color: Color(0xFF222222)); focusNode = FocusNode(); - focusNode.addListener(() { - if (focusNode.hasFocus) { + focusNode!.addListener(() { + if (focusNode!.hasFocus) { valueNotifier.value = true; } }); @@ -69,8 +71,8 @@ class _NavBarPageState extends State with TickerProviderStateMixin { ); } - PreferredSizeWidget buildBarByIndex(BuildContext context) { - PreferredSizeWidget appBar; + PreferredSizeWidget? buildBarByIndex(BuildContext context) { + PreferredSizeWidget? appBar; switch (widget.index) { case 0: //2个文字模块切换 左右两个icon hei @@ -142,8 +144,8 @@ class _NavBarPageState extends State with TickerProviderStateMixin { return appBar; } - Widget buildContentByIndex(BuildContext context) { - Widget widget; + Widget? buildContentByIndex(BuildContext context) { + Widget? widget; switch (this.widget.index) { case 0: widget = @@ -475,7 +477,7 @@ class _NavBarPageState extends State with TickerProviderStateMixin { leading: Padding( padding: const EdgeInsets.only(right: 16), child: Row( - key: keyleading, + key: keyLeading, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( @@ -501,7 +503,7 @@ class _NavBarPageState extends State with TickerProviderStateMixin { //update 是setState方法的方法命,update() 就可以刷新输入框 BrnPopupListWindow.showPopListWindow( context, - keyleading, + keyLeading, data: ["aaaa", "bbbbb"], ); }, @@ -538,7 +540,7 @@ class _NavBarPageState extends State with TickerProviderStateMixin { leading: Padding( padding: const EdgeInsets.only(right: 16), child: Row( - key: keyleading, + key: keyLeading, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( @@ -561,7 +563,7 @@ class _NavBarPageState extends State with TickerProviderStateMixin { leadClickCallback: (controller, update) { //controller 是文本控制器,通过controller 可以拿到输入的内容 以及 对输入的内容更改 //update 是setState方法的方法命,update() 就可以刷新输入框 - BrnPopupListWindow.showPopListWindow(context, keyleading, data: ["aaaa", "bbbbb"]); + BrnPopupListWindow.showPopListWindow(context, keyLeading, data: ["aaaa", "bbbbb"]); }, //输入框 文本内容变化的监听 searchBarInputChangeCallback: (input) { diff --git a/example/lib/sample/components/noticebar/brn_notice_bar_example.dart b/example/lib/sample/components/noticebar/brn_notice_bar_example.dart index fa7c06b2..94eec187 100644 --- a/example/lib/sample/components/noticebar/brn_notice_bar_example.dart +++ b/example/lib/sample/components/noticebar/brn_notice_bar_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:example/sample/components/noticebar/notice_bar_example.dart'; diff --git a/example/lib/sample/components/noticebar/notice_bar_example.dart b/example/lib/sample/components/noticebar/notice_bar_example.dart index 438dc52a..073ac2c4 100644 --- a/example/lib/sample/components/noticebar/notice_bar_example.dart +++ b/example/lib/sample/components/noticebar/notice_bar_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/noticebar/notice_bar_with_button_example.dart b/example/lib/sample/components/noticebar/notice_bar_with_button_example.dart index 4f710353..be11f666 100644 --- a/example/lib/sample/components/noticebar/notice_bar_with_button_example.dart +++ b/example/lib/sample/components/noticebar/notice_bar_with_button_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/picker/cutomer_bottom_picker_example.dart b/example/lib/sample/components/picker/cutomer_bottom_picker_example.dart index 144f9981..e63e6188 100644 --- a/example/lib/sample/components/picker/cutomer_bottom_picker_example.dart +++ b/example/lib/sample/components/picker/cutomer_bottom_picker_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/picker/date_picker_example.dart b/example/lib/sample/components/picker/date_picker_example.dart index 46408e2b..ece9492a 100644 --- a/example/lib/sample/components/picker/date_picker_example.dart +++ b/example/lib/sample/components/picker/date_picker_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:flutter/material.dart'; @@ -154,7 +156,7 @@ class DatePickerExamplePage extends StatelessWidget { format = 'HH时:mm分'; BrnPickerTitleConfig timePickerTheme = BrnPickerTitleConfig( title: BrnPickerTitleConfig.Default.title, - showTitle: PICKER_SHOW_TITLE_DEFAULT, + showTitle: pickerShowTitleDefault, titleContent: "选择时间范围"); BrnDateRangePicker.showDatePicker(context, minDateTime: DateTime.parse(MIN_DATETIME), diff --git a/example/lib/sample/components/picker/multi_picker_example.dart b/example/lib/sample/components/picker/multi_picker_example.dart index 00ff73c3..b1aa2b87 100644 --- a/example/lib/sample/components/picker/multi_picker_example.dart +++ b/example/lib/sample/components/picker/multi_picker_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:flutter/material.dart'; @@ -180,7 +182,7 @@ class Brn1RowDelegate implements BrnMultiDataPickerDelegate { } @override - double rowHeightForComponent(int component) { + double? rowHeightForComponent(int component) { return null; } @@ -247,7 +249,7 @@ class Brn2RowDelegate implements BrnMultiDataPickerDelegate { } @override - double rowHeightForComponent(int component) { + double? rowHeightForComponent(int component) { return null; } @@ -324,7 +326,7 @@ class Brn3RowDelegate implements BrnMultiDataPickerDelegate { } @override - double rowHeightForComponent(int component) { + double? rowHeightForComponent(int component) { return null; } @@ -384,7 +386,7 @@ class Brn2RowCustomDelegate implements BrnMultiDataPickerDelegate { } @override - double rowHeightForComponent(int component) { + double? rowHeightForComponent(int component) { return null; } diff --git a/example/lib/sample/components/picker/picker_entry_page.dart b/example/lib/sample/components/picker/picker_entry_page.dart index 508db7ca..33b907a5 100644 --- a/example/lib/sample/components/picker/picker_entry_page.dart +++ b/example/lib/sample/components/picker/picker_entry_page.dart @@ -1,3 +1,5 @@ + + import 'dart:convert'; import 'package:bruno/bruno.dart'; @@ -11,7 +13,7 @@ import 'multi_picker_example.dart'; class PickerEntryPage extends StatelessWidget { final String _title; - List dataList = List(); + List dataList = []; PickerEntryPage(this._title); @@ -80,11 +82,11 @@ class PickerEntryPage extends StatelessWidget { describe: "底部级联选择框", onPressed: () { rootBundle.loadString('assets/list_picker.json').then((data) { - List _selectionData = List() - ..addAll((JsonDecoder().convert(data)["data"]['list'] as List ?? []) + List _selectionData = [] + ..addAll((JsonDecoder().convert(data)["data"]['list'] as List? ?? []) .map((o) => BrnPickerEntity.fromMap(o))); - if (_selectionData != null && _selectionData.length > 0) { - _selectionData?.forEach((f) => f.configChild()); + if ( _selectionData.length > 0) { + _selectionData.forEach((f) => f.configChild()); if (dataList.length == 0) { dataList.addAll(_selectionData); } @@ -98,11 +100,11 @@ class PickerEntryPage extends StatelessWidget { describe: "底部级联选择框(Title 动态改变)", onPressed: () { rootBundle.loadString('assets/list_picker.json').then((data) { - List _selectionData = List() - ..addAll((JsonDecoder().convert(data)["data"]['list'] as List ?? []) + List _selectionData = [] + ..addAll((JsonDecoder().convert(data)["data"]['list'] as List? ?? []) .map((o) => BrnPickerEntity.fromMap(o))); - if (_selectionData != null && _selectionData.length > 0) { - _selectionData?.forEach((f) => f.configChild()); + if (_selectionData.length > 0) { + _selectionData.forEach((f) => f.configChild()); if (dataList.length == 0) { dataList.addAll(_selectionData); } @@ -129,7 +131,7 @@ class PickerEntryPage extends StatelessWidget { ///多选弹框 void _showBottomMultiSelectPicker(BuildContext context) { - List items = new List(); + List items = []; items.add(new BrnMultiSelectBottomPickerItem("100", "这里是标题1")); items.add(new BrnMultiSelectBottomPickerItem("101", "这里是标题2")); items.add(new BrnMultiSelectBottomPickerItem("102", "这里是标题3", isChecked: true)); @@ -153,7 +155,7 @@ class PickerEntryPage extends StatelessWidget { /// 实现限制选择数量的情况 void _showCountLimitBottomMultiSelectPicker(BuildContext context) { - List items = new List(); + List items = []; items.add(new BrnMultiSelectBottomPickerItem("100", "这里是标题1")); items.add(new BrnMultiSelectBottomPickerItem("101", "这里是标题2")); items.add(new BrnMultiSelectBottomPickerItem("102", "这里是标题3", isChecked: true)); @@ -201,7 +203,7 @@ class PickerEntryPage extends StatelessWidget { cancelDismiss: true, confirmDismiss: false, onConfirm: (context, string) { - BrnToast.show(string, context); + BrnToast.show(string ?? '', context); return; }, onCancel: (_) { @@ -213,15 +215,15 @@ class PickerEntryPage extends StatelessWidget { } void _showRangePicker(BuildContext context, List _selectionData) { - _selectionData?.forEach((f) => f.configChild()); + _selectionData.forEach((f) => f.configChild()); var selectionMenuView = BrnMultiColumnPicker( entity: _selectionData[3], defaultFocusedIndexes: [0, -1, -1], - onConfirm: (Map> result, int firstIndex, - int secondIndex, int thirdIndex) { - List pickResult = List(); + onConfirm: (Map> result, int? firstIndex, + int? secondIndex, int? thirdIndex) { + List pickResult = []; result.forEach((key, val) { - List tmp = List(); + List tmp = []; val.forEach((item) { tmp.add(item.name); }); @@ -243,7 +245,7 @@ class PickerEntryPage extends StatelessWidget { } void _showRangePicker1(BuildContext context, List _selectionData) { - _selectionData?.forEach((f) => f.configChild()); + _selectionData.forEach((f) => f.configChild()); String titleName = "测试标题"; showModalBottomSheet( context: context, @@ -253,11 +255,11 @@ class PickerEntryPage extends StatelessWidget { pickerTitleConfig: BrnPickerTitleConfig(titleContent: titleName), entity: _selectionData[3], defaultFocusedIndexes: [0, -1, -1], - onConfirm: (Map> result, int firstIndex, - int secondIndex, int thirdIndex) { - List pickResult = List(); + onConfirm: (Map> result, int? firstIndex, + int? secondIndex, int? thirdIndex) { + List pickResult = []; result.forEach((key, val) { - List tmp = List(); + List tmp = []; val.forEach((item) { tmp.add(item.name); }); @@ -291,7 +293,7 @@ class PickerEntryPage extends StatelessWidget { '可爱多池', ]; - List items = List(); + List items = []; for (int i = 0; i < tags.length; i++) { String it = tags[i]; BrnTagItemBean item = BrnTagItemBean(name: it, code: it, index: i); @@ -348,10 +350,10 @@ class PickerEntryPage extends StatelessWidget { '我是可选择的标签1', ]; - List items = List(); + List items = []; for (int i = 0; i < tags.length; i++) { String it = tags[i]; - BrnTagInputItemBean item = BrnTagInputItemBean(name: it, index: i, needExplane: (i % 2 == 0)); + BrnTagInputItemBean item = BrnTagInputItemBean(name: it, index: i, needExpend: (i % 2 == 0)); items.add(item); } @@ -369,8 +371,8 @@ class PickerEntryPage extends StatelessWidget { tagItemSource: items, tagTitleFontSize: 12, tagTitleColor: Color(0xff222222), - tagBackgroudColor: Color(0xffF8F8F8), - selectedTagBackgroudColor: Color(0x140984F9), + tagBackgroundColor: Color(0xffF8F8F8), + selectedTagBackgroundColor: Color(0x140984F9), selectedTagTitleColor: Color(0xFF0984F9), ), onTagValueGetter: (choice) { diff --git a/example/lib/sample/components/popup/overlay_window_example.dart b/example/lib/sample/components/popup/overlay_window_example.dart index cad07a2c..458ba188 100644 --- a/example/lib/sample/components/popup/overlay_window_example.dart +++ b/example/lib/sample/components/popup/overlay_window_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -11,9 +13,9 @@ class OverlayWindowExample extends StatefulWidget { } class OverlayWindowExamplePageState extends State { - BrnOverlayController _overlayController; - var _focusNode = FocusNode(); - var _searchBarKey = GlobalKey(); + BrnOverlayController? _overlayController; + FocusNode _focusNode = FocusNode(); + GlobalKey _searchBarKey = GlobalKey(); @override void initState() { @@ -66,7 +68,7 @@ class OverlayWindowExamplePageState extends State { _overlayController?.removeOverlay(); return; } - if (_overlayController == null || _overlayController.isOverlayShowing == false) { + if (_overlayController == null || _overlayController!.isOverlayShowing == false) { _overlayController = BrnOverlayWindow.showOverlayWindow(context, _searchBarKey, content: _sugListView(), autoDismissOnTouchOutSide: true, diff --git a/example/lib/sample/components/popup/popwindow_example.dart b/example/lib/sample/components/popup/popwindow_example.dart index cb01d1d6..0645716f 100644 --- a/example/lib/sample/components/popup/popwindow_example.dart +++ b/example/lib/sample/components/popup/popwindow_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -11,19 +13,19 @@ class PopWindowExamplePage extends StatefulWidget { } class PopWindowExamplePageState extends State { - GlobalKey _leftKeylist0; - GlobalKey _leftKeylist1; - GlobalKey _leftKeylist2; - GlobalKey _leftKey; - GlobalKey _leftKey1; - GlobalKey _leftKey2; - GlobalKey _leftKey3; - GlobalKey _leftKey4; - GlobalKey _leftKey5; - GlobalKey _leftKey6; - GlobalKey _leftKey7; + GlobalKey? _leftKeylist0; + GlobalKey? _leftKeylist1; + GlobalKey? _leftKeylist2; + GlobalKey? _leftKey; + GlobalKey? _leftKey1; + GlobalKey? _leftKey2; + GlobalKey? _leftKey3; + GlobalKey? _leftKey4; + GlobalKey? _leftKey5; + GlobalKey? _leftKey6; + GlobalKey? _leftKey7; - BrnOverlayController overlayController; + BrnOverlayController? overlayController; @override void initState() { @@ -43,7 +45,6 @@ class PopWindowExamplePageState extends State { @override Widget build(BuildContext context) { - double top = MediaQuery.of(context).padding.top ?? 0; return Scaffold( appBar: BrnAppBar( title: widget._title, @@ -57,7 +58,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容", _leftKey, + BrnPopupWindow.showPopWindow(context, "提示内容", _leftKey!, hasCloseIcon: true); }, child: Text("左侧带关闭Tips"), @@ -68,7 +69,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey1, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey1, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey1!, hasCloseIcon: false); }, child: Text("左侧带无关闭Tips"), @@ -79,7 +80,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey2, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey2, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey2!, popDirection: BrnPopupDirection.top, hasCloseIcon: true); }, child: Text("左侧带关闭,箭头朝下Tips"), @@ -90,7 +91,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey3, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey3, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey3!, dismissCallback: () {}, popDirection: BrnPopupDirection.top); }, child: Text("左侧无关闭,箭头朝下Tips"), @@ -101,7 +102,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey4, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey4, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey4!, hasCloseIcon: true, dismissCallback: () {}, popDirection: BrnPopupDirection.bottom); @@ -114,7 +115,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey5, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容", _leftKey5, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容", _leftKey5!, hasCloseIcon: false, dismissCallback: () {}, popDirection: BrnPopupDirection.bottom); @@ -127,7 +128,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey6, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey6, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey6!, hasCloseIcon: true, canWrap: false, dismissCallback: () {}, @@ -141,7 +142,7 @@ class PopWindowExamplePageState extends State { child: RaisedButton( key: _leftKey7, onPressed: () { - BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey7, + BrnPopupWindow.showPopWindow(context, "提示内容提示内容提示内容提示内容提示内容提示内容", _leftKey7!, hasCloseIcon: false, dismissCallback: () {}, popDirection: BrnPopupDirection.top); diff --git a/example/lib/sample/components/rating/rating_example.dart b/example/lib/sample/components/rating/rating_example.dart index 4c1addfc..61acdb71 100644 --- a/example/lib/sample/components/rating/rating_example.dart +++ b/example/lib/sample/components/rating/rating_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -72,12 +74,12 @@ class _RatingExampleState extends State { Widget _buildRating(RatingState state) { switch (state) { case RatingState.select: - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STAR, 16, 16, color: Color(0xFF3571DC)); + return BrunoTools.getAssetSizeImage(BrnAsset.iconStar, 16, 16, color: Color(0xFF3571DC)); case RatingState.half: - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STAR_HALF, 16, 16); + return BrunoTools.getAssetSizeImage(BrnAsset.iconStarHalf, 16, 16); case RatingState.unselect: default: - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STAR, 16, 16, color: Color(0xFFF0F0F0)); + return BrunoTools.getAssetSizeImage(BrnAsset.iconStar, 16, 16, color: Color(0xFFF0F0F0)); } } } diff --git a/example/lib/sample/components/scroll_anchor/scroll_actor_tab_example.dart b/example/lib/sample/components/scroll_anchor/scroll_actor_tab_example.dart index 9060636a..ffba733b 100644 --- a/example/lib/sample/components/scroll_anchor/scroll_actor_tab_example.dart +++ b/example/lib/sample/components/scroll_anchor/scroll_actor_tab_example.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; diff --git a/example/lib/sample/components/selectcity/selected_city_example.dart b/example/lib/sample/components/selectcity/selected_city_example.dart index 9082bd77..0f6fdfb6 100644 --- a/example/lib/sample/components/selectcity/selected_city_example.dart +++ b/example/lib/sample/components/selectcity/selected_city_example.dart @@ -1,3 +1,5 @@ + + import 'dart:convert'; import 'package:bruno/bruno.dart'; @@ -13,8 +15,8 @@ class CitySelectRoute extends StatefulWidget { } class _CitySelectRouteState extends State { - List _cityList = List(); - List _hotCityList = List(); + List _cityList = []; + List _hotCityList = []; int _suspensionHeight = 40; int _itemHeight = 50; @@ -44,7 +46,7 @@ class _CitySelectRouteState extends State { } void _handleList(List list) { - if (list == null || list.isEmpty) return; + if (list.isEmpty) return; for (int i = 0, length = list.length; i < length; i++) { String pinyin = PinyinHelper.getPinyinE(list[i].name); String tag = pinyin.substring(0, 1).toUpperCase(); @@ -132,7 +134,7 @@ class _CitySelectRouteState extends State { flex: 1, child: AzListView( data: _cityList, - itemBuilder: (context, model) => _buildListItem(model), + itemBuilder: (context, model) => _buildListItem(model as BrnSelectCityModel), suspensionWidget: _buildSusWidget(_suspensionTag), isUseRealIndex: true, itemHeight: _itemHeight, diff --git a/example/lib/sample/components/selection/filter_entity.dart b/example/lib/sample/components/selection/filter_entity.dart index 23f2d8e5..50d19dfb 100644 --- a/example/lib/sample/components/selection/filter_entity.dart +++ b/example/lib/sample/components/selection/filter_entity.dart @@ -1,17 +1,17 @@ + + import 'package:bruno/bruno.dart'; class BrnFilterEntity { - String key; - String name; - String defaultValue; - List children; + String? key; + late String name; + String? defaultValue; + late List children; BrnFilterEntity.fromJson(Map map) { - if (map == null) return; - key = map['key'] ?? ""; - name = map['title'] ?? ""; - defaultValue = map['defaultValue'] ?? ""; - children = List() - ..addAll((map['children'] as List ?? []).map((o) => ItemEntity.fromJson(o))); + key = map['key'] ?? ''; + name = map['title'] ?? ''; + defaultValue = map['defaultValue'] ?? ''; + children = []..addAll((map['children'] as List? ?? []).map((o) => ItemEntity.fromJson(o))); } } diff --git a/example/lib/sample/components/selection/flat_selection_five_tags_example.dart b/example/lib/sample/components/selection/flat_selection_five_tags_example.dart index e4e7f2e6..6cd63d43 100644 --- a/example/lib/sample/components/selection/flat_selection_five_tags_example.dart +++ b/example/lib/sample/components/selection/flat_selection_five_tags_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -12,11 +14,11 @@ class NewSelectionViewExamplePage23 extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - BrnSelectionEntity entity; + BrnSelectionEntity? entity; - BrnFlatSelectionController controller; + BrnFlatSelectionController? controller; - var selectionKey = GlobalKey(); + GlobalKey selectionKey = GlobalKey(); bool _isShow = true; @@ -29,7 +31,7 @@ class _SelectionViewExamplePageState extends State { - BrnSelectionEntity entity; + BrnSelectionEntity? entity; - BrnFlatSelectionController controller; + BrnFlatSelectionController? controller; var selectionKey = GlobalKey(); @@ -29,7 +31,7 @@ class _SelectionViewExamplePageState extends State @override void dispose() { - controller.dispose(); + controller!.dispose(); controller = null; super.dispose(); } @@ -109,7 +111,7 @@ class _SelectionViewExamplePageState extends State ), onTap: () { if (controller != null) { - controller.resetSelectedOptions(); + controller!.resetSelectedOptions(); } }, ), @@ -122,7 +124,7 @@ class _SelectionViewExamplePageState extends State title: "取消", onTap: () { if (controller != null) { - controller.cancelSelectedOptions(); + controller!.cancelSelectedOptions(); setState(() { _isShow = false; }); @@ -136,7 +138,7 @@ class _SelectionViewExamplePageState extends State title: "确定", onTap: () { if (controller != null) { - controller.confirmSelectedOptions(); + controller!.confirmSelectedOptions(); setState(() { _isShow = false; }); diff --git a/example/lib/sample/components/selection/flat_selection_three_tags_example.dart b/example/lib/sample/components/selection/flat_selection_three_tags_example.dart index 16de0f0a..73f60dbc 100644 --- a/example/lib/sample/components/selection/flat_selection_three_tags_example.dart +++ b/example/lib/sample/components/selection/flat_selection_three_tags_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -12,9 +14,9 @@ class FlatSelectionThreeTagsExample extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - BrnSelectionEntity entity; + BrnSelectionEntity? entity; - BrnFlatSelectionController controller; + BrnFlatSelectionController? controller; var selectionKey = GlobalKey(); @@ -29,7 +31,7 @@ class _SelectionViewExamplePageState extends State 0) { @@ -56,7 +58,7 @@ class FlatSelectionEntryPage extends StatelessWidget { onPressed: () { rootBundle.loadString('assets/flat_selection_filter.json').then((data) { var datas = - BrnSelectionEntityListBean.fromMap(JsonDecoder().convert(data)["data"]).list; + BrnSelectionEntityListBean.fromJson(JsonDecoder().convert(data)["data"])!.list!; void _configMaxSelectedCount(BrnSelectionEntity entity, int maxCount) { entity.maxSelectedCount = maxCount; if (entity.children != null && entity.children.length > 0) { @@ -81,7 +83,7 @@ class FlatSelectionEntryPage extends StatelessWidget { onPressed: () { rootBundle.loadString('assets/flat_selection_filter.json').then((data) { var datas = - BrnSelectionEntityListBean.fromMap(JsonDecoder().convert(data)["data"]).list; + BrnSelectionEntityListBean.fromJson(JsonDecoder().convert(data)["data"])!.list!; void _configMaxSelectedCount(BrnSelectionEntity entity, int maxCount) { entity.maxSelectedCount = maxCount; if (entity.children != null && entity.children.length > 0) { diff --git a/example/lib/sample/components/selection/selectionview_custom_floating_layer_example.dart b/example/lib/sample/components/selection/selectionview_custom_floating_layer_example.dart index 016d6571..e01167c2 100644 --- a/example/lib/sample/components/selection/selectionview_custom_floating_layer_example.dart +++ b/example/lib/sample/components/selection/selectionview_custom_floating_layer_example.dart @@ -1,10 +1,12 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/card/bubble/common_bubble_example.dart'; import 'package:flutter/material.dart'; class SelectionViewMoreCustomFloatLayerExamplePage extends StatefulWidget { final String _title; - final List _filterData; + final List? _filterData; SelectionViewMoreCustomFloatLayerExamplePage(this._title, this._filterData); @@ -13,9 +15,9 @@ class SelectionViewMoreCustomFloatLayerExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List items; + List? items; - BrnSelectionViewController controller; + BrnSelectionViewController? controller; var selectionKey = GlobalKey(); @@ -44,14 +46,14 @@ class _SelectionViewExamplePageState extends State result = Map(); result['Key1'] = 'Value1'; result['Key2'] = 'Value2'; - List resultEntity = List(); - result?.forEach((userId, userName) { + List resultEntity = []; + result.forEach((userId, userName) { resultEntity.add(BrnSelectionEntity( value: userId, title: userName, isSelected: true, type: 'radio')); }); diff --git a/example/lib/sample/components/selection/selectionview_customhandle_filter_example_page.dart b/example/lib/sample/components/selection/selectionview_customhandle_filter_example_page.dart index ae7f7681..7e122c0b 100644 --- a/example/lib/sample/components/selection/selectionview_customhandle_filter_example_page.dart +++ b/example/lib/sample/components/selection/selectionview_customhandle_filter_example_page.dart @@ -1,9 +1,11 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class SelectionViewCustomHandleFilterExamplePage extends StatefulWidget { final String _title; - final List _filters; + final List? _filters; SelectionViewCustomHandleFilterExamplePage(this._title, this._filters); @@ -26,7 +28,7 @@ class _SelectionViewExamplePageState extends State[ BrnSelectionView( - originalSelectionData: widget._filters, + originalSelectionData: widget._filters!, onCustomSelectionMenuClick: (int index, BrnSelectionEntity customMenuItem, BrnSetCustomSelectionParams customHandleCallBack) { /// 用户操作一段时间之后,将自定义参数回传,触发 onSelectionChanged回调。 @@ -40,7 +42,7 @@ class _SelectionViewExamplePageState extends State filterParams, Map customParams, BrnSetCustomSelectionMenuTitle setCustomTitleFunction) { - if (menuIndex == 1 && setCustomTitleFunction != null) { + if (menuIndex == 1) { setCustomTitleFunction( menuTitle: BrunoTools.isEmpty(customParams) ? "" : customParams['CKey'] ?? "", isMenuTitleHighLight: !BrunoTools.isEmpty(customParams['CKey'])); diff --git a/example/lib/sample/components/selection/selectionview_customview_example_page.dart b/example/lib/sample/components/selection/selectionview_customview_example_page.dart index d2e9475a..e84b04ef 100644 --- a/example/lib/sample/components/selection/selectionview_customview_example_page.dart +++ b/example/lib/sample/components/selection/selectionview_customview_example_page.dart @@ -1,9 +1,11 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class SelectionViewCustomViewExamplePage extends StatefulWidget { final String _title; - final List _filters; + final List? _filters; SelectionViewCustomViewExamplePage(this._title, this._filters); @@ -12,11 +14,11 @@ class SelectionViewCustomViewExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List _filterData; + List? _filterData; var selectionKey = GlobalKey(); bool isCustomFilterViewShow = false; - OverlayEntry filterViewEntry; + OverlayEntry? filterViewEntry; /// 筛选组件的回调函数,用于把用户选中的参数回传给筛选组件,同意在 onSelectionChanged 回调处理。 参数在 customParams 中存储 var _customHandleCallBack; @@ -25,13 +27,13 @@ class _SelectionViewExamplePageState extends State _currentCalendarSelectedDate; + late ValueNotifier _currentCalendarSelectedDate; String _dateForamt = 'yyyy-MM-dd HH:mm:ss'; - _SelectionViewExamplePageState(List filters) { + _SelectionViewExamplePageState(List? filters) { _filterData = filters; } @@ -58,14 +60,14 @@ class _SelectionViewExamplePageState extends State[ ValueListenableBuilder( valueListenable: _currentCalendarSelectedDate, - builder: (context, value, widget) { - return BrnCalendarView( + builder: (context, dynamic value, widget) { + return BrnCalendarView.single( initStartSelectedDate: _currentCalendarSelectedDate.value, initEndSelectedDate: _currentCalendarSelectedDate.value, - startEndDateChange: (_, __) { + dateChange: (_){ _currentCalendarSelectedDate.value = _; }); }, @@ -186,7 +188,7 @@ class _SelectionViewExamplePageState extends State() - : {'date': _currentCalendarSelectedDate.value.toString() ?? ''}); + : {'date': _currentCalendarSelectedDate.value.toString()}); _filterSelectedDate = _currentCalendarSelectedDate.value?.toString(); closeCustomFilterView(); }, @@ -199,8 +201,8 @@ class _SelectionViewExamplePageState extends State { - List _filterData; + late List _filterData; _SelectionViewExamplePageState(List filters) { _filterData = filters; diff --git a/example/lib/sample/components/selection/selectionview_date_range_example_page.dart b/example/lib/sample/components/selection/selectionview_date_range_example_page.dart index dbec59e6..25979345 100644 --- a/example/lib/sample/components/selection/selectionview_date_range_example_page.dart +++ b/example/lib/sample/components/selection/selectionview_date_range_example_page.dart @@ -1,9 +1,11 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class SelectionViewDateRangeExamplePage extends StatefulWidget { final String _title; - final List _filterData; + final List? _filterData; SelectionViewDateRangeExamplePage(this._title, this._filterData); @@ -12,9 +14,9 @@ class SelectionViewDateRangeExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List items; + List? items; - BrnSelectionViewController controller; + BrnSelectionViewController? controller; @override void initState() { @@ -41,13 +43,13 @@ class _SelectionViewExamplePageState extends State filterParams, Map customParams, @@ -56,9 +58,9 @@ class _SelectionViewExamplePageState extends State _filterData; + final List? _filterData; SelectionViewCloseOrInterceptorExamplePage(this._title, this._filterData); @@ -12,9 +14,9 @@ class SelectionViewCloseOrInterceptorExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List items; + List? items; - BrnSelectionViewController controller; + BrnSelectionViewController? controller; @override void initState() { @@ -36,7 +38,7 @@ class _SelectionViewExamplePageState extends State filterParams, Map customParams, BrnSetCustomSelectionMenuTitle setCustomTitleFunction) { - BrnToast.show(filterParams.toString(), context); + BrnToast.show('选中 ${filterParams.toString()},但筛选条件被清除了', context); if (menuIndex == 1 && filterParams != null && filterParams['two_list_key'] != null) { - widget._filterData[1].clearChildSelection(); - widget._filterData[1].configRelationshipAndDefaultValue(); - controller.refreshSelectionTitle(); + widget._filterData![1].clearChildSelection(); + widget._filterData![1].configRelationshipAndDefaultValue(); + controller!.refreshSelectionTitle(); } }, onMenuClickInterceptor: (index) { diff --git a/example/lib/sample/components/selection/selectionview_limit_max_selected_count_example.dart b/example/lib/sample/components/selection/selectionview_limit_max_selected_count_example.dart index d70a16b2..acf53e3a 100644 --- a/example/lib/sample/components/selection/selectionview_limit_max_selected_count_example.dart +++ b/example/lib/sample/components/selection/selectionview_limit_max_selected_count_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -12,9 +14,9 @@ class SelectionViewLimitMaxSelectedCountExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List items; + List? items; - BrnSelectionViewController controller; + BrnSelectionViewController? controller; @override void initState() { @@ -41,7 +43,7 @@ class _SelectionViewExamplePageState extends State _filters; + final List? _filters; SelectionViewMoreFilterExamplePage(this._title, this._filters); @@ -27,7 +29,7 @@ class _SelectionViewExamplePageState extends State[ BrnSelectionView( - originalSelectionData: widget._filters, + originalSelectionData: widget._filters!, onMoreSelectionMenuClick: (int index, BrnOpenMorePage openMore) { openMore(updateData: false); }, diff --git a/example/lib/sample/components/selection/selectionview_multi_list_example_page.dart b/example/lib/sample/components/selection/selectionview_multi_list_example_page.dart index 3d3c6172..bb5937fa 100644 --- a/example/lib/sample/components/selection/selectionview_multi_list_example_page.dart +++ b/example/lib/sample/components/selection/selectionview_multi_list_example_page.dart @@ -1,9 +1,11 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class SelectionViewMultiListExamplePage extends StatefulWidget { final String _title; - final List _filterData; + final List? _filterData; SelectionViewMultiListExamplePage(this._title, this._filterData); @@ -12,7 +14,7 @@ class SelectionViewMultiListExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List items; + List? items; @override void initState() { @@ -26,7 +28,7 @@ class _SelectionViewExamplePageState extends State[ BrnSelectionView( - originalSelectionData: widget._filterData, + originalSelectionData: widget._filterData!, onSelectionChanged: (int menuIndex, Map filterParams, Map customParams, diff --git a/example/lib/sample/components/selection/selectionview_multi_range_example_page.dart b/example/lib/sample/components/selection/selectionview_multi_range_example_page.dart index bd5555de..f9594e28 100644 --- a/example/lib/sample/components/selection/selectionview_multi_range_example_page.dart +++ b/example/lib/sample/components/selection/selectionview_multi_range_example_page.dart @@ -1,9 +1,11 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class SelectionViewMultiRangeExamplePage extends StatefulWidget { final String _title; - final List _filters; + final List? _filters; SelectionViewMultiRangeExamplePage(this._title, this._filters); @@ -12,7 +14,7 @@ class SelectionViewMultiRangeExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List titles; + List? titles; @override void initState() { @@ -26,7 +28,7 @@ class _SelectionViewExamplePageState extends State[ BrnSelectionView( - originalSelectionData: widget._filters, + originalSelectionData: widget._filters!, onSelectionChanged: (int menuIndex, Map filterParams, Map customParams, @@ -35,9 +37,9 @@ class _SelectionViewExamplePageState extends State { - List items; + List? items; @override void initState() { @@ -28,7 +30,7 @@ class _SelectionViewExamplePageState extends State[ BrnSimpleSelection.checkbox( menuName: widget._filterData.name, - menuKey: widget._filterData.key ?? defaultMenuKey, + menuKey: widget._filterData.key ?? 'defaultMenuKey', items: widget._filterData.children, maxSelectedCount: 4, defaultValue: widget._filterData.defaultValue, diff --git a/example/lib/sample/components/selection/selectionview_simple_single_list_example_page.dart b/example/lib/sample/components/selection/selectionview_simple_single_list_example_page.dart index b05f00ef..3ef33f9e 100755 --- a/example/lib/sample/components/selection/selectionview_simple_single_list_example_page.dart +++ b/example/lib/sample/components/selection/selectionview_simple_single_list_example_page.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/selection/filter_entity.dart'; import 'package:flutter/material.dart'; @@ -13,7 +15,7 @@ class SelectionViewSimpleSingleListExamplePage extends StatefulWidget { } class _SelectionViewExamplePageState extends State { - List items; + List? items; @override void initState() { @@ -28,7 +30,7 @@ class _SelectionViewExamplePageState extends State[ BrnSimpleSelection.radio( menuName: widget._filterData.name, - menuKey: widget._filterData.key ?? defaultMenuKey, + menuKey: widget._filterData.key ?? 'defaultMenuKey', items: widget._filterData.children, defaultValue: widget._filterData.defaultValue, onSimpleSelectionChanged: ( diff --git a/example/lib/sample/components/step/brn_horizontal_step_example.dart b/example/lib/sample/components/step/brn_horizontal_step_example.dart index 5f92beb6..f65c31de 100644 --- a/example/lib/sample/components/step/brn_horizontal_step_example.dart +++ b/example/lib/sample/components/step/brn_horizontal_step_example.dart @@ -4,7 +4,8 @@ import 'package:flutter/material.dart'; class BrnHorizontalStepExamplePage extends StatefulWidget { final String title; - BrnHorizontalStepExamplePage({this.title}); + const BrnHorizontalStepExamplePage({Key? key, required this.title}) + : super(key: key); @override State createState() { @@ -12,49 +13,164 @@ class BrnHorizontalStepExamplePage extends StatefulWidget { } } -class BrnHorizontalStepExamplePageState extends State { - int _index; - BrnHorizontalStepsManager _stepsManager = BrnHorizontalStepsManager(); +class BrnHorizontalStepExamplePageState + extends State { + late int _index; + double sliderValue = 2; + late BrnStepsController _controller; + late ValueNotifier valueNotifier; @override void initState() { - _index = 1; super.initState(); + _index = 0; + _controller = BrnStepsController(currentIndex: _index); + valueNotifier = ValueNotifier(sliderValue); } @override Widget build(BuildContext context) { return Scaffold( - appBar: BrnAppBar( - title: widget.title, - actions: controlSteps(context), - ), - body: _stepsManager.buildSteps(currentIndex: _index, isCompleted: false, steps: [ - BrunoStep( - stepContentText: "文案步骤", + appBar: BrnAppBar(title: widget.title), + body: Column( + children: [ + SliverBrnHorizontalStep( + controller: _controller, + valueNotifier: valueNotifier, ), - BrunoStep( - stepContentText: "文案步骤", + const Text('步骤个数:'), + SliderWidget( + initValue: sliderValue, + valueNotifier: valueNotifier, ), - BrunoStep( - stepContentText: "文案步骤", + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + ElevatedButton( + child: const Text('上一步'), + onPressed: () { + _controller.backStep(); + }, + ), + ElevatedButton( + child: const Text('下一步'), + onPressed: () { + _controller.forwardStep(); + }, + ), + ], ), - BrunoStep( - stepContentText: "文案步骤", + Row( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: [ + ElevatedButton( + child: const Text('跳至第3步'), + onPressed: () { + _controller.setCurrentIndex(2); + }, + ), + ElevatedButton( + child: const Text('完成'), + onPressed: () { + _controller.setCompleted(); + }, + ), + ], ), - ])); + ], + ), + ); } +} + +/// 自定义 widget +class SliderWidget extends StatefulWidget { + const SliderWidget({ + Key? key, + required this.initValue, + required this.valueNotifier, + }) : super(key: key); + final double initValue; + final ValueNotifier valueNotifier; + + @override + _SliderWidgetState createState() => _SliderWidgetState(); +} + +class _SliderWidgetState extends State { + late double sliderValue; + + @override + void initState() { + super.initState(); + sliderValue = widget.initValue; + } + + @override + Widget build(BuildContext context) { + return Slider( + value: sliderValue, + min: 2, + max: 5, + divisions: 3, + onChanged: (value) { + setState(() { + sliderValue = value; + widget.valueNotifier.value = value; + }); + }, + ); + } +} - List controlSteps(BuildContext context) { - List result = List(); +/// 自定义 widget +class SliverBrnHorizontalStep extends StatefulWidget { + const SliverBrnHorizontalStep({ + Key? key, + required this.controller, + required this.valueNotifier, + }) : super(key: key); + final BrnStepsController controller; + final ValueNotifier valueNotifier; - result.add(BrnTextAction("上一步", iconPressed: () { - _stepsManager.backStep(); - })); + @override + _SliverBrnHorizontalStepsState createState() => _SliverBrnHorizontalStepsState(); +} + +class _SliverBrnHorizontalStepsState extends State { + List brunoSteps() { + final List _list = []; + final int value = widget.valueNotifier.value.toInt(); + for (int i = 0; i < value; i++) { + _list.add(BrunoStep(stepContentText: ('第你好11${i + 1}步'))); + } + return _list; + } + + void _onChange() { + setState(() { + brunoSteps(); + widget.controller.setCurrentIndex(0); + }); + } + + @override + void initState() { + super.initState(); + widget.valueNotifier.addListener(_onChange); + } + + @override + void dispose() { + widget.valueNotifier.removeListener(_onChange); + super.dispose(); + } - result.add(BrnTextAction("下一步", iconPressed: () { - _stepsManager.forwardStep(); - })); - return result; + @override + Widget build(BuildContext context) { + return BrnHorizontalSteps( + steps: brunoSteps(), + controller: widget.controller, + ); } } diff --git a/example/lib/sample/components/step/step_example.dart b/example/lib/sample/components/step/step_example.dart index b07eee16..9d493417 100644 --- a/example/lib/sample/components/step/step_example.dart +++ b/example/lib/sample/components/step/step_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/step/brn_horizontal_step_example.dart'; import 'package:example/sample/components/step/step_line_example.dart'; diff --git a/example/lib/sample/components/step/step_line_example.dart b/example/lib/sample/components/step/step_line_example.dart index 7e2ad87f..d189385c 100644 --- a/example/lib/sample/components/step/step_line_example.dart +++ b/example/lib/sample/components/step/step_line_example.dart @@ -1,15 +1,19 @@ + + import 'dart:math'; import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; class StepLineExample extends StatefulWidget { + const StepLineExample({Key? key}) : super(key: key); + @override _StepLineExampleState createState() => _StepLineExampleState(); } class _StepLineExampleState extends State { - int count; + int? count; @override void initState() { @@ -32,24 +36,30 @@ class _StepLineExampleState extends State { Text( '规则', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .colorTextBase, fontSize: 28, fontWeight: FontWeight.bold), ), - BrnBubbleText( + const BrnBubbleText( maxLines: 2, text: '头部icon需要显示主题相关的icon,线条需要时圆头\n,' '线条的高度随着左侧内容变化而改变,线宽2'), Text( '第一个高亮', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, fontSize: 16, ), ), ListView.builder( - padding: EdgeInsets.only(top: 20), - physics: NeverScrollableScrollPhysics(), + padding: const EdgeInsets.only(top: 20), + physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: 3, itemBuilder: (context, index) { @@ -57,10 +67,12 @@ class _StepLineExampleState extends State { lineWidth: 1, //非第一个是灰色 isGrey: index != 0, + iconTopPadding: 20, //最后一个的线条为透明色 做到不显示的效果 - lineColor: index == 2 ? Colors.transparent : Color(0xffeeeeee), + lineColor: + index == 2 ? Colors.transparent : const Color(0xffeeeeee), contentWidget: Container( - padding: EdgeInsets.only(left: 8), + padding: const EdgeInsets.only(left: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -97,13 +109,16 @@ class _StepLineExampleState extends State { Text( '最后一个灰色', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, fontSize: 16, ), ), ListView.builder( - padding: EdgeInsets.only(top: 20), - physics: NeverScrollableScrollPhysics(), + padding: const EdgeInsets.only(top: 20), + physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: 3, itemBuilder: (context, index) { @@ -113,10 +128,12 @@ class _StepLineExampleState extends State { isGrey: index == 2, //最后一个的线条为透明色 做到不显示的效果 lineColor: index == 2 ? Colors.transparent : null, - highlightColor: - BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + highlightColor: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, contentWidget: Container( - padding: EdgeInsets.only(left: 8), + padding: const EdgeInsets.only(left: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -153,74 +170,86 @@ class _StepLineExampleState extends State { Text( '颜色线条变化', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, - fontSize: 16, - ), - ), -ListView.builder( - padding: EdgeInsets.only(top: 20), - physics: NeverScrollableScrollPhysics(), - shrinkWrap: true, - itemCount: 3, - itemBuilder: (context, index) { - return BrnStepLine( - lineWidth: 1, - //最后一个的线条为透明色 做到不显示的效果 - lineColor: index == 2 - ? Colors.transparent - : (index == 1 - ? [ - BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, - Colors.red - ] - : null), - highlightColor: index == 2 - ? Colors.red - : BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, - contentWidget: Container( - padding: EdgeInsets.only(left: 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text( - '步骤${index + 1}', - style: TextStyle( - height: 0.9, color: BrnThemeConfigurator.instance .getConfig() .commonConfig - .colorTextBase, + .brandPrimary, fontSize: 16, ), ), - Padding( - padding: const EdgeInsets.only(top: 20, bottom: 20), - child: Text( - '辅助信息', - style: TextStyle( - color: BrnThemeConfigurator.instance + ListView.builder( + padding: const EdgeInsets.only(top: 20), + physics: const NeverScrollableScrollPhysics(), + shrinkWrap: true, + itemCount: 3, + itemBuilder: (context, index) { + return BrnStepLine( + lineWidth: 1, + //最后一个的线条为透明色 做到不显示的效果 + lineColor: index == 2 + ? Colors.transparent + : (index == 1 + ? [ + BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, + Colors.red + ] + : null), + highlightColor: index == 2 + ? Colors.red + : BrnThemeConfigurator.instance .getConfig() .commonConfig - .colorTextSecondary, - fontSize: 14, - ), - ), - ) - ], - ), - ), - ); - }, -), + .brandPrimary, + contentWidget: Container( + padding: const EdgeInsets.only(left: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '步骤${index + 1}', + style: TextStyle( + height: 0.9, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .colorTextBase, + fontSize: 16, + ), + ), + Padding( + padding: const EdgeInsets.only(top: 20, bottom: 20), + child: Text( + '辅助信息', + style: TextStyle( + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .colorTextSecondary, + fontSize: 14, + ), + ), + ) + ], + ), + ), + ); + }, + ), Text( '全灰色', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, fontSize: 16, ), ), ListView.builder( - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: 5, itemBuilder: (context, index) { @@ -237,13 +266,16 @@ ListView.builder( Text( '最后一条不显示', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, fontSize: 16, ), ), ListView.builder( shrinkWrap: true, - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), itemCount: 5, itemBuilder: (context, index) { if (index == 4) { @@ -268,20 +300,26 @@ ListView.builder( Text( '线条颜色有变化', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, fontSize: 16, ), ), ListView.builder( shrinkWrap: true, - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), itemCount: 5, itemBuilder: (context, index) { if (index == 4) { return BrnStepLine( lineWidth: 1, lineColor: [ - BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, Colors.red, ], contentWidget: Container( @@ -302,19 +340,25 @@ ListView.builder( Text( '虚线显示', style: TextStyle( - color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, fontSize: 16, ), ), ListView.builder( shrinkWrap: true, - physics: NeverScrollableScrollPhysics(), + physics: const NeverScrollableScrollPhysics(), itemCount: 5, itemBuilder: (context, index) { return BrnStepLine( lineWidth: 1, lineColor: [ - BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, Colors.red, ], isDashLine: true, @@ -334,12 +378,15 @@ ListView.builder( dynamic getLineColor(int index) { return index == 1 - ? [BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, Colors.red] - : (index == 2 ? Colors.transparent : Color(0xffeeeeee)); + ? [ + BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + Colors.red + ] + : (index == 2 ? Colors.transparent : const Color(0xffeeeeee)); } Color getRandomColor() { - return Color.fromARGB( - Random().nextInt(255), Random().nextInt(255), Random().nextInt(255), Random().nextInt(255)); + return Color.fromARGB(Random().nextInt(255), Random().nextInt(255), + Random().nextInt(255), Random().nextInt(255)); } } diff --git a/example/lib/sample/components/sugsearch/search_text_example.dart b/example/lib/sample/components/sugsearch/search_text_example.dart index d29ebe20..1347faff 100644 --- a/example/lib/sample/components/sugsearch/search_text_example.dart +++ b/example/lib/sample/components/sugsearch/search_text_example.dart @@ -1,3 +1,4 @@ + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/switch/checkbox_example.dart b/example/lib/sample/components/switch/checkbox_example.dart index 33894921..d7ad41ba 100644 --- a/example/lib/sample/components/switch/checkbox_example.dart +++ b/example/lib/sample/components/switch/checkbox_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/switch/radio_example.dart b/example/lib/sample/components/switch/radio_example.dart index a07db2f1..08fb1ce2 100644 --- a/example/lib/sample/components/switch/radio_example.dart +++ b/example/lib/sample/components/switch/radio_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/tabbar/brn_switch_title_example.dart b/example/lib/sample/components/tabbar/brn_switch_title_example.dart index 55b826c9..73658682 100644 --- a/example/lib/sample/components/tabbar/brn_switch_title_example.dart +++ b/example/lib/sample/components/tabbar/brn_switch_title_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -7,7 +9,7 @@ class BrnSwitchTitleExample extends StatefulWidget { } class _BrnSwitchTitleExampleState extends State with TickerProviderStateMixin { - TabController _controller; + late TabController _controller; @override void initState() { diff --git a/example/lib/sample/components/tabbar/brn_tab_example.dart b/example/lib/sample/components/tabbar/brn_tab_example.dart index dd05f85f..a75c263c 100644 --- a/example/lib/sample/components/tabbar/brn_tab_example.dart +++ b/example/lib/sample/components/tabbar/brn_tab_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/list_item.dart'; import 'package:flutter/material.dart'; @@ -10,7 +12,7 @@ class BrnTabExample extends StatefulWidget { } class _BrnTabExampleState extends State with TickerProviderStateMixin { - BrnCloseWindowController closeWindowController; + BrnCloseWindowController? closeWindowController; @override void initState() { @@ -35,7 +37,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM ), Divider(), Center( - child: OutlineButton( + child: OutlinedButton( onPressed: () { Navigator.of(context).push(new MaterialPageRoute(builder: (context) { return BrnTabbarStickyExample(); @@ -69,8 +71,8 @@ class _BrnTabExampleState extends State with TickerProviderStateM ), ), onWillPop: () { - if (closeWindowController.isShow) { - closeWindowController.closeMoreWindow(); + if (closeWindowController!.isShow) { + closeWindowController!.closeMoreWindow(); return Future.value(false); } return Future.value(true); @@ -78,7 +80,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createExpandedMoreTabbarWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一")); tabs.add(BadgeTab(text: "业务二")); tabs.add(BadgeTab(text: "业务三")); @@ -98,7 +100,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createStableTabbar4Widgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一")); tabs.add(BadgeTab(text: "业务二")); tabs.add(BadgeTab(text: "业务三")); @@ -114,7 +116,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createStableTabbarWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "特殊业务详情一", badgeText: "新")); tabs.add(BadgeTab(text: "业务二", badgeNum: 22)); tabs.add(BadgeTab(text: "业务三", badgeNum: 11)); @@ -140,7 +142,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createTabbarBadgeWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一", badgeText: "新")); tabs.add(BadgeTab(text: "业务二", badgeNum: 22)); tabs.add(BadgeTab(text: "业务三", badgeNum: 11)); @@ -161,7 +163,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createStableTabbarBadgeWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一", badgeNum: 100)); tabs.add(BadgeTab(text: "业务二", badgeNum: 22)); tabs.add(BadgeTab(text: "业务三", badgeNum: 11)); @@ -177,7 +179,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createDividerTabbarWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一", topText: "1")); tabs.add(BadgeTab(text: "业务二", topText: "2")); tabs.add(BadgeTab(text: "业务三", topText: "3")); @@ -197,7 +199,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM /// 自定义Tab宽度,如果tab宽度之和大于屏幕宽度,默认能左右滚动 /// _createCustomTabbarWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一", badgeNum: 2)); tabs.add(BadgeTab(text: "业务二")); tabs.add(BadgeTab(text: "业务三", badgeNum: 33)); @@ -213,7 +215,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createTopTabbarWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "08月09日", topText: "今天")); tabs.add(BadgeTab(text: "08月10日", topText: "明天")); tabs.add(BadgeTab(text: "08月11日", topText: "周三")); @@ -232,7 +234,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createTopTabbarCountWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "08月09日", topText: "今天")); tabs.add(BadgeTab(text: "08月10日", topText: "明天")); tabs.add(BadgeTab(text: "08月11日", topText: "周三")); @@ -249,7 +251,7 @@ class _BrnTabExampleState extends State with TickerProviderStateM } _createOriginWidgets() { - var tabs = List(); + var tabs = []; tabs.add(BadgeTab(text: "业务一", badgeText: "新")); tabs.add(BadgeTab(text: "业务二", badgeNum: 22)); tabs.add(BadgeTab(text: "业务三", badgeNum: 11)); diff --git a/example/lib/sample/components/tabbar/brn_tabbar_sticky_example.dart b/example/lib/sample/components/tabbar/brn_tabbar_sticky_example.dart index 886dd88b..a12d990d 100644 --- a/example/lib/sample/components/tabbar/brn_tabbar_sticky_example.dart +++ b/example/lib/sample/components/tabbar/brn_tabbar_sticky_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -8,14 +10,14 @@ class BrnTabbarStickyExample extends StatefulWidget { class _BrnTabbarStickyExampleState extends State with SingleTickerProviderStateMixin { - TabController tabController; + TabController? tabController; GlobalKey globalKey = GlobalKey(); ScrollController scrollController = ScrollController(); - BrnCloseWindowController closeWindowController; - var tabs = List(); + BrnCloseWindowController? closeWindowController; + List tabs = []; @override void initState() { @@ -29,7 +31,7 @@ class _BrnTabbarStickyExampleState extends State tabController = TabController(length: tabs.length, vsync: this); closeWindowController = BrnCloseWindowController(); scrollController.addListener(() { - closeWindowController.closeMoreWindow(); + closeWindowController!.closeMoreWindow(); }); } @@ -64,7 +66,7 @@ class _BrnTabbarStickyExampleState extends State moreWindowText: "Tabs描述", onTap: (state, index) { state.refreshBadgeState(index); - scrollController.animateTo(globalKey.currentContext.size.height, + scrollController.animateTo(globalKey.currentContext!.size!.height, duration: Duration(milliseconds: 200), curve: Curves.linear); }, onMorePop: () {}, @@ -88,8 +90,8 @@ class _BrnTabbarStickyExampleState extends State ), ), onWillPop: () { - if (closeWindowController.isShow) { - closeWindowController.closeMoreWindow(); + if (closeWindowController!.isShow) { + closeWindowController!.closeMoreWindow(); return Future.value(false); } return Future.value(true); @@ -112,7 +114,7 @@ class _BrnTabbarStickyExampleState extends State class StickyTabBarDelegate extends SliverPersistentHeaderDelegate { final BrnTabBar child; - StickyTabBarDelegate({@required this.child}); + StickyTabBarDelegate({required this.child}); @override Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { @@ -120,10 +122,10 @@ class StickyTabBarDelegate extends SliverPersistentHeaderDelegate { } @override - double get maxExtent => this.child.tabHeight; + double get maxExtent => this.child.tabHeight!; @override - double get minExtent => this.child.tabHeight; + double get minExtent => this.child.tabHeight!; @override bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) { diff --git a/example/lib/sample/components/tabbar/sub_switch_title_example.dart b/example/lib/sample/components/tabbar/sub_switch_title_example.dart index 4c870862..83ee38b7 100644 --- a/example/lib/sample/components/tabbar/sub_switch_title_example.dart +++ b/example/lib/sample/components/tabbar/sub_switch_title_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -8,7 +10,7 @@ class SubSwitchTitleExample extends StatefulWidget { class _SubSwitchTitleExampleState extends State with TickerProviderStateMixin { - TabController _controller; + late TabController _controller; @override void initState() { diff --git a/example/lib/sample/components/tag/border_tag_example.dart b/example/lib/sample/components/tag/border_tag_example.dart index aff03ec1..e37b580f 100644 --- a/example/lib/sample/components/tag/border_tag_example.dart +++ b/example/lib/sample/components/tag/border_tag_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/tag/custom_tag_example.dart b/example/lib/sample/components/tag/custom_tag_example.dart index db9f8083..8b5d425d 100644 --- a/example/lib/sample/components/tag/custom_tag_example.dart +++ b/example/lib/sample/components/tag/custom_tag_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/tag/delete_tag_example.dart b/example/lib/sample/components/tag/delete_tag_example.dart index 8a4a657e..969007a8 100644 --- a/example/lib/sample/components/tag/delete_tag_example.dart +++ b/example/lib/sample/components/tag/delete_tag_example.dart @@ -37,28 +37,37 @@ class TagViewExamplePageState extends State { } Widget _buildDeleteWidget() { - BrnDeleteTagController controller = BrnDeleteTagController( - initTags: ['这是一条很长很长很长很长很长很长很长很长很长很长的标签', '标签信息', '标签信息标签信息', '标签信息', '标签信息标签信息标签信息标签信息']); + BrnDeleteTagController controller = BrnDeleteTagController(initTags: [ + '这是一条很长很长很长很长很长很长很长很长很长很长的标签', + '标签信息', + '标签信息标签信息', + '标签信息', + '标签信息标签信息标签信息标签信息' + ]); return Container( margin: EdgeInsets.only(top: 20), color: Colors.white, child: Column( children: [ -BrnDeleteTag( - controller: controller, - onTagDelete: (tags, tag, index) { - BrnToast.show('剩余的标签为:${tags.toString()},删除了的标签为:$tag ,删除的标签index为$index', context); - }, -), -BrnDeleteTag( - controller: controller, - tagTextStyle: TextStyle(color: Colors.blue, fontSize: 20), - deleteIconSize: Size(16, 16), - onTagDelete: (tags, tag, index) { - BrnToast.show('剩余的标签为:${tags.toString()},删除了的标签为:$tag ,删除的标签index为$index', context); - }, -), + BrnDeleteTag( + controller: controller, + onTagDelete: (tags, tag, index) { + BrnToast.show( + '剩余的标签为:${tags.toString()},删除了的标签为:$tag ,删除的标签index为$index', + context); + }, + ), + BrnDeleteTag( + controller: controller, + tagTextStyle: TextStyle(color: Colors.blue, fontSize: 20), + deleteIconSize: Size(16, 16), + onTagDelete: (tags, tag, index) { + BrnToast.show( + '剩余的标签为:${tags.toString()},删除了的标签为:$tag ,删除的标签index为$index', + context); + }, + ), BrnDeleteTag( controller: controller, tagTextStyle: TextStyle(color: Colors.yellow), @@ -66,7 +75,9 @@ BrnDeleteTag( deleteIconColor: Colors.red, softWrap: false, onTagDelete: (tags, tag, index) { - BrnToast.show('剩余的标签为:${tags.toString()},删除了的标签为:$tag ,删除的标签index为$index', context); + BrnToast.show( + '剩余的标签为:${tags.toString()},删除了的标签为:$tag ,删除的标签index为$index', + context); }, ), Row( diff --git a/example/lib/sample/components/tag/select_tag_example.dart b/example/lib/sample/components/tag/select_tag_example.dart index 56f56e24..03122e59 100644 --- a/example/lib/sample/components/tag/select_tag_example.dart +++ b/example/lib/sample/components/tag/select_tag_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -152,8 +154,7 @@ class SelectTagExamplePageState extends State { double _getTagWidth(context, {int rowCount: 4}) { double leftRightPadding = 40; double rowSpace = 12; - return MediaQuery.of(context).size.width - - leftRightPadding - - rowSpace * (rowCount - 1) / rowCount; + return (MediaQuery.of(context).size.width - leftRightPadding - rowSpace * (rowCount - 1)) / + rowCount; } } diff --git a/example/lib/sample/components/tag/state_tag_example.dart b/example/lib/sample/components/tag/state_tag_example.dart index 3363d57a..70b3facc 100644 --- a/example/lib/sample/components/tag/state_tag_example.dart +++ b/example/lib/sample/components/tag/state_tag_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/tag/tag_example.dart b/example/lib/sample/components/tag/tag_example.dart index 60aca84c..c7222e94 100644 --- a/example/lib/sample/components/tag/tag_example.dart +++ b/example/lib/sample/components/tag/tag_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/components/tag/border_tag_example.dart'; import 'package:example/sample/components/tag/custom_tag_example.dart'; diff --git a/example/lib/sample/components/tag/tag_row_example.dart b/example/lib/sample/components/tag/tag_row_example.dart index ed035494..510eec30 100644 --- a/example/lib/sample/components/tag/tag_row_example.dart +++ b/example/lib/sample/components/tag/tag_row_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; diff --git a/example/lib/sample/components/toast/toast_example.dart b/example/lib/sample/components/toast/toast_example.dart index d7ade587..50821aff 100644 --- a/example/lib/sample/components/toast/toast_example.dart +++ b/example/lib/sample/components/toast/toast_example.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; @@ -6,7 +8,8 @@ class ToastExample extends StatefulWidget { _ToastExampleState createState() => _ToastExampleState(); } -class _ToastExampleState extends State with TickerProviderStateMixin { +class _ToastExampleState extends State + with TickerProviderStateMixin { @override Widget build(BuildContext context) { return Scaffold( @@ -14,54 +17,75 @@ class _ToastExampleState extends State with TickerProviderStateMix title: 'BrnToast示例', ), body: SingleChildScrollView( - child: Column( - children: [ - Padding( - padding: EdgeInsets.only(top: 50, bottom: 50), - child: Center( - child: RaisedButton( - onPressed: () { - BrnToast.show("普通长Toast", context, duration: BrnToast.LENGTH_LONG, gravity: 1); - }, - child: Text("普通长Toast"), - ), + child: Center( + child: Column( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + ElevatedButton( + onPressed: () { + BrnToast.show( + "普通长Toast", + context, + duration: BrnDuration.long, + gravity: BrnToastGravity.center, + ); + }, + child: Text("普通长Toast"), + ), + ElevatedButton( + onPressed: () { + BrnToast.show( + "失败图标Toast", + context, + preIcon: Image.asset( + "assets/image/icon_toast_fail.png", + width: 24, + height: 24, + ), + duration: BrnDuration.short, + ); + }, + child: Text("失败图标Toast"), + ), + ElevatedButton( + onPressed: () { + BrnToast.show( + "成功图标Toast", + context, + preIcon: Image.asset( + "assets/image/icon_toast_success.png", + width: 24, + height: 24, + ), + duration: BrnDuration.short, + ); + }, + child: Text("成功图标Toast"), ), - ), - Padding( - padding: EdgeInsets.only(top: 50, bottom: 50), - child: Center( - child: RaisedButton( - onPressed: () { - BrnToast.show("失败图标Toast", context, - preIcon: Image.asset( - "assets/image/icon_toast_fail.png", - width: 24, - height: 24, - ), - duration: BrnToast.LENGTH_SHORT); - }, - child: Text("失败图标Toast"), - ), + ElevatedButton( + onPressed: () { + BrnToast.show( + "自定义位置Toast", + context, + duration: BrnDuration.short, + verticalOffset: 100, + gravity: BrnToastGravity.bottom + ); + }, + child: Text("自定义位置Toast"), ), - ), - Padding( - padding: EdgeInsets.only(top: 50, bottom: 50), - child: Center( - child: RaisedButton( - onPressed: () { - BrnToast.show("成功图标Toast", context, - preIcon: Image.asset( - "assets/image/icon_toast_success.png", - width: 24, - height: 24, - ), - duration: BrnToast.LENGTH_SHORT); - }, - child: Text("成功图标Toast"), - ), + ElevatedButton( + onPressed: () { + BrnToast.show( + "自定义时长Toast", + context, + duration: Duration(seconds: 5), + ); + }, + child: Text("自定义时长Toast(5s)"), ), - ) - ], + ], + ), ), ), ); diff --git a/example/lib/sample/home/card_data_config.dart b/example/lib/sample/home/card_data_config.dart index 99e7684f..aa94ddfe 100644 --- a/example/lib/sample/home/card_data_config.dart +++ b/example/lib/sample/home/card_data_config.dart @@ -1,3 +1,5 @@ + + import 'dart:convert'; import 'package:bruno/bruno.dart'; @@ -47,7 +49,7 @@ import 'package:flutter/services.dart'; /// 卡片信息 class GroupInfo { /// 唯一ID - int groupId; + int? groupId; /// 组名称 String groupName; @@ -62,10 +64,10 @@ class GroupInfo { bool isSupportTheme; /// 子Widget - List children; + List? children; /// 跳转到下一个页面 - Function(BuildContext context) navigatorPage; + Function(BuildContext context)? navigatorPage; GroupInfo( {this.groupId, @@ -81,7 +83,7 @@ class GroupInfo { class CardDataConfig { /// 全部 static List getAllGroup() { - List list = List(); + List list = []; list.add(_getChartGroup()); list.add(_getDataInputGroup()); list.add(_getOperateGroup()); @@ -93,14 +95,14 @@ class CardDataConfig { /// 数据图表 static GroupInfo _getChartGroup() { - List children = List(); + List children = []; children.add(GroupInfo( groupName: "BrokenLine 折线图 ", desc: "数据折线图", navigatorPage: (BuildContext context) { rootBundle.loadString('assets/brokenline_data.json').then((data) { - var brokenData = List() - ..addAll(((JsonDecoder().convert(data) as List) ?? []) + var brokenData = [] + ..addAll(((JsonDecoder().convert(data) as List?) ?? []) .map((o) => DBDataNodeModel.fromJson(o))); Navigator.push(context, MaterialPageRoute( builder: (BuildContext context) { @@ -165,7 +167,7 @@ class CardDataConfig { /// 数据录入 static GroupInfo _getDataInputGroup() { - List children = List(); + List children = []; children.add(GroupInfo( groupName: "Form 表单项", desc: "各种表单项", @@ -213,7 +215,7 @@ class CardDataConfig { /// 操作反馈类 static GroupInfo _getOperateGroup() { - List children = List(); + List children = []; children.add(GroupInfo( groupName: "Dialog 弹窗", desc: "Dialog多种类型展示", @@ -271,7 +273,7 @@ class CardDataConfig { /// 导航类 static GroupInfo _getNavigatorGroup() { - List children = List(); + List children = []; children.add(GroupInfo( groupName: "Appbar 导航栏", desc: "Appbar 导航栏", @@ -359,7 +361,7 @@ class CardDataConfig { /// 按钮 static GroupInfo _getButtonGroup() { - List children = List(); + List children = []; children.add(GroupInfo( groupName: "NormalButton 普通按钮", desc: "主按钮、次按钮、按钮集合", @@ -426,7 +428,7 @@ class CardDataConfig { /// 内容 static GroupInfo _getContentGroup() { - List children = List(); + List children =[]; children.add(GroupInfo( groupName: "Tag 标签", desc: "标签多种样式", @@ -556,7 +558,7 @@ class CardDataConfig { /// 城市选择 static Widget _buildSingleSelectCityPage() { - List hotCityList = List(); + List hotCityList = []; hotCityList.addAll([ BrnSelectCityModel(name: "北京市"), BrnSelectCityModel(name: "广州市"), diff --git a/example/lib/sample/home/expandable_container_widget.dart b/example/lib/sample/home/expandable_container_widget.dart index 517d15c6..d8264175 100644 --- a/example/lib/sample/home/expandable_container_widget.dart +++ b/example/lib/sample/home/expandable_container_widget.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + + import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -21,21 +23,20 @@ import 'package:flutter/widgets.dart'; /// * The "Expand/collapse" section of class BrnExpandableContainerWidget extends StatefulWidget { - final Widget Function(BuildContext context) headerBuilder; + final Widget Function(BuildContext context)? headerBuilder; /// Creates a single-line [ListTile] with a trailing button that expands or collapses /// the tile to reveal or hide the [children]. The [initiallyExpanded] property must /// be non-null. const BrnExpandableContainerWidget({ - Key key, + Key? key, this.onExpansionChanged, this.headerBuilder, this.child, this.initiallyExpanded = false, this.animationDuration, this.expandableController, - }) : assert(initiallyExpanded != null), - super(key: key); + }) : super(key: key); /// A widget to display before the title. /// @@ -45,19 +46,19 @@ class BrnExpandableContainerWidget extends StatefulWidget { /// When the tile starts expanding, this function is called with the value /// true. When the tile starts collapsing, this function is called with /// the value false. - final ValueChanged onExpansionChanged; + final ValueChanged? onExpansionChanged; /// The widgets that are displayed when the tile expands. /// /// Typically [ListTile] widgets. - final Widget child; + final Widget? child; /// Specifies if the list tile is initially expanded (true) or collapsed (false, the default). final bool initiallyExpanded; - final Duration animationDuration; + final Duration? animationDuration; - final BrnExpandableContainerController expandableController; + final BrnExpandableContainerController? expandableController; @override _BrnExpansionContainerElementState createState() => _BrnExpansionContainerElementState(); @@ -67,13 +68,13 @@ class _BrnExpansionContainerElementState extends State _easeInTween = CurveTween(curve: Curves.easeIn); - BrnExpandableContainerController _expandableController; - AnimationController _animationController; - Animation _heightFactor; + BrnExpandableContainerController? _expandableController; + AnimationController? _animationController; + late Animation _heightFactor; bool _isExpanded = false; - Widget arrowIcon; + Widget? arrowIcon; @override void initState() { @@ -82,21 +83,21 @@ class _BrnExpansionContainerElementState extends State with SingleTickerProviderStateMixin { static final Animatable _easeInTween = CurveTween(curve: Curves.easeIn); static final Animatable _halfTween = Tween(begin: 0.0, end: 0.5); - BrnExpandableContainerController _controller; - Widget _arrowIcon; - Animation _iconTurns; - bool _initExpand; - AnimationController _animationController; + BrnExpandableContainerController? _controller; + Widget? _arrowIcon; + late Animation _iconTurns; + late bool _initExpand; + AnimationController? _animationController; @override void initState() { super.initState(); _controller = BrnExpandableContainerController(); _animationController = AnimationController(duration: Duration(milliseconds: 200), vsync: this); - _initExpand = widget.groupInfo.isExpand; - _iconTurns = _animationController.drive(_halfTween.chain(_easeInTween)); + _initExpand = widget.groupInfo!.isExpand; + _iconTurns = _animationController!.drive(_halfTween.chain(_easeInTween)); if (_initExpand) { _arrowIcon = Icon(Icons.keyboard_arrow_up); } else { @@ -62,7 +64,7 @@ class GroupCardState extends State with SingleTickerProviderStateMixi } else { _arrowIcon = Icon(Icons.keyboard_arrow_down); } - widget.groupInfo.isExpand = isExpand; + widget.groupInfo!.isExpand = isExpand; }, headerBuilder: (_) { return GestureDetector( @@ -76,7 +78,7 @@ class GroupCardState extends State with SingleTickerProviderStateMixi children: [ Expanded( child: Text( - widget.groupInfo.groupName, + widget.groupInfo!.groupName, style: TextStyle(color: Color(0xFF222222), fontSize: 18), )), RotationTransition( @@ -94,6 +96,9 @@ class GroupCardState extends State with SingleTickerProviderStateMixi } Widget _getContentWidget() { + if(widget.groupInfo == null || widget.groupInfo!.children == null){ + return SizedBox.shrink(); + } return ListView.builder( physics: new NeverScrollableScrollPhysics(), shrinkWrap: true, @@ -102,14 +107,14 @@ class GroupCardState extends State with SingleTickerProviderStateMixi return Container( color: Colors.white, child: ListItem( - isSupportTheme: widget.groupInfo?.children[index]?.isSupportTheme, + isSupportTheme: widget.groupInfo?.children![index].isSupportTheme ?? false, isShowLine: !(index == 0), - title: widget.groupInfo?.children[index].groupName, - describe: widget.groupInfo?.children[index].desc, + title: widget.groupInfo?.children![index].groupName ?? '', + describe: widget.groupInfo?.children![index].desc ?? '', onPressed: () { if (widget.groupInfo?.children != null && - widget.groupInfo?.children[index].navigatorPage != null) { - widget.groupInfo?.children[index].navigatorPage(context); + widget.groupInfo?.children![index].navigatorPage != null) { + widget.groupInfo?.children![index].navigatorPage!(context); } }, ), diff --git a/example/lib/sample/home/home.dart b/example/lib/sample/home/home.dart index 9b3abc45..cf745500 100644 --- a/example/lib/sample/home/home.dart +++ b/example/lib/sample/home/home.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/bruno.dart'; import 'package:example/sample/home/card_data_config.dart'; import 'package:example/sample/home/group_card.dart'; @@ -25,7 +27,7 @@ class HomePage extends StatelessWidget { padding: EdgeInsets.fromLTRB(16, 10, 16, 0), child: ListView.builder( shrinkWrap: true, - itemCount: list?.length, + itemCount: list.length, itemBuilder: (BuildContext context, int index) { return Container( padding: EdgeInsets.only(top: 10), diff --git a/example/lib/sample/home/list_item.dart b/example/lib/sample/home/list_item.dart index 616f1729..81fd2cc2 100644 --- a/example/lib/sample/home/list_item.dart +++ b/example/lib/sample/home/list_item.dart @@ -1,35 +1,37 @@ + + import 'package:bruno/bruno.dart'; import 'package:flutter/material.dart'; /// 列表项 class ListItem extends StatefulWidget { /// 点击事件 - final VoidCallback onPressed; + final VoidCallback? onPressed; /// 标题 final String title; - final double titleFontSize; - final Color titleColor; - final String imgPath; + final double? titleFontSize; + final Color? titleColor; + final String? imgPath; /// 描述 final String describe; final Color describeColor; /// 右侧控件 - final Widget rightWidget; + final Widget? rightWidget; final bool isSupportTheme; final bool isShowLine; /// 构造函数 ListItem({ - Key key, + Key? key, this.onPressed, this.title = "", this.titleFontSize, this.titleColor, this.describe = "", - this.describeColor: Colors.grey, + this.describeColor = const Color(0xFF999999), this.rightWidget, this.imgPath, this.isSupportTheme = false, @@ -91,7 +93,7 @@ class _ListItemState extends State { Padding(padding: EdgeInsets.all(2)), Text( widget.describe, - style: TextStyle(color: widget.describeColor ?? Color(0xFF999999), fontSize: 12), + style: TextStyle(color: widget.describeColor, fontSize: 12), ), BrnLine( height: 14, diff --git a/example/lib/sample/theme/config_test_utils.dart b/example/lib/sample/theme/config_test_utils.dart index 7837353d..a9256ce8 100644 --- a/example/lib/sample/theme/config_test_utils.dart +++ b/example/lib/sample/theme/config_test_utils.dart @@ -1,3 +1,5 @@ + + import 'dart:ui'; import 'package:bruno/bruno.dart'; @@ -158,16 +160,6 @@ class TestConfigUtils { titleMaxLength: 20, titleStyle: BrnTextStyle(color: Color(0xff222222), fontWeight: FontWeight.w600, fontSize: 24), actionsStyle: BrnTextStyle(color: Color(0xFF3072F6), fontWeight: FontWeight.w600, fontSize: 18), - flexibleSpace: Container( - width: double.infinity, - height: MediaQueryData.fromWindow(window).padding.top + 57, - decoration: BoxDecoration( - gradient: LinearGradient(colors: [ - Color(0xfffafafa), - Color(0xfff5f5f5), - ], begin: Alignment.topCenter, end: Alignment.bottomCenter), - ), - ), ); static BrnButtonConfig defaultButtonConfig = BrnButtonConfig( diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 1d71f15b..ffb77c08 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -14,7 +14,7 @@ description: A new Flutter project. version: 1.0.0+1 environment: - sdk: ">=2.1.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: @@ -24,20 +24,18 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^0.1.2 bruno: path: ../ flutter_easyrefresh: ^2.2.1 http: any badges: ^2.0.2 - flutter_swiper: 1.1.6 dev_dependencies: flutter_test: sdk: flutter dependency_overrides: - intl: 0.16.0 + intl: ^0.17.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/lib/bruno.dart b/lib/bruno.dart index b2b13bea..8ca380d3 100644 --- a/lib/bruno.dart +++ b/lib/bruno.dart @@ -74,8 +74,6 @@ export 'src/components/tabbar/normal/brn_tabbar_controller.dart'; export 'src/components/tabbar/indicator/brn_fixed_underline_decoration.dart'; export 'src/components/tabbar/indicator/brn_triangle_decoration.dart'; -//分割线 - //空页面 export 'src/components/empty/brn_empty_status.dart'; @@ -84,7 +82,6 @@ export 'src/components/loading/brn_loading.dart'; //导航栏 export 'src/components/navbar/brn_appbar.dart'; -export 'src/components/navbar/brn_empty_appbar.dart'; //搜索bar export 'src/components/navbar/brn_search_bar.dart'; @@ -125,9 +122,9 @@ export 'src/components/form/items/general/brn_title_select_input_item.dart'; export 'src/components/form/items/misc/brn_title_item.dart'; export 'src/components/form/items/misc/brn_add_label_item.dart'; export 'src/components/form/items/group/brn_normal_group.dart'; -export 'src/components/form/undetermined/brn_expandable_group.dart'; -export 'src/components/form/undetermined/brn_portrait_radio_group.dart'; -export 'src/components/form/items/group/brn_expand_group.dart'; +export 'src/components/form/items/group/brn_expandable_group.dart'; +export 'src/components/form/items/group/brn_portrait_radio_group.dart'; +export 'src/components/form/items/group/brn_expandable_group_with_opreate.dart'; // 新增表单项 export 'src/components/form/items/title/brn_base_title_item.dart'; @@ -151,6 +148,8 @@ export 'src/components/appraise/brn_appraise_bottom_picker.dart'; export 'src/components/appraise/brn_appraise_emoji_list_view.dart'; export 'src/components/appraise/brn_appraise_header.dart'; export 'src/components/appraise/brn_appraise.dart'; +export 'src/components/appraise/brn_appraise_config.dart'; +export 'src/components/appraise/brn_appraise_interface.dart'; export 'src/components/appraise/brn_appraise_star_list_view.dart'; //大图预览 diff --git a/lib/src/components/actionsheet/brn_common_action_sheet.dart b/lib/src/components/actionsheet/brn_common_action_sheet.dart index 42a8bf32..ab18f617 100644 --- a/lib/src/components/actionsheet/brn_common_action_sheet.dart +++ b/lib/src/components/actionsheet/brn_common_action_sheet.dart @@ -26,16 +26,16 @@ class BrnCommonActionSheetItem { String title; /// 辅助信息 - String desc; + String? desc; /// 样式 [BrnActionSheetActionStyle] final BrnCommonActionSheetItemStyle actionStyle; /// 主标题文本样式 - final TextStyle titleStyle; + final TextStyle? titleStyle; /// 辅助信息文本样式 - final TextStyle descStyle; + final TextStyle? descStyle; BrnCommonActionSheetItem( this.title, { @@ -55,19 +55,19 @@ class BrnCommonActionSheet extends StatelessWidget { final List actions; /// ActionSheet 标题 - final String title; + final String? title; /// title区域widget, 与 title 字段互斥,当 titleWidget 不为 null 时优先使用 titleWidget。 - final Widget titleWidget; + final Widget? titleWidget; /// Action 之间分割线颜色,默认值 Color(0xfff0f0f0) - final Color separatorLineColor; + final Color? separatorLineColor; /// 取消按钮与 Action 之间的分割线的颜色,默认值 Color(0xfff8f8f8) final Color spaceColor; /// 取消按钮文本 - final String cancelTitle; + final String? cancelTitle; /// 标题最大行数,默认为2 final int maxTitleLines; @@ -77,16 +77,16 @@ class BrnCommonActionSheet extends StatelessWidget { final double maxSheetHeight; /// Action Item 的点击事件 - final BrnCommonActionSheetItemClickCallBack clickCallBack; + final BrnCommonActionSheetItemClickCallBack? clickCallBack; /// Action Item 点击事件拦截回调 - final BrnCommonActionSheetItemClickInterceptor onItemClickInterceptor; + final BrnCommonActionSheetItemClickInterceptor? onItemClickInterceptor; /// 主题定制 - BrnActionSheetConfig themeData; + BrnActionSheetConfig? themeData; BrnCommonActionSheet({ - @required this.actions, + required this.actions, this.title, this.titleWidget, this.cancelTitle, @@ -97,10 +97,10 @@ class BrnCommonActionSheet extends StatelessWidget { this.maxSheetHeight = 0, this.onItemClickInterceptor, this.themeData, - }) : assert(actions != null) { + }) { themeData ??= BrnActionSheetConfig(); themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: themeData!.configId) .actionSheetConfig .merge(themeData); } @@ -122,8 +122,8 @@ class BrnCommonActionSheet extends StatelessWidget { color: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( - topLeft: Radius.circular(themeData.topRadius), - topRight: Radius.circular(themeData.topRadius), + topLeft: Radius.circular(themeData!.topRadius), + topRight: Radius.circular(themeData!.topRadius), ), ), ), @@ -135,11 +135,11 @@ class BrnCommonActionSheet extends StatelessWidget { /// 构建actionSheet的按钮 Widget _configActionWidgets(BuildContext context, double _maxSheetHeight) { - List widgets = List(); + List widgets = []; // 构建整体标题 if (titleWidget != null) { // 如果传入了则直接使用 - widgets.add(titleWidget); + widgets.add(titleWidget!); } else if (title != null && title.toString().trim() != "") { // 如果只传入title则根据文案构建默认title widgets.add(_configTitleActions()); @@ -147,7 +147,7 @@ class BrnCommonActionSheet extends StatelessWidget { widgets.add(_configListActions(context)); // 添加间隔 widgets.add(Divider( - color: spaceColor ?? Color(0xfff8f8f8), + color: spaceColor, thickness: 8, height: 8, )); @@ -168,13 +168,13 @@ class BrnCommonActionSheet extends StatelessWidget { return Column( children: [ Container( - padding: themeData.titlePadding, + padding: themeData!.titlePadding, child: Center( child: Text( - title, + title!, textAlign: TextAlign.center, maxLines: maxTitleLines, - style: themeData.titleStyle.generateTextStyle(), + style: themeData!.titleStyle.generateTextStyle(), ), ), ), @@ -182,7 +182,7 @@ class BrnCommonActionSheet extends StatelessWidget { //有标题则添加分割线 thickness: 1, height: 1, - color: separatorLineColor ?? themeData.commonConfig.dividerColorBase, + color: separatorLineColor ?? themeData!.commonConfig.dividerColorBase, ), ], ); @@ -190,22 +190,22 @@ class BrnCommonActionSheet extends StatelessWidget { /// 构建列表widget Widget _configListActions(BuildContext context) { - List tiles = List(); + List tiles = []; //构建列表内容 for (int index = 0; index < actions.length; index++) { tiles.add( GestureDetector( behavior: HitTestBehavior.opaque, child: Container( - padding: themeData.contentPadding, + padding: themeData!.contentPadding, child: _configTile(actions[index]), ), onTap: () { if (onItemClickInterceptor == null || - !onItemClickInterceptor(index, actions[index])) { + !onItemClickInterceptor!(index, actions[index])) { // 推荐使用回调方法处理点击事件!!!!!!!!!! if (clickCallBack != null) { - clickCallBack(index, actions[index]); + clickCallBack!(index, actions[index]); } // 如果未拦截,则pop掉当前页面,并且携带信息(不建议使用此信息进行点击时间处理) Navigator.of(context).pop([index, actions[index]]); @@ -216,7 +216,7 @@ class BrnCommonActionSheet extends StatelessWidget { tiles.add(Divider( thickness: 1, height: 1, - color: separatorLineColor ?? themeData.commonConfig.dividerColorBase, + color: separatorLineColor ?? themeData!.commonConfig.dividerColorBase, )); } return Flexible( @@ -231,7 +231,7 @@ class BrnCommonActionSheet extends StatelessWidget { // 配置每个选项内部信息 // action 每个item配置项 [BrnCommonActionSheetItem] Widget _configTile(BrnCommonActionSheetItem action) { - List tileElements = List(); + List tileElements = []; bool hasTitle = false; // 如果有标题则添加标题 if (action.title != null) { @@ -241,10 +241,10 @@ class BrnCommonActionSheet extends StatelessWidget { maxLines: 1, style: action.titleStyle ?? (action.actionStyle == BrnCommonActionSheetItemStyle.alert - ? this.themeData.itemTitleStyleAlert.generateTextStyle() + ? this.themeData!.itemTitleStyleAlert.generateTextStyle() : (action.actionStyle == BrnCommonActionSheetItemStyle.link - ? this.themeData.itemTitleStyleLink.generateTextStyle() - : this.themeData.itemTitleStyle.generateTextStyle())), + ? this.themeData!.itemTitleStyleLink.generateTextStyle() + : this.themeData!.itemTitleStyle.generateTextStyle())), ), )); hasTitle = true; @@ -260,15 +260,15 @@ class BrnCommonActionSheet extends StatelessWidget { tileElements.add( Center( child: Text( - action.desc, + action.desc!, textAlign: TextAlign.center, maxLines: 1, style: action.descStyle ?? (action.actionStyle == BrnCommonActionSheetItemStyle.alert - ? this.themeData.itemDescStyleAlert.generateTextStyle() + ? this.themeData!.itemDescStyleAlert.generateTextStyle() : (action.actionStyle == BrnCommonActionSheetItemStyle.link - ? this.themeData.itemDescStyleLink.generateTextStyle() - : this.themeData.itemDescStyle.generateTextStyle())), + ? this.themeData!.itemDescStyleLink.generateTextStyle() + : this.themeData!.itemDescStyle.generateTextStyle())), ), ), ); @@ -292,8 +292,8 @@ class BrnCommonActionSheet extends StatelessWidget { padding: EdgeInsets.only(top: 12, bottom: 12), child: Center( child: Text( - (cancelTitle != null) ? cancelTitle : "取消", - style: this.themeData.cancelStyle.generateTextStyle(), + cancelTitle ?? "取消", + style: this.themeData!.cancelStyle.generateTextStyle(), ), ), ), diff --git a/lib/src/components/actionsheet/brn_selected_list_action_sheet.dart b/lib/src/components/actionsheet/brn_selected_list_action_sheet.dart index 2b0dd36e..06bf0ef7 100644 --- a/lib/src/components/actionsheet/brn_selected_list_action_sheet.dart +++ b/lib/src/components/actionsheet/brn_selected_list_action_sheet.dart @@ -45,19 +45,16 @@ class BrnSelectedListActionSheetController extends ChangeNotifier { /// 自动与 globalKey 绑定的组件左右对齐,并从其顶部弹出。clear /// 2. 外界需要自己监听 Android 上的系统返回事件,并且调用组件的 [dismiss] 方法!否则,组件不能正常关闭。 class BrnSelectedListActionSheet { - @required final BuildContext context; /// 数据源列表 - @required final List items; /// 获取对应 index 行内容的回调。类型必须为 String 或者自定义的 widget.自定义 widget 时,左边的 icon 会自动隐藏,自定义widget填充整行。 - @required final dynamic Function(int index, T entity) itemTitleBuilder; /// 控制视图隐藏/刷新列表等方法 - final BrnSelectedListActionSheetController controller; + final BrnSelectedListActionSheetController? controller; /// 视图的最大高度。默认值 290,列表的内容的高度=maxHeight-65 final double maxHeight; @@ -75,10 +72,10 @@ class BrnSelectedListActionSheet { /// fontWeight: FontWeight.w600, /// decoration: TextDecoration.none) /// ``` - final String title; + final String? title; /// 自定义标题视图。默认外层有 `const EdgeInsets.fromLTRB(20, 20, 20, 15)` 的 padding,且优先级比 [title] 高 - final Widget titleWidget; + final Widget? titleWidget; /// 清空按钮是否显示,默认为 false final bool isClearButtonHidden; @@ -87,33 +84,33 @@ class BrnSelectedListActionSheet { final bool isDeleteButtonHidden; /// 每一行前边的 icon,可不传。如果该 image 没有设置,并且 itemTitleBuilder 返回的是自定义 widget,则该 widget 自动填充整行区域 - final Image itemIconImage; + final Image? itemIconImage; /// 点击清空按钮后的回调,如果没有实现该回调,则会显示默认弹窗。如果要关闭已选列表,请调用 dismiss()。 - final VoidCallback onClear; + final VoidCallback? onClear; /// 清空按钮点击显示默认确认弹窗之后,`确定` 按钮的点击回调 - final VoidCallback onClearConfirmed; + final VoidCallback? onClearConfirmed; /// 清空按钮点击显示默认确认弹窗之后,`取消` 按钮的点击回调 - final VoidCallback onClearCanceled; + final VoidCallback? onClearCanceled; /// 每一行删除按钮的点击回调。返回值:是否要删除该 entity,如果该 handler 没有实现或者返回 true,则删除 - final bool Function(int deleteIdx, T deleteEntity) onItemDelete; + final bool Function(int deleteIdx, T deleteEntity)? onItemDelete; /// 视图显示时的回调 - final VoidCallback onListShowed; + final VoidCallback? onListShowed; /// 视图隐藏时的回调,会把是否是清空按钮触发的销毁视图回传 - final void Function(bool isClosedByClearButton) onListDismissed; + final void Function(bool isClosedByClearButton)? onListDismissed; - OverlayEntry _overlayEntry; - double _leftOffset; + OverlayEntry? _overlayEntry; + double? _leftOffset; double _bottomKeyOffset = 0; - double _maxWidth; + double? _maxWidth; BrnSelectedListActionSheet( - {this.context, + {required this.context, this.maxHeight = 290, this.bottomOffset = 82, this.title, @@ -121,8 +118,8 @@ class BrnSelectedListActionSheet { this.isClearButtonHidden = false, this.isDeleteButtonHidden = false, this.itemIconImage, - this.items, - this.itemTitleBuilder, + required this.items, + required this.itemTitleBuilder, this.onClear, this.onClearConfirmed, this.onClearCanceled, @@ -133,21 +130,21 @@ class BrnSelectedListActionSheet { void _dismissHandler(bool isClear) { if (onListDismissed != null) { - onListDismissed(isClear); + onListDismissed!(isClear); } if (_overlayEntry != null) { - _overlayEntry.remove(); + _overlayEntry!.remove(); _overlayEntry = null; } } /// bottomWidgetKey: 已选列表下边操作区域绑定的 GlobalKey,已选列表会自动与操作区域左右对齐,且从操作区域的顶部滑出 - void showWithTargetKey({GlobalKey bottomWidgetKey}) { - assert(bottomWidgetKey != null); - RenderBox renderBox = bottomWidgetKey?.currentContext?.findRenderObject(); + void showWithTargetKey({required GlobalKey bottomWidgetKey}) { + RenderBox? renderBox = + bottomWidgetKey.currentContext?.findRenderObject() as RenderBox?; var offset = renderBox?.localToGlobal(Offset.zero); _leftOffset = offset?.dx ?? 0; - _maxWidth = renderBox?.size?.width ?? MediaQuery.of(context).size.width; + _maxWidth = renderBox?.size.width ?? MediaQuery.of(context).size.width; _bottomKeyOffset = MediaQuery.of(context).size.height - (offset?.dy ?? 0); this._innerShow(true); } @@ -160,7 +157,7 @@ class BrnSelectedListActionSheet { if (_overlayEntry != null) { return; } - BrnSelectedListActionSheetController tempCcontroller = controller; + BrnSelectedListActionSheetController? tempCcontroller = controller; if (tempCcontroller == null) { tempCcontroller = BrnSelectedListActionSheetController(); tempCcontroller._isHidden = false; @@ -186,7 +183,7 @@ class BrnSelectedListActionSheet { return Positioned( top: MediaQuery.of(context).viewInsets.top, left: _leftOffset, - bottom: (showByKey ?? false) + bottom: (showByKey) ? _bottomKeyOffset : (bottomOffset + MediaQuery.of(context).padding.bottom + @@ -196,11 +193,11 @@ class BrnSelectedListActionSheet { child: content, )); }); - content._overlayState.insert(overlayEntry); + content._overlayState!.insert(overlayEntry); _overlayEntry = overlayEntry; if (onListShowed != null) { - onListShowed(); + onListShowed!(); } } } @@ -208,25 +205,25 @@ class BrnSelectedListActionSheet { // ignore: must_be_immutable class _BrnActionSheetSelectedItemListContentWidget extends StatefulWidget { final BrnSelectedListActionSheet itemWidget; - final void Function(bool isClear) onDismiss; + final void Function(bool isClear)? onDismiss; final dynamic Function(int index, T entity) itemTitleBuilder; - final bool Function(int deleteIdx, T deleteEntity) onItemDelete; - final BrnSelectedListActionSheetController controller; + final bool Function(int deleteIdx, T deleteEntity)? onItemDelete; + final BrnSelectedListActionSheetController? controller; - OverlayState _overlayState; + OverlayState? _overlayState; // 位置动画 - Animation _yAnimation; + late Animation _yAnimation; // 背景透明度动画 - Animation _alphaAnimation; - AnimationController _yAnimationController; - AnimationController _alphaAnimationController; + late Animation _alphaAnimation; + late AnimationController _yAnimationController; + late AnimationController _alphaAnimationController; _BrnActionSheetSelectedItemListContentWidget( - {this.itemWidget, + {required this.itemWidget, this.onDismiss, - this.itemTitleBuilder, + required this.itemTitleBuilder, this.onItemDelete, this.controller}); @@ -245,10 +242,10 @@ class _BrnActionSheetSelectedItemListContentWidget extends StatefulWidget { } class _BrnActionSheetSelectedItemListState - extends State<_BrnActionSheetSelectedItemListContentWidget> + extends State<_BrnActionSheetSelectedItemListContentWidget> with TickerProviderStateMixin { bool _isClosedByClear = false; - BrnSelectedListActionSheetController _controller; + BrnSelectedListActionSheetController? _controller; @override initState() { @@ -263,26 +260,22 @@ class _BrnActionSheetSelectedItemListState @override dispose() { //路由销毁时需要释放动画资源 - if (widget._yAnimationController != null) { - widget._yAnimationController.dispose(); - } - if (widget._alphaAnimationController != null) { - widget._alphaAnimationController.dispose(); - } + widget._yAnimationController.dispose(); + widget._alphaAnimationController.dispose(); _controller?.removeListener(_onListenHandler); _controller = null; super.dispose(); } void _onListenHandler() { - if (_controller.isShouldReloadData) { + if (_controller!.isShouldReloadData) { if (mounted) { setState(() {}); } - _controller.isShouldReloadData = false; - } else if (_controller.isSelectedListDismissed) { + _controller!.isShouldReloadData = false; + } else if (_controller!.isSelectedListDismissed) { widget.dismissWithAnimation(); - _controller.isSelectedListDismissed = false; + _controller!.isSelectedListDismissed = false; } } @@ -293,21 +286,21 @@ class _BrnActionSheetSelectedItemListState AnimationController alphaAnimationController = AnimationController( duration: const Duration(milliseconds: 200), vsync: this); widget._alphaAnimationController = alphaAnimationController; - Animation yAnimation = Tween(begin: 65.0, end: this.getContentHeight()) + Animation yAnimation = Tween(begin: 65.0, end: this.getContentHeight()) .animate(yAnimationController) - ..addListener(() { - setState(() => {}); - }) - ..addStatusListener((status) { - if (status == AnimationStatus.dismissed) { - widget.onDismiss(_isClosedByClear); - } - }); - widget._yAnimation = yAnimation; + ..addListener(() { + setState(() => {}); + }) + ..addStatusListener((status) { + if (status == AnimationStatus.dismissed) { + widget.onDismiss!(_isClosedByClear); + } + }); + widget._yAnimation = yAnimation as Animation; Animation alphaAnimation = Tween(begin: 0.0, end: 0.7) .animate(alphaAnimationController) - ..addListener(() {}); - widget._alphaAnimation = alphaAnimation; + ..addListener(() {}); + widget._alphaAnimation = alphaAnimation as Animation; yAnimationController.forward(); alphaAnimationController.forward(); } @@ -328,25 +321,21 @@ class _BrnActionSheetSelectedItemListState BrnDialogManager.showConfirmDialog(context, title: "确定要清空已选列表吗?", cancel: '取消', confirm: '确定', onConfirm: () { if (widget.itemWidget.onClearConfirmed != null) { - widget.itemWidget.onClearConfirmed(); - } - if (widget.itemWidget.items != null) { - widget.itemWidget.items - .removeRange(0, widget.itemWidget.items.length); + widget.itemWidget.onClearConfirmed!(); } + widget.itemWidget.items.removeRange(0, widget.itemWidget.items.length); }, onCancel: () { if (widget.itemWidget.onClearCanceled != null) { - widget.itemWidget.onClearCanceled(); + widget.itemWidget.onClearCanceled!(); } }); } else { - widget.itemWidget.onClear(); + widget.itemWidget.onClear!(); } } void onDeleteItemAction(int idx) { - if (widget.itemWidget.items == null || - idx >= widget.itemWidget.items.length) { + if (idx >= widget.itemWidget.items.length) { debugPrint( 'idx:$idx out of range of selectedModelList:${widget.itemWidget.items.length}!!!'); return; @@ -354,7 +343,7 @@ class _BrnActionSheetSelectedItemListState bool shouldDelete = true; if (widget.onItemDelete != null) { - shouldDelete = widget.onItemDelete(idx, widget.itemWidget.items[idx]); + shouldDelete = widget.onItemDelete!(idx, widget.itemWidget.items[idx]); } if (shouldDelete) { setState(() { @@ -367,8 +356,8 @@ class _BrnActionSheetSelectedItemListState Widget build(BuildContext context) { // 顶部标题处理 String title = - (widget.itemWidget.title != null && widget.itemWidget.title.length > 0) - ? widget.itemWidget.title + (widget.itemWidget.title != null && widget.itemWidget.title!.length > 0) + ? widget.itemWidget.title! : '已选列表'; TextStyle titleStyle = const TextStyle( fontSize: 18, @@ -384,10 +373,9 @@ class _BrnActionSheetSelectedItemListState style: titleStyle, ), )); - List topWidgetList = List(); + List topWidgetList = []; topWidgetList.add(topTitle); - if (widget.itemWidget.isClearButtonHidden != null && - !widget.itemWidget.isClearButtonHidden) { + if (!widget.itemWidget.isClearButtonHidden) { Widget clearWidget = GestureDetector( onTap: () { this.onClearAction(); @@ -456,16 +444,13 @@ class _BrnActionSheetSelectedItemListState Expanded( child: ListView.builder( padding: EdgeInsets.zero, - itemCount: widget.itemWidget.items != null - ? widget.itemWidget.items.length - : 0, + itemCount: widget.itemWidget.items.length, itemBuilder: (BuildContext context, int index) { // 是否展示左侧的图标 bool shouldHideIcon = false; // 获取标题 Widget content = Container(color: Colors.white); - if (widget.itemWidget.items != null && - index < widget.itemWidget.items.length) { + if (index < widget.itemWidget.items.length) { var item = widget.itemTitleBuilder( index, widget.itemWidget.items[index]); if (item is String) { @@ -511,7 +496,7 @@ class _BrnActionSheetSelectedItemListState padding: const EdgeInsets.only( left: 5, right: 20), child: BrunoTools.getAssetImage( - BrnAsset.ICON_TRASH_BIN)), + BrnAsset.iconTrashBin)), ), ), ], diff --git a/lib/src/components/actionsheet/brn_share_action_sheet.dart b/lib/src/components/actionsheet/brn_share_action_sheet.dart index d547ebf4..6cfc6e62 100644 --- a/lib/src/components/actionsheet/brn_share_action_sheet.dart +++ b/lib/src/components/actionsheet/brn_share_action_sheet.dart @@ -19,10 +19,10 @@ class BrnShareItem extends Object { int shareType; /// 自定义标题 - String customTitle; + String? customTitle; /// 自定义图标 - Widget customImage; + Widget? customImage; /// 是否可点击(如果为预设类型,设置为不可点击后会变为相应的置灰图标)默认为true bool canClick; @@ -38,16 +38,16 @@ class BrnShareItem extends Object { // ignore: must_be_immutable class BrnShareActionSheet extends StatelessWidget { /// 第一行渠道列表 - final List firstShareChannels; + final List? firstShareChannels; /// 第二行渠道列表 - final List secondShareChannels; + final List? secondShareChannels; /// 列表标题 - final String mainTitle; + final String? mainTitle; /// 取消按钮名称 - final String cancelTitle; + final String? cancelTitle; /// 取消按钮的文本颜色,默认值为 Color(0xff222222) final Color textColor; @@ -56,10 +56,10 @@ class BrnShareActionSheet extends StatelessWidget { final Color shareTextColor; /// 点击事件回调 - final BrnShareActionSheetItemClickCallBack clickCallBack; + final BrnShareActionSheetItemClickCallBack? clickCallBack; /// 点击事件拦截回调(如果配置了此项,返回值为是否拦截,如果为true,则进行拦截,不进行默认回调) - final BrnShareActionSheetOnItemClickInterceptor clickInterceptor; + final BrnShareActionSheetOnItemClickInterceptor? clickInterceptor; BrnShareActionSheet({ this.firstShareChannels, @@ -97,13 +97,13 @@ class BrnShareActionSheet extends StatelessWidget { } /// 构建单个分享渠道 - Widget _configChannelWidget(BuildContext context, int section, int index) { + Widget? _configChannelWidget(BuildContext context, int section, int index) { // 分享类型 BrnShareItem channel; // 渠道名称 - String title; + String? title; // 图片 - Widget image; + Widget? image; // 元素宽度(图片边长也是48) double itemsWidth = 48; // 元素间隔为20写死 @@ -112,16 +112,16 @@ class BrnShareActionSheet extends StatelessWidget { image = null; // 判断区域 if (section == 0) { - channel = firstShareChannels[index]; + channel = firstShareChannels![index]; } else { - channel = secondShareChannels[index]; + channel = secondShareChannels![index]; } // 判断是否为自定义标题 - title = (channel.shareType == BrnShareItemConstants.SHARE_CUSTOM) + title = (channel.shareType == BrnShareItemConstants.shareCustom) ? (channel.customTitle ?? "") : BrnShareItemConstants.shareItemTitleList[channel.shareType]; // 判断是否为自定义,如果不是自定义图标,则判断是否可点击(决定是否使用置灰图标) - image = (channel.shareType == BrnShareItemConstants.SHARE_CUSTOM) + image = (channel.shareType == BrnShareItemConstants.shareCustom) ? channel.customImage : (channel.canClick ? BrunoTools.getAssetImage( @@ -129,7 +129,7 @@ class BrnShareActionSheet extends StatelessWidget { : BrunoTools.getAssetImage(BrnShareItemConstants .disableShareItemImagePathList[channel.shareType])); //如果没图或没文字则不显示 - if (title == null || image == null) { + if (image == null) { return null; } @@ -160,10 +160,10 @@ class BrnShareActionSheet extends StatelessWidget { ), onTap: () { if (clickInterceptor == null || - !clickInterceptor(section, index, channel)) { + !clickInterceptor!(section, index, channel)) { // 推荐使用回调方法处理点击事件!!!!!!!!!! if (clickCallBack != null && channel.canClick) { - clickCallBack(section, index, channel); + clickCallBack!(section, index, channel); // 如果未拦截并且可点击,则pop掉当前页面 Navigator.of(context).pop(); } @@ -174,11 +174,11 @@ class BrnShareActionSheet extends StatelessWidget { /// 构建actionSheet的按钮 Widget _configActionWidgets(BuildContext context) { - List tiles = List(); + List tiles = []; // 预设分享渠道 - List firstSectionItems = List(); + List firstSectionItems = []; // 自定义分享渠道 - List secondSectionItems = List(); + List secondSectionItems = []; // 容器左侧留白 double leftGap = 10; // 容器上方留白 @@ -187,8 +187,8 @@ class BrnShareActionSheet extends StatelessWidget { double bottomGap = 20; // 构建第一行 if (firstShareChannels != null) { - for (int index = 0; index < firstShareChannels.length; index++) { - Widget item = _configChannelWidget(context, 0, index); + for (int index = 0; index < firstShareChannels!.length; index++) { + Widget? item = _configChannelWidget(context, 0, index); if (item != null) { firstSectionItems.add(item); } @@ -196,8 +196,8 @@ class BrnShareActionSheet extends StatelessWidget { } // 构建第二行 if (secondShareChannels != null) { - for (int index = 0; index < secondShareChannels.length; index++) { - Widget item = _configChannelWidget(context, 1, index); + for (int index = 0; index < secondShareChannels!.length; index++) { + Widget? item = _configChannelWidget(context, 1, index); if (item != null) { secondSectionItems.add(item); } @@ -268,7 +268,7 @@ class BrnShareActionSheet extends StatelessWidget { padding: EdgeInsets.only(left: 61, right: 61, top: 12, bottom: 12), child: Center( child: Text( - (cancelTitle != null) ? cancelTitle : "取消", + cancelTitle ?? "取消", style: TextStyle( fontSize: 16, fontWeight: FontWeight.w600, color: textColor), ), diff --git a/lib/src/components/appraise/brn_appraise.dart b/lib/src/components/appraise/brn_appraise.dart index c396c807..96963656 100644 --- a/lib/src/components/appraise/brn_appraise.dart +++ b/lib/src/components/appraise/brn_appraise.dart @@ -5,25 +5,9 @@ import 'package:bruno/src/components/appraise/brn_mulit_select_tags.dart'; import 'package:bruno/src/components/button/brn_big_main_button.dart'; import 'package:bruno/src/components/input/brn_input_text.dart'; import 'package:bruno/src/components/picker/brn_tags_picker_config.dart'; +import 'package:bruno/src/components/appraise/brn_appraise_config.dart'; import 'package:flutter/material.dart'; - -/// 点击表情或者星星时的回调 -/// index 点击的表情或者星星的index -typedef BrnAppraiseIconClick = void Function(int index); - -/// 点击tag的回调 -/// selectedTags 所有选中标签的集合 -typedef BrnAppraiseTagClick = void Function(List selectedTags); - -/// 提交按钮点击事件回调 -/// index 选中的表情或者星星的index -/// selectedTags 所有选中标签的集合 -/// input 自定义输入的内容 -typedef BrnAppraiseConfirmClick = void Function( - int index, List selectedTags, String input); - -/// 点击关闭的回掉 -typedef BrnAppraiseCloseClickCallBack = void Function(BuildContext context); +import 'package:bruno/src/components/appraise/brn_appraise_interface.dart'; /// /// /// /// /// /// /// /// /// / /// 描述: 评价组件 @@ -57,13 +41,13 @@ class BrnAppraise extends StatefulWidget { final List iconDescriptions; /// 标签 - final List tags; + final List? tags; ///输入框允许提示文案 final String inputHintText; /// 提交按钮的点击回调 - final BrnAppraiseConfirmClick onConfirm; + final BrnAppraiseConfirmClick? onConfirm; /// 评价组件的配置项 final BrnAppraiseConfig config; @@ -77,16 +61,17 @@ class BrnAppraise extends StatefulWidget { '超惊喜' ]; - BrnAppraise({ - this.title, - this.headerType = BrnAppraiseHeaderType.spaceBetween, - this.type = BrnAppraiseType.Star, - this.iconDescriptions = _defaultIconDescriptions, - this.tags, - this.inputHintText, - this.onConfirm, - this.config = cConfig, - }); + BrnAppraise( + {Key? key, + this.title = '', + this.headerType = BrnAppraiseHeaderType.spaceBetween, + this.type = BrnAppraiseType.star, + this.iconDescriptions = _defaultIconDescriptions, + this.tags, + this.inputHintText = '', + this.onConfirm, + this.config = cConfig}) + : super(key: key); @override _BrnAppraiseState createState() => _BrnAppraiseState(); @@ -94,19 +79,19 @@ class BrnAppraise extends StatefulWidget { class _BrnAppraiseState extends State { int _appraiseIndex = -1; - bool _enable; - String _inputText; - List _selectedTag; + bool? _enable; + String? _inputText; + List _selectedTag = []; @override void initState() { - _enable = widget.config?.isConfirmButtonEnabled; + _enable = widget.config.isConfirmButtonEnabled; super.initState(); } @override void didUpdateWidget(BrnAppraise oldWidget) { - _enable = widget.config?.isConfirmButtonEnabled; + _enable = widget.config.isConfirmButtonEnabled; super.didUpdateWidget(oldWidget); } @@ -149,41 +134,41 @@ class _BrnAppraiseState extends State { ? EdgeInsets.only(top: 20, bottom: 20) : EdgeInsets.only(left: 20, top: 16, right: 16, bottom: 20); return BrnAppraiseHeader( - showHeader: widget.config?.showHeader ?? true, - headerType: widget.headerType ?? BrnAppraiseHeaderType.spaceBetween, - title: widget.title ?? '', - maxLines: widget.config?.titleMaxLines ?? 1, - headPadding: widget.config?.headerPadding ?? defaultPadding, - cancelCallBack: widget.config?.onCancel, + showHeader: widget.config.showHeader, + headerType: widget.headerType, + title: widget.title, + maxLines: widget.config.titleMaxLines, + headPadding: widget.config.headerPadding ?? defaultPadding, + cancelCallBack: widget.config.onCancel, ); } /// 获取评分组件 Widget _getIconWidget() { - if (widget.type == BrnAppraiseType.Emoji) { + if (widget.type == BrnAppraiseType.emoji) { return BrnAppraiseEmojiListView( - indexes: widget.config?.indexes, + indexes: widget.config.indexes, titles: widget.iconDescriptions, onTap: (index) { setState(() { _appraiseIndex = index; }); - if (widget.config?.iconClickCallback != null) { - widget.config.iconClickCallback(index); + if (widget.config.iconClickCallback != null) { + widget.config.iconClickCallback!(index); } }, ); } else { return BrnAppraiseStarListView( - count: widget.config?.count ?? 5, + count: widget.config.count, titles: widget.iconDescriptions, - hint: widget.config?.starAppraiseHint, + hint: widget.config.starAppraiseHint, onTap: (index) { setState(() { _appraiseIndex = index; }); - if (widget.config?.iconClickCallback != null) { - widget.config.iconClickCallback(index); + if (widget.config.iconClickCallback != null) { + widget.config.iconClickCallback!(index); } }, ); @@ -207,12 +192,12 @@ class _BrnAppraiseState extends State { return choice.name; }, // tagStyle: BrnMultiSelectStyle.auto, - multiSelect: widget.config?.multiSelect ?? true, - brnCrossAxisCount: widget.config?.tagCountEachRow ?? 2, + multiSelect: widget.config.multiSelect, + brnCrossAxisCount: widget.config.tagCountEachRow, selectedTagsCallback: (list) { _selectedTag = tag2String(list); - if (widget.config?.tagSelectCallback != null) { - widget.config.tagSelectCallback(_selectedTag); + if (widget.config.tagSelectCallback != null) { + widget.config.tagSelectCallback!(_selectedTag); } }, ), @@ -221,22 +206,22 @@ class _BrnAppraiseState extends State { /// 输入框 Widget _inputArea() { - if (widget.config?.showTextInput ?? true) { + if (widget.config.showTextInput) { return Padding( padding: EdgeInsets.only(top: 24), child: BrnInputText( - maxLength: widget.config?.maxLength ?? 100, + maxLength: widget.config.maxLength, bgColor: Color(0xfff8f8f8), - hint: widget.inputHintText ?? '', - textString: _inputText ?? '', - maxHeight: widget.config?.inputMaxHeight ?? 120, + hint: widget.inputHintText, + textString: (_inputText ?? widget.config.inputDefaultText) ?? '', + maxHeight: widget.config.inputMaxHeight, minHeight: 40, - maxHintLines: widget.config?.maxHintLines ?? 1, + maxHintLines: widget.config.maxHintLines, padding: EdgeInsets.all(12), onTextChange: (input) { _inputText = input; - if (widget.config?.inputTextChangeCallback != null) { - widget.config.inputTextChangeCallback(input); + if (widget.config.inputTextChangeCallback != null) { + widget.config.inputTextChangeCallback!(input); } }, ), @@ -247,16 +232,17 @@ class _BrnAppraiseState extends State { /// 提交按钮 Widget _confirmButton() { - if (widget.config?.showConfirmButton ?? true) { + if (widget.config.showConfirmButton) { return Padding( padding: EdgeInsets.symmetric(horizontal: 16), child: BrnBigMainButton( - title: widget.config?.confirmButtonText ?? '提交', + title: widget.config.confirmButtonText, isEnable: _enable ?? _appraiseIndex != -1, onTap: () { if (_enable ?? _appraiseIndex != -1) { if (widget.onConfirm != null) { - widget.onConfirm(_appraiseIndex, _selectedTag, _inputText); + widget.onConfirm!( + _appraiseIndex, _selectedTag, _inputText ?? ''); } } }, @@ -267,10 +253,10 @@ class _BrnAppraiseState extends State { return Container(); } - List string2Tag(List tags) { - List items = List(); + List string2Tag(List? tags) { + List items = []; if (tags?.isNotEmpty ?? false) { - for (int i = 0; i < tags.length; i++) { + for (int i = 0; i < tags!.length; i++) { items.add(BrnTagItemBean(name: tags[i], code: tags[i], index: i)); } } @@ -278,104 +264,10 @@ class _BrnAppraiseState extends State { } List tag2String(List tags) { - List result = List(); - tags?.forEach((item) { + List result = []; + tags.forEach((item) { result.add(item.name); }); return result; } } - -class BrnAppraiseConfig { - /// 是否显示标题和关闭 - final bool showHeader; - - /// 标题的padding - final EdgeInsets headerPadding; - - /// 标题的最大行数 - final int titleMaxLines; - - /// 取消的回调 - final BrnAppraiseCloseClickCallBack onCancel; - - /// 所需表情包的index列表,index最大值为4 - final List indexes; - - /// 展示的星星的数目 - final int count; - - /// 展示星星时的默认提示 - final String starAppraiseHint; - - /// 标签是否支持多选,默认为 true - final bool multiSelect; - - /// 每行能显示的tag数目,默认为 2 - final int tagCountEachRow; - - ///是否显示输入框,默认为 true - final bool showTextInput; - - ///输入框允许输入的最大长度,默认为 100 - final int maxLength; - - ///提示文案的最大行数,默认为1 - final int maxHintLines; - - /// 输入框默认输入文案 - final String inputDefaultText; - - /// 输入框的最大高度,默认为 120 - final double inputMaxHeight; - - /// 是否显示确认按钮 - final bool showConfirmButton; - - /// 确认按钮的文案 - final String confirmButtonText; - - /// 外部控制提交button的enable状态,null有效,不设置默认值 - final bool isConfirmButtonEnabled; - - /// 点击icon的回调 - final BrnAppraiseIconClick iconClickCallback; - - /// 输入框改变的回调 - final BrnInputTextChangeCallback inputTextChangeCallback; - - /// 选择标签的回调 - final BrnAppraiseTagClick tagSelectCallback; - - const BrnAppraiseConfig({ - this.showHeader = true, - this.headerPadding, - this.titleMaxLines = 1, - this.onCancel, - this.indexes = const [0, 1, 2, 3, 4], - this.count = 5, - this.starAppraiseHint = '', - this.multiSelect = true, - this.tagCountEachRow = 2, - this.showTextInput = true, - this.maxLength = 100, - this.maxHintLines = 1, - this.inputDefaultText, - this.inputMaxHeight = 120, - this.showConfirmButton = true, - this.confirmButtonText = '提交', - this.isConfirmButtonEnabled, - this.iconClickCallback, - this.inputTextChangeCallback, - this.tagSelectCallback, - }); -} - -/// 评价组件类型 -enum BrnAppraiseType { - /// 表情包评价组件 - Emoji, - - /// 星星评价组件 - Star, -} diff --git a/lib/src/components/appraise/brn_appraise_bottom_picker.dart b/lib/src/components/appraise/brn_appraise_bottom_picker.dart index 2701efef..9d6d18da 100644 --- a/lib/src/components/appraise/brn_appraise_bottom_picker.dart +++ b/lib/src/components/appraise/brn_appraise_bottom_picker.dart @@ -1,6 +1,8 @@ import 'package:bruno/src/components/appraise/brn_appraise.dart'; import 'package:bruno/src/components/appraise/brn_appraise_header.dart'; +import 'package:bruno/src/components/appraise/brn_appraise_config.dart'; import 'package:flutter/material.dart'; +import 'package:bruno/src/components/appraise/brn_appraise_interface.dart'; /// 描述: 评价组件bottom picker, /// 对BrnAppraise做了一层封装,可直接使用在showDialog里面 @@ -21,13 +23,13 @@ class BrnAppraiseBottomPicker extends StatefulWidget { final List iconDescriptions; /// 标签 - final List tags; + final List? tags; ///输入框允许提示文案 final String inputHintText; /// 提交按钮的点击回调 - final BrnAppraiseConfirmClick onConfirm; + final BrnAppraiseConfirmClick? onConfirm; /// 评价组件的配置项 final BrnAppraiseConfig config; @@ -42,15 +44,16 @@ class BrnAppraiseBottomPicker extends StatefulWidget { ]; BrnAppraiseBottomPicker({ - this.title, + Key? key, + this.title = '', this.headerType = BrnAppraiseHeaderType.spaceBetween, - this.type = BrnAppraiseType.Star, + this.type = BrnAppraiseType.star, this.iconDescriptions = _defaultIconDescriptions, this.tags, - this.inputHintText, + this.inputHintText = '', this.onConfirm, - this.config, - }); + this.config = const BrnAppraiseConfig(), + }) : super(key: key); @override _BrnAppraiseBottomPickerState createState() => @@ -74,7 +77,7 @@ class _BrnAppraiseBottomPickerState extends State { inputHintText: widget.inputHintText, onConfirm: (index, list, input) { if (widget.onConfirm != null) { - widget.onConfirm(index, list, input); + widget.onConfirm!(index, list, input); } }, config: widget.config, diff --git a/lib/src/components/appraise/brn_appraise_config.dart b/lib/src/components/appraise/brn_appraise_config.dart new file mode 100644 index 00000000..5309e308 --- /dev/null +++ b/lib/src/components/appraise/brn_appraise_config.dart @@ -0,0 +1,97 @@ +import 'package:flutter/material.dart'; +import 'package:bruno/src/components/input/brn_input_text.dart'; +import 'package:bruno/src/components/appraise/brn_appraise_interface.dart'; + +class BrnAppraiseConfig { + /// 是否显示标题和关闭 + final bool showHeader; + + /// 标题的padding + final EdgeInsets? headerPadding; + + /// 标题的最大行数 + final int titleMaxLines; + + /// 取消的回调 + final BrnAppraiseCloseClickCallBack? onCancel; + + /// 所需表情包的index列表,index最大值为4 + final List indexes; + + /// 展示的星星的数目 + final int count; + + /// 展示星星时的默认提示 + final String starAppraiseHint; + + /// 标签是否支持多选,默认为 true + final bool multiSelect; + + /// 每行能显示的tag数目,默认为 2 + final int tagCountEachRow; + + ///是否显示输入框,默认为 true + final bool showTextInput; + + ///输入框允许输入的最大长度,默认为 100 + final int maxLength; + + ///提示文案的最大行数,默认为1 + final int maxHintLines; + + /// 输入框默认输入文案 + final String? inputDefaultText; + + /// 输入框的最大高度,默认为 120 + final double inputMaxHeight; + + /// 是否显示确认按钮 + final bool showConfirmButton; + + /// 确认按钮的文案,默认 '提交' + final String confirmButtonText; + + /// 外部控制提交button的enable状态,null有效,不设置默认值 + final bool? isConfirmButtonEnabled; + + /// 点击icon的回调 + final BrnAppraiseIconClick? iconClickCallback; + + /// 输入框改变的回调 + final BrnInputTextChangeCallback? inputTextChangeCallback; + + /// 选择标签的回调 + final BrnAppraiseTagClick? tagSelectCallback; + + const BrnAppraiseConfig({ + this.showHeader = true, + this.headerPadding, + this.titleMaxLines = 1, + this.onCancel, + this.indexes = const [0, 1, 2, 3, 4], + this.count = 5, + this.starAppraiseHint = '', + this.multiSelect = true, + this.tagCountEachRow = 2, + this.showTextInput = true, + this.maxLength = 100, + this.maxHintLines = 1, + this.inputDefaultText, + this.inputMaxHeight = 120, + this.showConfirmButton = true, + this.confirmButtonText = '提交', + this.isConfirmButtonEnabled, + this.iconClickCallback, + this.inputTextChangeCallback, + this.tagSelectCallback, + }); +} + +/// 评价组件类型 +enum BrnAppraiseType { + /// 表情包评价组件 + emoji, + + /// 星星评价组件 + star, +} diff --git a/lib/src/components/appraise/brn_appraise_emoji_item.dart b/lib/src/components/appraise/brn_appraise_emoji_item.dart index b3867c82..e6e19e0e 100644 --- a/lib/src/components/appraise/brn_appraise_emoji_item.dart +++ b/lib/src/components/appraise/brn_appraise_emoji_item.dart @@ -18,34 +18,36 @@ class BrnAppraiseEmojiItem extends StatefulWidget { /// 默认图片,传入asserts/image 全路径 final String defaultName; - /// 表情所在的index + /// 表情所在的 index final int index; - /// 选中的的index + /// 选中的的 index final int selectedIndex; /// 表情图片下面的说明 - final String title; + final String? title; - /// 加载的gif图帧数 + /// 加载的 gif 图帧数,默认 24 final double frameCount; /// 点击的回调 - final BrnAppraiseEmojiClickCallback onTap; + final BrnAppraiseEmojiClickCallback? onTap; - /// item的padding + /// item的padding,默认 EdgeInsets.only(horizontal: 7) final EdgeInsets padding; BrnAppraiseEmojiItem( - {this.selectedName, - this.unselectedName, - this.defaultName, - this.index, - this.selectedIndex, + {Key? key, + required this.selectedName, + required this.unselectedName, + required this.defaultName, + this.index = 0, + this.selectedIndex = -1, this.title, this.frameCount = 24, this.onTap, - this.padding}); + this.padding = const EdgeInsets.symmetric(horizontal: 7)}) + : super(key: key); @override _BrnAppraiseEmojiItemState createState() => _BrnAppraiseEmojiItemState(); @@ -53,11 +55,11 @@ class BrnAppraiseEmojiItem extends StatefulWidget { class _BrnAppraiseEmojiItemState extends State with SingleTickerProviderStateMixin { - AnimationController _controller; + late AnimationController _controller; - int _selectedIndex; + int _selectedIndex = -1; - GifImage _gif; + late GifImage _gif; @override void initState() { @@ -94,7 +96,7 @@ class _BrnAppraiseEmojiItemState extends State Widget build(BuildContext context) { return GestureDetector( child: Padding( - padding: widget.padding ?? EdgeInsets.only(left: 7, right: 7), + padding: widget.padding, child: Column( mainAxisSize: MainAxisSize.min, children: [ @@ -118,7 +120,7 @@ class _BrnAppraiseEmojiItemState extends State onTap: () { if (_selectedIndex != widget.index) { if (widget.onTap != null) { - widget.onTap(widget.index); + widget.onTap!(widget.index); } _selectedIndex = widget.index; _reset(); diff --git a/lib/src/components/appraise/brn_appraise_emoji_list_view.dart b/lib/src/components/appraise/brn_appraise_emoji_list_view.dart index 52c1cf75..93ef8d1d 100644 --- a/lib/src/components/appraise/brn_appraise_emoji_list_view.dart +++ b/lib/src/components/appraise/brn_appraise_emoji_list_view.dart @@ -1,7 +1,7 @@ -import 'package:bruno/src/components/appraise/brn_appraise.dart'; import 'package:bruno/src/components/appraise/brn_appraise_emoji_item.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:flutter/material.dart'; +import 'package:bruno/src/components/appraise/brn_appraise_interface.dart'; /// 描述: 表情评价列表 /// 最多支持5个表情,默认也是5个,支持选择任意个数, @@ -15,16 +15,18 @@ class BrnAppraiseEmojiListView extends StatefulWidget { final List titles; /// 点击回调 - final BrnAppraiseIconClick onTap; + final BrnAppraiseIconClick? onTap; static const List _defaultTitles = ['不好', '还行', '满意', '很棒', '超惊喜']; BrnAppraiseEmojiListView( - {this.indexes = const [0, 1, 2, 3, 4], + {Key? key, + this.indexes = const [0, 1, 2, 3, 4], this.titles = _defaultTitles, this.onTap}) - : assert((indexes?.length ?? 0) > 0), - assert(titles?.length == 5); + : assert(indexes.length > 0), + assert(titles.length == 5), + super(key: key); @override _BrnAppraiseEmojiListViewState createState() => @@ -34,40 +36,40 @@ class BrnAppraiseEmojiListView extends StatefulWidget { class _BrnAppraiseEmojiListViewState extends State { /// 未选中表情,灰色 List _unselectedIcons = [ - BrnAsset.ICON_APPRAISE_BAD_UNSELECTED, - BrnAsset.ICON_APPRAISE_NOT_GOOD_UNSELECTED, - BrnAsset.ICON_APPRAISE_OK_UNSELECTED, - BrnAsset.ICON_APPRAISE_GOOD_UNSELECTED, - BrnAsset.ICON_APPRAISE_SURPRISE_UNSELECTED, + BrnAsset.iconAppraiseBadUnselected, + BrnAsset.iconAppraiseNotGoodUnselected, + BrnAsset.iconAppraiseOkUnselected, + BrnAsset.iconAppraiseGoodUnselected, + BrnAsset.iconAppraiseSurpriseUnselected, ]; /// 默认表情,黄色 List _defaultIcons = [ - BrnAsset.ICON_APPRAISE_BAD_DEFAULT, - BrnAsset.ICON_APPRAISE_NOT_GOOD_DEFAULT, - BrnAsset.ICON_APPRAISE_OK_DEFAULT, - BrnAsset.ICON_APPRAISE_GOOD_DEFAULT, - BrnAsset.ICON_APPRAISE_SURPRISE_DEFAULT, + BrnAsset.iconAppraiseBadDefault, + BrnAsset.iconAppraiseNotGoodDefault, + BrnAsset.iconAppraiseOkDefault, + BrnAsset.iconAppraiseGoodDefault, + BrnAsset.iconAppraiseSurpriseDefault, ]; /// 选中表情,gif List _selectedIcons = [ - BrnAsset.ICON_APPRAISE_BAD_SELECTED, - BrnAsset.ICON_APPRAISE_NOT_GOOD_SELECTED, - BrnAsset.ICON_APPRAISE_OK_SELECTED, - BrnAsset.ICON_APPRAISE_GOOD_SELECTED, - BrnAsset.ICON_APPRAISE_SURPRISE_SELECTED, + BrnAsset.iconAppraiseBadSelected, + BrnAsset.iconAppraiseNotGoodSelected, + BrnAsset.iconAppraiseOkSelected, + BrnAsset.iconAppraiseGoodSelected, + BrnAsset.iconAppraiseSurpriseSelected, ]; int _selectedIndex = -1; @override Widget build(BuildContext context) { - if (widget.indexes?.isEmpty ?? true) { + if (widget.indexes.isEmpty) { return Container(); } - List list = List(); + List list = []; for (int i = 0; i < widget.indexes.length; i++) { list.add(BrnAppraiseEmojiItem( selectedName: _selectedIcons[widget.indexes[i]], @@ -81,7 +83,7 @@ class _BrnAppraiseEmojiListViewState extends State { onTap: (index) { _selectedIndex = index; if (widget.onTap != null) { - widget.onTap(index); + widget.onTap!(_selectedIndex); } }, )); diff --git a/lib/src/components/appraise/brn_appraise_header.dart b/lib/src/components/appraise/brn_appraise_header.dart index 065962a4..252a0344 100644 --- a/lib/src/components/appraise/brn_appraise_header.dart +++ b/lib/src/components/appraise/brn_appraise_header.dart @@ -1,37 +1,39 @@ -import 'package:bruno/src/components/appraise/brn_appraise.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; +import 'package:bruno/src/components/appraise/brn_appraise_interface.dart'; /// 描述: 评价组件title - class BrnAppraiseHeader extends StatelessWidget { - /// 是否显示标题 + /// 是否显示标题,默认为 true,显示 final bool showHeader; - /// 标题文字 + /// 标题文字,默认 '' final String title; - /// 标题最大行数 + /// 标题最大行数,默认为 1 final int maxLines; - /// 标题类型 + /// 标题类型,默认 [BrnAppraiseHeaderType.spaceBetween] final BrnAppraiseHeaderType headerType; - /// 标题的padding - final EdgeInsets headPadding; + /// 标题的 padding,为 null 时为默认 padding。 + /// headerType 为 spaceBetween 时默认为 EdgeInsets.only(left: 20, top: 16, right: 16, bottom: 20) + /// headerType 为 center 时默认为 EdgeInsets.only(top: 20, bottom: 20) + final EdgeInsets? headPadding; /// 点击关闭的回掉 - final BrnAppraiseCloseClickCallBack cancelCallBack; + final BrnAppraiseCloseClickCallBack? cancelCallBack; BrnAppraiseHeader( - {this.showHeader = true, + {Key? key, + this.showHeader = true, this.title = '', this.maxLines = 1, this.headerType = BrnAppraiseHeaderType.spaceBetween, this.headPadding, - this.cancelCallBack}); + this.cancelCallBack}) : super(key: key); @override Widget build(BuildContext context) { @@ -42,16 +44,16 @@ class BrnAppraiseHeader extends StatelessWidget { return _centerHeader(); } } - return Container(); + return SizedBox.shrink(); } Widget _centerHeader() { return Container( color: Colors.white, - padding: headPadding ?? EdgeInsets.only(top: 20, bottom: 20), + padding: headPadding ?? const EdgeInsets.only(top: 20, bottom: 20), child: Text( - title ?? '', - maxLines: maxLines ?? 1, + title, + maxLines: maxLines, style: TextStyle( color: BrnThemeConfigurator.instance .getConfig() @@ -67,7 +69,7 @@ class BrnAppraiseHeader extends StatelessWidget { Widget _spaceHeader(BuildContext context) { return Container( color: Colors.white, - height: 38 + (maxLines ?? 1) * 22.0, + height: 38 + maxLines * 22.0, child: Padding( padding: headPadding ?? EdgeInsets.only(left: 20, top: 16, right: 16, bottom: 20), @@ -79,8 +81,8 @@ class BrnAppraiseHeader extends StatelessWidget { child: Padding( padding: EdgeInsets.only(top: 4, right: 12), child: Text( - title ?? '', - maxLines: maxLines ?? 1, + title, + maxLines: maxLines, style: TextStyle( color: BrnThemeConfigurator.instance .getConfig() @@ -96,11 +98,11 @@ class BrnAppraiseHeader extends StatelessWidget { InkWell( onTap: () { if (cancelCallBack != null) { - cancelCallBack(context); + cancelCallBack!(context); } Navigator.of(context).pop(); }, - child: BrunoTools.getAssetImage(BrnAsset.ICON_PICKER_CLOSE), + child: BrunoTools.getAssetImage(BrnAsset.iconPickerClose), ), ], ), diff --git a/lib/src/components/appraise/brn_appraise_interface.dart b/lib/src/components/appraise/brn_appraise_interface.dart new file mode 100644 index 00000000..f3b70cb2 --- /dev/null +++ b/lib/src/components/appraise/brn_appraise_interface.dart @@ -0,0 +1,19 @@ +import 'package:flutter/material.dart'; + +/// 点击表情或者星星时的回调 +/// index 点击的表情或者星星的index +typedef BrnAppraiseIconClick = void Function(int index); + +/// 点击tag的回调 +/// selectedTags 所有选中标签的集合 +typedef BrnAppraiseTagClick = void Function(List selectedTags); + +/// 提交按钮点击事件回调 +/// index 选中的表情或者星星的index +/// selectedTags 所有选中标签的集合 +/// input 自定义输入的内容 +typedef BrnAppraiseConfirmClick = void Function( + int index, List selectedTags, String input); + +/// 点击关闭的回掉 +typedef BrnAppraiseCloseClickCallBack = void Function(BuildContext context); \ No newline at end of file diff --git a/lib/src/components/appraise/brn_appraise_star_list_view.dart b/lib/src/components/appraise/brn_appraise_star_list_view.dart index c4aef940..9859a9ee 100644 --- a/lib/src/components/appraise/brn_appraise_star_list_view.dart +++ b/lib/src/components/appraise/brn_appraise_star_list_view.dart @@ -1,4 +1,3 @@ -import 'package:bruno/src/components/appraise/brn_appraise.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; @@ -11,17 +10,19 @@ class BrnAppraiseStarListView extends StatefulWidget { final int count; /// 未选中时的提示 - final String hint; + final String? hint; /// 星星下面的文案,点击对应的星星会显示相应index的文案,titles长度不能比count小 final List titles; /// 点击回调 - final BrnAppraiseIconClick onTap; + final ValueChanged? onTap; - BrnAppraiseStarListView({this.count = 5, this.titles, this.hint, this.onTap}) + BrnAppraiseStarListView( + {Key? key, this.count = 5, required this.titles, this.hint, this.onTap}) : assert(count > 0 && count <= 5), - assert(titles == null || titles.length >= count); + assert(titles.length >= count), + super(key: key); @override _BrnAppraiseStarListViewState createState() => @@ -39,11 +40,11 @@ class _BrnAppraiseStarListViewState extends State { @override Widget build(BuildContext context) { - if (widget.titles?.isEmpty ?? true) { + if (widget.titles.isEmpty) { return _buildStars(); } else { Widget subWidget = Container(); - String subTitle = widget.hint; + String? subTitle = widget.hint; if (_selectedIndex >= 0 && _selectedIndex < widget.titles.length) { subTitle = widget.titles[_selectedIndex]; } @@ -72,7 +73,7 @@ class _BrnAppraiseStarListViewState extends State { } Widget _buildStars() { - List list = List(); + List list = []; for (int i = 0; i < widget.count; i++) { Widget item = GestureDetector( child: Padding( @@ -81,7 +82,7 @@ class _BrnAppraiseStarListViewState extends State { ), onTap: () { if (widget.onTap != null) { - widget.onTap(i); + widget.onTap!(i); } _selectedIndex = i; }, diff --git a/lib/src/components/appraise/brn_flutter_gif_image.dart b/lib/src/components/appraise/brn_flutter_gif_image.dart index efa21010..cd624bba 100644 --- a/lib/src/components/appraise/brn_flutter_gif_image.dart +++ b/lib/src/components/appraise/brn_flutter_gif_image.dart @@ -1,7 +1,6 @@ import 'dart:ui' as ui show Codec; import 'dart:ui'; -import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; /// 描述: 用于加载gif图, @@ -9,26 +8,26 @@ import 'package:flutter/widgets.dart'; /// 感谢 Jpeng class GifImage extends StatefulWidget { - final VoidCallback onFetchCompleted; + final VoidCallback? onFetchCompleted; final AnimationController controller; final ImageProvider image; - final double width; - final double height; - final Color color; - final BlendMode colorBlendMode; - final BoxFit fit; + final double? width; + final double? height; + final Color? color; + final BlendMode? colorBlendMode; + final BoxFit? fit; final AlignmentGeometry alignment; final ImageRepeat repeat; - final Rect centerSlice; + final Rect? centerSlice; final bool matchTextDirection; final bool gaplessPlayback; - final String semanticLabel; + final String? semanticLabel; final bool excludeFromSemantics; - final Widget defaultImage; + final Widget? defaultImage; GifImage({ - @required this.image, - @required this.controller, + required this.image, + required this.controller, this.semanticLabel, this.excludeFromSemantics = false, this.width, @@ -50,8 +49,7 @@ class GifImage extends StatefulWidget { } class GifImageState extends State { - ValueNotifier> _images = - ValueNotifier>(List()); + ValueNotifier> _images = ValueNotifier>([]); double _curValue = 0.0; @override @@ -80,7 +78,7 @@ class GifImageState extends State { return ValueListenableBuilder( ///数据发生变化时回调 builder: (context, value, child) { - return _buildImage(value); + return _buildImage(value as List); }, ///监听的数据 @@ -88,19 +86,19 @@ class GifImageState extends State { ); } - Widget _buildImage(List imageInfo) { + Widget _buildImage(List? imageInfo) { int length = (imageInfo?.length ?? 0); int _curIndex = (_curValue * length).toInt(); int index = -1; if (length > 0) { index = length == _curIndex ? length - 1 : _curIndex; } - if (index != -1 && imageInfo[index]?.image != null) { + if (index != -1 && imageInfo?[index].image != null) { RawImage _image = RawImage( - image: imageInfo[index].image, + image: imageInfo?[index].image, width: widget.width, height: widget.height, - scale: imageInfo[index]?.scale ?? 1.0, + scale: imageInfo?[index].scale ?? 1.0, color: widget.color, colorBlendMode: widget.colorBlendMode, fit: widget.fit, @@ -124,17 +122,17 @@ class GifImageState extends State { } Future fetchGif(ImageProvider provider) async { - List infos = List(); - dynamic data; - - AssetBundleImageKey key = await provider.obtainKey(ImageConfiguration()); - data = await key.bundle.load(key.name); - - ui.Codec codec = await PaintingBinding.instance - .instantiateImageCodec(data.buffer.asUint8List()); - for (int i = 0; i < codec.frameCount; i++) { - FrameInfo frameInfo = await codec.getNextFrame(); - infos.add(ImageInfo(image: frameInfo.image)); + List infos = []; + if (provider is AssetImage) { + dynamic data; + AssetBundleImageKey key = await provider.obtainKey(ImageConfiguration()); + data = await key.bundle.load(key.name); + ui.Codec codec = await PaintingBinding.instance! + .instantiateImageCodec(data.buffer.asUint8List()); + for (int i = 0; i < codec.frameCount; i++) { + FrameInfo frameInfo = await codec.getNextFrame(); + infos.add(ImageInfo(image: frameInfo.image)); + } } _images.value = infos; } diff --git a/lib/src/components/appraise/brn_mulit_select_tags.dart b/lib/src/components/appraise/brn_mulit_select_tags.dart index 3d463c82..495db92f 100644 --- a/lib/src/components/appraise/brn_mulit_select_tags.dart +++ b/lib/src/components/appraise/brn_mulit_select_tags.dart @@ -23,12 +23,12 @@ typedef BrnMultiSelectedTagsCallback = void Function( class BrnMultiSelectTags extends StatefulWidget { ///当点击到最大数目时的点击事件 - final VoidCallback onMaxSelectClick; + final VoidCallback? onMaxSelectClick; - ///一行多少个数据 + ///一行多少个数据,默认 2 final int brnCrossAxisCount; - ///最多选择多少个item - 默认可以无限选 + ///最多选择多少个item - 默认0,可以无限选 final int maxSelectItemCount; /// 本类属性 @@ -38,12 +38,12 @@ class BrnMultiSelectTags extends StatefulWidget { final BrnMultiSelectTagText tagText; /// 已选中列表 - final BrnMultiSelectedTagsCallback selectedTagsCallback; + final BrnMultiSelectedTagsCallback? selectedTagsCallback; /// 没有数据时的样式 - final Widget emptyWidget; + final Widget? emptyWidget; - /// 没有数据时的样式 + /// 没有数据时的样式,如果为 null,默认 EdgeInsets.only(top: 0.0, left: 20.0, right: 20.0, bottom: 0.0) final EdgeInsets padding; ///是等分样式还是流式布局样式 默认等分 @@ -53,25 +53,26 @@ class BrnMultiSelectTags extends StatefulWidget { final bool multiSelect; /// 滑动选项 - final ScrollPhysics physics; + final ScrollPhysics? physics; - /// 最小宽度 + /// 最小宽度,默认 75 final double minWidth; BrnMultiSelectTags({ - @required this.tagPickerBean, - @required this.tagText, + Key? key, + required this.tagPickerBean, + required this.tagText, this.onMaxSelectClick, this.maxSelectItemCount = 0, - this.brnCrossAxisCount, + this.brnCrossAxisCount = 2, this.tagStyle = BrnMultiSelectStyle.average, this.selectedTagsCallback, this.emptyWidget, - this.padding, + this.padding = const EdgeInsets.symmetric(horizontal: 20), this.multiSelect = true, this.physics, - this.minWidth, - }); + this.minWidth = 75, + }) : super(key: key); @override _BrnMultiSelectTagsState createState() => _BrnMultiSelectTagsState(); @@ -79,8 +80,8 @@ class BrnMultiSelectTags extends StatefulWidget { class _BrnMultiSelectTagsState extends State { /// 操作类型属性 - List _selectedTags; - List _sourceTags; + List _selectedTags = []; + List _sourceTags = []; @override void initState() { @@ -90,7 +91,7 @@ class _BrnMultiSelectTagsState extends State { @override Widget build(BuildContext context) { - if (widget.tagPickerBean?.tagItemSource?.isNotEmpty ?? false) { + if (widget.tagPickerBean.tagItemSource.isNotEmpty) { return _buildContent(context); } else { return widget.emptyWidget ?? @@ -113,7 +114,7 @@ class _BrnMultiSelectTagsState extends State { ///等宽度的布局 Widget _buildGridViewWidget(BuildContext context) { - int brnCrossAxisCount = widget.brnCrossAxisCount ?? 2; + int brnCrossAxisCount = widget.brnCrossAxisCount; double width = (MediaQuery.of(context).size.width - (brnCrossAxisCount - 1) * 12 - 40) / @@ -122,8 +123,7 @@ class _BrnMultiSelectTagsState extends State { double brnChildAspectRatio = width / 34.0; return Container( - padding: widget.padding ?? - EdgeInsets.only(top: 0.0, left: 20.0, right: 20.0, bottom: 0.0), + padding: widget.padding, constraints: BoxConstraints(maxHeight: 322, minHeight: 120), child: GridView.count( shrinkWrap: true, @@ -146,7 +146,7 @@ class _BrnMultiSelectTagsState extends State { ///流式布局 Widget _buildWrapViewWidget(BuildContext context) { return Container( - padding: widget.padding ?? EdgeInsets.symmetric(horizontal: 20), + padding: widget.padding, child: Wrap( spacing: 12, runSpacing: 12, @@ -158,8 +158,8 @@ class _BrnMultiSelectTagsState extends State { } void _dataSetup() { - List tagItems = List(); - List tagSelectItems = List(); + List tagItems = []; + List tagSelectItems = []; for (BrnTagItemBean item in widget.tagPickerBean.tagItemSource) { tagItems.add(item); //选中的按钮 @@ -176,14 +176,14 @@ class _BrnMultiSelectTagsState extends State { void _clickTag(bool selected, BrnTagItemBean tagName) { if (!widget.multiSelect) { /// 单选 - _sourceTags?.forEach((tag) { + _sourceTags.forEach((tag) { tag.isSelect = false; }); - _selectedTags?.clear(); + _selectedTags.clear(); tagName.isSelect = true; _selectedTags.add(tagName); if (widget.selectedTagsCallback != null) { - widget.selectedTagsCallback(_selectedTags); + widget.selectedTagsCallback!(_selectedTags); } } else { /// 多选 @@ -195,7 +195,7 @@ class _BrnMultiSelectTagsState extends State { _selectedTags.remove(tagName); } if (widget.selectedTagsCallback != null) { - widget.selectedTagsCallback(_selectedTags); + widget.selectedTagsCallback!(_selectedTags); } } } @@ -226,7 +226,7 @@ class _BrnMultiSelectTagsState extends State { setState(() {}); }, child: Container( - constraints: BoxConstraints(minWidth: widget.minWidth ?? 75), + constraints: BoxConstraints(minWidth: widget.minWidth), decoration: BoxDecoration( color: bgColor, borderRadius: BorderRadius.circular(3.0)), padding: padding, diff --git a/lib/src/components/button/brn_big_ghost_button.dart b/lib/src/components/button/brn_big_ghost_button.dart index 9722e302..c75d2369 100644 --- a/lib/src/components/button/brn_big_ghost_button.dart +++ b/lib/src/components/button/brn_big_ghost_button.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/button/brn_normal_button.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; @@ -17,31 +19,25 @@ import 'package:flutter/material.dart'; /// * [BrnBigMainButton], 大主色调按钮 /// * [BrnBigOutlineButton], 大边框按钮 -/// 默认水平间距 -const double _BHorizontalPadding = 16; - -/// 默认垂直间距 -const double _BVerticalPadding = 8; - class BrnBigGhostButton extends StatelessWidget { ///按钮文案,默认'确认' final String title; ///文案颜色 - final Color titleColor; + final Color? titleColor; ///按钮背景颜色 - final Color bgColor; + final Color? bgColor; ///点击回调 - final VoidCallback onTap; + final VoidCallback? onTap; ///默认父布局可用空间 - final double width; - final BrnButtonConfig themeData; + final double? width; + final BrnButtonConfig? themeData; const BrnBigGhostButton({ - Key key, + Key? key, this.title = '确认', this.titleColor, this.bgColor, @@ -55,8 +51,7 @@ class BrnBigGhostButton extends StatelessWidget { BrnButtonConfig defaultThemeConfig = themeData ?? BrnButtonConfig(); defaultThemeConfig = BrnThemeConfigurator.instance .getConfig(configId: defaultThemeConfig.configId) - .buttonConfig - .merge(defaultThemeConfig); + .buttonConfig.merge(defaultThemeConfig); return BrnNormalButton( borderRadius: BorderRadius.circular(defaultThemeConfig.bigButtonRadius), @@ -67,11 +62,9 @@ class BrnBigGhostButton extends StatelessWidget { defaultThemeConfig.commonConfig.brandPrimary.withOpacity(0.05), onTap: onTap, alignment: Alignment.center, - text: title ?? '确认', + text: title, textColor: titleColor ?? defaultThemeConfig.commonConfig.brandPrimary, fontSize: defaultThemeConfig.bigButtonFontSize, - insertPadding: EdgeInsets.symmetric( - vertical: _BVerticalPadding, horizontal: _BHorizontalPadding), ); } } diff --git a/lib/src/components/button/brn_big_main_button.dart b/lib/src/components/button/brn_big_main_button.dart index 3077bc6d..26e5b8cd 100644 --- a/lib/src/components/button/brn_big_main_button.dart +++ b/lib/src/components/button/brn_big_main_button.dart @@ -1,6 +1,6 @@ -import 'package:bruno/bruno.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; +import 'brn_normal_button.dart'; /// 页面中的主按钮,支持动态设置背景颜色,置灰 /// @@ -27,12 +27,6 @@ import 'package:flutter/material.dart'; /// * [BrnBigGhostButton], 大主色调的幽灵按钮 /// * [BrnBigOutlineButton], 大边框按钮 -/// 默认水平间距 -const double _BHorizontalPadding = 16; - -/// 默认垂直间距 -const double _BVerticalPadding = 8; - class BrnBigMainButton extends StatelessWidget { ///按钮显示文案,默认'确认' final String title; @@ -41,18 +35,18 @@ class BrnBigMainButton extends StatelessWidget { final bool isEnable; ///点击回调 - final VoidCallback onTap; + final VoidCallback? onTap; ///默认父布局可用空间 - final double width; + final double? width; ///背景颜色 - final Color bgColor; + final Color? bgColor; - final BrnButtonConfig themeData; + final BrnButtonConfig? themeData; const BrnBigMainButton({ - Key key, + Key? key, this.title = '确认', this.width, this.isEnable = true, @@ -67,24 +61,21 @@ class BrnBigMainButton extends StatelessWidget { defaultThemeConfig = BrnThemeConfigurator.instance .getConfig(configId: defaultThemeConfig.configId) - .buttonConfig - .merge(defaultThemeConfig); + .buttonConfig.merge(defaultThemeConfig); return BrnNormalButton( constraints: BoxConstraints.tightFor( width: width ?? double.infinity, height: defaultThemeConfig.bigButtonHeight), alignment: Alignment.center, - isEnable: isEnable ?? true, - text: title ?? '确认', + isEnable: isEnable, + text: title, backgroundColor: bgColor ?? defaultThemeConfig.commonConfig.brandPrimary, disableBackgroundColor: Color(0xFFCCCCCC), onTap: onTap, textColor: Colors.white, disableTextColor: defaultThemeConfig.commonConfig.colorTextBaseInverse.withOpacity(0.7), - insertPadding: EdgeInsets.symmetric( - horizontal: _BHorizontalPadding, vertical: _BVerticalPadding), ); } } diff --git a/lib/src/components/button/brn_big_outline_button.dart b/lib/src/components/button/brn_big_outline_button.dart index 9940fe9d..b6b6804d 100644 --- a/lib/src/components/button/brn_big_outline_button.dart +++ b/lib/src/components/button/brn_big_outline_button.dart @@ -1,7 +1,8 @@ + + import 'package:bruno/src/components/button/brn_big_ghost_button.dart'; import 'package:bruno/src/components/button/brn_normal_button.dart'; import 'package:bruno/src/theme/brn_theme.dart'; -import 'package:bruno/src/utils/brn_multi_click_util.dart'; import 'package:flutter/material.dart'; /// 页面的边框按钮,没有背景颜色,占据父节点分配的最大空间 @@ -27,12 +28,6 @@ import 'package:flutter/material.dart'; /// * [BrnBigGhostButton], 大幽灵按钮 /// -/// 默认水平间距 -const double _BHorizontalPadding = 16; - -/// 默认垂直间距 -const double _BVerticalPadding = 8; - /// 默认线宽 const double _BBorderWith = 1; @@ -41,23 +36,23 @@ class BrnBigOutlineButton extends StatelessWidget { final String title; ///边框的颜色 - final Color lineColor; + final Color? lineColor; ///点击回调 - final VoidCallback onTap; + final VoidCallback? onTap; ///显示的文案的颜色 - final Color textColor; + final Color? textColor; ///是否可用,默认为true。false为不可用:置灰、不可点击。 final bool isEnable; ///默认父布局可用空间 - final double width; - final BrnButtonConfig themeData; + final double? width; + final BrnButtonConfig? themeData; const BrnBigOutlineButton({ - Key key, + Key? key, this.title = '确认', this.lineColor, this.textColor, @@ -73,16 +68,15 @@ class BrnBigOutlineButton extends StatelessWidget { defaultThemeConfig = BrnThemeConfigurator.instance .getConfig(configId: defaultThemeConfig.configId) - .buttonConfig - .merge(defaultThemeConfig); + .buttonConfig.merge(defaultThemeConfig); - Color _lineColor = + Color? _lineColor = lineColor ?? defaultThemeConfig.commonConfig.borderColorBase; return BrnNormalButton.outline( borderWith: _BBorderWith, radius: defaultThemeConfig.bigButtonRadius, - text: title ?? "", + text: title, disableLineColor: _lineColor, lineColor: _lineColor, textColor: textColor ?? defaultThemeConfig.commonConfig.colorTextBase, @@ -95,8 +89,6 @@ class BrnBigOutlineButton extends StatelessWidget { width: width ?? double.infinity, height: defaultThemeConfig.bigButtonHeight), onTap: onTap, - insertPadding: EdgeInsets.symmetric( - vertical: _BVerticalPadding, horizontal: _BHorizontalPadding), backgroundColor: Colors.white, disableBackgroundColor: Color(0xffcccccc).withOpacity(0.1), ); diff --git a/lib/src/components/button/brn_icon_button.dart b/lib/src/components/button/brn_icon_button.dart index e834a3df..57894d43 100644 --- a/lib/src/components/button/brn_icon_button.dart +++ b/lib/src/components/button/brn_icon_button.dart @@ -25,10 +25,10 @@ class BrnIconButton extends StatefulWidget { final String name; /// 需要传的icon - final Widget iconWidget; + final Widget? iconWidget; /// 点击的回调 - final VoidCallback onTap; + final VoidCallback? onTap; /// 文字相对于图片的位置 final Direction direction; @@ -43,7 +43,7 @@ class BrnIconButton extends StatefulWidget { final double fontSize; /// 文字样式 - final TextStyle style; + final TextStyle? style; /// 图文组合的宽度,默认 80 final double widgetWidth; @@ -58,8 +58,8 @@ class BrnIconButton extends StatefulWidget { final MainAxisAlignment mainAxisAlignment; const BrnIconButton({ - Key key, - @required this.name, + Key? key, + required this.name, this.iconWidget, this.onTap, this.iconWidth = 24, @@ -71,7 +71,7 @@ class BrnIconButton extends StatefulWidget { this.padding = 4, this.style, this.mainAxisAlignment = MainAxisAlignment.center, - }); + }): super(key: key); @override _BrnIconButtonState createState() => _BrnIconButtonState(); @@ -85,17 +85,15 @@ class _BrnIconButtonState extends State { // Left、文字在左 icon在右 right、文字在右 icon在左 if (widget.direction == Direction.bottom) { ctn = Container( - height: widget.widgetHeight ?? 80, - width: widget.widgetWidth ?? 80, + height: widget.widgetHeight, + width: widget.widgetWidth, child: Column( mainAxisAlignment: widget.mainAxisAlignment, mainAxisSize: MainAxisSize.min, children: [ // 图片 Container( - height: widget.iconHeight, - width: widget.iconWidth, - child: widget.iconWidget), + height: widget.iconHeight, width: widget.iconWidth, child: widget.iconWidget), Padding( padding: EdgeInsets.only(top: widget.padding), child: Text( @@ -113,16 +111,19 @@ class _BrnIconButtonState extends State { ) ], )); - } else if (widget.direction == Direction.top) { + } else if (widget.direction == Direction.left) { ctn = Container( - height: widget.widgetHeight ?? 80, - width: widget.widgetWidth ?? 80, - child: Column( + height: widget.widgetHeight, + width: widget.widgetWidth, + child: Row( mainAxisAlignment: widget.mainAxisAlignment, mainAxisSize: MainAxisSize.min, children: [ + // 图片 + Container( + height: widget.iconHeight, width: widget.iconWidth, child: widget.iconWidget), Padding( - padding: EdgeInsets.only(bottom: widget.padding), + padding: EdgeInsets.only(left: widget.padding), child: Text( widget.name, style: widget.style ?? @@ -135,31 +136,19 @@ class _BrnIconButtonState extends State { ), overflow: TextOverflow.ellipsis, ), - ), - - // 图片 - Container( - child: widget.iconWidget, - height: widget.iconHeight, - width: widget.iconWidth, - ), + ) ], )); - } else if (widget.direction == Direction.left) { + } else if (widget.direction == Direction.right) { ctn = Container( - height: widget.widgetHeight ?? 80, - width: widget.widgetWidth ?? 80, + height: widget.widgetHeight, + width: widget.widgetWidth, child: Row( mainAxisAlignment: widget.mainAxisAlignment, mainAxisSize: MainAxisSize.min, children: [ - // 图片 - Container( - height: widget.iconHeight, - width: widget.iconWidth, - child: widget.iconWidget), Padding( - padding: EdgeInsets.only(left: widget.padding), + padding: EdgeInsets.only(right: widget.padding), child: Text( widget.name, style: widget.style ?? @@ -172,19 +161,22 @@ class _BrnIconButtonState extends State { ), overflow: TextOverflow.ellipsis, ), - ) + ), + // 图片 + Container( + height: widget.iconHeight, width: widget.iconWidth, child: widget.iconWidget), ], )); - } else if (widget.direction == Direction.right) { + } else { ctn = Container( - height: widget.widgetHeight ?? 80, - width: widget.widgetWidth ?? 80, - child: Row( + height: widget.widgetHeight, + width: widget.widgetWidth, + child: Column( mainAxisAlignment: widget.mainAxisAlignment, mainAxisSize: MainAxisSize.min, children: [ Padding( - padding: EdgeInsets.only(right: widget.padding), + padding: EdgeInsets.only(bottom: widget.padding), child: Text( widget.name, style: widget.style ?? @@ -198,11 +190,13 @@ class _BrnIconButtonState extends State { overflow: TextOverflow.ellipsis, ), ), + // 图片 Container( - height: widget.iconHeight, - width: widget.iconWidth, - child: widget.iconWidget), + child: widget.iconWidget, + height: widget.iconHeight, + width: widget.iconWidth, + ), ], )); } @@ -211,7 +205,7 @@ class _BrnIconButtonState extends State { return GestureDetector( child: ctn, onTap: () { - widget?.onTap(); + widget.onTap!(); }, ); } diff --git a/lib/src/components/button/brn_normal_button.dart b/lib/src/components/button/brn_normal_button.dart index 4cdef410..a5dc4e91 100644 --- a/lib/src/components/button/brn_normal_button.dart +++ b/lib/src/components/button/brn_normal_button.dart @@ -1,4 +1,4 @@ -import 'package:bruno/bruno.dart'; +import 'package:bruno/src/constants/brn_constants.dart'; import 'package:bruno/src/utils/brn_multi_click_util.dart'; import 'package:flutter/material.dart'; @@ -8,8 +8,6 @@ const Color _BBackgroundColor = Color(0xFF0984F9); const Color _BDisableBackgroundColor = Color(0xFFCCCCCC); const FontWeight _BFontWeight = FontWeight.bold; const double _BRadius = 6; -const double _BHorizontalPadding = 16; -const double _BVerticalPadding = 8; /// 通用按钮,支持用户设置背景色、是否可用等属性 /// 若[BrnBigMainButton]、[BrnSmallMainButton]、[BrnBigOutlineButton]不能满足用户需要 @@ -75,7 +73,7 @@ class BrnNormalButton extends StatelessWidget { final bool isEnable; /// 按钮点击的回调 - final VoidCallback onTap; + final VoidCallback? onTap; /// 按钮显示的文案 final String text; @@ -87,25 +85,25 @@ class BrnNormalButton extends StatelessWidget { final double fontSize; /// 按钮不可用的文字颜色 - final Color disableTextColor; - - /// 按钮不可用背景色 默认[_BDisableBackgroundColor] - final Color disableBackgroundColor; + final Color? disableTextColor; /// 按钮背景色 默认[_BBackgroundColor] final Color backgroundColor; + /// 按钮不可用背景色 默认[_BDisableBackgroundColor] + final Color disableBackgroundColor; + /// 按钮内边距 默认水平[_BHorizontalPadding] 垂直[_BVerticalPadding] final EdgeInsetsGeometry insertPadding; /// 按钮的修饰 默认实色背景 - final Decoration decoration; + final Decoration? decoration; /// 按钮的显示子节点 优先级高于[text] - final Widget child; + final Widget? child; /// 按钮的文本显示样式 优先级高于[textColor]等属性 - final TextStyle textStyle; + final TextStyle? textStyle; /// 按钮的文本Weight 默认是[FontWeight.bold] final FontWeight fontWeight; @@ -114,78 +112,82 @@ class BrnNormalButton extends StatelessWidget { final BoxConstraints constraints; /// 按钮的内部对齐 默认为null - final Alignment alignment; + final Alignment? alignment; /// 按钮圆角大小 final BorderRadiusGeometry borderRadius; - BrnNormalButton( - {@required this.text, - this.backgroundColor, - this.isEnable = true, - this.onTap, - this.insertPadding, - this.decoration, - this.child, - this.textStyle, - this.fontWeight, - this.fontSize, - this.textColor, - this.disableTextColor, - this.disableBackgroundColor, - this.constraints, - this.borderRadius, - this.alignment}); + BrnNormalButton({ + Key? key, + required this.text, + this.backgroundColor = _BBackgroundColor, + this.isEnable = true, + this.onTap, + this.insertPadding = const EdgeInsets.symmetric( + vertical: BrnButtonConstant.verticalPadding, + horizontal: BrnButtonConstant.horizontalPadding), + this.decoration, + this.child, + this.textStyle, + this.fontWeight = _BFontWeight, + this.fontSize = _BFontSize, + this.textColor = _BTextColor, + this.disableTextColor, + this.disableBackgroundColor = _BDisableBackgroundColor, + this.constraints = const BoxConstraints.tightFor(), + this.borderRadius = const BorderRadius.all(Radius.circular(_BRadius)), + this.alignment, + }) : super(key: key); BrnNormalButton.outline({ - Color disableLineColor, - Color lineColor, + Key? key, + Color? disableLineColor, + Color? lineColor, double radius = 6, double borderWith = 1.0, - @required this.text, + required this.text, this.isEnable = true, - this.backgroundColor, - this.disableBackgroundColor, + this.backgroundColor = _BBackgroundColor, + this.disableBackgroundColor = _BDisableBackgroundColor, this.alignment, this.child, this.onTap, - this.textColor, - this.fontSize, + this.textColor = _BTextColor, + this.fontWeight = _BFontWeight, + this.fontSize = _BFontSize, this.disableTextColor, - this.insertPadding, + this.insertPadding = const EdgeInsets.symmetric( + vertical: BrnButtonConstant.verticalPadding, + horizontal: BrnButtonConstant.horizontalPadding), this.textStyle, - this.fontWeight, - this.constraints, - this.borderRadius, - }) : decoration = _OutlineBoxDecorationCreator.createOutlineBoxDecoration( + this.constraints = const BoxConstraints.tightFor(), + this.borderRadius = const BorderRadius.all(Radius.circular(_BRadius)), + }) : decoration = _OutlineBoxDecorationCreator.createOutlineBoxDecoration( isEnable: isEnable, disableBackgroundColor: disableBackgroundColor, disableLineColor: disableLineColor, lineColor: lineColor, backgroundColor: backgroundColor, radius: radius, - borderWith: borderWith); + borderWith: borderWith), + super(key: key); @override Widget build(BuildContext context) { - Color bgColor = _getBackgroundColor(); - return GestureDetector( onTap: () { if (BrnMultiClickUtils.isMultiClick()) { return; } if (isEnable && onTap != null) { - onTap(); + onTap!(); } }, child: Container( alignment: alignment, - decoration: decoration ?? _getBoxDecoration(bgColor), - constraints: constraints ?? BoxConstraints.tightFor(), - padding: insertPadding ?? - EdgeInsets.symmetric( - vertical: _BVerticalPadding, horizontal: _BHorizontalPadding), + decoration: decoration ?? _getBoxDecoration(_getBackgroundColor()), + constraints: constraints, + padding: insertPadding, child: child ?? Text( text, @@ -199,62 +201,45 @@ class BrnNormalButton extends StatelessWidget { TextStyle _getTextStyle() { if (textStyle != null) { - return textStyle; + return textStyle!; } Color textColor; if (isEnable) { textColor = this.textColor; - if (textColor == null) { - textColor = _BTextColor; - } } else { - textColor = this.disableTextColor; - if (textColor == null) { - textColor = (this.textColor ?? _BTextColor).withOpacity(0.7); - } + textColor = this.disableTextColor ?? (this.textColor).withOpacity(0.7); } return TextStyle( - fontSize: fontSize ?? _BFontSize, + fontSize: fontSize, color: textColor, - fontWeight: fontWeight ?? _BFontWeight, + fontWeight: fontWeight, ); } Color _getBackgroundColor() { - Color bgColor; - if (isEnable) { - bgColor = backgroundColor; - if (bgColor == null) { - bgColor = _BBackgroundColor; - } - } else { - bgColor = disableBackgroundColor; - if (bgColor == null) { - bgColor = _BDisableBackgroundColor; - } - } - return bgColor; + return isEnable ? backgroundColor : disableBackgroundColor; } - BoxDecoration _getBoxDecoration(Color bgColor) { + BoxDecoration _getBoxDecoration(Color? bgColor) { return BoxDecoration( color: bgColor, - borderRadius: borderRadius ?? BorderRadius.all(Radius.circular(_BRadius)), + borderRadius: borderRadius, ); } } class _OutlineBoxDecorationCreator { - static BoxDecoration createOutlineBoxDecoration( - {bool isEnable, - Color disableLineColor, - Color lineColor, - Color disableBackgroundColor, - Color backgroundColor, - double radius = 6, - double borderWith = 1.0}) { - Color _lineColor = isEnable ? lineColor : disableLineColor; + static BoxDecoration createOutlineBoxDecoration({ + required bool isEnable, + Color? disableLineColor, + Color? lineColor, + required Color backgroundColor, + required Color disableBackgroundColor, + double radius = 6, + double borderWith = 1.0, + }) { + Color _lineColor = isEnable ? lineColor! : disableLineColor!; Color _bgColor = isEnable ? backgroundColor : disableBackgroundColor; return BoxDecoration( diff --git a/lib/src/components/button/brn_small_main_button.dart b/lib/src/components/button/brn_small_main_button.dart index 93801488..4bb05cec 100644 --- a/lib/src/components/button/brn_small_main_button.dart +++ b/lib/src/components/button/brn_small_main_button.dart @@ -1,6 +1,7 @@ import 'dart:math'; import 'package:bruno/src/components/button/brn_normal_button.dart'; +import 'package:bruno/src/constants/brn_constants.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; @@ -20,12 +21,6 @@ import 'package:flutter/material.dart'; /// /// -/// 默认水平间距 -const double _BHorizontalPadding = 6; - -/// 默认垂直间距 -const double _BVerticalPadding = 8; - /// 默认最小宽度 const double _BMinWidth = 84; @@ -34,63 +29,63 @@ class BrnSmallMainButton extends StatelessWidget { final String title; ///点击回调 - final VoidCallback onTap; + final VoidCallback? onTap; ///是否可用,默认为true。false为不可用:置灰、不可点击。 final bool isEnable; + final Color? bgColor; final Color textColor; - final Color bgColor; - final double radius; final FontWeight fontWeight; - final double fontSize; - final double maxWidth; - final double width; + final double? fontSize; + final double? radius; + final double? maxWidth; + final double? width; /// 配置样式 - final BrnButtonConfig themeData; + final BrnButtonConfig? themeData; /// 传入属性优先级最高,未传入的走默认配置,更多请看[BrnSmallMainButtonConfig.defaultConfig] const BrnSmallMainButton({ + Key? key, this.title = '确认', this.onTap, this.isEnable = true, - this.textColor, this.bgColor, - this.fontWeight, + this.textColor = Colors.white, + this.fontWeight = FontWeight.w600, this.fontSize, this.radius, this.maxWidth, this.width, this.themeData, - }); + }): super(key: key); @override Widget build(BuildContext context) { BrnButtonConfig defaultThemeConfig = themeData ?? BrnButtonConfig(); - defaultThemeConfig = defaultThemeConfig.merge(BrnButtonConfig( - smallButtonFontSize: fontSize, smallButtonRadius: radius)); + defaultThemeConfig = defaultThemeConfig + .merge(BrnButtonConfig(smallButtonFontSize: fontSize, smallButtonRadius: radius)); defaultThemeConfig = BrnThemeConfigurator.instance .getConfig(configId: defaultThemeConfig.configId) .buttonConfig .merge(defaultThemeConfig); - TextPainter textPainter = - TextPainter(textScaleFactor: MediaQuery.of(context).textScaleFactor); + TextPainter textPainter = TextPainter(textScaleFactor: MediaQuery.of(context).textScaleFactor); return LayoutBuilder( builder: (_, con) { TextStyle style = TextStyle( fontSize: defaultThemeConfig.smallButtonFontSize, - fontWeight: fontWeight ?? FontWeight.w600, - color: textColor ?? Colors.white, + fontWeight: fontWeight, + color: textColor, ); textPainter.textDirection = TextDirection.ltr; textPainter.text = TextSpan(text: title, style: style); textPainter.layout(maxWidth: con.maxWidth); double textWidth = textPainter.width; //按钮本身大小 - double _maxWidth = textWidth + _BHorizontalPadding * 2; + double _maxWidth = textWidth + BrnButtonConstant.horizontalPadding * 2; double _minWidth = min(_BMinWidth, con.maxWidth); //保证最小宽度是 (84、可用空间)的最小值 @@ -99,8 +94,8 @@ class BrnSmallMainButton extends StatelessWidget { } else { //外部要求最大宽度 if (maxWidth != null) { - if (_maxWidth > maxWidth) { - _maxWidth = maxWidth; + if (_maxWidth > maxWidth!) { + _maxWidth = maxWidth!; } } } @@ -110,22 +105,18 @@ class BrnSmallMainButton extends StatelessWidget { } return BrnNormalButton( - isEnable: isEnable ?? true, + isEnable: isEnable, constraints: BoxConstraints( minWidth: this.width ?? _minWidth, maxWidth: this.width ?? _maxWidth, ), alignment: Alignment.center, - text: title ?? '确认', - backgroundColor: - bgColor ?? defaultThemeConfig.commonConfig.brandPrimary, + text: title, + backgroundColor: bgColor ?? defaultThemeConfig.commonConfig.brandPrimary, disableBackgroundColor: Color(0xFFCCCCCC), - borderRadius: BorderRadius.all( - Radius.circular(defaultThemeConfig.smallButtonRadius)), + borderRadius: BorderRadius.all(Radius.circular(defaultThemeConfig.smallButtonRadius)), onTap: onTap, textStyle: style, - insertPadding: EdgeInsets.symmetric( - vertical: _BVerticalPadding, horizontal: _BHorizontalPadding), ); }, ); diff --git a/lib/src/components/button/brn_small_outline_button.dart b/lib/src/components/button/brn_small_outline_button.dart index bfda7d0b..e415ec20 100644 --- a/lib/src/components/button/brn_small_outline_button.dart +++ b/lib/src/components/button/brn_small_outline_button.dart @@ -1,14 +1,14 @@ + + import 'dart:math'; import 'package:bruno/src/components/button/brn_normal_button.dart'; +import 'package:bruno/src/constants/brn_constants.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; /// 边框 小、次按钮,小灰框,默认按钮确认,支持自定义边框、文字颜色 -Color greyColor = Color(0xffD7D7D7); -Color normalColor = Color(0xffF0F0F0); - /// 小的边框按钮 /// 该按钮有一个最小的宽度84,在此基础上,宽度随着文本内容的多少变更 /// @@ -19,12 +19,6 @@ Color normalColor = Color(0xffF0F0F0); /// 其他按钮如下: /// * [BrnSmallMainButton], 小主色调按钮 -/// 默认水平间距 -const double _BHorizontalPadding = 6; - -/// 默认垂直间距 -const double _BVerticalPadding = 8; - /// 默认最小宽度 const double _BMinWidth = 84; @@ -32,26 +26,26 @@ const double _BMinWidth = 84; const double _BBorderWith = 1; class BrnSmallOutlineButton extends StatelessWidget { - /// 按钮显示文案,默认'确认' + /// 按钮显示文案,默认'确认 final String title; /// 点击的回调 - final VoidCallback onTap; + final VoidCallback? onTap; ///是否可用,默认为true。false为不可用:置灰、不可点击。 final bool isEnable; /// 边框的颜色,边框颜色, - final Color lineColor; + final Color? lineColor; /// 文字颜色 - final Color textColor; + final Color? textColor; ///圆角 - final double radius; + final double? radius; ///宽度 - final double width; + final double? width; ///字体weigh final FontWeight fontWeight; @@ -60,10 +54,11 @@ class BrnSmallOutlineButton extends StatelessWidget { final double fontSize; /// 配置样式 - final BrnButtonConfig themeData; + final BrnButtonConfig? themeData; /// 传入属性优先级最高,未传入的走默认配置,更多请看[BrnSmallSecondaryOutlineButtonConfig.defaultConfig] const BrnSmallOutlineButton({ + Key? key, this.title = '确认', this.onTap, this.isEnable = true, @@ -72,9 +67,9 @@ class BrnSmallOutlineButton extends StatelessWidget { this.radius, this.width, this.fontSize = 14, - this.fontWeight, + this.fontWeight = FontWeight.w600, this.themeData, - }); + }): super(key: key); @override Widget build(BuildContext context) { @@ -86,8 +81,7 @@ class BrnSmallOutlineButton extends StatelessWidget { )); defaultThemeConfig = BrnThemeConfigurator.instance .getConfig(configId: defaultThemeConfig.configId) - .buttonConfig - .merge(defaultThemeConfig); + .buttonConfig.merge(defaultThemeConfig); TextPainter textPainter = TextPainter(textScaleFactor: MediaQuery.of(context).textScaleFactor); @@ -96,7 +90,7 @@ class BrnSmallOutlineButton extends StatelessWidget { builder: (_, con) { TextStyle style = TextStyle( fontSize: defaultThemeConfig.smallButtonFontSize, - fontWeight: fontWeight ?? FontWeight.w600, + fontWeight: fontWeight, ); textPainter.textDirection = TextDirection.ltr; @@ -104,7 +98,7 @@ class BrnSmallOutlineButton extends StatelessWidget { textPainter.layout(maxWidth: con.maxWidth); double textWidth = textPainter.width; double _maxWidth = - textWidth + _BHorizontalPadding * 2 + 2 * _BBorderWith; + textWidth + BrnButtonConstant.horizontalPadding * 2 + 2 * _BBorderWith; double _minWidth = min(_BMinWidth, con.maxWidth); if (_maxWidth <= _minWidth) { @@ -121,7 +115,7 @@ class BrnSmallOutlineButton extends StatelessWidget { ), borderWith: _BBorderWith, radius: defaultThemeConfig.smallButtonRadius, - text: title ?? "", + text: title, disableLineColor: defaultThemeConfig.commonConfig.borderColorBase, lineColor: defaultThemeConfig.commonConfig.borderColorBase, textColor: textColor ?? defaultThemeConfig.commonConfig.colorTextBase, @@ -131,8 +125,6 @@ class BrnSmallOutlineButton extends StatelessWidget { fontWeight: FontWeight.bold, fontSize: defaultThemeConfig.smallButtonFontSize, onTap: onTap, - insertPadding: EdgeInsets.symmetric( - vertical: _BVerticalPadding, horizontal: _BHorizontalPadding), backgroundColor: Colors.white, disableBackgroundColor: Color(0xffcccccc).withOpacity(0.1), ); diff --git a/lib/src/components/button/brn_vertical_icon_button.dart b/lib/src/components/button/brn_vertical_icon_button.dart index 02d1be17..5576c4e9 100644 --- a/lib/src/components/button/brn_vertical_icon_button.dart +++ b/lib/src/components/button/brn_vertical_icon_button.dart @@ -33,11 +33,14 @@ class BrnVerticalIconButton extends StatelessWidget { final Widget iconWidget; /// 按钮点击的回调 - final VoidCallback onTap; + final VoidCallback? onTap; - const BrnVerticalIconButton( - {Key key, @required this.name, @required this.iconWidget, this.onTap}) - : super(key: key); + const BrnVerticalIconButton({ + Key? key, + required this.name, + required this.iconWidget, + this.onTap, + }) : super(key: key); @override Widget build(BuildContext context) { diff --git a/lib/src/components/button/collection/brn_bottom_button_panel.dart b/lib/src/components/button/collection/brn_bottom_button_panel.dart index 05f9486a..70f670f7 100644 --- a/lib/src/components/button/collection/brn_bottom_button_panel.dart +++ b/lib/src/components/button/collection/brn_bottom_button_panel.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/button/brn_vertical_icon_button.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; @@ -64,13 +66,13 @@ class BrnBottomButtonPanel extends StatelessWidget { final VoidCallback mainButtonOnTap; /// 次按钮的文案 - final String secondaryButtonName; + final String? secondaryButtonName; /// 次按钮的点击回调 - final VoidCallback secondaryButtonOnTap; + final VoidCallback? secondaryButtonOnTap; /// icon按钮的集合 - final List iconButtonList; + final List? iconButtonList; /// 主按钮是否可用 默认可用 /// 如果设置为false,按钮置灰且不响应[mainButtonOnTap] @@ -81,9 +83,9 @@ class BrnBottomButtonPanel extends StatelessWidget { final bool enableSecondaryButton; const BrnBottomButtonPanel( - {Key key, - @required this.mainButtonName, - @required this.mainButtonOnTap, + {Key? key, + required this.mainButtonName, + required this.mainButtonOnTap, this.secondaryButtonName, this.secondaryButtonOnTap, this.enableMainButton = true, @@ -102,16 +104,13 @@ class BrnBottomButtonPanel extends StatelessWidget { /// secondaryButtonOnTap 次按钮的点击事件 /// iconButtonList icon按钮 static Widget createByList(List buttonTitleList, - {VoidCallback mainButtonOnTap, - VoidCallback secondaryButtonOnTap, + {VoidCallback? mainButtonOnTap, + VoidCallback? secondaryButtonOnTap, bool enableMainButton = true, - List iconButtonList}) { - if ((buttonTitleList == null || buttonTitleList.isEmpty) && + List? iconButtonList}) { + if ((buttonTitleList.isEmpty) && iconButtonList == null) { - return Container( - height: 0, - width: 0, - ); + return SizedBox.shrink(); } if (buttonTitleList.length >= 2) { return BrnBottomButtonPanel( @@ -144,15 +143,12 @@ class BrnBottomButtonPanel extends StatelessWidget { iconButtonList: iconButtonList, ); } - return Container( - height: 0, - width: 0, - ); + return SizedBox.shrink(); } @override Widget build(BuildContext context) { - List rowChildren = List(); + List rowChildren = []; if (null != iconButtonList) { Widget iconListWidget = _iconWidgetListWidget(); rowChildren.add(iconListWidget); @@ -171,7 +167,7 @@ class BrnBottomButtonPanel extends StatelessWidget { } Widget _buttonListWidget() { - List btnList = List(); + List btnList = []; Widget mBtn = _mainButtonWidget(); btnList.add(mBtn); if (secondaryButtonName != null) { @@ -187,7 +183,7 @@ class BrnBottomButtonPanel extends StatelessWidget { } Widget _iconWidgetListWidget() { - List finalIconList = iconButtonList.map((wdt) { + List finalIconList = iconButtonList!.map((wdt) { return Padding(padding: EdgeInsets.only(left: 0), child: wdt); }).toList(); return Row( @@ -203,7 +199,7 @@ class BrnBottomButtonPanel extends StatelessWidget { child: GestureDetector( onTap: () { if (secondaryButtonOnTap != null && enableSecondaryButton) { - secondaryButtonOnTap(); + secondaryButtonOnTap!(); } }, child: Container( @@ -213,8 +209,7 @@ class BrnBottomButtonPanel extends StatelessWidget { color: enableSecondaryButton ? BrnThemeConfigurator.instance .getConfig() - .commonConfig - .brandAuxiliary + .commonConfig.brandAuxiliary : Color(0xFFCCCCCC), borderRadius: BorderRadius.all(Radius.circular(6.0)), ), @@ -231,9 +226,7 @@ class BrnBottomButtonPanel extends StatelessWidget { ? Colors.white : BrnThemeConfigurator.instance .getConfig() - .commonConfig - .colorTextBaseInverse - .withOpacity(0.7), + .commonConfig.colorTextBaseInverse.withOpacity(0.7), ), ), )), @@ -245,7 +238,7 @@ class BrnBottomButtonPanel extends StatelessWidget { Widget _mainButtonWidget() { Widget mainWidget = GestureDetector( onTap: () { - if (mainButtonOnTap != null && enableMainButton) { + if (enableMainButton) { mainButtonOnTap(); } }, @@ -256,14 +249,13 @@ class BrnBottomButtonPanel extends StatelessWidget { color: enableMainButton ? BrnThemeConfigurator.instance .getConfig() - .commonConfig - .brandPrimary + .commonConfig.brandPrimary : Color(0xFFCCCCCC), borderRadius: BorderRadius.all(Radius.circular(6.0)), ), child: Center( child: Text( - mainButtonName ?? "", + mainButtonName, textAlign: TextAlign.center, maxLines: 1, overflow: TextOverflow.ellipsis, @@ -274,9 +266,7 @@ class BrnBottomButtonPanel extends StatelessWidget { ? Colors.white : BrnThemeConfigurator.instance .getConfig() - .commonConfig - .colorTextBaseInverse - .withOpacity(0.7), + .commonConfig.colorTextBaseInverse.withOpacity(0.7), ), ), )), @@ -292,7 +282,7 @@ class BrnBottomButtonPanel extends StatelessWidget { } bool _isEmptyIcon() { - return iconButtonList == null || iconButtonList.isEmpty; + return iconButtonList == null || iconButtonList!.isEmpty; } bool _isEmptySecondary() { diff --git a/lib/src/components/button/collection/brn_button_panel.dart b/lib/src/components/button/collection/brn_button_panel.dart index 3ec50256..8d2442c4 100644 --- a/lib/src/components/button/collection/brn_button_panel.dart +++ b/lib/src/components/button/collection/brn_button_panel.dart @@ -5,7 +5,6 @@ import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; /// 描述: 主次按钮组成的横向面板 /// 主按钮和边框按钮组成的集合 @@ -28,13 +27,13 @@ class BrnButtonPanel extends StatefulWidget { final bool isMainBtnEnable; /// 默认状态下,次按钮的文案集合。如果需要改变按钮的可用状态,请使用 [secondaryButtonList] 初始化。 - final List secondaryButtonNameList; + final List? secondaryButtonNameList; /// 包含config状态的次按钮,默认状态的话直接传[secondaryButtonNameList]即可 - final List secondaryButtonList; + final List? secondaryButtonList; /// 次按钮的点击回调 - final void Function(int) secondaryButtonOnTap; + final void Function(int)? secondaryButtonOnTap; /// 控件的左右的padding /// 默认值为20 @@ -44,9 +43,9 @@ class BrnButtonPanel extends StatefulWidget { final BrnPopupDirection popDirection; const BrnButtonPanel( - {Key key, - @required this.mainButtonName, - @required this.mainButtonOnTap, + {Key? key, + required this.mainButtonName, + required this.mainButtonOnTap, this.isMainBtnEnable = true, this.secondaryButtonNameList, this.secondaryButtonOnTap, @@ -60,9 +59,9 @@ class BrnButtonPanel extends StatefulWidget { } class _BrnButtonPanelState extends State { - GlobalKey _popWindowKey; + late GlobalKey _popWindowKey; - List _secondaryButtonList = List(); + List _secondaryButtonList = []; @override void initState() { @@ -79,20 +78,19 @@ class _BrnButtonPanelState extends State { /// 初始化次按钮列表 void initSecondaryButton() { - _secondaryButtonList = List(); + _secondaryButtonList = []; if (widget.secondaryButtonList?.isNotEmpty ?? false) { - _secondaryButtonList = widget.secondaryButtonList; + _secondaryButtonList = widget.secondaryButtonList!; } else if (widget.secondaryButtonNameList?.isNotEmpty ?? false) { - widget.secondaryButtonNameList.forEach((name) { - _secondaryButtonList - .add(BrnButtonPanelConfig(name: name, isEnable: true)); + widget.secondaryButtonNameList!.forEach((name) { + _secondaryButtonList.add(BrnButtonPanelConfig(name: name, isEnable: true)); }); } } @override Widget build(BuildContext context) { - List list = List(); + List list = []; if (_secondaryButtonList.length > 2) { //次按钮两个以上特殊处理,所有button等分 @@ -140,8 +138,7 @@ class _BrnButtonPanelState extends State { } return Padding( - padding: EdgeInsets.fromLTRB( - widget.horizontalPadding ?? 20, 0, widget.horizontalPadding ?? 20, 0), + padding: EdgeInsets.fromLTRB(widget.horizontalPadding, 0, widget.horizontalPadding, 0), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: list, @@ -153,19 +150,18 @@ class _BrnButtonPanelState extends State { return BrnSmallMainButton( title: widget.mainButtonName, onTap: widget.mainButtonOnTap, - isEnable: widget.isMainBtnEnable ?? true, + isEnable: widget.isMainBtnEnable, maxWidth: 132, ); } Widget _secondaryButton(int btnIndex) { - String name = _secondaryButtonList[btnIndex].name; BrnSmallOutlineButton button = BrnSmallOutlineButton( - title: name, - isEnable: _secondaryButtonList[btnIndex].isEnable ?? true, + title:_secondaryButtonList[btnIndex].name, + isEnable: _secondaryButtonList[btnIndex].isEnable, onTap: () { if (widget.secondaryButtonOnTap != null) { - widget.secondaryButtonOnTap(btnIndex); + widget.secondaryButtonOnTap!(btnIndex); } }, ); @@ -177,8 +173,8 @@ class _BrnButtonPanelState extends State { /// 更多按钮 Widget _moreButton() { - if (null != _secondaryButtonList && _secondaryButtonList.length > 2) { - List list = List(); + if (_secondaryButtonList.length > 2) { + List list = []; for (int i = 2; i < _secondaryButtonList.length; i++) { list.add(_secondaryButtonList[i].name); } @@ -199,14 +195,8 @@ class _BrnButtonPanelState extends State { maxLines: 1, style: TextStyle( color: _secondaryButtonList[index + 2].isEnable - ? BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBase - : BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextHint, + ? BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase + : BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextHint, fontSize: 16)); }, popDirection: widget.popDirection, @@ -214,7 +204,7 @@ class _BrnButtonPanelState extends State { // 按钮不可用的时候,点击无响应; if (widget.secondaryButtonOnTap != null) { if (_secondaryButtonList[index + 2].isEnable) { - widget.secondaryButtonOnTap(index + 2); + widget.secondaryButtonOnTap!(index + 2); return false; } else { return true; @@ -239,7 +229,7 @@ class BrnButtonPanelConfig { final bool isEnable; BrnButtonPanelConfig({ - this.name, + required this.name, this.isEnable = true, }); } diff --git a/lib/src/components/button/collection/brn_multiple_bottom_button.dart b/lib/src/components/button/collection/brn_multiple_bottom_button.dart index 61ca51b7..367553c2 100644 --- a/lib/src/components/button/collection/brn_multiple_bottom_button.dart +++ b/lib/src/components/button/collection/brn_multiple_bottom_button.dart @@ -1,5 +1,6 @@ + + import 'package:bruno/src/components/radio/brn_checkbox.dart'; -import 'package:bruno/src/components/radio/brn_radio_core.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; @@ -24,31 +25,31 @@ enum BrnMultipleButtonArrowState { /// 支持 **[全选]+[选中状态]+[次要按钮]+[主要按钮]** 的组合(中括号代表可选) class BrnMultipleBottomButton extends StatefulWidget { /// 全选的点击回调,不传则不展示多选按钮,回传参数 true 表示选中全选,false 表示取消全选 - final void Function(bool) onSelectAll; + final void Function(bool?)? onSelectAll; /// selectedButtonOnTap, 点击已选的回调,存在三种状态:-1:不可展开(当 value 为 0 的时候),0:收起,1:展开 - final void Function(BrnMultipleButtonArrowState) onSelectedButtonTap; + final void Function(BrnMultipleButtonArrowState)? onSelectedButtonTap; - /// 主按钮的文案,默认为主题色 可以传入自定义 Widget,不传则不展示 + /// 主按钮的文案,默认为主题色 可以传入自定义 Widget 以及 String 类型的文案,不传则不展示 final dynamic mainButton; - /// 次按钮的文案可以传入自定义 Widget,不传则不展示 + /// 次按钮的文案可以传入自定义 Widget 以及 String 类型的文案,不传则不展示 final dynamic subButton; /// 主按钮点击回调 - final VoidCallback onMainButtonTap; + final VoidCallback? onMainButtonTap; /// 次按钮点击回调 - final VoidCallback onSubButtonTap; + final VoidCallback? onSubButtonTap; /// 已选后面是否需要带小箭头。默认 false final bool hasArrow; /// 暴露给外界设置多选状态的控制器 - final BrnMultipleBottomController bottomController; + final BrnMultipleBottomController? bottomController; const BrnMultipleBottomButton( - {Key key, + {Key? key, this.mainButton, this.subButton, this.onMainButtonTap, @@ -65,7 +66,7 @@ class BrnMultipleBottomButton extends StatefulWidget { } class _BrnMultipleBottomButtonState extends State { - BrnMultipleBottomController _controller; + late BrnMultipleBottomController _controller; bool _unfoldState = false; @override @@ -76,7 +77,7 @@ class _BrnMultipleBottomButtonState extends State { @override Widget build(BuildContext context) { - List rowChildren = List() + List rowChildren = [] ..add(_allSelectedWidget()) ..add(_selectedCountWidget()) ..add(_buttonArea()); @@ -99,7 +100,7 @@ class _BrnMultipleBottomButtonState extends State { bool currentState = !_controller.valueNotifier.value.selectAllState; _controller.setState(selectAllState: currentState); - if (widget.onSelectAll != null) widget.onSelectAll(currentState); + if (widget.onSelectAll != null) widget.onSelectAll!(currentState); }, behavior: HitTestBehavior.opaque, child: Row( @@ -118,7 +119,7 @@ class _BrnMultipleBottomButtonState extends State { //同步到外界的当前的全选状态 _controller.setState(selectAllState: value); if (widget.onSelectAll != null) - widget.onSelectAll(value); + widget.onSelectAll!(value); }, key: Key(DateTime.now().toString()), ); @@ -140,14 +141,13 @@ class _BrnMultipleBottomButtonState extends State { Widget _selectedCountWidget() { Image unfoldWidget = BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_SELECTED_UP_TRIANGLE, + BrnAsset.iconSelectedUpTriangle, BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary); - Image foldWidget = - BrunoTools.getAssetImage(BrnAsset.ICON_UNSELECT_DOWN_TRIANGLE); + BrunoTools.getAssetImage(BrnAsset.iconUnSelectDownTriangle); Image cantFoldWidget = BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_UNSELECT_DOWN_TRIANGLE, Color(0XCCCCCCCC)); + BrnAsset.iconUnSelectDownTriangle, Color(0XCCCCCCCC)); return GestureDetector( onTap: () { @@ -156,14 +156,14 @@ class _BrnMultipleBottomButtonState extends State { if (_controller.valueNotifier.value.selectedCount == 0) { _unfoldState = false; widget - .onSelectedButtonTap(BrnMultipleButtonArrowState.cantUnfold); + .onSelectedButtonTap!(BrnMultipleButtonArrowState.cantUnfold); return; } _unfoldState = !_unfoldState; if (_unfoldState) { - widget.onSelectedButtonTap(BrnMultipleButtonArrowState.unfold); + widget.onSelectedButtonTap!(BrnMultipleButtonArrowState.unfold); } else { - widget.onSelectedButtonTap(BrnMultipleButtonArrowState.fold); + widget.onSelectedButtonTap!(BrnMultipleButtonArrowState.fold); } } }); @@ -179,15 +179,14 @@ class _BrnMultipleBottomButtonState extends State { ValueListenableBuilder( valueListenable: _controller.valueNotifier, builder: (context, value, _) { - List rowChildren = List(); + List rowChildren = []; rowChildren.add(Text( '(${value.selectedCount})', style: TextStyle( color: value.selectedCount != 0 ? BrnThemeConfigurator.instance .getConfig() - .commonConfig - .brandPrimary + .commonConfig.brandPrimary : Color(0x99999999), fontSize: 16), )); @@ -196,8 +195,8 @@ class _BrnMultipleBottomButtonState extends State { if (value.arrowStatus != BrnMultipleButtonArrowState.defaultStatus) { //使用方主动设置箭头状态的时候 - Widget arrow; - switch (value.arrowStatus) { + Widget? arrow; + switch (value.arrowStatus!) { case BrnMultipleButtonArrowState.cantUnfold: arrow = cantFoldWidget; break; @@ -264,7 +263,7 @@ class _BrnMultipleBottomButtonState extends State { ? Expanded( child: GestureDetector( onTap: () { - if (widget.onMainButtonTap != null) widget.onMainButtonTap(); + if (widget.onMainButtonTap != null) widget.onMainButtonTap!(); }, child: ValueListenableBuilder( valueListenable: _controller.valueNotifier, @@ -274,19 +273,16 @@ class _BrnMultipleBottomButtonState extends State { padding: EdgeInsets.only(left: 10, right: 10), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(4)), - color: value.mainButtonState - ? BrnThemeConfigurator.instance + color: value.mainButtonState? BrnThemeConfigurator.instance .getConfig() - .commonConfig - .brandPrimary + .commonConfig.brandPrimary : Color(0xFFCCCCCC)), child: widget.mainButton is String ? Center( child: Text( widget.mainButton, style: TextStyle( - color: value.mainButtonState - ? Colors.white + color: value.mainButtonState? Colors.white : Color(0xAAFFFFFF), fontSize: 16, fontWeight: FontWeight.w600), @@ -307,7 +303,7 @@ class _BrnMultipleBottomButtonState extends State { ? Expanded( child: GestureDetector( onTap: () { - if (widget.onSubButtonTap != null) widget.onSubButtonTap(); + if (widget.onSubButtonTap != null) widget.onSubButtonTap!(); }, child: ValueListenableBuilder( valueListenable: _controller.valueNotifier, @@ -317,19 +313,16 @@ class _BrnMultipleBottomButtonState extends State { padding: EdgeInsets.only(left: 10, right: 10), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(4)), - color: value.subButtonState - ? BrnThemeConfigurator.instance + color: value.subButtonState? BrnThemeConfigurator.instance .getConfig() - .commonConfig - .brandAuxiliary + .commonConfig.brandAuxiliary : Color(0xFFCCCCCC)), child: widget.subButton is String ? Center( child: Text( widget.subButton, style: TextStyle( - color: value.subButtonState - ? Colors.white + color: value.subButtonState? Colors.white : Color(0xAAFFFFFF), fontSize: 16, fontWeight: FontWeight.w600), @@ -352,9 +345,9 @@ class BrnMultipleBottomController { valueNotifier = ValueNotifier(initMultiSelectState ?? MultiSelectState()); } - final MultiSelectState initMultiSelectState; + final MultiSelectState? initMultiSelectState; - ValueNotifier valueNotifier; + late ValueNotifier valueNotifier; /// 设置按钮的状态,当主按钮或者此按钮置灰的时候,对应的点击任然会回调,控件只做按钮置灰 /// [selectedCount] 已选括号中的数目 @@ -363,18 +356,18 @@ class BrnMultipleBottomController { /// [subButtonState] 次按钮是否置灰 /// [arrowStatus] 控制箭头的状态 void setState( - {int selectedCount, - bool selectAllState, - bool mainButtonState, - bool subButtonState, - BrnMultipleButtonArrowState arrowStatus}) { + {int? selectedCount, + bool? selectAllState, + bool? mainButtonState, + bool? subButtonState, + BrnMultipleButtonArrowState? arrowStatus}) { MultiSelectState data = MultiSelectState( - selectedCount: selectedCount ?? valueNotifier?.value?.selectedCount, - selectAllState: selectAllState ?? valueNotifier?.value?.selectAllState, + selectedCount: selectedCount ?? valueNotifier.value.selectedCount, + selectAllState: selectAllState ?? valueNotifier.value.selectAllState, mainButtonState: - mainButtonState ?? valueNotifier?.value?.mainButtonState, - subButtonState: subButtonState ?? valueNotifier?.value?.subButtonState, - arrowStatus: arrowStatus ?? valueNotifier?.value?.arrowStatus); + mainButtonState ?? valueNotifier.value.mainButtonState, + subButtonState: subButtonState ?? valueNotifier.value.subButtonState, + arrowStatus: arrowStatus ?? valueNotifier.value.arrowStatus); valueNotifier.value = data; } } @@ -393,7 +386,7 @@ class MultiSelectState { bool subButtonState; /// 控制箭头的状态 - BrnMultipleButtonArrowState arrowStatus; + BrnMultipleButtonArrowState? arrowStatus; MultiSelectState( {this.selectedCount = 0, diff --git a/lib/src/components/button/collection/brn_text_button_panel.dart b/lib/src/components/button/collection/brn_text_button_panel.dart index 64b324d1..93e2f582 100644 --- a/lib/src/components/button/collection/brn_text_button_panel.dart +++ b/lib/src/components/button/collection/brn_text_button_panel.dart @@ -17,26 +17,26 @@ class BrnTextButtonPanel extends StatefulWidget { final List nameList; /// 点击某个文本按钮的回调 - final void Function(int index) onTap; + final void Function(int index)? onTap; /// popUpWindow位于targetView的方向 /// 取[BrnPopupDirection]里面的值 /// 默认值为PopDirection.bottom final BrnPopupDirection popDirection; - const BrnTextButtonPanel( - {Key key, - @required this.nameList, - this.onTap, - this.popDirection = BrnPopupDirection.bottom}) - : super(key: key); + const BrnTextButtonPanel({ + Key? key, + required this.nameList, + this.onTap, + this.popDirection = BrnPopupDirection.bottom, + }) : super(key: key); @override _BrnTextButtonPanelState createState() => _BrnTextButtonPanelState(); } class _BrnTextButtonPanelState extends State { - GlobalKey _popWindowKey; + GlobalKey _popWindowKey = GlobalKey(); /// 更多按钮的展开收起状态 bool _isExpanded = false; @@ -44,21 +44,9 @@ class _BrnTextButtonPanelState extends State { /// 展示的文本按钮的最大数目,超过这个数目时展示更多 int _maxNum = 4; - @override - void initState() { - super.initState(); - _popWindowKey = GlobalKey(); - } - - @override - void didUpdateWidget(covariant BrnTextButtonPanel oldWidget) { - super.didUpdateWidget(oldWidget); - _popWindowKey = GlobalKey(); - } - @override Widget build(BuildContext context) { - if (widget.nameList != null && widget.nameList.length > 0) { + if (widget.nameList.length > 0) { Row row = Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceAround, @@ -70,22 +58,20 @@ class _BrnTextButtonPanelState extends State { } List _textOperationWidgetList(context) { - List widgetList = List(); + List widgetList = []; //文本按钮不超过4个,就全不显示 //超过4个的话,就只显示3个,剩下的显示在更多里 - int length = widget.nameList.length <= _maxNum - ? widget.nameList.length - : _maxNum - 1; + int length = widget.nameList.length <= _maxNum ? widget.nameList.length : _maxNum - 1; for (int textIndex = 0; textIndex < length; textIndex++) { Widget operationWidget = _operationWidgetAtIndex(textIndex); widgetList.add(operationWidget); } - if (widget.nameList != null && widget.nameList.length > _maxNum) { + if (widget.nameList.length > _maxNum) { widgetList.add(_moreButton()); } - List showWidget = List(); + List showWidget = []; for (int i = 0, n = widgetList.length; i < n; ++i) { showWidget.add(Expanded( child: Center( @@ -113,10 +99,7 @@ class _BrnTextButtonPanelState extends State { style: TextStyle( fontSize: 14, fontWeight: FontWeight.w500, - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary), + color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary), ); return GestureDetector( @@ -129,15 +112,15 @@ class _BrnTextButtonPanelState extends State { return; } if (null != widget.onTap) { - widget.onTap(index); + widget.onTap!(index); } }); } /// 更多按钮 Widget _moreButton() { - if (widget.nameList != null && widget.nameList.length > _maxNum) { - List list = List(); + if (widget.nameList.length > _maxNum) { + List list = []; for (int i = _maxNum - 1; i < widget.nameList.length; i++) { list.add(widget.nameList[i]); } @@ -153,8 +136,8 @@ class _BrnTextButtonPanelState extends State { ); Widget imageWidget = _isExpanded - ? BrunoTools.getAssetImage(BrnAsset.ICON_UP_ARROW) - : BrunoTools.getAssetImage(BrnAsset.ICON_DOWN_ARROW); + ? BrunoTools.getAssetImage(BrnAsset.iconUpArrow) + : BrunoTools.getAssetImage(BrnAsset.iconDownArrow); return GestureDetector( child: Row( @@ -174,7 +157,7 @@ class _BrnTextButtonPanelState extends State { popDirection: widget.popDirection, data: list, onItemClick: (index, item) { if (widget.onTap != null) { - widget.onTap(index + 3); + widget.onTap!(index + 3); } }, onDismiss: () { setState(() { @@ -186,7 +169,7 @@ class _BrnTextButtonPanelState extends State { }); }); } else { - return Container(); + return SizedBox.shrink(); } } } diff --git a/lib/src/components/calendar/brn_calendar_view.dart b/lib/src/components/calendar/brn_calendar_view.dart index 93bcb87e..3f5feb97 100644 --- a/lib/src/components/calendar/brn_calendar_view.dart +++ b/lib/src/components/calendar/brn_calendar_view.dart @@ -1,15 +1,20 @@ -import 'package:bruno/bruno.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +///单选日期回调函数 +typedef CalendarDateChange = Function(DateTime date); + +///范围选择日期回调函数 +typedef CalendarRangeDateChange = Function(DateTimeRange range); + /// 展示模式,周视图模式,月视图模式 -enum DisplayMode { Week, Month } +enum DisplayMode { week, month } /// 时间选择模式,单个时间,时间范围 -enum SelectMode { SINGLE, RANGE } +enum SelectMode { single, range } const List _defaultWeekNames = ['日', '一', '二', '三', '四', '五', '六']; @@ -18,18 +23,54 @@ const List _defaultWeekNames = ['日', '一', '二', '三', '四', '五' /// 2、日历组件支持时间范围展示,仅展示范围内的日历视图,范围外日期置灰不可点击。日期范围边界后不可再翻页。 class BrnCalendarView extends StatefulWidget { const BrnCalendarView( - {Key key, - this.selectMode = SelectMode.SINGLE, - this.displayMode = DisplayMode.Month, + {Key? key, + this.selectMode = SelectMode.single, + this.displayMode = DisplayMode.month, this.weekNames = _defaultWeekNames, this.showControllerBar = true, this.initStartSelectedDate, this.initEndSelectedDate, this.initDisplayDate, - this.startEndDateChange, + this.dateChange, + this.rangeDateChange, this.minDate, this.maxDate}) - : assert(weekNames != null && weekNames.length > 0), + : assert(weekNames.length == 7), + assert( + selectMode == SelectMode.single && dateChange != null || + selectMode == SelectMode.range && rangeDateChange != null), + super(key: key); + + const BrnCalendarView.single( + {Key? key, + this.displayMode = DisplayMode.month, + this.weekNames = _defaultWeekNames, + this.showControllerBar = true, + this.initStartSelectedDate, + this.initEndSelectedDate, + this.initDisplayDate, + required this.dateChange, + this.minDate, + this.maxDate}) + : this.selectMode = SelectMode.single, + this.rangeDateChange = null, + assert(weekNames.length == 7), + super(key: key); + + const BrnCalendarView.range( + {Key? key, + this.displayMode = DisplayMode.month, + this.weekNames = _defaultWeekNames, + this.showControllerBar = true, + this.initStartSelectedDate, + this.initEndSelectedDate, + this.initDisplayDate, + required this.rangeDateChange, + this.minDate, + this.maxDate}) + : this.selectMode = SelectMode.range, + this.dateChange = null, + assert(weekNames.length == 7), super(key: key); /// 展示模式, Week, Month @@ -39,16 +80,20 @@ class BrnCalendarView extends StatefulWidget { final SelectMode selectMode; /// 日历日期选择范围最小值 - final DateTime minDate; + /// + /// 默认 `DateTime(1970)` + final DateTime? minDate; /// 日历日期选择范围最大值 - final DateTime maxDate; + /// + /// 默认 `DateTime(2100)` + final DateTime? maxDate; /// 日历日期初始选中最小值 - final DateTime initStartSelectedDate; + final DateTime? initStartSelectedDate; /// 日历日期初始选中最大值 - final DateTime initEndSelectedDate; + final DateTime? initEndSelectedDate; /// 是否展示顶部控制按钮 final bool showControllerBar; @@ -57,10 +102,15 @@ class BrnCalendarView extends StatefulWidget { final List weekNames; /// 初始展示月份 - final DateTime initDisplayDate; + /// + /// 默认当前时间 + final DateTime? initDisplayDate; + + /// single 类型选择日期回调 + final CalendarDateChange? dateChange; - final Function(DateTime startSelectedDate, DateTime endSelectedDate) - startEndDateChange; + /// range 类型选择日期回调 + final CalendarRangeDateChange? rangeDateChange; @override _CustomCalendarViewState createState() => _CustomCalendarViewState(); @@ -68,12 +118,10 @@ class BrnCalendarView extends StatefulWidget { class _CustomCalendarViewState extends State { List dateList = []; - DateTime _currentDate; - DisplayMode _displayMode; - DateTime _minDate, - _maxDate, - _currentStartSelectedDate, - _currentEndSelectedDate; + late DateTime _currentDate; + late DisplayMode _displayMode; + late DateTime _minDate, _maxDate; + DateTime? _currentStartSelectedDate, _currentEndSelectedDate; @override void initState() { @@ -84,22 +132,17 @@ class _CustomCalendarViewState extends State { _currentStartSelectedDate = widget.initStartSelectedDate; _currentEndSelectedDate = widget.initEndSelectedDate; - if (_displayMode == DisplayMode.Month) { + if (_displayMode == DisplayMode.month) { _setListOfMonthDate(_currentDate); - } else if (_displayMode == DisplayMode.Week) { + } else if (_displayMode == DisplayMode.week) { _setListOfWeekDate(_currentDate); } super.initState(); } - @override - void dispose() { - super.dispose(); - } - void _setListOfWeekDate(DateTime weekDate) { dateList.clear(); - List tmpDateList = List(); + List tmpDateList = []; int previousDay = weekDate.weekday % 7; for (int i = 0; i < weekDate.weekday; i++) { tmpDateList.add(weekDate.subtract(Duration(days: previousDay - i))); @@ -114,7 +157,7 @@ class _CustomCalendarViewState extends State { void _setListOfMonthDate(DateTime monthDate) { dateList.clear(); - List tmpDateList = List(); + List tmpDateList = []; final DateTime newDate = DateTime(monthDate.year, monthDate.month, 0); int previousMonthDay = (newDate.weekday + 1) % 7; for (int i = 1; i <= previousMonthDay; i++) { @@ -159,11 +202,11 @@ class _CustomCalendarViewState extends State { onTap: () { if (!isPreIconEnable) return; setState(() { - if (_displayMode == DisplayMode.Month) { + if (_displayMode == DisplayMode.month) { _currentDate = DateTime(_currentDate.year, _currentDate.month, 0); _setListOfMonthDate(_currentDate); - } else if (_displayMode == DisplayMode.Week) { + } else if (_displayMode == DisplayMode.week) { _currentDate = _currentDate.subtract(Duration(days: 7)); _setListOfWeekDate(_currentDate); } @@ -175,9 +218,9 @@ class _CustomCalendarViewState extends State { color: Colors.transparent, padding: EdgeInsets.only(left: 15), child: isPreIconEnable - ? BrunoTools.getAssetImage(BrnAsset.ICON_CALENDAR_PRE_MONTH) + ? BrunoTools.getAssetImage(BrnAsset.iconCalendarPreMonth) : BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_CALENDAR_PRE_MONTH, Color(0xFFCCCCCC)), + BrnAsset.iconCalendarPreMonth, Color(0xFFCCCCCC)), alignment: Alignment.center, ), ), @@ -199,11 +242,11 @@ class _CustomCalendarViewState extends State { onTap: () { if (!isNextIconEnable) return; setState(() { - if (_displayMode == DisplayMode.Month) { + if (_displayMode == DisplayMode.month) { _currentDate = DateTime(_currentDate.year, _currentDate.month + 2, 0); _setListOfMonthDate(_currentDate); - } else if (_displayMode == DisplayMode.Week) { + } else if (_displayMode == DisplayMode.week) { _currentDate = _currentDate.add(Duration(days: 7)); _setListOfWeekDate(_currentDate); } @@ -215,10 +258,9 @@ class _CustomCalendarViewState extends State { color: Colors.transparent, padding: EdgeInsets.only(right: 15), child: isNextIconEnable - ? BrunoTools.getAssetImage( - BrnAsset.ICON_CALENDAR_NEXT_MONTH) + ? BrunoTools.getAssetImage(BrnAsset.iconCalendarNextMonth) : BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_CALENDAR_NEXT_MONTH, Color(0xFFCCCCCC)), + BrnAsset.iconCalendarNextMonth, Color(0xFFCCCCCC)), alignment: Alignment.center, ), ) @@ -226,10 +268,7 @@ class _CustomCalendarViewState extends State { ), ); } - return Container( - height: 0, - width: 0, - ); + return SizedBox.shrink(); } bool _isIconEnable(bool isPre) { @@ -238,7 +277,7 @@ class _CustomCalendarViewState extends State { return false; } if (dateList[0].year == _minDate.year) { - if (_displayMode == DisplayMode.Week) { + if (_displayMode == DisplayMode.week) { if (dateList[0].month < _minDate.month) { return false; } @@ -260,7 +299,7 @@ class _CustomCalendarViewState extends State { return false; } if (dateList.last.year == _maxDate.year) { - if (_displayMode == DisplayMode.Week) { + if (_displayMode == DisplayMode.week) { if (dateList.last.month > _maxDate.month) { return false; } @@ -339,17 +378,11 @@ class _CustomCalendarViewState extends State { .withOpacity(0.14) : Colors.transparent) : Colors.transparent, - borderRadius: BorderRadius.only( - bottomLeft: _isStartDateRadius(date) - ? const Radius.circular(24.0) - : const Radius.circular(0.0), - topLeft: _isStartDateRadius(date) + borderRadius: BorderRadius.horizontal( + left: _isStartDateRadius(date) ? const Radius.circular(24.0) : const Radius.circular(0.0), - topRight: _isEndDateRadius(date) - ? const Radius.circular(24.0) - : const Radius.circular(0.0), - bottomRight: _isEndDateRadius(date) + right: _isEndDateRadius(date) ? const Radius.circular(24.0) : const Radius.circular(0.0), ), @@ -394,12 +427,12 @@ class _CustomCalendarViewState extends State { if (date.isAfter(newMinimumDate) && date.isBefore(newMaximumDate)) { _currentDate = date; - if (_displayMode == DisplayMode.Week) { + if (_displayMode == DisplayMode.week) { _setListOfWeekDate(_currentDate); - } else if (_displayMode == DisplayMode.Month) { + } else if (_displayMode == DisplayMode.month) { _setListOfMonthDate(_currentDate); } - if (widget.selectMode == SelectMode.SINGLE) { + if (widget.selectMode == SelectMode.single) { _onSingleDateClick(date); } else { _onRangeDateClick(date); @@ -407,13 +440,13 @@ class _CustomCalendarViewState extends State { } }, child: Padding( - padding: const EdgeInsets.all(0), + padding: EdgeInsets.zero, child: Container( child: Center( child: Text( date.day > 9 ? '${date.day}' : '0${date.day}', style: TextStyle( - color: _displayMode == DisplayMode.Month + color: _displayMode == DisplayMode.month ? (_getIsItStartAndEndDate(date) ? Colors.white : _currentDate.month == @@ -491,8 +524,8 @@ class _CustomCalendarViewState extends State { bool _getIsInRange(DateTime date) { if (_currentStartSelectedDate != null && _currentEndSelectedDate != null) { - if (date.isAfter(_currentStartSelectedDate) && - date.isBefore(_currentEndSelectedDate)) { + if (date.isAfter(_currentStartSelectedDate!) && + date.isBefore(_currentEndSelectedDate!)) { return true; } else { return false; @@ -504,14 +537,14 @@ class _CustomCalendarViewState extends State { bool _getIsItStartAndEndDate(DateTime date) { if (_currentStartSelectedDate != null && - _currentStartSelectedDate.day == date.day && - _currentStartSelectedDate.month == date.month && - _currentStartSelectedDate.year == date.year) { + _currentStartSelectedDate!.day == date.day && + _currentStartSelectedDate!.month == date.month && + _currentStartSelectedDate!.year == date.year) { return true; } else if (_currentEndSelectedDate != null && - _currentEndSelectedDate.day == date.day && - _currentEndSelectedDate.month == date.month && - _currentEndSelectedDate.year == date.year) { + _currentEndSelectedDate!.day == date.day && + _currentEndSelectedDate!.month == date.month && + _currentEndSelectedDate!.year == date.year) { return true; } else { return false; @@ -520,8 +553,8 @@ class _CustomCalendarViewState extends State { bool _isStartDateRadius(DateTime date) { if (_currentStartSelectedDate != null && - _currentStartSelectedDate.day == date.day && - _currentStartSelectedDate.month == date.month) { + _currentStartSelectedDate!.day == date.day && + _currentStartSelectedDate!.month == date.month) { return true; } else if (date.weekday == 7) { return true; @@ -532,8 +565,8 @@ class _CustomCalendarViewState extends State { bool _isEndDateRadius(DateTime date) { if (_currentEndSelectedDate != null && - _currentEndSelectedDate.day == date.day && - _currentEndSelectedDate.month == date.month) { + _currentEndSelectedDate!.day == date.day && + _currentEndSelectedDate!.month == date.month) { return true; } else if (date.weekday == 6) { return true; @@ -547,8 +580,9 @@ class _CustomCalendarViewState extends State { _currentEndSelectedDate = date; setState(() { try { - widget.startEndDateChange( - _currentStartSelectedDate, _currentEndSelectedDate); + if (widget.dateChange != null) { + widget.dateChange!(date); + } } catch (_) {} }); } @@ -569,24 +603,29 @@ class _CustomCalendarViewState extends State { } if (_currentStartSelectedDate != null && _currentEndSelectedDate != null) { - if (!_currentEndSelectedDate.isAfter(_currentStartSelectedDate)) { - final DateTime d = _currentStartSelectedDate; + if (!_currentEndSelectedDate!.isAfter(_currentStartSelectedDate!)) { + final DateTime d = _currentStartSelectedDate!; _currentStartSelectedDate = _currentEndSelectedDate; _currentEndSelectedDate = d; } - if (date.isBefore(_currentStartSelectedDate)) { + if (date.isBefore(_currentStartSelectedDate!)) { _currentStartSelectedDate = date; } - if (date.isAfter(_currentEndSelectedDate)) { + if (date.isAfter(_currentEndSelectedDate!)) { _currentEndSelectedDate = date; } + setState(() { + try { + if (widget.rangeDateChange != null) { + widget.rangeDateChange!(DateTimeRange( + start: _currentStartSelectedDate!, + end: _currentEndSelectedDate!, + )); + } + } catch (_) {} + }); } - setState(() { - try { - widget.startEndDateChange( - _currentStartSelectedDate, _currentEndSelectedDate); - } catch (_) {} - }); + } String _getChinaWeekName(int weekOfDay) { diff --git a/lib/src/components/card/bubble_card/brn_bubble_text.dart b/lib/src/components/card/bubble_card/brn_bubble_text.dart index 0af90b23..e5161c5b 100644 --- a/lib/src/components/card/bubble_card/brn_bubble_text.dart +++ b/lib/src/components/card/bubble_card/brn_bubble_text.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/text/brn_expandable_text.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; @@ -28,26 +30,41 @@ import 'package:bruno/src/utils/brn_tools.dart'; /// * [BrnInsertInfo], 气泡背景的文本组件 /// class BrnBubbleText extends StatelessWidget { - ///显示的文本 + /// 显示的文本 final String text; - ///最多显示的行数 - final int maxLines; + /// 最多显示的行数 + final int? maxLines; - ///展开收起回调 - final TextExpandedCallback onExpanded; + /// 展开收起回调 + final TextExpandedCallback? onExpanded; - ///气泡的圆角 默认是4 + /// 气泡的圆角 默认是4 final double radius; + /// 气泡背景色 默认是 Color(0xFFF8F8F8) + final Color bgColor; + + /// 内容文本样式 + final TextStyle? textStyle; + + + const BrnBubbleText( - {Key key, this.text, this.maxLines, this.onExpanded, this.radius = 4}) + {Key? key, + this.text = '', + this.maxLines, + this.onExpanded, + this.radius = 4, + this.bgColor = const Color(0xFFF8F8F8), + this.textStyle}) : super(key: key); @override @override Widget build(BuildContext context) { - Image image = BrunoTools.getAssetImage('icons/icon_right_top_pointer.png'); + Image image = BrunoTools.getAssetImageWithColor( + 'icons/icon_right_top_pointer.png', bgColor); Widget bubbleText = Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, @@ -66,27 +83,28 @@ class BrnBubbleText extends StatelessWidget { Expanded( child: Container( decoration: BoxDecoration( - color: Color(0xFFF8F8F8), + color: bgColor, shape: BoxShape.rectangle, borderRadius: BorderRadius.only( topLeft: Radius.circular(0), - topRight: Radius.circular(radius ?? 4), - bottomLeft: Radius.circular(radius ?? 4), - bottomRight: Radius.circular(radius ?? 4))), + topRight: Radius.circular(radius), + bottomLeft: Radius.circular(radius), + bottomRight: Radius.circular(radius))), padding: EdgeInsets.only(left: 20, right: 20, top: 12, bottom: 12), child: BrnExpandableText( - text: text ?? "", + text: text, maxLines: maxLines, - color: Color(0xFFF8F8F8), + color: bgColor, onExpanded: onExpanded, - textStyle: TextStyle( - fontWeight: FontWeight.w500, - fontSize: 14, - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBase, - ), + textStyle: textStyle ?? + TextStyle( + fontWeight: FontWeight.w500, + fontSize: 14, + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .colorTextBase, + ), ), ), ) diff --git a/lib/src/components/card/bubble_card/brn_insert_info.dart b/lib/src/components/card/bubble_card/brn_insert_info.dart index 2a402468..a1872aa4 100644 --- a/lib/src/components/card/bubble_card/brn_insert_info.dart +++ b/lib/src/components/card/bubble_card/brn_insert_info.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; @@ -26,7 +28,7 @@ class BrnInsertInfo extends StatelessWidget { final String infoText; final int maxLines; - const BrnInsertInfo({Key key, @required this.infoText, this.maxLines = 2}) + const BrnInsertInfo({Key? key, required this.infoText, this.maxLines = 2}) : super(key: key); @override diff --git a/lib/src/components/card/content_card/brn_enhance_number_card.dart b/lib/src/components/card/content_card/brn_enhance_number_card.dart index 0081dbe2..12f683f7 100644 --- a/lib/src/components/card/content_card/brn_enhance_number_card.dart +++ b/lib/src/components/card/content_card/brn_enhance_number_card.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/constants/brn_strings_constants.dart'; import 'package:bruno/src/theme/brn_theme.dart'; @@ -55,13 +57,13 @@ import 'package:flutter/widgets.dart'; /// /// class BrnEnhanceNumberCard extends StatelessWidget { - final List itemChildren; + final List? itemChildren; ///如果超过一行,行间距则 默认为16 - final double runningSpace; + final double? runningSpace; ///Item的上半部分和下半部分的间距 默认为8 - final double itemRunningSpace; + final double? itemRunningSpace; ///每一行显示的数量 默认为3 final int rowCount; @@ -74,10 +76,10 @@ class BrnEnhanceNumberCard extends StatelessWidget { final TextAlign itemTextAlign; - final BrnEnhanceNumberCardConfig themeData; + final BrnEnhanceNumberCardConfig? themeData; BrnEnhanceNumberCard({ - Key key, + Key? key, this.itemChildren, this.rowCount = 3, this.runningSpace, @@ -100,7 +102,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { .enhanceNumberCardConfig .merge(defaultConfig); - if (itemChildren == null || itemChildren.length == 0) { + if (itemChildren == null || itemChildren!.length == 0) { return Container( height: 0, width: 0, @@ -114,25 +116,25 @@ class BrnEnhanceNumberCard extends StatelessWidget { ); // 容错显示的行数 显示三行 int count = rowCount; - if (rowCount <= 0 || rowCount > itemChildren.length) { + if (rowCount <= 0 || rowCount > itemChildren!.length) { count = 3; } double width = constraints.maxWidth; double singleWidth = (width - padding.left - padding.right) / count; - if (itemChildren.length > 1) { + if (itemChildren!.length > 1) { // 平铺下来 contentWidget = Wrap( runSpacing: defaultConfig.runningSpace, spacing: 0.0, - children: itemChildren.map((data) { + children: itemChildren!.map((data) { //每行的最后一个 不显示分割线 //最后一个元素 不显示分割线 - bool condition1 = (itemChildren.indexOf(data) + 1) % count == 0; - bool condition2 = itemChildren.last == data; + bool condition1 = (itemChildren!.indexOf(data) + 1) % count == 0; + bool condition2 = itemChildren!.last == data; bool allCondition = condition1 || condition2; - bool isFirst = (itemChildren.indexOf(data) + 1) % count == 1; + bool isFirst = (itemChildren!.indexOf(data) + 1) % count == 1; return Container( width: singleWidth, child: Row( @@ -163,7 +165,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { }).toList(), ); } else { - contentWidget = _buildItemWidget(itemChildren[0], defaultConfig); + contentWidget = _buildItemWidget(itemChildren![0], defaultConfig); } return Container( @@ -177,7 +179,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { Widget _buildItemWidget( BrnNumberInfoItemModel model, BrnEnhanceNumberCardConfig config, - {double width}) { + {double? width}) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, @@ -194,9 +196,9 @@ class BrnEnhanceNumberCard extends StatelessWidget { Widget _buildTopWidget( BrnNumberInfoItemModel model, BrnEnhanceNumberCardConfig config, - {double width}) { + {double? width}) { if (model.topWidget != null) { - return model.topWidget; + return model.topWidget!; } return Row( mainAxisSize: MainAxisSize.min, @@ -207,7 +209,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { Container( height: 26, transform: Matrix4.translationValues(0, 1, 0), - child: Text(model.number, + child: Text(model.number!, style: TextStyle( height: 1.0, textBaseline: TextBaseline.ideographic, @@ -225,9 +227,9 @@ class BrnEnhanceNumberCard extends StatelessWidget { Widget _buildBottomWidget( BrnNumberInfoItemModel model, BrnEnhanceNumberCardConfig config, - {double width}) { + {double? width}) { if (model.bottomWidget != null) { - return model.bottomWidget; + return model.bottomWidget!; } TextSpan span = TextSpan( text: model.title ?? "", @@ -247,10 +249,10 @@ class BrnEnhanceNumberCard extends StatelessWidget { ); if (model.iconTapCallBack != null) { Widget icon = - BrunoTools.getAssetSizeImage(BrnAsset.ICON_QUESTION, 14, 14); + BrunoTools.getAssetSizeImage(BrnAsset.iconQuestion, 14, 14); - if (model.numberInfoIcon == BrnNumberInfoIcon.ARROW) { - icon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_RIGHT_ARROW, 14, 14); + if (model.numberInfoIcon == BrnNumberInfoIcon.arrow) { + icon = BrunoTools.getAssetSizeImage(BrnAsset.iconRightArrow, 14, 14); } debugPrint('${tp.height}'); debugPrint(model.title); @@ -268,7 +270,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { ), GestureDetector( onTap: () { - model.iconTapCallBack(model); + model.iconTapCallBack!(model); }, child: icon, ) @@ -278,7 +280,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { return text; } - Widget _getPreWidget(String preDesc, BrnEnhanceNumberCardConfig config) { + Widget _getPreWidget(String? preDesc, BrnEnhanceNumberCardConfig config) { if (preDesc == null || preDesc.isEmpty) { return Container( height: 0, @@ -288,7 +290,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { return Padding( padding: const EdgeInsets.only(left: 1), child: Text( - preDesc ?? "", + preDesc, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -300,7 +302,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { ); } - Widget _getLastWidget(String lastDesc, BrnEnhanceNumberCardConfig config) { + Widget _getLastWidget(String? lastDesc, BrnEnhanceNumberCardConfig config) { if (lastDesc == null || lastDesc.isEmpty) { return Container( height: 0, @@ -309,7 +311,7 @@ class BrnEnhanceNumberCard extends StatelessWidget { } return Padding( padding: const EdgeInsets.only(left: 1, top: 0), - child: Text(lastDesc ?? "", + child: Text(lastDesc, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( @@ -323,35 +325,35 @@ class BrnEnhanceNumberCard extends StatelessWidget { /// 用来显示强化数据的model class BrnNumberInfoItemModel { ///number必须是非中文,否则会展示异常,如果有中文信息 则设置pre和last字段 - final String number; + final String? number; ///下半部分的辅助信息 - final String title; + final String? title; ///强化信息的前面展示字段 - final String preDesc; + final String? preDesc; ///强化信息的后面展示字段 - final String lastDesc; + final String? lastDesc; ///icon的事件 - final Function(BrnNumberInfoItemModel) iconTapCallBack; + final Function(BrnNumberInfoItemModel)? iconTapCallBack; ///icon的样式 可枚举 , 默认为问号 final BrnNumberInfoIcon numberInfoIcon; ///上半部分的自定义内容 如果设置了优先级则高于 number、preDesc和lastDesc - final Widget topWidget; + final Widget? topWidget; ///下半部分的自定义内容 如果设置了优先级则高于 title - final Widget bottomWidget; + final Widget? bottomWidget; ///上部分的:(number、preDesc、lastDesc)和topWidget 必须设置一个 ///下部分的:title和title 必须设置一个 BrnNumberInfoItemModel({ this.number, this.title, - this.numberInfoIcon = BrnNumberInfoIcon.QUESTION, + this.numberInfoIcon = BrnNumberInfoIcon.question, this.iconTapCallBack, this.preDesc, this.lastDesc, @@ -362,6 +364,6 @@ class BrnNumberInfoItemModel { ///可扩展 enum BrnNumberInfoIcon { - ARROW, - QUESTION, + arrow, + question, } diff --git a/lib/src/components/card/content_card/brn_pair_info_rich_grid.dart b/lib/src/components/card/content_card/brn_pair_info_rich_grid.dart index f9c9d7fd..ca1f2666 100644 --- a/lib/src/components/card/content_card/brn_pair_info_rich_grid.dart +++ b/lib/src/components/card/content_card/brn_pair_info_rich_grid.dart @@ -1,3 +1,5 @@ + + import 'dart:ui' as ui; import 'package:bruno/src/constants/brn_asset_constants.dart'; @@ -37,27 +39,27 @@ import 'package:flutter/material.dart'; /// * [BrnPairInfoTable], 单列key-value信息集合组件 /// class BrnRichInfoGrid extends StatelessWidget { - final List pairInfoList; + final List? pairInfoList; ///行间距 纵向 - final double rowSpace; + final double? rowSpace; ///gridView 为children包裹的padding,默认是从media中获取,支持修改 ///同gridView的padding - final EdgeInsetsGeometry padding; + final EdgeInsetsGeometry? padding; ///元素间距 横向 - final double space; + final double? space; - final double itemHeight; + final double? itemHeight; /// 一共多少列 默认2列 final int crossAxisCount; - final BrnPairRichInfoGridConfig themeData; + final BrnPairRichInfoGridConfig? themeData; BrnRichInfoGrid({ - Key key, + Key? key, this.pairInfoList, this.padding, this.rowSpace, @@ -69,7 +71,7 @@ class BrnRichInfoGrid extends StatelessWidget { @override Widget build(BuildContext context) { - if (pairInfoList == null || pairInfoList.isEmpty) { + if (pairInfoList == null || pairInfoList!.isEmpty) { return Container( height: 0, width: 0, @@ -117,16 +119,16 @@ class BrnRichInfoGrid extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.center, children: [ _getKeyWidget( - pairInfoList[index], + pairInfoList![index], gridWidth, context, defaultConfig, ), - _getValueWidget(pairInfoList[index], defaultConfig) + _getValueWidget(pairInfoList![index], defaultConfig) ], ); }, - itemCount: (null != this.pairInfoList) ? this.pairInfoList.length : 0, + itemCount: (null != this.pairInfoList) ? this.pairInfoList!.length : 0, ); return gridView; }, @@ -135,7 +137,7 @@ class BrnRichInfoGrid extends StatelessWidget { Widget _getKeyWidget(BrnRichGridInfo info, double width, BuildContext context, BrnPairRichInfoGridConfig config) { - if (info == null || info.keyPart == null) { + if (info.keyPart == null) { return Container( height: 0, width: 0, @@ -163,12 +165,6 @@ class BrnRichInfoGrid extends StatelessWidget { Widget _getValueWidget( BrnRichGridInfo info, BrnPairRichInfoGridConfig config) { - if (info == null) { - return Container( - height: 0, - width: 0, - ); - } if (info.valuePart == null) { return Text('--', style: _getValueStyle('--', themeData: config)); } @@ -210,12 +206,12 @@ class BrnRichGridInfo { static BrnRichGridInfo valueLastClickInfo( String keyTitle, String valueTitle, { - Function(String key) keyQuestionCallback, - Function(String value) valueQuestionCallback, - String clickTitle, - Color clickColor, - Function(String clickValue) clickCallback, - BrnPairRichInfoGridConfig themeData, + Function(String key)? keyQuestionCallback, + Function(String value)? valueQuestionCallback, + String clickTitle = '', + Color? clickColor, + Function(String clickValue)? clickCallback, + BrnPairRichInfoGridConfig? themeData, }) { themeData ??= BrnPairRichInfoGridConfig(); themeData = themeData.merge(BrnPairRichInfoGridConfig( @@ -229,19 +225,19 @@ class BrnRichGridInfo { return GestureDetector( onTap: () { if (isKey) { - keyQuestionCallback(keyTitle); + keyQuestionCallback!(keyTitle); } else { - valueQuestionCallback(valueTitle); + valueQuestionCallback!(valueTitle); } }, child: Padding( padding: EdgeInsets.only(left: isKey ? 0 : 4), child: BrunoTools.getAssetSizeImage( - BrnAsset.ICON_PAIR_INFO_QUESTION, 14, 14), + BrnAsset.iconPairInfoQuestion, 14, 14), )); } - Widget _getClickValue({BrnPairRichInfoGridConfig themeData}) { + Widget _getClickValue({required BrnPairRichInfoGridConfig themeData}) { return GestureDetector( onTap: () { if (clickCallback != null) { @@ -264,10 +260,10 @@ class BrnRichGridInfo { bool isShowKeyQuestion = keyQuestionCallback != null; bool isShowValueQuestion = valueQuestionCallback != null; - bool isShowValueClick = clickTitle != null && clickTitle.isNotEmpty; + bool isShowValueClick = clickTitle.isNotEmpty; MediaQueryData mediaQuery = MediaQueryData.fromWindow(ui.window); - double screen = mediaQuery?.size?.width ?? 375; + double screen = mediaQuery.size.width; Widget key = Container( constraints: BoxConstraints( @@ -280,7 +276,7 @@ class BrnRichGridInfo { children: [ Flexible( child: Text( - keyTitle ?? "", + keyTitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: _getKeyStyle(themeData: themeData), @@ -308,7 +304,7 @@ class BrnRichGridInfo { children: [ Flexible( child: Text( - valueTitle ?? "", + valueTitle, maxLines: 1, overflow: TextOverflow.ellipsis, style: _getValueStyle(valueTitle, themeData: themeData), @@ -334,13 +330,13 @@ class BrnRichGridInfo { } } -TextStyle _getKeyStyle({BrnPairRichInfoGridConfig themeData}) => - themeData.keyTextStyle?.generateTextStyle(); +TextStyle? _getKeyStyle({BrnPairRichInfoGridConfig? themeData}) => + themeData?.keyTextStyle.generateTextStyle(); -TextStyle _getClickStyle(String content, Color clickColor, - {BrnPairRichInfoGridConfig themeData}) => - themeData.linkTextStyle?.generateTextStyle(); +TextStyle? _getClickStyle(String? content, Color? clickColor, + {BrnPairRichInfoGridConfig? themeData}) => + themeData?.linkTextStyle.generateTextStyle(); -TextStyle _getValueStyle(String content, - {BrnPairRichInfoGridConfig themeData}) => - themeData?.valueTextStyle?.generateTextStyle(); +TextStyle? _getValueStyle(String content, + {BrnPairRichInfoGridConfig? themeData}) => + themeData?.valueTextStyle.generateTextStyle(); diff --git a/lib/src/components/card/content_card/brn_pair_info_table.dart b/lib/src/components/card/content_card/brn_pair_info_table.dart index 6a840977..2e7b7a4c 100644 --- a/lib/src/components/card/content_card/brn_pair_info_table.dart +++ b/lib/src/components/card/content_card/brn_pair_info_table.dart @@ -5,6 +5,7 @@ import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:bruno/src/utils/brn_rich_text.dart'; import 'package:bruno/src/utils/brn_tools.dart'; +import 'package:bruno/src/utils/css/brn_core_funtion.dart'; import 'package:bruno/src/utils/css/brn_css_2_text.dart'; import 'package:flutter/material.dart'; @@ -84,21 +85,21 @@ class BrnPairInfoTable extends StatefulWidget { final bool isFolded; /// 每一行的间距 默认4 - final double rowDistance; + final double? rowDistance; /// key和value的间距 默认2 - final double itemSpacing; + final double? itemSpacing; - final BrnPairInfoTableConfig themeData; + final BrnPairInfoTableConfig? themeData; ///对齐情况下,自定义的key展示规则 ///默认是最大的Key展示长度是107 ///可以参考[_MaxWrapTableWidth]实现自定义的展示规则,指定长度等 - final TableColumnWidth customKeyWidth; + final TableColumnWidth? customKeyWidth; BrnPairInfoTable({ - Key key, - @required this.children, + Key? key, + required this.children, this.isValueAlign = true, this.expandAtIndex = -1, this.rowDistance, @@ -114,27 +115,27 @@ class BrnPairInfoTable extends StatefulWidget { class _BrnPairInfoTableState extends State { //当前的展示状态 - bool _isFolded; + late bool _isFolded; //指定索引位置去具备展开功能 - int _expandAtIndex; + late int _expandAtIndex; // 收起状态显示的孩子 - List foldList; + List? foldList; // 展开状态显示的孩子 - List expandedList; + List? expandedList; // 在页面呈现的孩子 - List showList; + List? showList; // 指定位置的最原始 modal - BrnInfoModal indexModal; + BrnInfoModal? indexModal; // 是否具备展开收起功能 如果不展示则显示全部 bool canExpanded = false; - BrnPairInfoTableConfig themeData; + late BrnPairInfoTableConfig themeData; @override void initState() { @@ -166,7 +167,6 @@ class _BrnPairInfoTableState extends State { @override void didUpdateWidget(BrnPairInfoTable oldWidget) { super.didUpdateWidget(oldWidget); - themeData ??= BrnPairInfoTableConfig(); themeData = themeData.merge(BrnPairInfoTableConfig(rowSpacing: widget.rowDistance)); themeData = BrnThemeConfigurator.instance @@ -208,8 +208,8 @@ class _BrnPairInfoTableState extends State { return showWidget; } - Widget _finalValueWidget(BrnInfoModal data, {double itemSpacing}) { - Widget valueWidget; + Widget _finalValueWidget(BrnInfoModal data, {double? itemSpacing}) { + Widget? valueWidget; if (data.valuePart is String) { valueWidget = _valueTitleText(data.valuePart, @@ -222,7 +222,7 @@ class _BrnPairInfoTableState extends State { if (valueWidget == null) { valueWidget = Text( '--', - style: themeData.valueTextStyle?.generateTextStyle(), + style: themeData.valueTextStyle.generateTextStyle(), ); } } @@ -233,7 +233,7 @@ class _BrnPairInfoTableState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(child: valueWidget), - BrunoTools.getAssetImage(BrnAsset.ICON_RIGHT_ARROW), + BrunoTools.getAssetImage(BrnAsset.iconRightArrow), ], ); } @@ -259,8 +259,8 @@ class _BrnPairInfoTableState extends State { /// 张开状态的孩子 /// 替换最后的value 为具备收起功能的 value /// 替换index的value 为原始的value - List _generateExpandedList() { - List finalChildren = List.of(widget.children); + List _generateExpandedList() { + List finalChildren = List.of(widget.children); BrnInfoModal foldRowWidget = _expandedButtonWidget(); finalChildren[_expandAtIndex] = indexModal; finalChildren[widget.children.length - 1] = foldRowWidget; @@ -268,7 +268,7 @@ class _BrnPairInfoTableState extends State { } BrnInfoModal _foldButtonWidget() { - Image img = BrunoTools.getAssetImage('icons/icon_uparrow.png'); + Image img = BrunoTools.getAssetImage(BrnAsset.iconUpArrow); Transform trsm = Transform.rotate(angle: pi, child: img); Row row = Row( children: [ @@ -310,9 +310,9 @@ class _BrnPairInfoTableState extends State { /// 将原有的value显示替换为 stack BrnInfoModal brnMetaInfoModal = BrnInfoModal( - isArrow: indexModal.isArrow, - keyPart: indexModal.keyPart, - valuePart: indexModal.valuePart, + isArrow: indexModal!.isArrow, + keyPart: indexModal!.keyPart, + valuePart: indexModal!.valuePart, ); Container stack = Container( child: Stack( @@ -327,7 +327,7 @@ class _BrnPairInfoTableState extends State { } BrnInfoModal _expandedButtonWidget() { - Image img = BrunoTools.getAssetImage('icons/icon_uparrow.png'); + Image img = BrunoTools.getAssetImage(BrnAsset.iconUpArrow); Row row = Row( children: [ Padding( @@ -388,7 +388,7 @@ class _BrnPairInfoTableState extends State { Widget _valueTitleText(String text, {bool isValueAlign = true, bool isArrow = false, - BrnPairInfoTableConfig themeData}) { + required BrnPairInfoTableConfig themeData}) { bool isSingle; if (isArrow) { isSingle = true; @@ -407,7 +407,7 @@ class _BrnPairInfoTableState extends State { show, overflow: isSingle ? TextOverflow.ellipsis : TextOverflow.clip, maxLines: isSingle ? 1 : null, - style: themeData.valueTextStyle?.generateTextStyle(), + style: themeData.valueTextStyle.generateTextStyle(), ); return keyOrValue; } @@ -417,9 +417,9 @@ mixin PairInfoPart { bool isValueAlign(); BrnPairInfoTableConfig configDefaultThemeData( - BrnPairInfoTableConfig themeData, - {double rowDistance, - double itemSpacing}) { + BrnPairInfoTableConfig? themeData, + {double? rowDistance, + double? itemSpacing}) { BrnPairInfoTableConfig defaultThemeData; defaultThemeData = themeData ?? BrnPairInfoTableConfig(); defaultThemeData = defaultThemeData.merge(BrnPairInfoTableConfig( @@ -431,8 +431,8 @@ mixin PairInfoPart { return defaultThemeData; } - Widget finalKeyWidget(BrnInfoModal data, BrnPairInfoTableConfig themeData) { - Widget keyWidget; + Widget? finalKeyWidget(BrnInfoModal data, BrnPairInfoTableConfig themeData) { + Widget? keyWidget; if (data.keyPart is String) { keyWidget = keyOrValueTitleText(true, data.keyPart.toString(), isValueAlign: isValueAlign(), @@ -445,8 +445,8 @@ mixin PairInfoPart { } Widget finalValueWidget(BrnInfoModal data, BrnPairInfoTableConfig themeData, - {double itemSpacing}) { - Widget valueWidget; + {double? itemSpacing}) { + Widget? valueWidget; if (data.valuePart is String) { valueWidget = keyOrValueTitleText(false, data.valuePart, @@ -459,7 +459,7 @@ mixin PairInfoPart { if (valueWidget == null) { valueWidget = Text( '--', - style: themeData.valueTextStyle?.generateTextStyle(), + style: themeData.valueTextStyle.generateTextStyle(), ); } } @@ -470,7 +470,7 @@ mixin PairInfoPart { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Expanded(child: valueWidget), - BrunoTools.getAssetImage(BrnAsset.ICON_RIGHT_ARROW), + BrunoTools.getAssetImage(BrnAsset.iconRightArrow), ], ); } @@ -483,7 +483,7 @@ mixin PairInfoPart { Widget keyOrValueTitleText(bool isKey, String text, {bool isValueAlign = true, bool isArrow = false, - BrnPairInfoTableConfig themeData}) { + required BrnPairInfoTableConfig themeData}) { bool isSingle; if (isArrow) { isSingle = true; @@ -507,8 +507,8 @@ mixin PairInfoPart { overflow: isSingle ? TextOverflow.ellipsis : TextOverflow.clip, maxLines: isSingle ? 1 : null, style: isKey - ? themeData.keyTextStyle?.generateTextStyle() - : themeData.valueTextStyle?.generateTextStyle(), + ? themeData.keyTextStyle.generateTextStyle() + : themeData.valueTextStyle.generateTextStyle(), ); return keyOrValue; } @@ -516,19 +516,19 @@ mixin PairInfoPart { class BrnFollowPairInfo extends StatelessWidget with PairInfoPart { /// 待展示的文本信息集合 - final List children; + final List? children; /// 每一行的间距 - final double rowDistance; + final double? rowDistance; /// key和value的间距 - final double itemSpacing; + final double? itemSpacing; - final BrnPairInfoTableConfig themeData; + final BrnPairInfoTableConfig? themeData; BrnFollowPairInfo({ - Key key, - @required this.children, + Key? key, + required this.children, this.rowDistance, this.itemSpacing, this.themeData, @@ -550,13 +550,13 @@ class BrnFollowPairInfo extends StatelessWidget with PairInfoPart { builder: (context, constraints) { return Column( crossAxisAlignment: CrossAxisAlignment.start, - children: children.map((data) { + children: children!.map((data) { index++; return Padding( - padding: - EdgeInsets.only(top: (index == 0) ? 0 : themeData.rowSpacing), + padding: EdgeInsets.only( + top: (index == 0) ? 0 : themeData!.rowSpacing), child: _buildSingleInfo( - data, constraints.maxWidth / 2, defaultThemeConfig), + data!, constraints.maxWidth / 2, defaultThemeConfig), ); }).toList(), ); @@ -571,7 +571,7 @@ class BrnFollowPairInfo extends StatelessWidget with PairInfoPart { value = GestureDetector( onTap: () { if (infoModal.valueClickCallback != null) { - infoModal.valueClickCallback(); + infoModal.valueClickCallback!(); } }, child: value, @@ -600,20 +600,20 @@ class BrnFollowPairInfo extends StatelessWidget with PairInfoPart { class BrnAlignPairInfo extends StatelessWidget with PairInfoPart { /// 待展示的文本信息集合 - final List children; + final List? children; ///控件的背景色 默认为白色 - final Color backgroundColor; + final Color? backgroundColor; /// 每一行的间距 - final double rowDistance; + final double? rowDistance; /// key和value的间距 - final double itemSpacing; + final double? itemSpacing; - final TableColumnWidth customKeyWidth; + final TableColumnWidth? customKeyWidth; - final BrnPairInfoTableConfig themeData; + final BrnPairInfoTableConfig? themeData; BrnAlignPairInfo( {this.children, @@ -645,14 +645,14 @@ class BrnAlignPairInfo extends StatelessWidget with PairInfoPart { defaultVerticalAlignment: TableCellVerticalAlignment.baseline, textBaseline: TextBaseline.ideographic, columnWidths: { - 0: customKeyWidth ?? _MaxWrapTableWidth(maxWidth: maxWith), + 0: customKeyWidth ?? _MaxWrapTableWidth(maxWith), 1: FlexColumnWidth() }, border: TableBorder.all(color: Colors.transparent), - children: children.map((data) { + children: children!.map((data) { index++; return _buildSingleInfo( - data, index == children.length - 1, defaultThemeConfig); + data!, index == children!.length - 1, defaultThemeConfig); }).toList(), ); return table; @@ -674,14 +674,14 @@ class BrnAlignPairInfo extends StatelessWidget with PairInfoPart { value = GestureDetector( onTap: () { if (infoModal.valueClickCallback != null) { - infoModal.valueClickCallback(); + infoModal.valueClickCallback!(); } }, child: value, ); } return TableRow( - children: [finalKeyWidget(infoModal, defaultThemeConfig), value]); + children: [finalKeyWidget(infoModal, defaultThemeConfig)!, value]); } } @@ -702,7 +702,7 @@ class BrnInfoModal { final bool isArrow; /// value的点击回调 - final VoidCallback valueClickCallback; + final VoidCallback? valueClickCallback; BrnInfoModal( {this.keyPart, @@ -710,8 +710,7 @@ class BrnInfoModal { this.isArrow = false, this.valueClickCallback}) : assert(keyPart == null || keyPart is String || keyPart is Widget), - assert( - valuePart == null || valuePart is String || valuePart is Widget) {} + assert(valuePart == null || valuePart is String || valuePart is Widget); ///-----------以下静态方法为常见显示的快捷构造----------- /// value的最后一部分带有可点击的超链接 @@ -726,14 +725,14 @@ class BrnInfoModal { String keyTitle, String valueTitle, String clickValue, { - double fontSize, - double itemSpacing, - TextStyle valueTextStyle, - Function(String clickValue) clickCallback, + double? fontSize, + double? itemSpacing, + TextStyle? valueTextStyle, + Function(String? clickValue)? clickCallback, bool isArrow = false, - VoidCallback valueClickCallback, - Color linkColor, - BrnPairInfoTableConfig themeData, + VoidCallback? valueClickCallback, + Color? linkColor, + BrnPairInfoTableConfig? themeData, }) { themeData ??= BrnPairInfoTableConfig(); themeData = themeData.merge(BrnPairInfoTableConfig( @@ -759,7 +758,7 @@ class BrnInfoModal { valueTitle, overflow: TextOverflow.ellipsis, maxLines: 1, - style: themeData.valueTextStyle?.generateTextStyle(), + style: themeData.valueTextStyle.generateTextStyle(), ), ), GestureDetector( @@ -772,7 +771,7 @@ class BrnInfoModal { clickValue, overflow: TextOverflow.ellipsis, maxLines: 1, - style: themeData.linkTextStyle?.generateTextStyle(), + style: themeData.linkTextStyle.generateTextStyle(), ), ) ], @@ -781,11 +780,11 @@ class BrnInfoModal { valueWidget = BrnRichTextGenerator() .addText( valueTitle, - textStyle: themeData.valueTextStyle?.generateTextStyle(), + textStyle: themeData.valueTextStyle.generateTextStyle(), ) .addTextWithLink( clickValue, - textStyle: themeData.linkTextStyle?.generateTextStyle(), + textStyle: themeData.linkTextStyle.generateTextStyle(), richTextLinkClick: (text, url) { if (clickCallback != null) { clickCallback(text); @@ -821,15 +820,15 @@ class BrnInfoModal { String valueTitle, { bool keyShow = false, bool valueShow = true, - double fontSize, - double itemSpacing, - TextStyle keyTextStyle, - TextStyle valueTextStyle, - Function keyCallback, - Function valueCallback, + double? fontSize, + double? itemSpacing, + TextStyle? keyTextStyle, + TextStyle? valueTextStyle, + Function? keyCallback, + Function? valueCallback, bool isArrow = false, - VoidCallback valueClickCallback, - BrnPairInfoTableConfig themeData, + VoidCallback? valueClickCallback, + BrnPairInfoTableConfig? themeData, }) { themeData ??= BrnPairInfoTableConfig(); themeData = themeData.merge(BrnPairInfoTableConfig( @@ -848,7 +847,7 @@ class BrnInfoModal { if (isArrow) { MediaQueryData mediaQuery = MediaQueryData.fromWindow(ui.window); - double screen = mediaQuery?.size?.width ?? 375; + double screen = mediaQuery.size.width; if (keyShow) { keyWidget = Container( @@ -862,7 +861,7 @@ class BrnInfoModal { keyTitle, overflow: TextOverflow.ellipsis, maxLines: 1, - style: themeData.keyTextStyle?.generateTextStyle(), + style: themeData.keyTextStyle.generateTextStyle(), ), ), GestureDetector( @@ -871,13 +870,13 @@ class BrnInfoModal { keyCallback(); } }, - child: BrunoTools.getAssetImage(BrnAsset.ICON_QUESTION), + child: BrunoTools.getAssetImage(BrnAsset.iconQuestion), ), Text( ':', overflow: TextOverflow.ellipsis, maxLines: 1, - style: themeData.valueTextStyle?.generateTextStyle(), + style: themeData.valueTextStyle.generateTextStyle(), ) ], ), @@ -895,7 +894,7 @@ class BrnInfoModal { valueTitle, overflow: TextOverflow.ellipsis, maxLines: 1, - style: themeData.keyTextStyle?.generateTextStyle(), + style: themeData.keyTextStyle.generateTextStyle(), ), ), GestureDetector( @@ -904,7 +903,7 @@ class BrnInfoModal { valueCallback(); } }, - child: BrunoTools.getAssetImage(BrnAsset.ICON_QUESTION), + child: BrunoTools.getAssetImage(BrnAsset.iconQuestion), ) ], ); @@ -914,7 +913,7 @@ class BrnInfoModal { } else { BrnRichTextGenerator keyGen = BrnRichTextGenerator(); keyGen.addText(keyTitle, - textStyle: themeData.keyTextStyle?.generateTextStyle()); + textStyle: themeData.keyTextStyle.generateTextStyle()); if (keyShow) { keyGen.addIcon(GestureDetector( onTap: () { @@ -922,16 +921,16 @@ class BrnInfoModal { keyCallback(); } }, - child: BrunoTools.getAssetImage(BrnAsset.ICON_QUESTION), + child: BrunoTools.getAssetImage(BrnAsset.iconQuestion), )); keyGen.addText(':', - textStyle: themeData.keyTextStyle?.generateTextStyle()); + textStyle: themeData.keyTextStyle.generateTextStyle()); } keyWidget = keyGen.build(); BrnRichTextGenerator valueGen = BrnRichTextGenerator(); valueGen.addText(valueTitle, - textStyle: themeData.valueTextStyle?.generateTextStyle()); + textStyle: themeData.valueTextStyle.generateTextStyle()); if (valueShow) { valueGen.addIcon(GestureDetector( onTap: () { @@ -939,7 +938,7 @@ class BrnInfoModal { valueCallback(); } }, - child: BrunoTools.getAssetImage(BrnAsset.ICON_QUESTION), + child: BrunoTools.getAssetImage(BrnAsset.iconQuestion), )); } valueWidget = valueGen.build(); @@ -963,14 +962,14 @@ class BrnInfoModal { static BrnInfoModal keyHeadIconInfo( String keyTitle, String valueTitle, { - Widget headIcon, - double fontSize, - double itemSpacing, - TextStyle keyTextStyle, - TextStyle valueTextStyle, + Widget? headIcon, + double? fontSize, + double? itemSpacing, + TextStyle? keyTextStyle, + TextStyle? valueTextStyle, bool isArrow = false, - VoidCallback valueClickCallback, - BrnPairInfoTableConfig themeData, + VoidCallback? valueClickCallback, + BrnPairInfoTableConfig? themeData, }) { themeData ??= BrnPairInfoTableConfig(); themeData = themeData.merge(BrnPairInfoTableConfig( @@ -1001,7 +1000,7 @@ class BrnInfoModal { } keyGen.addText(keyTitle, - textStyle: themeData.keyTextStyle?.generateTextStyle()); + textStyle: themeData.keyTextStyle.generateTextStyle()); return BrnInfoModal( keyPart: keyGen.build(), @@ -1014,13 +1013,13 @@ class BrnInfoModal { static BrnInfoModal valueRichTextInfo( String keyTitle, String valueTitle, { - double fontSize, - double itemSpacing, - TextStyle valueTextStyle, + double? fontSize, + required double itemSpacing, + TextStyle? valueTextStyle, bool isArrow = false, - BrnRichTextLinkClick richTextLinkClick, - VoidCallback valueClickCallback, - BrnPairInfoTableConfig themeData, + BrnHyperLinkCallback? richTextLinkClick, + VoidCallback? valueClickCallback, + BrnPairInfoTableConfig? themeData, }) { themeData ??= BrnPairInfoTableConfig(); themeData = themeData.merge(BrnPairInfoTableConfig( @@ -1042,7 +1041,7 @@ class BrnInfoModal { maxLines: isArrow ? 1 : null, textOverflow: isArrow ? TextOverflow.ellipsis : TextOverflow.clip, - defaultStyle: themeData.valueTextStyle?.generateTextStyle(), + defaultStyle: themeData.valueTextStyle.generateTextStyle(), linksCallback: (text, url) { if (richTextLinkClick != null) { richTextLinkClick(text, url); @@ -1083,5 +1082,5 @@ class _MaxWrapTableWidth extends TableColumnWidth { return 0; } - _MaxWrapTableWidth({this.maxWidth}); + _MaxWrapTableWidth(this.maxWidth); } diff --git a/lib/src/components/card/shadow_card/brn_shadow_card.dart b/lib/src/components/card/shadow_card/brn_shadow_card.dart index c68fda31..e2969c82 100644 --- a/lib/src/components/card/shadow_card/brn_shadow_card.dart +++ b/lib/src/components/card/shadow_card/brn_shadow_card.dart @@ -36,10 +36,10 @@ class BrnShadowCard extends StatelessWidget { final double borderWidth; BrnShadowCard( - {@required this.child, - this.color, - this.shadowColor, - this.padding, + {required this.child, + this.color = const Color(0xfffafafa), + this.shadowColor = const Color(0xffeeeeee), + this.padding = const EdgeInsets.all(0), this.circular = 4.0, this.blurRadius = 5.0, this.spreadRadius = 0, @@ -49,18 +49,14 @@ class BrnShadowCard extends StatelessWidget { @override Widget build(BuildContext context) { double tempBorderWidth = 0; - if (this.borderWidth != null && this.borderWidth > 0) { + if (this.borderWidth > 0) { tempBorderWidth = this.borderWidth; } return Container( - padding: padding ?? EdgeInsets.all(0), - child: this.child ?? - Container( - width: 0, - height: 0, - ), + padding: padding, + child: this.child, decoration: BoxDecoration( - color: this.color ?? Color(0xfffafafa), + color: this.color, borderRadius: BorderRadius.all(Radius.circular(circular)), border: tempBorderWidth != 0 ? Border.all( @@ -72,7 +68,7 @@ class BrnShadowCard extends StatelessWidget { : Border.all(style: BorderStyle.none), boxShadow: [ BoxShadow( - color: this.shadowColor ?? Color(0xffeeeeee), + color: this.shadowColor, offset: this.offset, //阴影xy轴偏移量 blurRadius: this.blurRadius, //阴影模糊程度 spreadRadius: this.spreadRadius //阴影扩散程度 diff --git a/lib/src/components/card_title/brn_action_card_title.dart b/lib/src/components/card_title/brn_action_card_title.dart index f483e641..4cb00a2c 100644 --- a/lib/src/components/card_title/brn_action_card_title.dart +++ b/lib/src/components/card_title/brn_action_card_title.dart @@ -1,5 +1,4 @@ -import 'package:bruno/bruno.dart'; -import 'package:bruno/src/constants/brn_strings_constants.dart'; +import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_card_title_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; @@ -38,29 +37,28 @@ class BrnActionCardTitle extends StatelessWidget { final String title; ///箭头左边的文字 - final String accessoryText; + final String? accessoryText; ///标题点击 - final VoidCallback onTap; + final VoidCallback? onTap; ///标题右侧的小文字 - final String subTitle; + final String? subTitle; ///标题右侧的显示widget - final Widget subTitleWidget; + final Widget? subTitleWidget; - final BrnCardTitleConfig themeData; + final BrnCardTitleConfig? themeData; BrnActionCardTitle({ - Key key, - @required this.title, + Key? key, + required this.title, this.accessoryText, this.onTap, this.subTitle, this.subTitleWidget, this.themeData, - }) : assert(null != title), - super(key: key); + }) : super(key: key); @override Widget build(BuildContext context) { @@ -112,10 +110,10 @@ class BrnActionCardTitle extends StatelessWidget { return Container( padding: EdgeInsets.only(right: 8), child: Text( - this.title ?? "", + this.title, maxLines: 1, overflow: TextOverflow.ellipsis, - style: defaultConfig.titleTextStyle?.generateTextStyle(), + style: defaultConfig.titleTextStyle.generateTextStyle(), ), ); } @@ -123,24 +121,24 @@ class BrnActionCardTitle extends StatelessWidget { // 如果传入了subTitleWidget 则以subTitleWidget为主 Widget _sub(BrnCardTitleConfig defaultConfig) { if (subTitleWidget != null) { - return subTitleWidget; + return subTitleWidget!; } if (subTitle != null) { return Container( constraints: BoxConstraints(maxWidth: 84), - child: Text(this.subTitle, + child: Text(this.subTitle!, maxLines: 1, overflow: TextOverflow.ellipsis, style: subTextStyle(defaultConfig)), ); } - return Container(); + return SizedBox.shrink(); } Widget _arrowWidget() { - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_RIGHT_ARROW, 16, 16); + return BrunoTools.getAssetSizeImage(BrnAsset.iconRightArrow, 16, 16); } Widget _accessoryTextWidget(BrnCardTitleConfig defaultConfig) { @@ -156,7 +154,7 @@ class BrnActionCardTitle extends StatelessWidget { child: Text( accessoryText ?? "", overflow: TextOverflow.ellipsis, - style: defaultConfig.accessoryTextStyle?.generateTextStyle(), + style: defaultConfig.accessoryTextStyle.generateTextStyle(), ), ), _arrowWidget() @@ -167,5 +165,5 @@ class BrnActionCardTitle extends StatelessWidget { //标题右侧的小文字 样式 TextStyle subTextStyle(BrnCardTitleConfig defaultConfig) => - defaultConfig?.subtitleTextStyle?.generateTextStyle(); + defaultConfig.subtitleTextStyle.generateTextStyle(); } diff --git a/lib/src/components/card_title/brn_common_card_title.dart b/lib/src/components/card_title/brn_common_card_title.dart index 86f0840b..cea76fdf 100644 --- a/lib/src/components/card_title/brn_common_card_title.dart +++ b/lib/src/components/card_title/brn_common_card_title.dart @@ -50,34 +50,34 @@ class BrnCommonCardTitle extends StatelessWidget { final String title; /// 最右侧的文字 - final String accessoryText; + final String? accessoryText; /// 最右侧的widget 如果两者同时存在 则以widget为主 - final Widget accessoryWidget; + final Widget? accessoryWidget; /// 整个区域点击的回调 - final VoidCallback onTap; + final VoidCallback? onTap; /// 标题右侧的显示widget - final Widget subTitleWidget; + final Widget? subTitleWidget; /// 标题下面的文字 - final String detailTextString; + final String? detailTextString; /// title的流式文本的对齐方式 - final PlaceholderAlignment alignment; + final PlaceholderAlignment? alignment; /// 标题下方文字 默认是深色的222222 - final Color detailColor; + final Color? detailColor; /// 内容的padding 默认上下16 左右0 - final EdgeInsetsGeometry padding; + final EdgeInsetsGeometry? padding; - final BrnCardTitleConfig themeData; + final BrnCardTitleConfig? themeData; BrnCommonCardTitle( - {Key key, - @required this.title, + {Key? key, + required this.title, this.accessoryText, this.accessoryWidget, this.onTap, @@ -95,7 +95,7 @@ class BrnCommonCardTitle extends StatelessWidget { defaultConfig = defaultConfig.merge(BrnCardTitleConfig( alignment: alignment, - cardTitlePadding: padding, + cardTitlePadding: padding as EdgeInsets?, detailTextStyle: BrnTextStyle(color: detailColor))); defaultConfig = BrnThemeConfigurator.instance @@ -103,27 +103,22 @@ class BrnCommonCardTitle extends StatelessWidget { .cardTitleConfig .merge(defaultConfig); + Widget titleContainer = Container( + color: defaultConfig.cardBackgroundColor, + child: _rowWidget(context, defaultConfig), + ); + if (onTap == null) return titleContainer; return GestureDetector( - onTap: () { - if (onTap != null) { - onTap(); - } - }, - child: Container( - color: defaultConfig?.cardBackgroundColor, - child: _rowWidget(context, defaultConfig), - ), + onTap: onTap, + child: titleContainer, ); } Widget _rowWidget(BuildContext context, BrnCardTitleConfig defaultConfig) { - List children = List(); + List children = []; children.add(Expanded(child: _titleWidget(context, defaultConfig))); - Widget accessory = Container( - height: 0, - width: 0, - ); + Widget accessory = SizedBox.shrink(); // 左侧的文本的行高是25,那么右侧的widget最大为25 if (this.accessoryWidget != null) { accessory = Container( @@ -151,7 +146,7 @@ class BrnCommonCardTitle extends StatelessWidget { Widget _accessoryTextWidget(BrnCardTitleConfig defaultConfig) { Text tx = Text( accessoryText ?? "", - style: defaultConfig?.accessoryTextStyle?.generateTextStyle(), + style: defaultConfig.accessoryTextStyle.generateTextStyle(), ); return Container( @@ -172,28 +167,25 @@ class BrnCommonCardTitle extends StatelessWidget { ///标题widget Widget _titleWidget(BuildContext context, BrnCardTitleConfig defaultConfig) { - Widget subWidget = Container( - height: 0, - width: 0, - ); + Widget subWidget = SizedBox.shrink(); if (subTitleWidget != null) { subWidget = _subTitleWidgetFromWidget(); } var titleWidget = RichText( - textScaleFactor: MediaQuery.of(context)?.textScaleFactor ?? 1.0, + textScaleFactor: MediaQuery.of(context).textScaleFactor, text: TextSpan( - text: title ?? "", - style: defaultConfig?.titleWithHeightTextStyle?.generateTextStyle(), + text: title, + style: defaultConfig.titleWithHeightTextStyle.generateTextStyle(), children: [ WidgetSpan(child: subWidget, alignment: defaultConfig.alignment), ]), ); - List colChildren = List(); + List colChildren = []; colChildren.add(titleWidget); - if (null != detailTextString && detailTextString.isNotEmpty) { + if (null != detailTextString && detailTextString!.isNotEmpty) { Widget detailWidget = _detailTextWidget(defaultConfig); colChildren.add(detailWidget); } @@ -212,7 +204,7 @@ class BrnCommonCardTitle extends StatelessWidget { detailTextString ?? "", overflow: TextOverflow.ellipsis, maxLines: 2, - style: defaultConfig?.detailTextStyle?.generateTextStyle(), + style: defaultConfig.detailTextStyle.generateTextStyle(), ); return Container( child: tx, diff --git a/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart.dart b/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart.dart index e27cc652..30ea9fb9 100644 --- a/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart.dart +++ b/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart.dart @@ -27,25 +27,25 @@ class BrnDoughnutDataItem { double radius = 0; BrnDoughnutDataItem({ - this.value, - this.title, + required this.value, + required this.title, this.color = Colors.blueAccent, }); } /// 选中扇形区域后执行的回调 typedef BrnDoughnutSelectCallback = void Function( - BrnDoughnutDataItem selectedItem); + BrnDoughnutDataItem? selectedItem); class BrnDoughnut extends CustomPainter { ///圆心位置 - Offset circleCenter; + late Offset circleCenter; /// 选中的区域 - final BrnDoughnutDataItem selectedItem; + final BrnDoughnutDataItem? selectedItem; /// 选中区域回调 - final BrnDoughnutSelectCallback brnDoughnutSelectCallback; + final BrnDoughnutSelectCallback? brnDoughnutSelectCallback; /// 字体大小 final double fontSize; @@ -73,7 +73,7 @@ class BrnDoughnut extends CustomPainter { BrnDoughnut( {this.ringWidth = 50, - this.data, + required this.data, this.fontSize = 12, this.fontColor = Colors.white, this.selectedItem, @@ -81,10 +81,10 @@ class BrnDoughnut extends CustomPainter { this.brnDoughnutSelectCallback}) { double lastEndRadius = 0; double totalValue = 0; - this.data?.forEach((BrnDoughnutDataItem item) { + this.data.forEach((BrnDoughnutDataItem item) { totalValue += item.value; }); - this.data?.forEach((BrnDoughnutDataItem item) { + this.data.forEach((BrnDoughnutDataItem item) { item.percentage = item.value / totalValue; item.startRadius = lastEndRadius; item.radius = 2 * pi * item.percentage; @@ -108,7 +108,7 @@ class BrnDoughnut extends CustomPainter { Offset center = drawArea.center; circleCenter = center; - this.data?.forEach((BrnDoughnutDataItem item) { + this.data.forEach((BrnDoughnutDataItem item) { // 画扇形 Paint _paint = Paint() ..color = item.color @@ -124,9 +124,8 @@ class BrnDoughnut extends CustomPainter { canvas.drawArc(rect, item.startRadius, item.radius, true, _paint); // 画文本 - if (item.title != null && - (this.showTitleWhenSelected == false || - item.startRadius == selectedItem?.startRadius)) { + if (this.showTitleWhenSelected == false || + item.startRadius == selectedItem?.startRadius) { // 画引线 Offset indicarorLPoint = calcOffsetWith(item.middleRadius, indicatorLCircleRadius); @@ -228,7 +227,7 @@ class BrnDoughnut extends CustomPainter { } @override - bool hitTest(Offset position) { + bool? hitTest(Offset position) { int length = data.length; for (int i = 0; i < length; i++) { BrnDoughnutDataItem item = data[i]; @@ -236,7 +235,7 @@ class BrnDoughnut extends CustomPainter { if (item.startRadius < radain && radain < (item.startRadius + item.radius)) { if (null != brnDoughnutSelectCallback) - brnDoughnutSelectCallback( + brnDoughnutSelectCallback!( item.startRadius == selectedItem?.startRadius ? null : item); break; } @@ -268,10 +267,10 @@ class BrnDoughnutChart extends StatelessWidget { final double height; /// 选中的项目 - final BrnDoughnutDataItem selectedItem; + final BrnDoughnutDataItem? selectedItem; /// 选中项目时候的回掉 - final BrnDoughnutSelectCallback selectCallback; + final BrnDoughnutSelectCallback? selectCallback; /// 选中时展示文字大小,默认12 final double fontSize; @@ -296,7 +295,7 @@ class BrnDoughnutChart extends StatelessWidget { this.height = 0, this.padding = EdgeInsets.zero, this.ringWidth = 50, - this.data, + required this.data, this.fontSize = 12, this.fontColor = Colors.white, this.selectedItem, diff --git a/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart_legend.dart b/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart_legend.dart index a5c4c8fa..14acb767 100644 --- a/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart_legend.dart +++ b/lib/src/components/charts/brn_doughunt_chart/brn_doughnut_chart_legend.dart @@ -24,21 +24,22 @@ class DoughnutChartLegend extends StatelessWidget { final List data; DoughnutChartLegend( - {this.legendStyle = BrnDoughnutChartLegendStyle.wrap, this.data}); + {this.legendStyle = BrnDoughnutChartLegendStyle.wrap, + required this.data}); @override Widget build(BuildContext context) { if (BrnDoughnutChartLegendStyle.list == this.legendStyle) { - List items = List(); - this.data?.forEach((BrnDoughnutDataItem item) { + List items = []; + this.data.forEach((BrnDoughnutDataItem item) { items.add(this.genItem(item)); }); return Column( children: items, ); } else if (BrnDoughnutChartLegendStyle.wrap == this.legendStyle) { - List items = List(); - this.data?.forEach((BrnDoughnutDataItem item) { + List items = []; + this.data.forEach((BrnDoughnutDataItem item) { items.add(this.genItem(item)); }); @@ -48,7 +49,7 @@ class DoughnutChartLegend extends StatelessWidget { children: items, ); } else { - return Container(); + return const SizedBox.shrink(); } } @@ -68,7 +69,7 @@ class DoughnutChartLegend extends StatelessWidget { width: 6, ), Text( - item.title ?? '', + item.title, style: TextStyle(color: Colors.black), ), ], diff --git a/lib/src/components/charts/brn_progress_bar_chart/brn_bar_chart_data.dart b/lib/src/components/charts/brn_progress_bar_chart/brn_bar_chart_data.dart index f8df9ff3..5cd4d015 100644 --- a/lib/src/components/charts/brn_progress_bar_chart/brn_bar_chart_data.dart +++ b/lib/src/components/charts/brn_progress_bar_chart/brn_bar_chart_data.dart @@ -7,7 +7,7 @@ class BrnBarChartScaleStyle { /// y轴获取的值,只读 double get titleValue { - if (title == null || title.isEmpty) { + if (title.isEmpty) { return 0; } else { return double.parse(title); @@ -15,23 +15,23 @@ class BrnBarChartScaleStyle { } /// 刻度标志样式 - TextStyle titleStyle; + TextStyle? titleStyle; /// 与最大数值的比率,用来计算绘制刻度的位置使用。 - double positionRetioy; + double? positionRetioy; /// 下面标注文案独属y轴使用,目前还没有x轴扩展需求,x轴设置下面参数无效,后期有需要再扩展 /// 两个刻度之间的标注文案(向前绘制即x轴在该刻度左侧绘制,y轴在该刻度下面绘制),不需要的话不设置 - String centerSubTitle; + String? centerSubTitle; /// 标注文案样式,centerSubTitle有内容时有效 - TextStyle centerSubTextStyle; + TextStyle? centerSubTextStyle; /// 标注文案位置是否是在左侧,false表示在右侧,centerSubTitle有内容时有效 bool isLeft; BrnBarChartScaleStyle( - {this.title, + {required this.title, this.titleStyle, this.centerSubTitle, this.centerSubTextStyle, @@ -58,10 +58,10 @@ class BrnBarDataBean { /// 每条线的定义 class BrnBarBean { /// 名称 - String name; + String? name; ///x轴的字体样式 - TextStyle xTitleStyle; + TextStyle? xTitleStyle; ///是否显示x轴的文字,用来处理多个线条绘制的时候,同一x轴坐标不需要绘制多次,则只需要将多条线中一个标记绘制即可 bool isDrawX; @@ -76,19 +76,19 @@ class BrnBarBean { bool isCurve; ///点集合 - List points; + List? points; ///曲线或折线的颜色 Color lineColor; ///填充色 - List colors; + List? colors; ///占位图是否需要打断线条绘制,如果打断的话这个点的y值将没有意义,只有x轴有效,如果不打断的话,y轴值有效 bool placehoderImageBreak; ///用户当前进行位置的小图标(比如一个小锁),默认没有只显示y轴的值,如果有内容则显示这个小图标, - ui.Image placehoderImage; + ui.Image? placehoderImage; BrnBarBean( {this.name, this.xTitleStyle, diff --git a/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart.dart b/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart.dart index df33b1ee..fb12f8de 100644 --- a/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart.dart +++ b/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart.dart @@ -27,7 +27,7 @@ class BrnProgressBarChart extends StatefulWidget { /// 单个柱形宽度,默认 30 final double singleBarWidth; - /// 柱状图的最大值,柱状图的宽/高会依此值计算,默认 0 + /// 柱状图的最大值,柱状图的宽/高会依此值计算,默认 0,为0时自动计算柱状图最大值 final double barMaxValue; /// 柱状图方向,默认 BarChartStyle.vertical @@ -40,25 +40,25 @@ class BrnProgressBarChart extends StatefulWidget { final Color selectedHintTextBackgroundColor; /// 是否可点击回调 - final OnBarItemClickInterceptor onBarItemClickInterceptor; + final OnBarItemClickInterceptor? onBarItemClickInterceptor; - /// 选中柱状图时候的回调 - final BrnProgressBarChartSelectCallback barChartSelectCallback; + /// 选中柱状图时候的回调(暂仅支持垂直柱状图) + final BrnProgressBarChartSelectCallback? barChartSelectCallback; /// 图表高度,竖直柱状图有效,默认300 final double height; BrnProgressBarChart( - {Key key, + {Key? key, this.minWidth = 0, this.padding = const EdgeInsets.all(20), this.barChartStyle = BarChartStyle.vertical, - this.xAxis, - this.yAxis, - this.barBundleList, + required this.xAxis, + required this.yAxis, + required this.barBundleList, this.barGroupSpace = 30, this.singleBarWidth = 30, - this.barMaxValue, + this.barMaxValue = 0, this.selectedHintTextColor = Colors.white, this.selectedHintTextBackgroundColor = Colors.black, this.onBarItemClickInterceptor, @@ -66,21 +66,12 @@ class BrnProgressBarChart extends StatefulWidget { this.height = 300}) : super(key: key) { if (BarChartStyle.horizontal == barChartStyle) { - assert(yAxis.axisItemList != null, '水平柱形图必须要有 Y 轴'); - assert(barBundleList != null && barBundleList.length != 0, '缺少柱形图数据'); - assert( - barBundleList[0].barList != null && - barBundleList[0].barList.length == yAxis.axisItemList.length, + assert(barBundleList[0].barList.length == yAxis.axisItemList.length, '水平柱状图个数与Y轴坐标数目要相等'); } else if (BarChartStyle.vertical == barChartStyle) { - assert(xAxis.axisItemList != null, '竖直柱形图必须要有 X 轴'); - assert(barBundleList != null && barBundleList.length != 0, '缺少柱形图数据'); - assert( - barBundleList[0].barList != null && - barBundleList[0].barList.length == xAxis.axisItemList.length, + assert(barBundleList[0].barList.length == xAxis.axisItemList.length, '竖直柱状图个数与X轴坐标数目要相等'); } - assert(0 != this.barMaxValue, '柱状图最大值不能为0'); } @override @@ -90,12 +81,9 @@ class BrnProgressBarChart extends StatefulWidget { } class BrnProgressBarChartState extends State { - BrnProgressBarItem _selectedBarItem; + BrnProgressBarItem? _selectedBarItem; Size chartSize() { - if (null == widget.barBundleList) { - return Size.zero; - } int barBundleCount = widget.barBundleList.length; int numberOfBars = widget.barBundleList[0].barList.length; if (BarChartStyle.horizontal == widget.barChartStyle) { @@ -104,8 +92,7 @@ class BrnProgressBarChartState extends State { numberOfBars; ///有 x 轴 需要加上 x 轴占用的高度 - if (null != widget.xAxis?.axisItemList && - 0 < widget.xAxis.axisItemList.length) { + if (widget.xAxis.axisItemList.isNotEmpty) { height += 22; } double width = MediaQuery.of(context).size.width; @@ -116,12 +103,11 @@ class BrnProgressBarChartState extends State { numberOfBars; /// 有 y 轴需要加上 y 轴占用的宽度 - if (null != widget.yAxis?.axisItemList && - 0 < widget.yAxis.axisItemList.length) { + if (widget.yAxis.axisItemList.isNotEmpty) { width += BrnProgressBarChartPainter.maxYAxisWidth(widget.yAxis); } - return Size(widget.minWidth > width ? widget.minWidth : width, - widget.height ?? 300); + return Size( + widget.minWidth > width ? widget.minWidth : width, widget.height); } else { return Size.zero; } @@ -134,10 +120,6 @@ class BrnProgressBarChartState extends State { } void clearSelectedBarItem(BrnProgressBarChart oldWidget) { - if (null == widget.barBundleList || null == widget.barBundleList) { - _selectedBarItem = null; - return; - } if (widget.barBundleList.length == oldWidget.barBundleList.length) { int bundleCount = widget.barBundleList.length; for (int bundleIndex = 0; bundleIndex < bundleCount; bundleIndex++) { @@ -170,8 +152,8 @@ class BrnProgressBarChartState extends State { @override Widget build(BuildContext context) { Size chartSize = this.chartSize(); - if (null == widget.barBundleList || chartSize == Size.zero) { - return Container(); + if (chartSize == Size.zero) { + return const SizedBox.shrink(); } if (BarChartStyle.vertical == widget.barChartStyle) { double yAxisWidth = @@ -216,9 +198,9 @@ class BrnProgressBarChartState extends State { selectedHintTextBackgroundColor: widget.selectedHintTextBackgroundColor, brnProgressBarChartSelectCallback: - (BrnProgressBarItem item) { + (BrnProgressBarItem? item) { if (null != widget.barChartSelectCallback) - widget.barChartSelectCallback(item); + widget.barChartSelectCallback!(item); setState(() { _selectedBarItem = item; }); @@ -246,7 +228,7 @@ class BrnProgressBarChartState extends State { ), ); } else { - return Container(); + return const SizedBox.shrink(); } } } diff --git a/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart_painter.dart b/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart_painter.dart index d1f52385..912efe4f 100644 --- a/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart_painter.dart +++ b/lib/src/components/charts/brn_progress_bar_chart/brn_progress_bar_chart_painter.dart @@ -10,7 +10,7 @@ typedef BarItemEnumeratorCallback = void Function( /// 点击柱状数据的回调 typedef BrnProgressBarChartSelectCallback = void Function( - BrnProgressBarItem barItem); + BrnProgressBarItem? barItem); /// 点击柱状数据的拦截器 typedef bool OnBarItemClickInterceptor( @@ -31,13 +31,13 @@ enum BarChartStyle { //坐标轴样式 enum AxisStyle { ///无线条 - AxisStyleNone, + axisStyleNone, ///虚线 - AxisStyleDot, + axisStyleDot, ///实线 - AxisStyleSolid, + axisStyleSolid, } /// 坐标轴项目 @@ -46,14 +46,13 @@ class AxisItem { final String showText; /// 文本大小 - Size textSize; - AxisItem({this.showText}); + late Size textSize; + AxisItem({required this.showText}); } /// ChartAxis 图表的坐标轴样式 /// 可对坐标轴的刻度样式、线条样式、偏移量等数据进行设置 class ChartAxis { - @required final List axisItemList; /// 是否有刻度 @@ -63,7 +62,7 @@ class ChartAxis { final AxisStyle axisStyle; /// 两个刻度间距 - double space; + double? space; double maxTextHeight = 0; double maxTextWidth = 0; @@ -72,9 +71,9 @@ class ChartAxis { TextStyle textStyle = TextStyle(color: Color(0x999999), fontSize: 12); ChartAxis({ - this.axisItemList = const [], - this.hasMark, - this.axisStyle = AxisStyle.AxisStyleSolid, + required this.axisItemList, + this.hasMark = true, + this.axisStyle = AxisStyle.axisStyleSolid, }); } @@ -85,30 +84,30 @@ const _showBarValueTextStyle = /// 可对数据的数值、展示文本、选中状态的文字以及柱形的样式进行设置 class BrnProgressBarItem { /// 柱状数据的描述文本 - final String text; + final String? text; /// 柱状数据的值 final double value; /// 柱状数据的参考值,展示在当前柱状图的后面 - final double hintValue; + final double? hintValue; ///选中时气泡文字 - final String selectedHintText; + final String? selectedHintText; /// 展示柱形的值 - final String showBarValueText; + final String? showBarValueText; /// 展示柱形值文本样式 final TextStyle showBarValueTextStyle; - double percentage; - double hintPercentage; - Rect barRect; - Rect barHintRect; - Offset barGroupAxisCenter; + late double percentage; + double? hintPercentage; + Rect? barRect; + Rect? barHintRect; + late Offset barGroupAxisCenter; BrnProgressBarItem( {this.text, - @required this.value, + required this.value, this.hintValue, this.selectedHintText, this.showBarValueText, @@ -125,7 +124,7 @@ class BrnProgressBarBundle { final List colors; final List hintColors; BrnProgressBarBundle( - {this.barList, + {required this.barList, this.colors = _defaultColor, this.hintColors = _defaultHintColor}); } @@ -158,15 +157,15 @@ class BrnProgressBarChartPainter extends CustomPainter { final bool drawBar; /// 是否可点击回调 - final OnBarItemClickInterceptor onBarItemClickInterceptor; + final OnBarItemClickInterceptor? onBarItemClickInterceptor; /// 选中柱状图时条形文案颜色 final Color selectedHintTextColor; /// 选中柱状图时条形文案背景颜色 final Color selectedHintTextBackgroundColor; - final BrnProgressBarItem selectedBarItem; - final BrnProgressBarChartSelectCallback brnProgressBarChartSelectCallback; + final BrnProgressBarItem? selectedBarItem; + final BrnProgressBarChartSelectCallback? brnProgressBarChartSelectCallback; Color unselectedColor = Color(0xffDAEDFE); @@ -187,13 +186,13 @@ class BrnProgressBarChartPainter extends CustomPainter { final double _xAxisHeight = 22; BrnProgressBarChartPainter( - {this.barChartStyle, - this.xAxis, - this.yAxis, - this.barBundleList, - this.barGroupSpace, - this.singleBarWidth, - this.barMaxValue, + {required this.barChartStyle, + required this.xAxis, + required this.yAxis, + required this.barBundleList, + required this.barGroupSpace, + required this.singleBarWidth, + required this.barMaxValue, this.drawX = true, this.drawY = true, this.drawBar = true, @@ -277,7 +276,7 @@ class BrnProgressBarChartPainter extends CustomPainter { } // 找到柱状图最大值 - if (null != this.barMaxValue && 0 != this.barMaxValue) { + if (0 != this.barMaxValue) { this.maxValue = this.barMaxValue; } else { this.barBundleList.forEach((BrnProgressBarBundle barbundle) { @@ -295,7 +294,7 @@ class BrnProgressBarChartPainter extends CustomPainter { barItem.percentage = barItem.value / this.maxValue; if (null != barItem.hintValue) { - barItem.hintPercentage = barItem.hintValue / this.maxValue; + barItem.hintPercentage = barItem.hintValue! / this.maxValue; } if (BarChartStyle.horizontal == this.barChartStyle) { @@ -311,11 +310,11 @@ class BrnProgressBarChartPainter extends CustomPainter { barItem.barRect = barRect; // 条形组的坐标轴中间Offset,此处目前仅考虑有一组条形值的情况 - barItem.barGroupAxisCenter = barItem.barRect.centerLeft; + barItem.barGroupAxisCenter = barItem.barRect!.centerLeft; // BarHintRect if (null != barItem.hintPercentage) { - double hintWidth = this.contentRect.width * barItem.hintPercentage; + double hintWidth = this.contentRect.width * barItem.hintPercentage!; Rect barHintRect = Rect.fromLTWH(leftTop.dx, leftTop.dy, hintWidth, height); barItem.barHintRect = barHintRect; @@ -346,7 +345,7 @@ class BrnProgressBarChartPainter extends CustomPainter { // BarHintRect if (null != barItem.hintPercentage) { - double hintHeight = this.contentRect.height * barItem.hintPercentage; + double hintHeight = this.contentRect.height * barItem.hintPercentage!; Rect barHintRect = Rect.fromLTWH( leftBottom.dx, leftBottom.dy - hintHeight, width, hintHeight); barItem.barHintRect = barHintRect; @@ -375,13 +374,13 @@ class BrnProgressBarChartPainter extends CustomPainter { } void _drawXAxisIn(Canvas canvas, Rect xAxisRect) { - if (0 == this.xAxis?.axisItemList?.length) return; - if (AxisStyle.AxisStyleSolid == this.xAxis.axisStyle) { + if (0 == this.xAxis.axisItemList.length) return; + if (AxisStyle.axisStyleSolid == this.xAxis.axisStyle) { Offset xLineStart = xAxisRect.topLeft; Offset xLineEnd = xAxisRect.topRight; Paint xAxisPaint = Paint()..color = Color(0xff222222); canvas.drawLine(xLineStart, xLineEnd, xAxisPaint); - } else if (AxisStyle.AxisStyleDot == this.xAxis.axisStyle) { + } else if (AxisStyle.axisStyleDot == this.xAxis.axisStyle) { Offset xLineStart = xAxisRect.topLeft; Offset xLineEnd = xAxisRect.topRight; _drawDashLineOn(canvas, xLineStart, xLineEnd, Color(0xff222222)); @@ -412,7 +411,7 @@ class BrnProgressBarChartPainter extends CustomPainter { AxisItem axisItem = this.xAxis.axisItemList[xAxisItemIndex]; TextPainter textPainter = TextPainter( text: TextSpan( - text: axisItem.showText ?? '', + text: axisItem.showText, style: TextStyle(fontSize: 12, color: Color(0xff999999))), textDirection: TextDirection.ltr) ..layout(maxWidth: double.infinity, minWidth: 0); @@ -438,7 +437,7 @@ class BrnProgressBarChartPainter extends CustomPainter { AxisItem axisItem = this.xAxis.axisItemList[barGroupIndex]; TextPainter textPainter = TextPainter( text: TextSpan( - text: axisItem.showText ?? '', + text: axisItem.showText, style: TextStyle(fontSize: 12, color: Color(0xff999999))), textDirection: TextDirection.ltr) ..layout(maxWidth: double.infinity, minWidth: 0); @@ -455,13 +454,13 @@ class BrnProgressBarChartPainter extends CustomPainter { } void _drawYAxisIn(Canvas canvas, Rect yAxisRect) { - if (0 == this.yAxis?.axisItemList?.length) return; - if (AxisStyle.AxisStyleSolid == this.yAxis.axisStyle) { + if (0 == this.yAxis.axisItemList.length) return; + if (AxisStyle.axisStyleSolid == this.yAxis.axisStyle) { Offset yLineStart = yAxisRect.bottomRight; Offset yLineEnd = yAxisRect.topRight; Paint yAxisPaint = Paint()..color = Color(0xff222222); canvas.drawLine(yLineStart, yLineEnd, yAxisPaint); - } else if (AxisStyle.AxisStyleDot == this.xAxis.axisStyle) { + } else if (AxisStyle.axisStyleDot == this.xAxis.axisStyle) { Offset yLineStart = yAxisRect.bottomRight; Offset yLineEnd = yAxisRect.topRight; _drawDashLineOn(canvas, yLineStart, yLineEnd, Color(0xff222222)); @@ -486,7 +485,7 @@ class BrnProgressBarChartPainter extends CustomPainter { height: textSize.height); TextPainter( text: TextSpan( - text: axisItem.showText ?? '', + text: axisItem.showText, style: TextStyle(fontSize: 12, color: Color(0xff999999))), textDirection: TextDirection.ltr) ..layout(maxWidth: double.infinity, minWidth: 0) @@ -514,7 +513,7 @@ class BrnProgressBarChartPainter extends CustomPainter { height: textSize.height); TextPainter( text: TextSpan( - text: axisItem.showText ?? '', + text: axisItem.showText, style: TextStyle(fontSize: 12, color: Color(0xff999999))), textDirection: TextDirection.ltr) ..layout(maxWidth: double.infinity, minWidth: 0) @@ -556,7 +555,7 @@ class BrnProgressBarChartPainter extends CustomPainter { end: Alignment.topCenter, tileMode: TileMode.clamp, colors: barBundle.hintColors) - .createShader(barItem.barHintRect); + .createShader(barItem.barHintRect!); Paint hintBarPaint = Paint() ..shader = hintShader @@ -565,22 +564,22 @@ class BrnProgressBarChartPainter extends CustomPainter { ..strokeWidth = 1.5 ..style = PaintingStyle.fill; - canvas.drawRect(barItem.barHintRect, hintBarPaint); + canvas.drawRect(barItem.barHintRect!, hintBarPaint); } - RRect barRRect = RRect.fromRectAndCorners(barItem.barRect, + RRect barRRect = RRect.fromRectAndCorners(barItem.barRect!, topRight: Radius.circular(4), topLeft: Radius.circular(4)); if (this.selectedBarItem != null) { // 有选中的柱形,选中柱形保持原样,未选中的置灰 Shader shader; - if (this.selectedBarItem.barRect == barItem.barRect) { + if (this.selectedBarItem!.barRect == barItem.barRect) { // 选中的柱形 shader = LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, tileMode: TileMode.clamp, colors: barBundle.colors) - .createShader(barItem.barRect); + .createShader(barItem.barRect!); } else { // 未选中需要置灰的柱形 shader = LinearGradient( @@ -588,7 +587,7 @@ class BrnProgressBarChartPainter extends CustomPainter { end: Alignment.topCenter, tileMode: TileMode.clamp, colors: [this.unselectedColor, this.unselectedColor]) - .createShader(barItem.barRect); + .createShader(barItem.barRect!); } Paint barPaint = Paint() ..shader = shader @@ -597,10 +596,10 @@ class BrnProgressBarChartPainter extends CustomPainter { ..strokeWidth = 1.5 ..style = PaintingStyle.fill; canvas.drawRRect(barRRect, barPaint); - if (this.selectedBarItem.barRect == barItem.barRect) { + if (this.selectedBarItem!.barRect == barItem.barRect) { // 选中柱形的虚线以及 HintText - this._drawDashLineOn(canvas, barItem.barRect.bottomCenter, - Offset(barItem.barRect.bottomCenter.dx, 0), Color(0xff222222)); + this._drawDashLineOn(canvas, barItem.barRect!.bottomCenter, + Offset(barItem.barRect!.bottomCenter.dx, 0), Color(0xff222222)); } } else { Shader shader = LinearGradient( @@ -608,7 +607,7 @@ class BrnProgressBarChartPainter extends CustomPainter { end: Alignment.topCenter, tileMode: TileMode.clamp, colors: barBundle.colors) - .createShader(barItem.barRect); + .createShader(barItem.barRect!); Paint barPaint = Paint() ..shader = shader ..isAntiAlias = true @@ -626,14 +625,14 @@ class BrnProgressBarChartPainter extends CustomPainter { if (null != barItem.showBarValueText) { TextPainter textPainter = TextPainter( text: TextSpan( - text: barItem.showBarValueText ?? '', + text: barItem.showBarValueText!, style: barItem.showBarValueTextStyle), textDirection: TextDirection.ltr) ..layout(maxWidth: double.infinity, minWidth: 0); double textWidth = textPainter.size.width; double textHeight = textPainter.size.height; - Offset textOffset = Offset(barItem.barRect.center.dx - textWidth / 2, - barItem.barRect.top - textHeight - 2); + Offset textOffset = Offset(barItem.barRect!.center.dx - textWidth / 2, + barItem.barRect!.top - textHeight - 2); textPainter.paint(canvas, textOffset); } }); @@ -643,8 +642,8 @@ class BrnProgressBarChartPainter extends CustomPainter { // 画选中文字 Start TextPainter selectedBarTextPainter = TextPainter( text: TextSpan( - text: selectedBarItem.selectedHintText ?? - (selectedBarItem.text ?? ''), + text: selectedBarItem!.selectedHintText ?? + (selectedBarItem!.text ?? ''), style: TextStyle(fontSize: 12, color: this.selectedHintTextColor)), textDirection: TextDirection.ltr) @@ -653,16 +652,16 @@ class BrnProgressBarChartPainter extends CustomPainter { double textHeight = selectedBarTextPainter.size.height; Offset selectedBarTextBgCenterOffset; - if (selectedBarItem.barRect.bottomCenter.dx + 10 + textWidth + 10 * 2 > + if (selectedBarItem!.barRect!.bottomCenter.dx + 10 + textWidth + 10 * 2 > this.contentRect.right) { // 需要显示在左侧 selectedBarTextBgCenterOffset = Offset( - selectedBarItem.barRect.bottomCenter.dx - 10 - 10 - textWidth / 2, + selectedBarItem!.barRect!.bottomCenter.dx - 10 - 10 - textWidth / 2, 16.0 + 16.0); } else { // 需要显示在右侧 selectedBarTextBgCenterOffset = Offset( - selectedBarItem.barRect.bottomCenter.dx + 10 + 10 + textWidth / 2, + selectedBarItem!.barRect!.bottomCenter.dx + 10 + 10 + textWidth / 2, 16.0 + 16.0); } @@ -702,7 +701,7 @@ class BrnProgressBarChartPainter extends CustomPainter { end: Alignment.centerRight, tileMode: TileMode.clamp, colors: barBundle.hintColors) - .createShader(barItem.barHintRect); + .createShader(barItem.barHintRect!); Paint hintBarPaint = Paint() ..shader = hintShader ..isAntiAlias = true @@ -710,11 +709,11 @@ class BrnProgressBarChartPainter extends CustomPainter { ..strokeWidth = 1.5 ..style = PaintingStyle.fill; - canvas.drawRect(barItem.barHintRect, hintBarPaint); + canvas.drawRect(barItem.barHintRect!, hintBarPaint); } // 绘制柱状图形 - RRect barRRect = RRect.fromRectAndCorners(barItem.barRect, + RRect barRRect = RRect.fromRectAndCorners(barItem.barRect!, topRight: Radius.circular(4), bottomRight: Radius.circular(4)); Shader shader = LinearGradient( @@ -722,7 +721,7 @@ class BrnProgressBarChartPainter extends CustomPainter { end: Alignment.centerRight, tileMode: TileMode.clamp, colors: barBundle.colors) - .createShader(barItem.barRect); + .createShader(barItem.barRect!); Paint barPaint = Paint() ..shader = shader ..isAntiAlias = true @@ -764,7 +763,7 @@ class BrnProgressBarChartPainter extends CustomPainter { } @override - bool hitTest(Offset position) { + bool? hitTest(Offset position) { if (this.brnProgressBarChartSelectCallback != null && BarChartStyle.vertical == this.barChartStyle) { this.barItemEnumerator((int barBundleIndex, @@ -772,12 +771,12 @@ class BrnProgressBarChartPainter extends CustomPainter { int barGroupIndex, BrnProgressBarItem barItem) { if (this.brnProgressBarChartSelectCallback != null && - barItem.barRect.contains(position)) { + barItem.barRect!.contains(position)) { if (this.onBarItemClickInterceptor == null || true == - this.onBarItemClickInterceptor( + this.onBarItemClickInterceptor!( barBundleIndex, barBundle, barGroupIndex, barItem)) { - this.brnProgressBarChartSelectCallback( + this.brnProgressBarChartSelectCallback!( barItem.barRect == this.selectedBarItem?.barRect ? null : barItem); diff --git a/lib/src/components/charts/brn_progress_chart/brn_progress_chart.dart b/lib/src/components/charts/brn_progress_chart/brn_progress_chart.dart index d1a9ca59..30a27266 100644 --- a/lib/src/components/charts/brn_progress_chart/brn_progress_chart.dart +++ b/lib/src/components/charts/brn_progress_chart/brn_progress_chart.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/charts/brn_progress_chart/brn_progress_chart_painter.dart'; import 'package:flutter/material.dart'; @@ -23,7 +25,7 @@ class BrnProgressChart extends StatefulWidget { final TextStyle textStyle; /// 自定义进度条上面的Widget,默认显示为文本 - final BrnProgressIndicatorBuilder brnProgressIndicatorBuilder; + final BrnProgressIndicatorBuilder? brnProgressIndicatorBuilder; /// 背景色,默认 Colors.lightBlueAccent final Color backgroundColor; @@ -35,7 +37,7 @@ class BrnProgressChart extends StatefulWidget { final bool showAnimation; const BrnProgressChart( - {Key key, + {Key? key, this.width = 0, this.height = 0, this.value = 0.2, @@ -56,8 +58,8 @@ class BrnProgressChart extends StatefulWidget { class BrnProgressChartState extends State with SingleTickerProviderStateMixin { - Animation _animation; - AnimationController _animationController; + late Animation _animation; + AnimationController? _animationController; double _value = 0; @override @@ -67,13 +69,13 @@ class BrnProgressChartState extends State _animationController = AnimationController( vsync: this, duration: Duration(milliseconds: 250)); Tween tween = Tween(begin: 0, end: widget.value); - _animation = tween.animate(_animationController); + _animation = tween.animate(_animationController!) as Animation; _animation.addListener(() { setState(() { _value = _animation.value; }); }); - _animationController.forward(); + _animationController!.forward(); } else { _value = widget.value; } @@ -106,7 +108,7 @@ class BrnProgressChartState extends State padding: EdgeInsets.only(left: widget.indicatorLeftPadding), alignment: Alignment.centerLeft, child: null != widget.brnProgressIndicatorBuilder - ? widget.brnProgressIndicatorBuilder(context, _value) + ? widget.brnProgressIndicatorBuilder!(context, _value) : _indicatorWidgetBuilder(context, _value), ) ], diff --git a/lib/src/components/charts/brn_progress_chart/brn_progress_chart_painter.dart b/lib/src/components/charts/brn_progress_chart/brn_progress_chart_painter.dart index de391f0d..396e6981 100644 --- a/lib/src/components/charts/brn_progress_chart/brn_progress_chart_painter.dart +++ b/lib/src/components/charts/brn_progress_chart/brn_progress_chart_painter.dart @@ -1,3 +1,5 @@ + + import 'package:flutter/material.dart'; class BrnProgressChartPainter extends CustomPainter { diff --git a/lib/src/components/charts/broken_line/brn_base_painter.dart b/lib/src/components/charts/broken_line/brn_base_painter.dart index c89a9832..ab648e9e 100644 --- a/lib/src/components/charts/broken_line/brn_base_painter.dart +++ b/lib/src/components/charts/broken_line/brn_base_painter.dart @@ -1,11 +1,9 @@ import 'package:flutter/material.dart'; -class BrnBasePainter extends CustomPainter { +abstract class BrnBasePainter extends CustomPainter { @override - void paint(Canvas canvas, Size size) {} + void paint(Canvas canvas, Size size); @override - bool shouldRepaint(CustomPainter oldDelegate) { - return true; - } + bool shouldRepaint(CustomPainter oldDelegate); } diff --git a/lib/src/components/charts/broken_line/brn_broken_line.dart b/lib/src/components/charts/broken_line/brn_broken_line.dart index c8ddbc0e..501f4799 100644 --- a/lib/src/components/charts/broken_line/brn_broken_line.dart +++ b/lib/src/components/charts/broken_line/brn_broken_line.dart @@ -1,11 +1,9 @@ import 'dart:math'; -import 'dart:ui'; import 'package:bruno/src/components/charts/broken_line/brn_line_data.dart'; import 'package:bruno/src/components/charts/broken_line/brn_line_painter.dart'; import 'package:bruno/src/components/charts/broken_line/brn_line_y_painter.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; /// 适用于需要折线图,曲线图的场景 /// 支持数据过多时左右滑动查看数据 @@ -21,16 +19,16 @@ class BrnBrokenLine extends StatefulWidget { final EdgeInsets contentPadding; /// 绘制的背景色 - final Color backgroundColor; + final Color? backgroundColor; /// xy轴线条的宽度,默认 2 final double xyDialLineWidth; /// xy轴的颜色 - final Color xDialColor, yDialColor; + final Color? xDialColor, yDialColor; /// x轴最小值,最大值,用来计算内部绘制点的x轴位置 - final double xDialMin, xDialMax; + final double? xDialMin, xDialMax; /// y轴最小值,最大值,用来计算内部绘制点的y轴位置 final double yDialMin, yDialMax; @@ -39,10 +37,10 @@ class BrnBrokenLine extends StatefulWidget { final double dialWidth; /// y轴左侧刻度显示,不传则没有 - final List yDialValues; + final List? yDialValues; /// x 轴刻度 - final List xDialValues; + final List? xDialValues; /// x轴的辅助线是否展示,默认 true final bool isShowXHintLine; @@ -54,7 +52,7 @@ class BrnBrokenLine extends StatefulWidget { final bool isHintLineSolid; /// 辅助线颜色 - final Color hintLineColor; + final Color? hintLineColor; /// 是否展示 x 坐标刻度,默认 false final bool isShowXDialText; @@ -72,9 +70,9 @@ class BrnBrokenLine extends StatefulWidget { final bool isTipWindowAutoDismiss; BrnBrokenLine({ - Key key, - @required this.size, - @required this.lines, + Key? key, + required this.size, + required this.lines, this.contentPadding = const EdgeInsets.only(left: 10, right: 10), this.backgroundColor, this.xyDialLineWidth = 2, @@ -86,8 +84,8 @@ class BrnBrokenLine extends StatefulWidget { this.xDialMin, this.xDialMax, this.xDialValues, - this.yDialMin, - this.yDialMax, + required this.yDialMin, + required this.yDialMax, this.yDialValues, this.isShowXHintLine = true, this.isShowYHintLine = false, @@ -96,11 +94,8 @@ class BrnBrokenLine extends StatefulWidget { this.isTipWindowAutoDismiss = true, this.isShowXDialText = false, this.isShowYDialText = false, - }) : assert(size != null), - assert(yDialMin != null), - assert(yDialMax != null), - super(key: key) { - /// 设置自定义 X 轴时,检查 x轴的最大、最小刻度范围 + }) : super(key: key) { + // 设置自定义 X 轴时,检查 x轴的最大、最小刻度范围 if (xDialValues != null) { assert(xDialMin != null); assert(xDialMax != null); @@ -156,9 +151,8 @@ class BrnBrokenLineState extends State { isShowYDialText: widget.isShowYDialText, ); //y 轴宽度 = Y 轴刻度宽度+ chartLeftPadding(SingleChildScrollView padding)+ y 轴偏移量 yAxisWidth - var yWidth = widget.size.width + - (widget.contentPadding?.left ?? 10) + - (widget.yHintLineOffset == null ? 20.0 : widget.yHintLineOffset); + var yWidth = + widget.size.width + widget.contentPadding.left + widget.yHintLineOffset; return Stack( children: [ CustomPaint( @@ -174,12 +168,12 @@ class BrnBrokenLineState extends State { : null, ), Padding( - padding: EdgeInsets.only(left: widget.yHintLineOffset ?? 20.0), + padding: EdgeInsets.only(left: widget.yHintLineOffset), child: SingleChildScrollView( padding: EdgeInsets.only( - left: widget.contentPadding?.left ?? 10, + left: widget.contentPadding.left, bottom: 25, - right: widget.contentPadding?.right ?? 10), + right: widget.contentPadding.right), scrollDirection: Axis.horizontal, child: GestureDetector( onPanDown: (DragDownDetails e) { @@ -205,14 +199,14 @@ class BrnBrokenLineState extends State { } }, onLongPressUp: () { - if (widget.isTipWindowAutoDismiss ?? true) { + if (widget.isTipWindowAutoDismiss) { pointSelectIndex = -1; lineSelectIndex = -1; setState(() {}); } }, onTapUp: (tapUpDetail) { - if (widget.isTipWindowAutoDismiss ?? true) { + if (widget.isTipWindowAutoDismiss) { pointSelectIndex = -1; lineSelectIndex = -1; setState(() {}); @@ -236,7 +230,7 @@ class BrnBrokenLineState extends State { (lineSelectIndex >= 0 && pointSelectIndex >= 0) ? _buildTouchTipWidget( widget.lines[lineSelectIndex].points[pointSelectIndex]) - : Container(), + : const SizedBox.shrink(), ]), ), ), @@ -247,19 +241,16 @@ class BrnBrokenLineState extends State { Widget _buildTouchTipWidget(BrnPointData pointData) { Widget touchTipWidget; - BrnLineTouchData selectLinePoint = pointData?.lineTouchData; - if (selectLinePoint != null && - pointData.isClickable != null && - pointData.isClickable && - selectLinePoint.onTouch != null) { - var content = selectLinePoint.onTouch(); + BrnLineTouchData? selectLinePoint = pointData.lineTouchData; + if (pointData.isClickable && selectLinePoint.onTouch != null) { + var content = selectLinePoint.onTouch!(); if (content is String) { touchTipWidget = Positioned( top: selectLinePoint.y, left: selectLinePoint.x, child: Container( - height: selectLinePoint.tipWindowSize?.height, - width: selectLinePoint.tipWindowSize?.width, + height: selectLinePoint.tipWindowSize.height, + width: selectLinePoint.tipWindowSize.width, padding: EdgeInsets.only(left: 10, right: 10, top: 8, bottom: 8), child: Center(child: Text(content)), decoration: BoxDecoration( @@ -281,20 +272,14 @@ class BrnBrokenLineState extends State { top: selectLinePoint.y, left: selectLinePoint.x, child: Container( - height: selectLinePoint.tipWindowSize?.height, - width: selectLinePoint.tipWindowSize?.width, + height: selectLinePoint.tipWindowSize.height, + width: selectLinePoint.tipWindowSize.width, child: content)); } else { - touchTipWidget = Container( - height: 0, - width: 0, - ); + touchTipWidget = const SizedBox.shrink(); } } else { - touchTipWidget = Container( - height: 0, - width: 0, - ); + touchTipWidget = const SizedBox.shrink(); } return touchTipWidget; @@ -308,8 +293,6 @@ class BrnBrokenLineState extends State { double endY, double fixedHeight, Point selectedPoint) { - if (selectedPoint == null || lineTouchData == null) return; - if (pointSelectIndex < 0 && lineSelectIndex < 0) { lineTouchData.x = -1.0; lineTouchData.y = -1.0; @@ -324,16 +307,16 @@ class BrnBrokenLineState extends State { if (selectY <= (startY - endY) / 2) { y = selectY + padding; } else { - y = selectY - (lineTouchData?.tipWindowSize?.height ?? 0.0) - padding; + y = selectY - (lineTouchData.tipWindowSize.height) - padding; } if (selectX <= (endX - startX) / 2) { x = selectX + padding; } else { - x = selectX - (lineTouchData?.tipWindowSize?.width ?? 0.0) - padding; + x = selectX - (lineTouchData.tipWindowSize.width) - padding; } - lineTouchData.x = x + lineTouchData.tipOffset?.dx ?? 0; - lineTouchData.y = y + lineTouchData.tipOffset?.dy ?? 0; + lineTouchData.x = x + lineTouchData.tipOffset.dx; + lineTouchData.y = y + lineTouchData.tipOffset.dy; } } diff --git a/lib/src/components/charts/broken_line/brn_line_data.dart b/lib/src/components/charts/broken_line/brn_line_data.dart index caa6bd33..e8ea7466 100644 --- a/lib/src/components/charts/broken_line/brn_line_data.dart +++ b/lib/src/components/charts/broken_line/brn_line_data.dart @@ -3,15 +3,15 @@ import 'package:flutter/material.dart'; class BrnDialItem { /// 刻度标志内容 - String dialText; + String? dialText; /// 刻度标志样式 - TextStyle dialTextStyle; + TextStyle? dialTextStyle; /// x,y 轴刻度值。用于刻度在坐标的真实定位 double value; - BrnDialItem({this.dialText, this.dialTextStyle, @required this.value}); + BrnDialItem({this.dialText, this.dialTextStyle, required this.value}); } class BrnPointData { @@ -25,10 +25,10 @@ class BrnPointData { Offset offset; /// 点要展示的内容 - String pointText; + String? pointText; /// 点展示内容样式 - TextStyle pointTextStyle; + TextStyle? pointTextStyle; /// 折线节点的点击击事件是否可用 bool isClickable; @@ -42,7 +42,7 @@ class BrnPointData { this.pointText, this.pointTextStyle, this.isClickable: true, - this.lineTouchData}) { + required this.lineTouchData}) { pointText ??= '$y'; pointTextStyle ??= TextStyle( fontWeight: FontWeight.w500, @@ -56,7 +56,7 @@ class BrnPointData { class BrnLineTouchData { /// 用于临时存储要展示 tip 内容在坐标的位置 - double x, y; + double? x, y; /// 要展示 tip 的相对偏移量 Offset tipOffset; @@ -65,10 +65,10 @@ class BrnLineTouchData { Size tipWindowSize; /// 点击回调,由于返回 展示内容(String 或 Widget) - Function() onTouch; + Function()? onTouch; BrnLineTouchData({ - @required this.tipWindowSize, + required this.tipWindowSize, this.tipOffset: const Offset(0, 0), this.onTouch, }); @@ -83,22 +83,22 @@ class BrnPointsLine { double lineWidth; /// Line渐变色,从曲线到x轴从上到下的闭合颜色集 - List shaderColors; + List? shaderColors; /// 曲线或折线的颜色 Color lineColor; /// 点外圈的颜色 - Color pointColor; + Color? pointColor; /// 点的外半径参数 double pointRadius; /// 点内圈的颜色 - Color pointInnerColor; + Color? pointInnerColor; /// 点内圈的半径 - double pointInnerRadius; + double? pointInnerRadius; /// 是否显示x轴的文字,用来处理多个线条绘制的时候,同一x轴坐标不需要绘制多次,则只需要将多条线中一个标记绘制即可 bool isShowXDial; @@ -120,12 +120,11 @@ class BrnPointsLine { this.pointInnerRadius, this.pointInnerColor, this.isCurve = false, - this.points, + required this.points, this.isShowPoint: true, this.isShowPointText = false, this.shaderColors, this.lineColor = Colors.purple}) { - lineColor ??= Colors.purple; pointColor ??= lineColor; pointInnerColor ??= lineColor; pointInnerRadius ??= pointRadius - 1.5; diff --git a/lib/src/components/charts/broken_line/brn_line_painter.dart b/lib/src/components/charts/broken_line/brn_line_painter.dart index 6bae7ec4..be8db97e 100644 --- a/lib/src/components/charts/broken_line/brn_line_painter.dart +++ b/lib/src/components/charts/broken_line/brn_line_painter.dart @@ -1,5 +1,4 @@ import 'dart:math'; -import 'dart:ui'; import 'package:bruno/src/components/charts/broken_line/brn_base_painter.dart'; import 'package:bruno/src/components/charts/broken_line/brn_line_data.dart'; @@ -9,32 +8,32 @@ import 'package:flutter/material.dart'; import 'package:path_drawing/path_drawing.dart'; class BrnLinePainter extends BrnBasePainter { - int lineSelectIndex = -1; - int pointSelectIndex = -1; + final int lineSelectIndex; + final int pointSelectIndex; /// xy轴线条的宽度 double xyLineWidth = 0.5; /// x轴的颜色 - Color xDialColor; + Color? xDialColor; ///y轴的颜色 - Color yDialColor; + Color? yDialColor; /// 刻度的宽度或者高度 - double rulerWidth; + final double rulerWidth; /// x轴最小值,最大值,用来计算内部绘制点的x轴位置 - double xDialMin, xDialMax; + double? xDialMin, xDialMax; /// y轴最小值,最大值,用来计算内部绘制点的y轴位置 - double yDialMin, yDialMax; + final double yDialMin, yDialMax; /// x轴 刻度 - List xDialValues; + List? xDialValues; /// y轴左侧刻度显示,不传则没有 - List yDialValues; + List? yDialValues; /// x、y轴的辅助线 bool isShowHintX, isShowHintY; @@ -43,14 +42,14 @@ class BrnLinePainter extends BrnBasePainter { bool hintLineSolid; /// 辅助线颜色 - Color hintLineColor; + Color? hintLineColor; /// 绘制线条的参数内容 List lines; bool isShowXText, isShowYText; - bool showPointDashLine; + final bool showPointDashLine; /// 默认的边距 static const double basePadding = 0; @@ -61,17 +60,13 @@ class BrnLinePainter extends BrnBasePainter { /// 图标距离 widget 顶部的 padding static const double paddingTop = 10; - double selectX; - double selectY; - double _startX = 0.0, - _endX = 0.0, - _startY = 0.0, - _endY = 0.0, - _fixedHeight, - _fixedWidth; - List _lineCanvasModels; + double? selectX; + double? selectY; + double _startX = 0.0, _endX = 0.0, _startY = 0.0, _endY = 0.0; + late double _fixedHeight, _fixedWidth; + late List _lineCanvasModels; - List> _linePointPositions = List(); + List> _linePointPositions = []; double get startX => _startX; @@ -85,23 +80,24 @@ class BrnLinePainter extends BrnBasePainter { BrnLinePainter( this.lines, { - this.lineSelectIndex = -1, - this.pointSelectIndex = -1, - this.showPointDashLine = true, - this.xDialColor, - this.yDialColor, - this.rulerWidth = 4, - this.xDialMin, - this.xDialMax, - this.xDialValues, - this.yDialMin, - this.yDialMax, - this.yDialValues, - this.isShowHintX = true, - this.isShowHintY = false, - this.hintLineSolid = true, - this.hintLineColor, + required this.lineSelectIndex, + required this.pointSelectIndex, + required this.showPointDashLine, + required this.xDialColor, + required this.yDialColor, + required this.rulerWidth, + required this.xDialMin, + required this.xDialMax, + required this.xDialValues, + required this.yDialMin, + required this.yDialMax, + required this.yDialValues, + required this.isShowHintX, + required this.isShowHintY, + required this.hintLineSolid, + required this.hintLineColor, this.isShowXText = false, + this.isShowYText = false, }) { if (xDialValues == null) { for (var i = 1; i < lines.length; i++) { @@ -164,13 +160,8 @@ class BrnLinePainter extends BrnBasePainter { .colorTextSecondary; hintLineColor ??= BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase; - hintLineSolid ??= true; - xyLineWidth ??= 0.5; xDialMin ??= 0; xDialMax ??= 1; - - yDialMin ??= 0; - yDialMax ??= 1; } ///计算边界 @@ -187,22 +178,22 @@ class BrnLinePainter extends BrnBasePainter { ///计算Path void _initPath(Canvas canvas, Paint xyPaint) { _lineCanvasModels = []; - if (lines != null && lines.isNotEmpty) { + if (lines.isNotEmpty) { _linePointPositions.clear(); // 计算点和线的 数据,用于渲染。 for (var item in lines) { var paths = [], shadowPaths = []; var pointArr = []; - if (item.points != null && item.points.isNotEmpty) { - var _path = Path(); - var _shadowPath = Path(); + if (item.points.isNotEmpty) { + Path _path = Path(); + Path _shadowPath = Path(); - if (xDialValues != null && xDialValues.isNotEmpty) { + if (xDialValues != null && xDialValues!.isNotEmpty) { for (var i = 0; i < item.points.length; i++) { var xPosition = _startX + - ((item.points[i].x - xDialMin) / - (xDialMax - xDialMin) * + ((item.points[i].x - xDialMin!) / + (xDialMax! - xDialMin!) * _fixedWidth); var yPosition = _startY - ((item.points[i].y - yDialMin) / @@ -211,7 +202,7 @@ class BrnLinePainter extends BrnBasePainter { pointArr.add(Point(xPosition, yPosition)); } } else { - var xScaleCount = item.points?.length ?? 0; + var xScaleCount = item.points.length; var W = _fixedWidth / (xScaleCount > 1 ? (xScaleCount - 1) : 1); //两个点之间的x方向距离 for (var i = 0; i < item.points.length; i++) { @@ -230,20 +221,23 @@ class BrnLinePainter extends BrnBasePainter { /// 生成 Shadow path。 _shadowPath = _getSmoothLinePath(pointArr); _shadowPath - ..lineTo(pointArr[pointArr.length - 1].x, _fixedHeight) - ..lineTo(pointArr[0].x, _fixedHeight) + ..lineTo(pointArr[pointArr.length - 1].x as double, _fixedHeight) + ..lineTo(pointArr[0].x as double, _fixedHeight) ..close(); } else { - _path.moveTo(pointArr[0].x, pointArr[0].y); - _shadowPath.moveTo(pointArr[0].x, pointArr[0].y); + _path.moveTo(pointArr[0].x as double, pointArr[0].y as double); + _shadowPath.moveTo( + pointArr[0].x as double, pointArr[0].y as double); for (var i = 1; i < pointArr.length; i++) { - _path.lineTo(pointArr[i].x, pointArr[i].y); - _shadowPath.lineTo(pointArr[i].x, pointArr[i].y); + _path.lineTo(pointArr[i].x as double, pointArr[i].y as double); + _shadowPath.lineTo( + pointArr[i].x as double, pointArr[i].y as double); if (i == pointArr.length - 1) { _shadowPath - ..lineTo(pointArr[pointArr.length - 1].x, _fixedHeight) - ..lineTo(pointArr[0].x, _fixedHeight) + ..lineTo( + pointArr[pointArr.length - 1].x as double, _fixedHeight) + ..lineTo(pointArr[0].x as double, _fixedHeight) ..close(); } } @@ -259,21 +253,22 @@ class BrnLinePainter extends BrnBasePainter { shadowPaths: shadowPaths, shaderColors: item.shaderColors, points: item.isShowPoint ? pointArr : null, - pointColor: item.pointColor, - pointInnerColor: item.pointInnerColor, + pointColor: item.pointColor!, + pointInnerColor: item.pointInnerColor!, pointRadius: item.pointRadius, - pointInnerRadius: item.pointInnerRadius)); + pointInnerRadius: item.pointInnerRadius!)); } } } /// Draws smooth lines between each point. Path _getSmoothLinePath(List points) { - var targetPoints = List(); + var targetPoints = []; targetPoints.addAll(points); targetPoints.add(Point( points[points.length - 1].x * 2, points[points.length - 1].y * 2)); - var x0, y0, x1, y1, t0, path = Path(); + double? x0, y0, x1, y1, t0; + var path = Path(); for (int i = 0; i < targetPoints.length; i++) { var t1; var x = targetPoints[i].x; @@ -281,23 +276,23 @@ class BrnLinePainter extends BrnBasePainter { if (x == x1 && y == y1) break; switch (i) { case 0: - path.moveTo(x, y); + path.moveTo(x as double, y as double); break; case 1: break; case 2: - t1 = MonotoneX.slope3(x0, y0, x1, y1, x, y); + t1 = MonotoneX.slope3(x0!, y0!, x1!, y1!, x as double, y as double); MonotoneX.point( path, x0, y0, x1, y1, MonotoneX.slope2(x0, y0, x1, y1, t1), t1); break; default: - t1 = MonotoneX.slope3(x0, y0, x1, y1, x, y); - MonotoneX.point(path, x0, y0, x1, y1, t0, t1); + t1 = MonotoneX.slope3(x0!, y0!, x1!, y1!, x as double, y as double); + MonotoneX.point(path, x0, y0, x1, y1, t0!, t1); } x0 = x1; y0 = y1; - x1 = x; - y1 = y; + x1 = x as double; + y1 = y as double; t0 = t1; } return path; @@ -306,15 +301,17 @@ class BrnLinePainter extends BrnBasePainter { ///x,y轴 void _drawXy(Canvas canvas, Paint paint) { if (isShowHintY) { - canvas.drawLine(Offset(_startX, _startY), - Offset(_startX, _endY - basePadding), paint..color = yDialColor); //y轴 + canvas.drawLine( + Offset(_startX, _startY), + Offset(_startX, _endY - basePadding), + paint..color = yDialColor!); //y轴 } - if (lines != null && lines.isNotEmpty) { + if (lines.isNotEmpty) { //绘制x轴的文字部分 for (var item in lines) { - if (item.points != null && item.points.isNotEmpty && item.isShowXDial) { - _drawXRuler(canvas, paint..color = xDialColor, item.points); + if (item.points.isNotEmpty && item.isShowXDial) { + _drawXRuler(canvas, paint..color = xDialColor!, item.points); } } } @@ -322,16 +319,16 @@ class BrnLinePainter extends BrnBasePainter { ///x轴刻度 & 辅助线 void _drawXRuler(Canvas canvas, Paint paint, List points) { - if (xDialValues != null && xDialValues.isNotEmpty) { + if (xDialValues != null && xDialValues!.isNotEmpty) { // 获取刻度长度 - for (var i = 0; i < xDialValues.length; i++) { + for (var i = 0; i < xDialValues!.length; i++) { ///绘制x轴文本 var tpX = TextPainter( textAlign: TextAlign.center, ellipsis: '.', text: TextSpan( - text: xDialValues[i].dialText, - style: xDialValues[i].dialTextStyle), + text: xDialValues![i].dialText, + style: xDialValues![i].dialTextStyle), textDirection: TextDirection.ltr) ..layout(); // 开始绘制刻度 @@ -339,8 +336,8 @@ class BrnLinePainter extends BrnBasePainter { tpX, canvas, _startX + - (xDialValues[i].value - xDialMin) / - (xDialMax - xDialMin) * + (xDialValues![i].value - xDialMin!) / + (xDialMax! - xDialMin!) * _fixedWidth, paint); } @@ -357,14 +354,14 @@ class BrnLinePainter extends BrnBasePainter { ..moveTo(xPosition, _startY) ..lineTo(xPosition, _endY - basePadding); if (hintLineSolid) { - canvas.drawPath(tempPath, paint..color = hintLineColor); + canvas.drawPath(tempPath, paint..color = hintLineColor!); } else { canvas.drawPath( dashPath( tempPath, dashArray: CircularIntervalList([4.0, 2.0]), ), - paint..color = hintLineColor, + paint..color = hintLineColor!, ); } } @@ -372,7 +369,7 @@ class BrnLinePainter extends BrnBasePainter { // 绘制 x轴刻度 if (isShowHintX) { canvas.drawLine(Offset(xPosition, _startY), - Offset(xPosition, _startY + rulerWidth), paint..color = xDialColor); + Offset(xPosition, _startY + rulerWidth), paint..color = xDialColor!); } } @@ -380,13 +377,13 @@ class BrnLinePainter extends BrnBasePainter { void _drawLine(Canvas canvas) { _lineCanvasModels.forEach((element) { //阴影区域 - if (element.shadowPaths != null && element.shaderColors != null) { + if (element.shaderColors != null) { element.shadowPaths.forEach((shadowPathElement) { var shader = LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, tileMode: TileMode.clamp, - colors: element.shaderColors) + colors: element.shaderColors!) .createShader( Rect.fromLTWH(_startX, _endY, _fixedWidth, _fixedHeight)); canvas @@ -398,25 +395,23 @@ class BrnLinePainter extends BrnBasePainter { ..style = PaintingStyle.fill); }); } - if (element.paths != null) { - //路径 - element.paths.forEach((pathElement) { - var pathPaint = Paint() - ..isAntiAlias = true - ..strokeWidth = element.pathWidth - ..strokeCap = StrokeCap.round - ..color = element.pathColor - ..style = PaintingStyle.stroke; - canvas.drawPath(pathElement, pathPaint); - }); - } + //路径 + element.paths.forEach((pathElement) { + var pathPaint = Paint() + ..isAntiAlias = true + ..strokeWidth = element.pathWidth + ..strokeCap = StrokeCap.round + ..color = element.pathColor + ..style = PaintingStyle.stroke; + canvas.drawPath(pathElement, pathPaint); + }); if (element.points != null) { //点 // 画圆环的计算规则是: // 圆环宽度 strokeWidth = element.pointRadius - element.pointInnerRadius // 实际 drawCircle 半径 outerR = (element.pointRadius - element.pointInnerRadius)/2 + element.pointInnerRadius // 内部半径 innerR = element.pointInnerRadius - element.points.forEach((pointElement) { + element.points!.forEach((pointElement) { var pointPaint = Paint() ..isAntiAlias = true ..strokeCap = StrokeCap.round @@ -424,7 +419,7 @@ class BrnLinePainter extends BrnBasePainter { ..strokeWidth = element.pointRadius - element.pointInnerRadius ..style = PaintingStyle.stroke; //描边为居中描边 canvas.drawCircle( - Offset(pointElement.x, pointElement.y), + Offset(pointElement.x as double, pointElement.y as double), (element.pointRadius - element.pointInnerRadius) / 2 + element.pointInnerRadius, pointPaint); @@ -433,8 +428,8 @@ class BrnLinePainter extends BrnBasePainter { //内圆 int currentLineIndex = _lineCanvasModels.indexOf(element); - element.points.forEach((pointElement) { - int currentPointIndex = element.points.indexOf(pointElement); + element.points!.forEach((pointElement) { + int currentPointIndex = element.points!.indexOf(pointElement); Color color = Colors.white; var pointPaintBg = Paint() @@ -442,8 +437,10 @@ class BrnLinePainter extends BrnBasePainter { ..strokeCap = StrokeCap.round ..color = color ..style = PaintingStyle.fill; - canvas.drawCircle(Offset(pointElement.x, pointElement.y), - element.pointInnerRadius, pointPaintBg); + canvas.drawCircle( + Offset(pointElement.x as double, pointElement.y as double), + element.pointInnerRadius, + pointPaintBg); if (currentLineIndex == lineSelectIndex && currentPointIndex == pointSelectIndex) { @@ -454,8 +451,10 @@ class BrnLinePainter extends BrnBasePainter { ..strokeCap = StrokeCap.round ..color = color ..style = PaintingStyle.fill; - canvas.drawCircle(Offset(pointElement.x, pointElement.y), - element.pointInnerRadius, pointPaint); + canvas.drawCircle( + Offset(pointElement.x as double, pointElement.y as double), + element.pointInnerRadius, + pointPaint); }); } }); @@ -468,11 +467,11 @@ class BrnLinePainter extends BrnBasePainter { var x = _linePointPositions[lineSelectIndex][pointSelectIndex].x; var xPath = Path() - ..moveTo(x, _startY) + ..moveTo(x as double, _startY) ..lineTo(x, _endY - basePadding); var y = _linePointPositions[lineSelectIndex][pointSelectIndex].y; var yPath = Path() - ..moveTo(_startX, y) + ..moveTo(_startX, y as double) ..lineTo(_endX, y); if (showPointDashLine) { canvas.drawPath( @@ -504,18 +503,16 @@ class BrnLinePainter extends BrnBasePainter { } void _drawPointDisplayText(Canvas canvas) { - if (_linePointPositions != null && _linePointPositions.isNotEmpty) { + if (_linePointPositions.isNotEmpty) { for (int lineIndex = 0; lineIndex < _linePointPositions.length; lineIndex++) { BrnPointsLine item = lines[lineIndex]; - if (item.isShowPointText && - item.points != null && - item.points.isNotEmpty) { + if (item.isShowPointText && item.points.isNotEmpty) { var length = item.points.length; for (var i = 0; i < length; i++) { if (item.points[i].pointText == null || - item.points[i].pointText.length == 0) { + item.points[i].pointText!.length == 0) { continue; } var tpX = TextPainter( @@ -533,10 +530,10 @@ class BrnLinePainter extends BrnBasePainter { tpX.paint( canvas, Offset( - (item.points[i].offset?.dx ?? 0) + + (item.points[i].offset.dx) + _linePointPositions[lineIndex][i].x - tpX.width / 2, - (item.points[i].offset?.dy ?? 0) + + (item.points[i].offset.dy) + _linePointPositions[lineIndex][i].y + adjustOffset)); } @@ -560,19 +557,13 @@ class BrnLinePainter extends BrnBasePainter { List> getSameXValuePoints( Point currentPoint, List>> lines) { - List> sameXPoints = List(); - if (lines != null) { - for (int lineIndex = 0; lineIndex < lines.length; lineIndex++) { - List> linePoints = lines[lineIndex]; - if (linePoints != null) { - for (int pointIndex = 0; - pointIndex < linePoints.length; - pointIndex++) { - if (currentPoint.x == linePoints[pointIndex].x && - currentPoint != linePoints[pointIndex]) { - sameXPoints.add(linePoints[pointIndex]); - } - } + List> sameXPoints = []; + for (int lineIndex = 0; lineIndex < lines.length; lineIndex++) { + List> linePoints = lines[lineIndex]; + for (int pointIndex = 0; pointIndex < linePoints.length; pointIndex++) { + if (currentPoint.x == linePoints[pointIndex].x && + currentPoint != linePoints[pointIndex]) { + sameXPoints.add(linePoints[pointIndex]); } } } @@ -582,31 +573,31 @@ class BrnLinePainter extends BrnBasePainter { //绘制图表的计算之后的结果模型集 class LineCanvasModel { - List paths; - Color pathColor; - double pathWidth; - - List shadowPaths; - List shaderColors; - - List points; - Color pointColor; - double pointRadius; - double pointInnerRadius; - Color pointInnerColor; - bool showPointText; - - LineCanvasModel({ - this.paths, - this.pathColor, - this.pathWidth, - this.shadowPaths, - this.shaderColors, - this.points, - this.pointColor, - this.pointRadius, - this.pointInnerRadius, - this.pointInnerColor, + final List paths; + final Color pathColor; + final double pathWidth; + + final List shadowPaths; + final List? shaderColors; + + final List? points; + final Color pointColor; + final double pointRadius; + final double pointInnerRadius; + final Color pointInnerColor; + final bool showPointText; + + const LineCanvasModel({ + required this.paths, + required this.pathColor, + required this.pathWidth, + required this.shadowPaths, + required this.shaderColors, + required this.points, + required this.pointColor, + required this.pointRadius, + required this.pointInnerRadius, + required this.pointInnerColor, this.showPointText = false, }); } diff --git a/lib/src/components/charts/broken_line/brn_line_y_painter.dart b/lib/src/components/charts/broken_line/brn_line_y_painter.dart index 9a8e9d8f..712d2c87 100644 --- a/lib/src/components/charts/broken_line/brn_line_y_painter.dart +++ b/lib/src/components/charts/broken_line/brn_line_y_painter.dart @@ -12,29 +12,29 @@ const double _basePadding = 0; const double _contentTopPadding = 10; class BrnLineYPainter extends BrnBasePainter { - int lineSelectIndex = -1; - int pointSelectIndex = -1; + final int lineSelectIndex; + final int pointSelectIndex; /// xy轴线条的宽度 double xyLineWidth = 0.5; /// x轴的颜色 - Color xColor; + Color? xColor; /// y轴的颜色 - Color yColor; + Color? yColor; /// y轴刻度的偏移量 - double yHintLineOffset; + final double yHintLineOffset; /// 刻度的宽度或者高度 double rulerWidth; /// y轴最大值,用来计算内部绘制点的y轴位置 - double yMin, yMax; + final double yMin, yMax; /// y轴左侧刻度显示,不传则没有 - List yDialValues; + final List? yDialValues; /// x、y轴的辅助线 bool isShowXHintLine, isShowYHintLine; @@ -43,34 +43,35 @@ class BrnLineYPainter extends BrnBasePainter { bool isHintLineSolid; /// 辅助线颜色 - Color hintLineColor; + Color? hintLineColor; /// 绘制线条的参数内容 List lines; bool isShowXDialText, isShowYDialText; - double selectX; - double selectY; - double _startX = 0.0, _endX = 0.0, _startY = 0.0, _endY = 0.0, _fixedHeight; + double? selectX; + double? selectY; + double _startX = 0.0, _endX = 0.0, _startY = 0.0, _endY = 0.0; + late double _fixedHeight; BrnLineYPainter( this.lines, { - this.lineSelectIndex = -1, - this.pointSelectIndex = -1, - this.yHintLineOffset = 20, - this.xColor, - this.yColor, - this.rulerWidth = 4, - this.yMin, - this.yMax, - this.yDialValues, - this.isShowXHintLine = true, - this.isShowYHintLine = false, - this.isHintLineSolid = true, - this.hintLineColor, - this.isShowXDialText = false, - this.isShowYDialText = false, + required this.lineSelectIndex, + required this.pointSelectIndex, + required this.yHintLineOffset, + required this.xColor, + required this.yColor, + required this.rulerWidth, + required this.yMin, + required this.yMax, + required this.yDialValues, + required this.isShowXHintLine, + required this.isShowYHintLine, + required this.isHintLineSolid, + required this.hintLineColor, + required this.isShowXDialText, + required this.isShowYDialText, }); @override @@ -105,11 +106,6 @@ class BrnLineYPainter extends BrnBasePainter { .colorTextSecondary; hintLineColor ??= BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase; - isHintLineSolid ??= true; - xyLineWidth ??= 0.5; - - yMin ??= 0; - yMax ??= 1; } /// 计算边界 @@ -119,7 +115,7 @@ class BrnLineYPainter extends BrnBasePainter { /// 如果展示y刻度文本,则左侧默认预留 20 像素高度展示x刻度 if (isShowYDialText) { - _startX = yHintLineOffset ?? 20.0; + _startX = yHintLineOffset; } /// 如果展示x刻度文本,则底部预留 20 像素高度展示x刻度 @@ -133,11 +129,11 @@ class BrnLineYPainter extends BrnBasePainter { void _drawXy(Canvas canvas, Paint paint) { if (isShowXHintLine) { canvas.drawLine(Offset(_startX, _startY), - Offset(_endX + _basePadding, _startY), paint..color = xColor); //x轴 + Offset(_endX + _basePadding, _startY), paint..color = xColor!); //x轴 } if (isShowYHintLine) { canvas.drawLine(Offset(_startX, _startY), - Offset(_startX, _endY - _basePadding), paint..color = yColor); //y轴 + Offset(_startX, _endY - _basePadding), paint..color = yColor!); //y轴 } _drawYRuler(canvas, paint); } @@ -147,8 +143,8 @@ class BrnLineYPainter extends BrnBasePainter { if (yDialValues == null) { return; } - for (var i = 0; i < yDialValues.length; i++) { - var ydialValue = yDialValues[i]; + for (var i = 0; i < yDialValues!.length; i++) { + var ydialValue = yDialValues![i]; // 绘制y轴文本 var yLength = (ydialValue.value - yMin) / (yMax - yMin) * _fixedHeight; @@ -177,7 +173,7 @@ class BrnLineYPainter extends BrnBasePainter { ..moveTo(_startX, _startY - yLength) ..lineTo(_startX + _endX - yHintLineOffset, _startY - yLength); if (isHintLineSolid) { - canvas.drawPath(hitXPath, paint..color = hintLineColor); + canvas.drawPath(hitXPath, paint..color = hintLineColor!); } else { canvas.drawPath( dashPath( @@ -185,7 +181,7 @@ class BrnLineYPainter extends BrnBasePainter { dashArray: CircularIntervalList([4.0, 4.0]), //虚线和间隔 ), - paint..color = hintLineColor, + paint..color = hintLineColor!, ); } } @@ -195,7 +191,7 @@ class BrnLineYPainter extends BrnBasePainter { canvas.drawLine( Offset(_startX, _startY - yLength), Offset(_startX + rulerWidth, _startY - yLength), - paint..color = yColor); + paint..color = yColor!); } } } diff --git a/lib/src/components/charts/broken_line/monotone_x.dart b/lib/src/components/charts/broken_line/monotone_x.dart index 930d7091..0494780a 100644 --- a/lib/src/components/charts/broken_line/monotone_x.dart +++ b/lib/src/components/charts/broken_line/monotone_x.dart @@ -23,7 +23,7 @@ class MonotoneX { double p = (s0 * h1 + s1 * h0) / (h0 + h1); var source = [s0.abs(), s1.abs(), 0.5 * p.abs()]; source.sort(); - return (sign(s0) + sign(s1)) * source.first ?? 0; + return (sign(s0) + sign(s1)) * source.first; } // According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations @@ -38,19 +38,16 @@ class MonotoneX { static Path addCurve(Path path, List points, {bool reversed = false, int endIndex = -1}) { - var targetPoints = List(); + var targetPoints = >[]; targetPoints.addAll(points); targetPoints.add(Point( points[points.length - 1].x * 2, points[points.length - 1].y * 2)); - double x0, y0, x1, y1, t0; - if (path == null) { - path = Path(); - } - List> arr = []; + double? x0, y0, x1, y1, t0; + List> arr = []; for (int i = 0; i < targetPoints.length; i++) { - double t1; - double x = targetPoints[i].x; - double y = targetPoints[i].y; + double? t1; + double x = targetPoints[i].x as double; + double y = targetPoints[i].y as double; if (x == x1 && y == y1) continue; switch (i) { case 0: @@ -58,11 +55,11 @@ class MonotoneX { case 1: break; case 2: - t1 = slope3(x0, y0, x1, y1, x, y); + t1 = slope3(x0!, y0!, x1!, y1!, x, y); arr.add([x0, y0, x1, y1, slope2(x0, y0, x1, y1, t1), t1]); break; default: - t1 = slope3(x0, y0, x1, y1, x, y); + t1 = slope3(x0!, y0!, x1!, y1!, x, y); arr.add([x0, y0, x1, y1, t0, t1]); } x0 = x1; @@ -75,13 +72,13 @@ class MonotoneX { if (reversed) { arr.reversed.forEach((f) { if (endIndex < 0 || index++ < endIndex) { - point(path, f[2], f[3], f[0], f[1], f[5], f[4]); + point(path, f[2]!, f[3]!, f[0]!, f[1]!, f[5]!, f[4]!); } }); } else { arr.forEach((f) { if (endIndex < 0 || index++ < endIndex) { - point(path, f[0], f[1], f[2], f[3], f[4], f[5]); + point(path, f[0]!, f[1]!, f[2]!, f[3]!, f[4]!, f[5]!); } }); } diff --git a/lib/src/components/charts/funnel_chart.dart b/lib/src/components/charts/funnel_chart.dart index da5955bd..a2ac4c7d 100644 --- a/lib/src/components/charts/funnel_chart.dart +++ b/lib/src/components/charts/funnel_chart.dart @@ -11,8 +11,8 @@ import 'package:flutter/rendering.dart'; /// \____文案____/ |____文案_____/ /// ___________ + ____________ /// \__文案___/ |____文案___/ -/// 第一种,是两边都向中间缩短的漏斗[FunnelShape.LeftAndRight]。 -/// 第二种,是只有一边向中间缩短的漏斗[FunnelShape.LeftOrRight]。 +/// 第一种,是两边都向中间缩短的漏斗[FunnelShape.leftAndRight]。 +/// 第二种,是只有一边向中间缩短的漏斗[FunnelShape.leftOrRight]。 /// 通过[inputTextStyle]来控制样式。 /// 在漏斗的两层layer之间或者左右可以插入标签markers,它们可以是一些常见的Widget,如[Text],在参数[children]中提供。 /// 通过[alignment]可以控制标签的插入位置。 @@ -60,23 +60,22 @@ class BrnFunnelChart extends MultiChildRenderObjectWidget { ]; BrnFunnelChart({ - Key key, - @required this.layerCount, - @required this.markerCount, - @required this.layerPainter, - @required MarkerBuilder builder, - this.shape = FunnelShape.LeftAndRight, + Key? key, + required this.layerCount, + required this.markerCount, + required this.layerPainter, + required MarkerBuilder builder, + this.shape = FunnelShape.leftAndRight, this.maxLayerWidth = 200, this.minLayerWidth = 0, this.layerHeight = 40, this.layerMargin = 0, this.childOffset = Offset.zero, this.alignment = MarkerAlignment.right, - }) : assert(layerCount != null), - assert(maxLayerWidth >= minLayerWidth), + }) : assert(maxLayerWidth >= minLayerWidth), assert(layerCount - markerCount == 0 || layerCount - markerCount == 1), assert(() { - if (shape == FunnelShape.LeftOrRight && + if (shape == FunnelShape.leftOrRight && alignment == MarkerAlignment.center) { debugPrint( '当shape为FunnelShape.LeftOrRight时,alignment为MarkerAlignment.center无效'); @@ -86,7 +85,7 @@ class BrnFunnelChart extends MultiChildRenderObjectWidget { super( key: key, children: () { - List children = List(); + List children = []; for (int i = 0; i < markerCount; i++) { children.add(builder(i)); } @@ -95,27 +94,25 @@ class BrnFunnelChart extends MultiChildRenderObjectWidget { ///漏斗图默认Bruno风格的命名构造函数,[layerCount]不能大于[defaultLayerColors.length]。 BrnFunnelChart.defaultStyle({ - Key key, - @required this.layerCount, - @required this.markerCount, - @required MarkerBuilder builder, + Key? key, + required this.layerCount, + required this.markerCount, + required MarkerBuilder builder, this.maxLayerWidth = 200, this.minLayerWidth = 0, this.layerHeight = 40, this.layerMargin = 0, this.childOffset = Offset.zero, }) : this.layerPainter = BrnDefaultFunnelLayerPainter(), - this.shape = FunnelShape.LeftAndRight, + this.shape = FunnelShape.leftAndRight, this.alignment = MarkerAlignment.right, - assert(layerCount != null && - layerCount <= defaultLayerColors.length && - layerCount >= 0), + assert(layerCount <= defaultLayerColors.length && layerCount >= 0), assert(maxLayerWidth >= minLayerWidth), assert(layerCount - markerCount == 0 || layerCount - markerCount == 1), super( key: key, children: () { - List children = List(); + List children = []; for (int i = 0; i < markerCount; i++) { children.add(builder(i)); } @@ -159,14 +156,14 @@ abstract class RenderFunnelChart extends RenderBox ContainerRenderObjectMixin, RenderBoxContainerDefaultsMixin { RenderFunnelChart({ - double layerMargin, - double layerHeight, - int layerCount, - double maxLayerWidth, - double minLayerWidth, - Offset childOffset, - MarkerAlignment alignment, - BrnFunnelLayerPainter layerPainter, + required double layerMargin, + required double layerHeight, + required int layerCount, + required double maxLayerWidth, + required double minLayerWidth, + required Offset childOffset, + required MarkerAlignment alignment, + required BrnFunnelLayerPainter layerPainter, }) : _layerMargin = layerMargin, _layerHeight = layerHeight, _layerCount = layerCount, @@ -275,20 +272,20 @@ abstract class RenderFunnelChart extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, {Offset position}) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @override double computeMinIntrinsicWidth(double height) { return getIntrinsicDimensionHorizontal( - height, (RenderBox child) => child.getMinIntrinsicWidth(height)); + height, (RenderBox child) => child.getMinIntrinsicWidth(height))!; } @override double computeMaxIntrinsicWidth(double height) { return getIntrinsicDimensionHorizontal( - height, (RenderBox child) => child.getMinIntrinsicWidth(height)); + height, (RenderBox child) => child.getMinIntrinsicWidth(height))!; } @override @@ -304,11 +301,11 @@ abstract class RenderFunnelChart extends RenderBox } @override - double computeDistanceToActualBaseline(TextBaseline baseline) { + double? computeDistanceToActualBaseline(TextBaseline baseline) { return defaultComputeDistanceToHighestActualBaseline(baseline); } - double getIntrinsicDimensionHorizontal( + double? getIntrinsicDimensionHorizontal( double height, double mainChildSizeGetter(RenderBox child)); double getIntrinsicDimensionVertical( @@ -322,17 +319,17 @@ class BrnFunnelRender extends RenderFunnelChart { static const double HALF_PIXEL = 0.5; BrnFunnelRender({ - double layerHeight, - double layerMargin, - int layerCount, - double maxLayerWidth, - double minLayerWidth, - Offset childOffset, - bool gradient, - List layerColors, - MarkerAlignment alignment, - BrnFunnelLayerPainter layerPainter, - FunnelShape shape, + required double layerHeight, + required double layerMargin, + required int layerCount, + required double maxLayerWidth, + required double minLayerWidth, + required Offset childOffset, + bool? gradient, + List? layerColors, + required MarkerAlignment alignment, + required BrnFunnelLayerPainter layerPainter, + required FunnelShape shape, }) : _shape = shape, _paint = Paint()..isAntiAlias = true, super( @@ -350,19 +347,20 @@ class BrnFunnelRender extends RenderFunnelChart { Paint _paint; bool _hasVisualOverflow = false; - Offset _overflowOffset; - Offset _centerOffset; + late Offset _overflowOffset; + late Offset _centerOffset; @override - double getIntrinsicDimensionHorizontal( + double? getIntrinsicDimensionHorizontal( double height, double mainChildSizeGetter(RenderBox child)) { - double extent = maxLayerWidth; + double? extent = maxLayerWidth; double intrinsicHeight = getIntrinsicDimensionVertical(null, null); - RenderBox child = firstChild; + RenderBox? child = firstChild; if (_alignment == MarkerAlignment.center) { while (child != null) { - final BrnFunnelChartParentData childParentData = child.parentData; - extent = max(extent, mainChildSizeGetter(child)); + final BrnFunnelChartParentData childParentData = + child.parentData as BrnFunnelChartParentData; + extent = max(extent!, mainChildSizeGetter(child)); child = childParentData.nextSibling; } } else { @@ -378,10 +376,11 @@ class BrnFunnelRender extends RenderFunnelChart { childOffset.dx; if (child == firstChild) { - extent = max(extent, left + mainChildSizeGetter(child)); + extent = max(extent!, left + mainChildSizeGetter(child)); } num++; - BrnFunnelChartParentData childParentData = child.parentData; + BrnFunnelChartParentData childParentData = + child.parentData as BrnFunnelChartParentData; child = childParentData.nextSibling; } } @@ -390,7 +389,7 @@ class BrnFunnelRender extends RenderFunnelChart { @override double getIntrinsicDimensionVertical( - double width, double mainChildSizeGetter(RenderBox child)) { + double? width, double mainChildSizeGetter(RenderBox child)?) { return layerCount * layerHeight + (layerCount - 1) * layerMargin; } @@ -403,8 +402,8 @@ class BrnFunnelRender extends RenderFunnelChart { ? layerMargin * childCount : layerMargin * (layerCount - 1)); - RenderBox child = firstChild; - double top, bottom, left, right; + RenderBox? child = firstChild; + late double top, bottom, left, right; int num = 0; while (child != null) { if (alignment == MarkerAlignment.center) { @@ -437,8 +436,9 @@ class BrnFunnelRender extends RenderFunnelChart { childOffset.dx; } - final BrnFunnelChartParentData childParentData = child.parentData; - BoxConstraints childConstraints; + final BrnFunnelChartParentData childParentData = + child.parentData as BrnFunnelChartParentData; + late BoxConstraints childConstraints; if (alignment == MarkerAlignment.center) { childConstraints = BoxConstraints( minWidth: 0, @@ -482,7 +482,7 @@ class BrnFunnelRender extends RenderFunnelChart { _hasVisualOverflow = true; } size = constraints.constrain(intrinsicSize); - _centerOffset = centerOffset(size - intrinsicSize); + _centerOffset = centerOffset(size - intrinsicSize as ui.Offset); if (_centerOffset.dx >= 0 && _centerOffset.dy >= 0) { //当实际尺寸比必须尺寸大时,需要居中偏移一下 if (alignment == MarkerAlignment.left) { @@ -503,7 +503,8 @@ class BrnFunnelRender extends RenderFunnelChart { num = 0; child = firstChild; while (child != null) { - final BrnFunnelChartParentData childParentData = child.parentData; + final BrnFunnelChartParentData childParentData = + child.parentData as BrnFunnelChartParentData; if (alignment == MarkerAlignment.center) { childParentData.offset = Offset(0, ((num * layerMargin) + (num + 1) * layerHeight)) + @@ -536,7 +537,7 @@ class BrnFunnelRender extends RenderFunnelChart { void paintFunnel(PaintingContext context, Offset offset) { Canvas canvas = context.canvas; canvas.save(); - Rect rect = (offset + _centerOffset ?? Offset.zero) & size; + Rect rect = (offset + _centerOffset) & size; canvas.clipRect(rect); _paint.blendMode = BlendMode.srcOver; canvas.saveLayer(rect, _paint); @@ -544,7 +545,7 @@ class BrnFunnelRender extends RenderFunnelChart { //绘制漏斗layer for (int i = 0; i < layerCount; i++) { - Offset topLeft, bottomRight; + late Offset topLeft, bottomRight; if (alignment == MarkerAlignment.center) { topLeft = Offset((size.width - maxLayerWidth) / 2, i * layerHeight + i * layerMargin); @@ -564,23 +565,19 @@ class BrnFunnelRender extends RenderFunnelChart { //绘制layer背景色 if (!layerPainter.isGradient(i)) { //单色背景 - if (layerPainter.getLayerColors(i) != null) { - _paint.color = layerPainter.getLayerColors(i)[0]; - canvas.drawRect(Rect.fromPoints(topLeft, bottomRight), _paint); - } + _paint.color = layerPainter.getLayerColors(i)[0]; + canvas.drawRect(Rect.fromPoints(topLeft, bottomRight), _paint); } else { //渐变背景 - if (layerPainter.getLayerColors(i) != null) { - ui.Gradient gradient = ui.Gradient.linear( - topLeft, bottomRight, layerPainter.getLayerColors(i)); - _paint.shader = gradient; - canvas.drawRect(Rect.fromPoints(topLeft, bottomRight), _paint); - } + ui.Gradient gradient = ui.Gradient.linear( + topLeft, bottomRight, layerPainter.getLayerColors(i)); + _paint.shader = gradient; + canvas.drawRect(Rect.fromPoints(topLeft, bottomRight), _paint); } //绘制layer文案 - double safeLeft, safeTop, safeRight, safeBottom; - if (_shape == FunnelShape.LeftAndRight) { + late double safeLeft, safeTop, safeRight, safeBottom; + if (_shape == FunnelShape.leftAndRight) { safeTop = i * layerHeight + i * layerMargin; if (alignment == MarkerAlignment.right) { safeLeft = ((i + 1) * layerHeight + i * layerMargin) * @@ -640,7 +637,7 @@ class BrnFunnelRender extends RenderFunnelChart { ..blendMode = BlendMode.dstOut ..style = PaintingStyle.fill ..shader = null; - double topLeftX; + late double topLeftX; if (alignment == MarkerAlignment.center) { topLeftX = (size.width - maxLayerWidth) / 2; } else if (alignment == MarkerAlignment.right) { @@ -650,7 +647,7 @@ class BrnFunnelRender extends RenderFunnelChart { } Path path; - if (_shape == FunnelShape.LeftAndRight || + if (_shape == FunnelShape.leftAndRight || alignment == MarkerAlignment.left) { path = Path(); //这里为什么都加了HALF_PIXEL,是因为裁剪的时候边缘会留下一定像素的误差。 @@ -665,7 +662,7 @@ class BrnFunnelRender extends RenderFunnelChart { canvas.drawPath(path, _paint); } - if (_shape == FunnelShape.LeftAndRight || + if (_shape == FunnelShape.leftAndRight || alignment == MarkerAlignment.right) { path = Path(); path.moveTo(maxLayerWidth + topLeftX + HALF_PIXEL, -HALF_PIXEL); @@ -742,7 +739,7 @@ class BrnDefaultFunnelLayerPainter extends BrnFunnelLayerPainter { }) : _textPainter = TextPainter()..textDirection = TextDirection.ltr; @override - void paintLayer(Canvas canvas, double left, double top, double right, + void paintLayer(Canvas canvas, double left, double? top, double right, double bottom, int layerIndex) { if (layerIndex >= titles.length) { return; @@ -755,7 +752,7 @@ class BrnDefaultFunnelLayerPainter extends BrnFunnelLayerPainter { _textPainter.paint( canvas, Offset((left + right - _textPainter.width) / 2, - (top + bottom - _textPainter.height) / 2), + (top! + bottom - _textPainter.height) / 2), ); } @@ -777,10 +774,10 @@ class BrnDefaultFunnelLayerPainter extends BrnFunnelLayerPainter { ///漏斗图表的形状 enum FunnelShape { ///两边从上往下都缩小 - LeftAndRight, + leftAndRight, ///一边从上往下缩小 - LeftOrRight, + leftOrRight, } ///漏斗标签的摆放位置 diff --git a/lib/src/components/charts/radar_chart.dart b/lib/src/components/charts/radar_chart.dart index 1c6550bb..4e7e2804 100644 --- a/lib/src/components/charts/radar_chart.dart +++ b/lib/src/components/charts/radar_chart.dart @@ -44,7 +44,7 @@ class BrnRadarChart extends MultiChildRenderObjectWidget { final double rotateAngle; ///每个标注文案的偏移量,必须和 [sidesCount] 保持一致。 - final List offset; + final List? offset; ///The default preset chart styles ordered in priority of usage. static const List defaultRadarChartStyles = [ @@ -87,9 +87,9 @@ class BrnRadarChart extends MultiChildRenderObjectWidget { ]; BrnRadarChart({ - Key key, - @required this.provider, - @required MarkerBuilder builder, + Key? key, + required this.provider, + required MarkerBuilder builder, this.radius = 50, this.levelCount = 3, this.maxValue = 10, @@ -101,14 +101,12 @@ class BrnRadarChart extends MultiChildRenderObjectWidget { this.crossedAxisLine = false, this.animateProgress = 1.0, this.rotateAngle = 0, - }) : assert(sidesCount != null), - assert(minValue < maxValue), + }) : assert(minValue < maxValue), assert(sidesCount >= 3), - assert(provider != null && builder != null), super( key: key, children: () { - List children = List(); + List children = []; for (int i = 0; i < sidesCount; i++) { children.add(builder(i)); } @@ -119,7 +117,7 @@ class BrnRadarChart extends MultiChildRenderObjectWidget { ///The [data] length should be less than the [defaultRadarChartStyles]'s length ///or you should use the default constructor. BrnRadarChart.defaultStyle({ - Key key, + Key? key, this.radius = 50, this.levelCount = 3, this.maxValue = 10, @@ -129,11 +127,9 @@ class BrnRadarChart extends MultiChildRenderObjectWidget { this.rotateAngle = 0, this.crossedAxisLine = false, this.offset, - @required List tagNames, - @required List> data, - }) : assert(sidesCount != null && sidesCount >= 3), - assert(tagNames != null), - assert(data != null), + required List tagNames, + required List> data, + }) : assert(sidesCount >= 3), assert(tagNames.length == sidesCount), assert(minValue < maxValue), assert(data.length <= defaultRadarChartStyles.length), @@ -143,7 +139,7 @@ class BrnRadarChart extends MultiChildRenderObjectWidget { super( key: key, children: () { - List children = List(); + List children = []; for (int i = 0; i < sidesCount; i++) { children.add(Container( constraints: BoxConstraints( @@ -224,17 +220,17 @@ class RenderRadarChart extends RenderBox BrnRadarChartDataProvider _dataProvider; RenderRadarChart({ - double radius, - double markerMargin, - int sideCount, - double maxValue, - double rotateAngle, - List offset, - BrnRadarChartDataProvider provider, - int levelCount, - Color axisLineColor, - bool crossedAxisLine, - double animateProgress, + required double radius, + required double markerMargin, + required int sideCount, + required double maxValue, + required double rotateAngle, + required List offset, + required BrnRadarChartDataProvider provider, + required int levelCount, + required Color axisLineColor, + required bool crossedAxisLine, + required double animateProgress, }) : _radius = radius, _markerMargin = markerMargin, _maxValue = maxValue, @@ -351,11 +347,12 @@ class RenderRadarChart extends RenderBox double mainChildSizeGetter(RenderBox child)) { double x; double maxX = 0, minX = 0; - RenderBox child = firstChild; + RenderBox? child = firstChild; //多边形的中心为原点 int i = 0; while (child != null) { - final BrnRadarChartParentData childParentData = child.parentData; + final BrnRadarChartParentData childParentData = + child.parentData as BrnRadarChartParentData; double angle = (2 * pi * i / _sideCount + _rotateAngle) % (2 * pi); x = _radius * sin(angle); if (x >= 0) { @@ -385,11 +382,12 @@ class RenderRadarChart extends RenderBox double mainChildSizeGetter(RenderBox child)) { double y; double maxY = 0, minY = 0; - RenderBox child = firstChild; + RenderBox? child = firstChild; //多边形的中心为原点 int i = 0; while (child != null) { - final BrnRadarChartParentData childParentData = child.parentData; + final BrnRadarChartParentData childParentData = + child.parentData as BrnRadarChartParentData; double angle = (2 * pi * i / _sideCount + _rotateAngle) % (2 * pi); y = _radius * cos(angle); @@ -443,7 +441,7 @@ class RenderRadarChart extends RenderBox } @override - double computeDistanceToActualBaseline(TextBaseline baseline) { + double? computeDistanceToActualBaseline(TextBaseline baseline) { return defaultComputeDistanceToHighestActualBaseline(baseline); } @@ -453,11 +451,12 @@ class RenderRadarChart extends RenderBox double x, y; double maxX = 0, minX = 0; double maxY = 0, minY = 0; - RenderBox child = firstChild; + RenderBox? child = firstChild; //多边形的中心为原点 int i = 0; while (child != null) { - final BrnRadarChartParentData childParentData = child.parentData; + final BrnRadarChartParentData childParentData = + child.parentData as BrnRadarChartParentData; BoxConstraints childConstraints = constraints.loosen(); child.layout(childConstraints, parentUsesSize: true); final Size childSize = child.size; @@ -526,7 +525,8 @@ class RenderRadarChart extends RenderBox double angle = (2 * pi * i / _sideCount + _rotateAngle) % (2 * pi); double x = _radius * sin(angle); //在以多边形中心为原点的坐标 double y = _radius * cos(angle); //在以多边形中心为原点的坐标 - final BrnRadarChartParentData childParentData = child.parentData; + final BrnRadarChartParentData childParentData = + child.parentData as BrnRadarChartParentData; //转换到左上角为原点中的坐标 if (y >= 0) { @@ -575,7 +575,7 @@ class RenderRadarChart extends RenderBox } @override - bool hitTestChildren(BoxHitTestResult result, {Offset position}) { + bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { return defaultHitTestChildren(result, position: position); } @@ -592,8 +592,8 @@ class RenderRadarChart extends RenderBox double translateX = rect.width / 2; double translateY = rect.height / 2; //translate the canvas's top left to widget'center since flutter canvas rotate pivot can only be the top left. - canvas.translate(translateX + _centerOffset?.dx ?? 0, - translateY + _centerOffset?.dy ?? 0); + canvas.translate( + translateX + _centerOffset.dx, translateY + _centerOffset.dy); canvas.rotate(_rotateAngle); _drawBackground(canvas, rect.size, translateX, translateY); _drawRadar(canvas); @@ -662,18 +662,13 @@ class RenderRadarChart extends RenderBox void _drawRadar(Canvas canvas) { int radarCount = _dataProvider.getRadarCount(); - assert(radarCount != null); for (int radarIndex = 0; radarIndex < radarCount; radarIndex++) { BrnRadarChartStyle radarStyle = _dataProvider.getRadarStyle(radarIndex); - assert(radarStyle != null); _radarPainter ..isAntiAlias = true - ..color = radarStyle?.strokeColor - ..strokeWidth = radarStyle?.strokeWidth; + ..color = radarStyle.strokeColor + ..strokeWidth = radarStyle.strokeWidth; List values = _dataProvider.getRadarValues(radarIndex); - if (values == null) { - continue; - } Path path = Path(); double percent = values[0] / _maxValue; double angle = 0; @@ -683,7 +678,7 @@ class RenderRadarChart extends RenderBox percent = 0; } double x, y; - List dotPosition = List(); + List dotPosition = []; x = _radius * percent * sin(angle) * _animateProgress; y = -_radius * percent * cos(angle) * _animateProgress; dotPosition.add(Offset(x, y)); @@ -708,10 +703,10 @@ class RenderRadarChart extends RenderBox for (int i = 0; i < dotPosition.length; i++) { _radarPainter.color = Colors.white; canvas.drawCircle( - dotPosition[i], radarStyle.dotRadius + 2 ?? 2, _radarPainter); + dotPosition[i], radarStyle.dotRadius + 2, _radarPainter); _radarPainter.color = radarStyle.dotColor ?? radarStyle.strokeColor; canvas.drawCircle( - dotPosition[i], radarStyle.dotRadius ?? 2, _radarPainter); + dotPosition[i], radarStyle.dotRadius, _radarPainter); } } } @@ -774,14 +769,14 @@ class BrnRadarChartStyle { final bool dotted; ///The color of the dotted vertexes. - final Color dotColor; + final Color? dotColor; ///The radius of the dotted circle. final double dotRadius; const BrnRadarChartStyle({ - @required this.strokeColor, - @required this.areaColor, + required this.strokeColor, + required this.areaColor, this.strokeWidth = 3, this.dotted = false, this.dotColor, @@ -796,9 +791,7 @@ class DefaultRadarProvider extends BrnRadarChartDataProvider { DefaultRadarProvider(this.dataList); @override - int getRadarCount() { - return dataList?.length ?? 0; - } + int getRadarCount() => dataList.length; @override BrnRadarChartStyle getRadarStyle(int radarIndex) { diff --git a/lib/src/components/dialog/brn_content_export_dialog.dart b/lib/src/components/dialog/brn_content_export_dialog.dart index 91d48d54..61d8b9eb 100644 --- a/lib/src/components/dialog/brn_content_export_dialog.dart +++ b/lib/src/components/dialog/brn_content_export_dialog.dart @@ -9,39 +9,39 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class BrnContentExportWidget extends StatelessWidget { /// 标题 - final String title; + final String? title; /// 是否可关闭 final bool isClose; /// 中间内容widget - final Widget contentWidget; + final Widget? contentWidget; /// 提交按钮文字 - final String submitText; + final String? submitText; /// 内容最大高度 - final Color submitBgColor; + final Color? submitBgColor; /// 提交操作 - final VoidCallback onSubmit; + final VoidCallback? onSubmit; /// 是否展示底部操作区域 final bool isShowOperateWidget; - BrnDialogConfig themeData; + BrnDialogConfig? themeData; BrnContentExportWidget(this.contentWidget, {this.title, - this.isClose, + required this.isClose, this.submitText, this.onSubmit, this.submitBgColor, - this.isShowOperateWidget, + required this.isShowOperateWidget, this.themeData}) { this.themeData ??= BrnDialogConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: themeData!.configId) .dialogConfig .merge(themeData); } @@ -67,7 +67,7 @@ class BrnContentExportWidget extends StatelessWidget { color: Colors.white, borderRadius: BorderRadius.all(Radius.circular( BrnDialogUtils.getDialogRadius( - themeData))), //设置四周圆角 角度 + themeData!))), //设置四周圆角 角度 ), child: Stack( children: [ @@ -76,7 +76,7 @@ class BrnContentExportWidget extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ _generateTitleWidget(), - contentWidget, + contentWidget ?? Container(), _generateBottomWidget(context), ], ), @@ -100,7 +100,7 @@ class BrnContentExportWidget extends StatelessWidget { behavior: HitTestBehavior.opaque, child: Padding( padding: EdgeInsets.all(15), - child: BrunoTools.getAssetImage(BrnAsset.ICON_PICKER_CLOSE), + child: BrunoTools.getAssetImage(BrnAsset.iconPickerClose), ))); } return Container(); @@ -109,13 +109,13 @@ class BrnContentExportWidget extends StatelessWidget { /// 构建Dialog标题 Widget _generateTitleWidget() { return Padding( - padding: null != title && title.isNotEmpty + padding: null != title && title!.isNotEmpty ? EdgeInsets.fromLTRB(20, 28, 20, 12) : EdgeInsets.only(top: 20), - child: null != title && title.isNotEmpty + child: null != title && title!.isNotEmpty ? Text( - title, - style: BrnDialogUtils.getDialogTitleStyle(themeData), + title!, + style: BrnDialogUtils.getDialogTitleStyle(themeData!), ) : Container(), ); @@ -133,20 +133,20 @@ class BrnContentExportWidget extends StatelessWidget { decoration: BoxDecoration( //背景 color: - submitBgColor ?? themeData.commonConfig.brandPrimary, + submitBgColor ?? themeData!.commonConfig.brandPrimary, borderRadius: BorderRadius.all(Radius.circular(6.0)), //设置四周圆角 角度 ), alignment: Alignment.center, height: 48, - child: Text(submitText, + child: Text(submitText ?? "", textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.w600, color: Colors.white, fontSize: 18))), onTap: () { - if (onSubmit != null) onSubmit(); + if (onSubmit != null) onSubmit!(); }, ) : Container()); diff --git a/lib/src/components/dialog/brn_dialog.dart b/lib/src/components/dialog/brn_dialog.dart index cdfefe63..44e06d0e 100644 --- a/lib/src/components/dialog/brn_dialog.dart +++ b/lib/src/components/dialog/brn_dialog.dart @@ -3,7 +3,6 @@ import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_dialog_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// 底部按钮的点击监听回调 @@ -79,78 +78,78 @@ const Divider cDividerLine = const Divider( color: Color(0xF0F0F0F0), ); -enum ButtonType { +enum _ButtonType { /// 单按钮 - Single, + single, /// 多按钮 - Multi, + multi, /// 左按钮 - Left, + left, /// 右按钮 - Right, + right, } /// 对话框的样式 class BrnDialogStyle { /// title的间距 - EdgeInsetsGeometry titlePadding; + EdgeInsets? titlePadding; /// 主色调按钮样式 - TextStyle mainTextStyle; + TextStyle? mainTextStyle; /// 主色调按钮的背景 - Color mainBackgroundColor; + Color? mainBackgroundColor; /// 其他按钮的样式 - TextStyle greyActionsTextStyle; + TextStyle? greyActionsTextStyle; /// 其他按钮的背景 - Color greyActionsBackgroundColor; + Color? greyActionsBackgroundColor; /// 标题的文字样式 - TextStyle titleTextStyle; + TextStyle? titleTextStyle; /// 标题的文字对齐 - TextAlign titleTextAlign; + TextAlign? titleTextAlign; /// 内容文字的对齐 - TextAlign contentTextAlign; + TextAlign? contentTextAlign; /// 内容widget的间距 - EdgeInsetsGeometry contentPadding; + EdgeInsets? contentPadding; /// 内容文字的样式 - TextStyle contentTextStyle; + TextStyle? contentTextStyle; /// 对话框的背景 - Color backgroundColor; + Color? backgroundColor; /// 对话框的底部按钮的高度 - double bottomHeight; + double? bottomHeight; /// 对话框圆角的大小 - double radius; + double? radius; /// 边框阴影 - double elevation; + double? elevation; /// 警示文案的样式 - TextStyle warningTextStyle; + TextStyle? warningTextStyle; /// 警示文案文字的对齐 - TextAlign warningTextAlign; + TextAlign? warningTextAlign; /// 警示文案的间距 - EdgeInsetsGeometry warningPadding; + EdgeInsets? warningPadding; /// icon的间距 - EdgeInsetsGeometry iconPadding; + EdgeInsets? iconPadding; /// 标题最大行数 - int titleMaxLines; + int? titleMaxLines; BrnDialogStyle({ this.titlePadding, @@ -207,30 +206,30 @@ class BrnDialogStyle { class BrnDialog extends AlertDialog { /// 标题控件 - final Widget titleWidget; + final Widget? titleWidget; /// 内容控件 - final Widget contentWidget; + final Widget? contentWidget; /// 警示文案部分的控件 - final Widget warningWidget; + final Widget? warningWidget; /// 按钮部分控件 - final List actionsWidget; + final List? actionsWidget; ///-----如果以上属性设置了,那么对话框中的相对应的部分 以他们为基准 /// 标题文本 - final String titleText; + final String? titleText; /// 内容文本 - final String messageText; + final String? messageText; /// 警示文本 - final String warningText; + final String? warningText; /// 底部按钮文案 - final List actionsText; + final List? actionsText; /// 根据以上属性 生成对应的text控件 @@ -240,20 +239,17 @@ class BrnDialog extends AlertDialog { /// 水平分割线 final Divider divider; - /// 对话框样式 - final BrnDialogStyle brnDialogStyle; - /// 底部按钮的点击监听回调 - final DialogIndexedActionClickCallback indexedActionCallback; + final DialogIndexedActionClickCallback? indexedActionCallback; /// 是否展示头部icon final bool showIcon; /// 头部的icon - final Image iconImage; + final Image? iconImage; /// dialog配置 - final BrnDialogConfig themeData; + final BrnDialogConfig? themeData; /// 标题最大行数 final int titleMaxLines; @@ -268,7 +264,6 @@ class BrnDialog extends AlertDialog { this.warningText, this.warningWidget, this.actionsWidget, - this.brnDialogStyle, this.divider = cDividerLine, this.verticalDivider = cVerticalDivider, this.actionsText, @@ -279,8 +274,7 @@ class BrnDialog extends AlertDialog { @override Widget build(BuildContext context) { - BrnDialogConfig defaultConfig = _convertStyleToConfig(); - defaultConfig = themeData ?? BrnDialogConfig(); + BrnDialogConfig? defaultConfig = BrnDialogConfig(); defaultConfig = BrnThemeConfigurator.instance .getConfig(configId: defaultConfig.configId) @@ -312,7 +306,7 @@ class BrnDialog extends AlertDialog { } children.add(Padding( - padding: defaultConfig?.dividerPadding, + padding: defaultConfig.dividerPadding, child: SizedBox( height: 0, width: 0, @@ -332,13 +326,13 @@ class BrnDialog extends AlertDialog { return UnconstrainedBox( child: SizedBox( - width: defaultConfig?.dialogWidth, + width: defaultConfig.dialogWidth, child: Material( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular( BrnDialogUtils.getDialogRadius(defaultConfig)))), child: dialogChild, - color: defaultConfig?.backgroundColor, + color: defaultConfig.backgroundColor, ))); } @@ -347,7 +341,7 @@ class BrnDialog extends AlertDialog { Widget _createWidget(Widget widget) { return Center( child: Padding( - padding: dialogConfig?.iconPadding, + padding: dialogConfig.iconPadding, child: SizedBox( width: 36, height: 36, @@ -358,7 +352,7 @@ class BrnDialog extends AlertDialog { } if (iconImage != null) { - return _createWidget(iconImage); + return _createWidget(iconImage!); } if (showIcon) { return _createWidget( @@ -376,20 +370,20 @@ class BrnDialog extends AlertDialog { BuildContext context, BrnDialogConfig dialogConfig) { if (titleWidget != null) { return DefaultTextStyle( - textAlign: dialogConfig?.titleTextAlign, + textAlign: dialogConfig.titleTextAlign, style: BrnDialogUtils.getDialogTitleStyle(dialogConfig), - child: titleWidget, + child: titleWidget!, ); } return Padding( padding: _configTitlePadding(dialogConfig), child: Text( - titleText, + titleText!, maxLines: titleMaxLines, overflow: TextOverflow.ellipsis, style: BrnDialogUtils.getDialogTitleStyle(dialogConfig), - textAlign: dialogConfig?.titleTextAlign, + textAlign: dialogConfig.titleTextAlign, ), ); } @@ -400,8 +394,8 @@ class BrnDialog extends AlertDialog { if (contentWidget != null) return Flexible( child: DefaultTextStyle( - style: (dialogConfig?.contentTextStyle)?.generateTextStyle(), - child: contentWidget, + style: dialogConfig.contentTextStyle.generateTextStyle(), + child: contentWidget!, ), ); @@ -409,9 +403,9 @@ class BrnDialog extends AlertDialog { padding: _configContentPadding(dialogConfig), child: Center( child: Text( - messageText, - style: (dialogConfig?.contentTextStyle)?.generateTextStyle(), - textAlign: dialogConfig?.contentTextAlign, + messageText ?? "", + style: dialogConfig.contentTextStyle.generateTextStyle(), + textAlign: dialogConfig.contentTextAlign, ), ), ); @@ -423,17 +417,17 @@ class BrnDialog extends AlertDialog { if (warningWidget != null) return Flexible( child: DefaultTextStyle( - style: (dialogConfig?.warningTextStyle)?.generateTextStyle(), - child: warningWidget, + style: dialogConfig.warningTextStyle.generateTextStyle(), + child: warningWidget!, ), ); return Padding( padding: _configWarningPadding(dialogConfig), child: Text( - warningText, - style: (dialogConfig?.warningTextStyle)?.generateTextStyle(), - textAlign: dialogConfig?.warningTextAlign, + warningText!, + style: dialogConfig.warningTextStyle.generateTextStyle(), + textAlign: dialogConfig.warningTextAlign, ), ); } @@ -442,30 +436,30 @@ class BrnDialog extends AlertDialog { /// 单个button 左右有圆角 /// 两个button 左button有左圆角&右直角 右button有右圆角&左直角 /// 多个button 最后一个左右圆角 其他均直角 - Widget _generateMainWidget(Widget widget, Color background, ButtonType type, + Widget _generateMainWidget(Widget widget, Color background, _ButtonType type, int index, BrnDialogConfig dialogConfig) { return Container( decoration: ShapeDecoration( color: background, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(type == ButtonType.Single || - type == ButtonType.Left || - (type == ButtonType.Multi && + bottomLeft: Radius.circular(type == _ButtonType.single || + type == _ButtonType.left || + (type == _ButtonType.multi && actionsText != null && - index == actionsText.length - 1) + index == actionsText!.length - 1) ? BrnDialogUtils.getDialogRadius(dialogConfig) : 0), - bottomRight: Radius.circular(type == ButtonType.Single || - type == ButtonType.Right || - (type == ButtonType.Multi && + bottomRight: Radius.circular(type == _ButtonType.single || + type == _ButtonType.right || + (type == _ButtonType.multi && actionsText != null && - index == actionsText.length - 1) + index == actionsText!.length - 1) ? BrnDialogUtils.getDialogRadius(dialogConfig) : 0)))), constraints: BoxConstraints.tightFor(height: cBottomHeight), child: DefaultTextStyle( - style: (dialogConfig?.mainActionTextStyle)?.generateTextStyle(), + style: dialogConfig.mainActionTextStyle.generateTextStyle(), child: Center( child: widget, ), @@ -477,7 +471,7 @@ class BrnDialog extends AlertDialog { /// 单个button 左右有圆角 /// 两个button 左button有左圆角&右直角 右button有右圆角&左直角 /// 多个button 最后一个左右圆角 其他均直角 - Widget _generateGreyWidget(Widget widget, Color background, ButtonType type, + Widget _generateGreyWidget(Widget widget, Color background, _ButtonType type, int index, BrnDialogConfig dialogConfig) { return Container( constraints: BoxConstraints.tightFor(height: cBottomHeight), @@ -485,22 +479,22 @@ class BrnDialog extends AlertDialog { color: background, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( - bottomLeft: Radius.circular(type == ButtonType.Single || - type == ButtonType.Left || - (type == ButtonType.Multi && + bottomLeft: Radius.circular(type == _ButtonType.single || + type == _ButtonType.left || + (type == _ButtonType.multi && actionsText != null && - index == actionsText.length - 1) + index == actionsText!.length - 1) ? BrnDialogUtils.getDialogRadius(dialogConfig) : 0), - bottomRight: Radius.circular(type == ButtonType.Single || - type == ButtonType.Right || - (type == ButtonType.Multi && + bottomRight: Radius.circular(type == _ButtonType.single || + type == _ButtonType.right || + (type == _ButtonType.multi && actionsText != null && - index == actionsText.length - 1) + index == actionsText!.length - 1) ? BrnDialogUtils.getDialogRadius(dialogConfig) : 0)))), child: DefaultTextStyle( - style: dialogConfig?.assistActionsTextStyle?.generateTextStyle(), + style: dialogConfig.assistActionsTextStyle.generateTextStyle(), child: Center( child: widget, ), @@ -511,18 +505,18 @@ class BrnDialog extends AlertDialog { Widget _generateActionsWidget( BuildContext context, BrnDialogConfig defaultConfig) { bool showTextActions = _isEmptyActionsWidget(); - int length = showTextActions ? actionsText.length : actionsWidget.length; + int length = showTextActions ? actionsText!.length : actionsWidget!.length; if (length == 1) { return showTextActions ? _mapTextToGesWidget( context, - actionsText[0], + actionsText![0], 0, true, defaultConfig, - type: ButtonType.Single, + type: _ButtonType.single, ) - : actionsWidget[0]; + : actionsWidget![0]; } else if (length == 2) { return Row( mainAxisSize: MainAxisSize.max, @@ -531,26 +525,26 @@ class BrnDialog extends AlertDialog { Expanded( child: showTextActions ? _mapTextToGesWidget( - context, actionsText[0], 0, false, defaultConfig, - type: ButtonType.Left) - : actionsWidget[0], + context, actionsText![0], 0, false, defaultConfig, + type: _ButtonType.left) + : actionsWidget![0], ), Container( - height: defaultConfig?.bottomHeight, + height: defaultConfig.bottomHeight, child: verticalDivider, ), Expanded( child: showTextActions ? _mapTextToGesWidget( - context, actionsText[1], 1, true, defaultConfig, - type: ButtonType.Right) - : actionsWidget[1], + context, actionsText![1], 1, true, defaultConfig, + type: _ButtonType.right) + : actionsWidget![1], ) ], ); } else { return Container( - height: 3 * (defaultConfig?.bottomHeight ?? 0 + 1), + height: 3 * (defaultConfig.bottomHeight + 1), width: double.maxFinite, child: ListView.separated( shrinkWrap: true, @@ -558,9 +552,9 @@ class BrnDialog extends AlertDialog { itemBuilder: (context, i) { return showTextActions ? _mapTextToGesWidget( - context, actionsText[i], i, true, defaultConfig, - type: ButtonType.Multi) - : actionsWidget[i]; + context, actionsText![i], i, true, defaultConfig, + type: _ButtonType.multi) + : actionsWidget![i]; }, separatorBuilder: (context, i) { return divider; @@ -572,22 +566,18 @@ class BrnDialog extends AlertDialog { Widget _mapTextToGesWidget(BuildContext context, String label, int index, bool main, BrnDialogConfig dialogConfig, - {ButtonType type = ButtonType.Single}) { + {_ButtonType type = _ButtonType.single}) { Text text = Text(label); Widget ges = GestureDetector( child: main - ? _generateMainWidget(text, dialogConfig?.mainActionBackgroundColor, + ? _generateMainWidget(text, dialogConfig.mainActionBackgroundColor, type, index, dialogConfig) - : _generateGreyWidget( - text, - dialogConfig?.assistActionsBackgroundColor, - type, - index, - dialogConfig), + : _generateGreyWidget(text, dialogConfig.assistActionsBackgroundColor, + type, index, dialogConfig), onTap: () { if (indexedActionCallback != null) { //点击的监听 - indexedActionCallback(index); + indexedActionCallback!(index); } else { Navigator.pop(context); } @@ -617,66 +607,32 @@ class BrnDialog extends AlertDialog { } bool _isEmptyActionsText() { - return actionsText == null || actionsText.isEmpty; + return actionsText == null || actionsText!.isEmpty; } bool _isEmptyActionsWidget() { - return actionsWidget == null || actionsWidget.isEmpty; - } - - /// 将已有的BrnDialogStyle转换成BrnDialogConfig - /// 当用户配置了最新的themeData则ljDialogStyle失效 - /// 当用户配置仅配置ljDialogStyle,则将ljDialogStyle转换成themeData - BrnDialogConfig _convertStyleToConfig() { - if (brnDialogStyle == null) { - return themeData; - } - BrnDialogConfig defaultConfig = themeData ?? BrnDialogConfig(); - defaultConfig = defaultConfig.merge(BrnDialogConfig( - mainActionTextStyle: BrnTextStyle.withStyle(brnDialogStyle.mainTextStyle), - mainActionBackgroundColor: brnDialogStyle.mainBackgroundColor, - assistActionsTextStyle: - BrnTextStyle.withStyle(brnDialogStyle.greyActionsTextStyle), - assistActionsBackgroundColor: brnDialogStyle.greyActionsBackgroundColor, - radius: brnDialogStyle.radius, - iconPadding: brnDialogStyle.iconPadding, - titlePaddingSm: brnDialogStyle.titlePadding, - titlePaddingLg: brnDialogStyle.titlePadding, - titleTextAlign: brnDialogStyle.titleTextAlign, - titleTextStyle: BrnTextStyle.withStyle(brnDialogStyle.titleTextStyle), - contentPaddingSm: brnDialogStyle.contentPadding, - contentPaddingLg: brnDialogStyle.contentPadding, - contentTextAlign: brnDialogStyle.contentTextAlign, - contentTextStyle: BrnTextStyle.withStyle(brnDialogStyle.contentTextStyle), - warningPaddingSm: brnDialogStyle.warningPadding, - warningPaddingLg: brnDialogStyle.warningPadding, - warningTextAlign: brnDialogStyle.warningTextAlign, - warningTextStyle: BrnTextStyle.withStyle(brnDialogStyle.warningTextStyle), - bottomHeight: brnDialogStyle.bottomHeight, - backgroundColor: brnDialogStyle.backgroundColor, - )); - return defaultConfig; + return actionsWidget == null || actionsWidget!.isEmpty; } /// 主题配置的标题间距 EdgeInsetsGeometry _configTitlePadding(BrnDialogConfig dialogConfig) { return _isShowIcon() - ? dialogConfig?.titlePaddingSm - : dialogConfig?.titlePaddingLg; + ? dialogConfig.titlePaddingSm + : dialogConfig.titlePaddingLg; } /// 主题配置的内容间距 EdgeInsetsGeometry _configContentPadding(BrnDialogConfig dialogConfig) { return (_isShowIcon() || _isShowTitle()) - ? dialogConfig?.contentPaddingSm - : dialogConfig?.contentPaddingLg; + ? dialogConfig.contentPaddingSm + : dialogConfig.contentPaddingLg; } /// 主题配置的警告间距 EdgeInsetsGeometry _configWarningPadding(BrnDialogConfig dialogConfig) { return (_isShowIcon() || _isShowTitle() || _isShowContent()) - ? dialogConfig?.warningPaddingSm - : dialogConfig?.warningPaddingLg; + ? dialogConfig.warningPaddingSm + : dialogConfig.warningPaddingLg; } } @@ -710,23 +666,23 @@ class BrnDialogManager { ///labelWidget 自定义底部按钮的显示 static void showSingleButtonDialog( BuildContext context, { - @required String label, + required String label, bool showIcon = false, - Image iconWidget, - String title, - Widget titleWidget, - String message, - Widget messageWidget, - String warning, - Widget warningWidget, - Widget labelWidget, - BrnDialogStyle dialogStyle, - GestureTapCallback onTap, + Image? iconWidget, + String? title, + Widget? titleWidget, + String? message, + Widget? messageWidget, + String? warning, + Widget? warningWidget, + Widget? labelWidget, + BrnDialogStyle? dialogStyle, + GestureTapCallback? onTap, bool barrierDismissible = true, int titleMaxLines = cTitleMaxLines, - BrnDialogConfig themeData, + BrnDialogConfig? themeData, }) { - List actionsWidget = List(); + List actionsWidget = []; if (labelWidget != null) { actionsWidget.add(labelWidget); @@ -745,7 +701,6 @@ class BrnDialogManager { warningText: warning, warningWidget: warningWidget, actionsText: [label], - brnDialogStyle: dialogStyle, actionsWidget: actionsWidget, titleMaxLines: titleMaxLines, themeData: themeData, @@ -768,26 +723,26 @@ class BrnDialogManager { /// conformWidget 自定义显示的右侧 static void showConfirmDialog( BuildContext context, { - @required String cancel, - @required String confirm, + required String cancel, + required String confirm, bool showIcon = false, - Image iconWidget, - String title, - Widget titleWidget, - String message, - Widget messageWidget, - String warning, - Widget warningWidget, - Widget cancelWidget, - Widget conformWidget, - BrnDialogStyle dialogStyle, - GestureTapCallback onCancel, - GestureTapCallback onConfirm, + Image? iconWidget, + String? title, + Widget? titleWidget, + String? message, + Widget? messageWidget, + String? warning, + Widget? warningWidget, + Widget? cancelWidget, + Widget? conformWidget, + BrnDialogStyle? dialogStyle, + GestureTapCallback? onCancel, + GestureTapCallback? onConfirm, bool barrierDismissible = true, int titleMaxLines = cTitleMaxLines, - BrnDialogConfig themeData, + BrnDialogConfig? themeData, }) { - List actionsWidget = List(); + List actionsWidget = []; if (cancelWidget != null) { actionsWidget.add(cancelWidget); @@ -810,7 +765,6 @@ class BrnDialogManager { warningText: warning, themeData: themeData, titleMaxLines: titleMaxLines, - brnDialogStyle: dialogStyle, actionsText: [cancel, confirm], actionsWidget: actionsWidget, indexedActionCallback: (index) { @@ -835,21 +789,21 @@ class BrnDialogManager { ///如果数量超过了三个 会滑动展示 static void showMoreButtonDialog( BuildContext context, { - @required List actions, + required List actions, bool showIcon = false, - Image iconWidget, - String title, - Widget titleWidget, - String message, - Widget messageWidget, - String warning, - Widget warningWidget, - List actionsWidget, + Image? iconWidget, + String? title, + Widget? titleWidget, + String? message, + Widget? messageWidget, + String? warning, + Widget? warningWidget, + List? actionsWidget, bool barrierDismissible = true, - BrnDialogStyle dialogStyle, + BrnDialogStyle? dialogStyle, int titleMaxLines = cTitleMaxLines, - BrnDialogConfig themeData, - DialogIndexedActionClickCallback indexedActionClickCallback, + BrnDialogConfig? themeData, + DialogIndexedActionClickCallback? indexedActionClickCallback, }) { showDialog( context: context, @@ -864,7 +818,6 @@ class BrnDialogManager { contentWidget: messageWidget, warningWidget: warningWidget, warningText: warning, - brnDialogStyle: dialogStyle, actionsText: actions, actionsWidget: actionsWidget, themeData: themeData, diff --git a/lib/src/components/dialog/brn_dialog_utils.dart b/lib/src/components/dialog/brn_dialog_utils.dart index 4cdf2801..fcc6b430 100644 --- a/lib/src/components/dialog/brn_dialog_utils.dart +++ b/lib/src/components/dialog/brn_dialog_utils.dart @@ -4,11 +4,11 @@ import 'package:flutter/material.dart'; class BrnDialogUtils { /// dialog标题配置 static TextStyle getDialogTitleStyle(BrnDialogConfig themeData) { - return themeData?.titleTextStyle?.generateTextStyle(); + return themeData.titleTextStyle.generateTextStyle(); } /// dialog圆角配置 static double getDialogRadius(BrnDialogConfig themeData) { - return themeData?.radius; + return themeData.radius; } } diff --git a/lib/src/components/dialog/brn_enhance_operation_dialog.dart b/lib/src/components/dialog/brn_enhance_operation_dialog.dart index 2215d39a..24263dcc 100644 --- a/lib/src/components/dialog/brn_enhance_operation_dialog.dart +++ b/lib/src/components/dialog/brn_enhance_operation_dialog.dart @@ -8,16 +8,16 @@ import 'package:flutter/material.dart'; class BrnDialogConstants { /// 提示图标 - static const int ICON_ALERT = 0; + static const int iconAlert = 0; /// 警示图标 - static const int ICON_WARNING = 1; + static const int iconWarning = 1; /// 成功图标 - static const int ICON_SUCCESS = 2; + static const int iconSuccess = 2; /// 自定义图标 - static const int ICON_CUSTOM = 100; + static const int iconCustom = 100; /// icon地址列表 static const List shareItemImagePathList = [ @@ -34,40 +34,40 @@ class BrnEnhanceOperationDialog extends StatelessWidget { /// 构建环境上下文 final BuildContext context; - /// 图片类型,默认 0,[BrnDialogConstants.ICON_ALERT] + /// 图片类型,默认 0,[BrnDialogConstants.iconAlert] final int iconType; /// 自定义图标 - final Widget customIconWidget; + final Widget? customIconWidget; /// 弹框标题文案,为空则不显示标题 - final String titleText; + final String? titleText; /// 弹框辅助信息文案,为空则不显示辅助信息 - final String descText; + final String? descText; /// 主要按钮文本 final String mainButtonText; /// 次要按钮文案,为空则不显示次要按钮 - final String secondaryButtonText; + final String? secondaryButtonText; /// 主要按钮回调 - final VoidCallback onMainButtonClick; + final VoidCallback? onMainButtonClick; /// 次要按钮回调 - final VoidCallback onSecondaryButtonClick; + final VoidCallback? onSecondaryButtonClick; /// 主题配置 - BrnDialogConfig themeData; + BrnDialogConfig? themeData; BrnEnhanceOperationDialog({ - this.iconType, + this.iconType = BrnDialogConstants.iconAlert, this.customIconWidget, - this.context, + required this.context, this.titleText, this.descText, - this.mainButtonText, + this.mainButtonText = '确认', this.secondaryButtonText, this.onMainButtonClick, this.onSecondaryButtonClick, @@ -75,7 +75,7 @@ class BrnEnhanceOperationDialog extends StatelessWidget { }) { this.themeData ??= BrnDialogConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .dialogConfig .merge(this.themeData); } @@ -86,8 +86,8 @@ class BrnEnhanceOperationDialog extends StatelessWidget { type: MaterialType.transparency, child: BrnDialog( themeData: themeData, - iconImage: (iconType == BrnDialogConstants.ICON_CUSTOM) - ? customIconWidget + iconImage: (iconType == BrnDialogConstants.iconCustom) + ? customIconWidget as Image : BrunoTools.getAssetImage( BrnDialogConstants.shareItemImagePathList[iconType]), titleText: titleText, @@ -113,11 +113,11 @@ class BrnEnhanceOperationDialog extends StatelessWidget { }).then((value) { if (value == mainButtonText) { if (onMainButtonClick != null) { - onMainButtonClick(); + onMainButtonClick!(); } } else { if (onSecondaryButtonClick != null) { - onSecondaryButtonClick(); + onSecondaryButtonClick!(); } } }); @@ -125,7 +125,7 @@ class BrnEnhanceOperationDialog extends StatelessWidget { /// 构建widgets框架 List _configDialogWidgets(BuildContext context) { - List widgets = List(); + List widgets = []; //分割 widgets.add(Container( height: 16, @@ -168,9 +168,9 @@ class BrnEnhanceOperationDialog extends StatelessWidget { highlightColor: Colors.transparent, child: Center( child: Text( - secondaryButtonText, + secondaryButtonText!, style: TextStyle( - color: themeData.commonConfig.brandPrimary, + color: themeData!.commonConfig.brandPrimary, fontSize: 16, ), ), diff --git a/lib/src/components/dialog/brn_middle_input_diaolg.dart b/lib/src/components/dialog/brn_middle_input_diaolg.dart index 2416da11..ec66d2ff 100644 --- a/lib/src/components/dialog/brn_middle_input_diaolg.dart +++ b/lib/src/components/dialog/brn_middle_input_diaolg.dart @@ -6,13 +6,13 @@ import 'package:flutter/services.dart'; /// 可输入文字的弹窗。从上至下依次是 标题[title]、提示信息[message]、输入框,底部左右两个按钮,左边取消,右边确定。 class BrnMiddleInputDialog { /// 标题 - final String title; + final String? title; /// 辅助提示信息 - final String message; + final String? message; /// 输入框占位文字 - final String hintText; + final String? hintText; /// 最多可输入多少字符,默认20个 final int maxLength; @@ -24,13 +24,13 @@ class BrnMiddleInputDialog { final String confirmText; /// 点击确定时的回调,参数为输入框中的字符 - final void Function(String value) onConfirm; + final void Function(String value)? onConfirm; /// 弹窗样式。具体参见 [BrnDialogStyle] - final BrnDialogStyle dialogStyle; + final BrnDialogStyle? dialogStyle; /// 点击取消时的回调 - final VoidCallback onCancel; + final VoidCallback? onCancel; /// 点击蒙层背景,弹窗是否可关闭。默认为 true,可关闭 final bool barrierDismissible; @@ -42,16 +42,16 @@ class BrnMiddleInputDialog { final int minLines; /// 可输入的最多行数。超过 [maxLines] 指定的行数后,输入内容会变成可滑动 - final int maxLines; + final int? maxLines; /// 焦点控制 [FocusNode] - final FocusNode inputFocusNode; + final FocusNode? inputFocusNode; /// 输入控制器。如果有初始状态的填充文字,可以通过 [inputEditingController] 设置 - final TextEditingController inputEditingController; + final TextEditingController? inputEditingController; /// 输入内容格式控制器 - final List inputFormatters; + final List? inputFormatters; /// 键盘操作按钮类型,参见系统的 [TextField.textInputAction],默认为 [TextInputAction.newline] final TextInputAction textInputAction; @@ -84,11 +84,11 @@ class BrnMiddleInputDialog { } void _doShow(BuildContext context) { - String _value = inputEditingController?.text; + String _value = inputEditingController?.text ?? ""; var dialogMessageWidgets = []; - if (message != null && message.length > 0) { + if (message != null && message!.length > 0) { dialogMessageWidgets.add(Text( - message, + message!, style: cContentTextStyle, textAlign: cContentTextAlign, )); @@ -100,12 +100,13 @@ class BrnMiddleInputDialog { if (inputFormatters == null) { tmpInputFormatters = [LengthLimitingTextInputFormatter(maxLength)]; } else { - tmpInputFormatters = List() - ..addAll(inputFormatters) + tmpInputFormatters = [] + ..addAll(inputFormatters!) ..add(LengthLimitingTextInputFormatter(maxLength)); } dialogMessageWidgets.add(TextField( + maxLengthEnforcement: MaxLengthEnforcement.enforced, textInputAction: this.textInputAction, focusNode: inputFocusNode, controller: inputEditingController, @@ -114,7 +115,7 @@ class BrnMiddleInputDialog { //光标颜色 cursorColor: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, - autofocus: autoFocus ?? false, + autofocus: autoFocus, //光标圆角弧度 cursorRadius: Radius.circular(2.0), style: TextStyle( @@ -123,7 +124,6 @@ class BrnMiddleInputDialog { .getConfig() .commonConfig .colorTextBase), - maxLengthEnforced: true, onChanged: (value) { _value = value; }, @@ -161,7 +161,7 @@ class BrnMiddleInputDialog { cancel: cancelText, confirm: confirmText, title: title, - barrierDismissible: barrierDismissible ?? true, + barrierDismissible: barrierDismissible, dialogStyle: dialogStyle ?? BrnDialogStyle(), messageWidget: Padding( padding: const EdgeInsets.only(top: 12, left: 24, right: 24), @@ -170,9 +170,9 @@ class BrnMiddleInputDialog { children: dialogMessageWidgets, ), ), onConfirm: () { - if (onConfirm != null) onConfirm(_value); + if (onConfirm != null) onConfirm!(_value); }, onCancel: () { - if (onCancel != null) onCancel(); + if (onCancel != null) onCancel!(); }); } } diff --git a/lib/src/components/dialog/brn_multi_select_dialog.dart b/lib/src/components/dialog/brn_multi_select_dialog.dart index 4e00e0d6..d85ebe5c 100644 --- a/lib/src/components/dialog/brn_multi_select_dialog.dart +++ b/lib/src/components/dialog/brn_multi_select_dialog.dart @@ -36,10 +36,10 @@ class BrnMultiSelectDialog extends Dialog { final String title; /// 描述文案 - final String messageText; + final String? messageText; /// 描述widget - final Widget messageWidget; + final Widget? messageWidget; /// 选项集合 final List conditions; @@ -48,16 +48,16 @@ class BrnMultiSelectDialog extends Dialog { final String submitText; /// 点击操作按钮 - final BrnMultiSelectDialogClickSubmitCallback onSubmitClick; + final BrnMultiSelectDialogClickSubmitCallback? onSubmitClick; /// 点击选项操作 可供埋点需求用 - final BrnMultiSelectDialogOnItemClickCallback onItemClick; + final BrnMultiSelectDialogOnItemClickCallback? onItemClick; /// 操作按钮背景色 - final Color submitBgColor; + final Color? submitBgColor; /// 自定义widget - final Widget customWidget; + final Widget? customWidget; /// 是否支持滚动 默认true支持滚动 final bool isCustomFollowScroll; @@ -68,7 +68,7 @@ class BrnMultiSelectDialog extends Dialog { BrnMultiSelectDialog({ this.isClose = true, this.title = "", - this.conditions, + required this.conditions, this.messageText, this.messageWidget, this.customWidget, @@ -104,31 +104,31 @@ class MultiSelect extends StatefulWidget { final bool isClose; /// 标题 - final String title; + final String? title; /// 描述文案 - final String messageText; + final String? messageText; /// 描述widget - final Widget messageWidget; + final Widget? messageWidget; /// 选项集合 final List conditions; /// 操作按钮文案 - final String submitText; + final String? submitText; /// 点击操作按钮 - final BrnMultiSelectDialogClickSubmitCallback onSubmitClick; + final BrnMultiSelectDialogClickSubmitCallback? onSubmitClick; /// 点击选项操作 - final BrnMultiSelectDialogOnItemClickCallback onItemClick; + final BrnMultiSelectDialogOnItemClickCallback? onItemClick; /// 操作按钮背景色 - final Color submitBgColor; + final Color? submitBgColor; /// 自定义widget - final Widget customWidget; + final Widget? customWidget; /// 是否支持滚动 final bool isCustomFollowScroll; @@ -137,18 +137,18 @@ class MultiSelect extends StatefulWidget { final bool isShowOperateWidget; MultiSelect({ - this.isClose, + this.isClose = true, this.title, this.messageText, this.messageWidget, this.customWidget, - this.isCustomFollowScroll, - this.conditions, + this.isCustomFollowScroll = true, + required this.conditions, this.submitText, this.submitBgColor, this.onSubmitClick, this.onItemClick, - this.isShowOperateWidget, + this.isShowOperateWidget = true, }); @override @@ -175,7 +175,7 @@ class MultiSelectPickerWidgetState extends State { physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index) => _buildItem(context, index), - itemCount: widget.conditions?.length), + itemCount: widget.conditions.length), widget.customWidget != null ? Container( child: widget.customWidget, @@ -195,7 +195,7 @@ class MultiSelectPickerWidgetState extends State { child: ListView.builder( itemBuilder: (context, index) => _buildItem(context, index), - itemCount: widget.conditions?.length), + itemCount: widget.conditions.length), ), widget.customWidget != null ? Container( @@ -218,14 +218,14 @@ class MultiSelectPickerWidgetState extends State { submitBgColor: widget.submitBgColor, isShowOperateWidget: widget.isShowOperateWidget, onSubmit: () { - List tempList = List(); + List tempList = []; if (widget.onSubmitClick != null) { - for (int i = 0; i < widget.conditions?.length; i++) { + for (int i = 0; i < widget.conditions.length; i++) { if (widget.conditions[i].isChecked) { tempList.add(widget.conditions[i]); } } - if (widget.onSubmitClick(tempList)) Navigator.of(context).pop(); + if (widget.onSubmitClick!(tempList)) Navigator.of(context).pop(); } }, ); @@ -246,7 +246,7 @@ class MultiSelectPickerWidgetState extends State { padding: EdgeInsets.only(bottom: 8, left: 20, right: 20), child: Center( child: Text( - widget.messageText, + widget.messageText!, style: cContentTextStyle, ), ), @@ -256,59 +256,55 @@ class MultiSelectPickerWidgetState extends State { } Widget _buildItem(BuildContext context, int index) { - if (widget.conditions[index] == null) { - return Container(); - } else { - return GestureDetector( - behavior: HitTestBehavior.opaque, - onTap: () { - setState(() { - widget.conditions[index].isChecked = - !widget.conditions[index].isChecked; - }); - if (widget.onItemClick != null) { - widget.onItemClick(context, index); - } - }, - child: Column( - children: [ - Padding( - padding: EdgeInsets.fromLTRB(20, 0, 20, 0), - child: Row( - children: [ - Expanded( - child: Text(widget.conditions[index].content, - style: TextStyle( - fontWeight: widget.conditions[index].isChecked - ? FontWeight.w600 - : FontWeight.normal, - fontSize: 16, - color: widget.conditions[index].isChecked - ? BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary - : BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBase))), - Container( - alignment: Alignment.center, - height: 44, - child: widget.conditions[index].isChecked - ? BrunoTools.getAssetImageWithBandColor( - BrnAsset.iconMultiSelected) - : BrunoTools.getAssetImage(BrnAsset.iconUnSelect)), - ], - ), + return GestureDetector( + behavior: HitTestBehavior.opaque, + onTap: () { + setState(() { + widget.conditions[index].isChecked = + !widget.conditions[index].isChecked; + }); + if (widget.onItemClick != null) { + widget.onItemClick!(context, index); + } + }, + child: Column( + children: [ + Padding( + padding: EdgeInsets.fromLTRB(20, 0, 20, 0), + child: Row( + children: [ + Expanded( + child: Text(widget.conditions[index].content, + style: TextStyle( + fontWeight: widget.conditions[index].isChecked + ? FontWeight.w600 + : FontWeight.normal, + fontSize: 16, + color: widget.conditions[index].isChecked + ? BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary + : BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .colorTextBase))), + Container( + alignment: Alignment.center, + height: 44, + child: widget.conditions[index].isChecked + ? BrunoTools.getAssetImageWithBandColor( + BrnAsset.iconMultiSelected) + : BrunoTools.getAssetImage(BrnAsset.iconUnSelect)), + ], ), - index != widget.conditions.length - 1 - ? Padding( - padding: EdgeInsets.fromLTRB(20, 0, 20, 0), - child: BrnLine()) - : Container() - ], - )); - } + ), + index != widget.conditions.length - 1 + ? Padding( + padding: EdgeInsets.fromLTRB(20, 0, 20, 0), + child: BrnLine()) + : Container() + ], + )); } } diff --git a/lib/src/components/dialog/brn_scrollable_text_dialog.dart b/lib/src/components/dialog/brn_scrollable_text_dialog.dart index 61af7496..292e4a29 100644 --- a/lib/src/components/dialog/brn_scrollable_text_dialog.dart +++ b/lib/src/components/dialog/brn_scrollable_text_dialog.dart @@ -8,7 +8,7 @@ import 'package:flutter/material.dart'; class BrnScrollableTextDialog extends Dialog { /// 标题 - final String title; + final String? title; /// 是否可关闭 默认true支持关闭 final bool isClose; @@ -23,16 +23,16 @@ class BrnScrollableTextDialog extends Dialog { final double textFontSize; /// 提交按钮文字 - final String submitText; + final String? submitText; /// 操作按钮背景色 - final Color submitBgColor; + final Color? submitBgColor; /// 提交操作 - final VoidCallback onSubmitClick; + final VoidCallback? onSubmitClick; /// 富文本超链接点击回调 - final BrnHyperLinkCallback linksCallback; + final BrnHyperLinkCallback? linksCallback; /// 是否展示底部操作区域 默认true展示 final bool isShowOperateWidget; @@ -40,7 +40,7 @@ class BrnScrollableTextDialog extends Dialog { const BrnScrollableTextDialog( {this.title, this.isClose = true, - this.contentText, + required this.contentText, this.textColor = const Color(0xFF666666), this.textFontSize = 16, this.submitText, @@ -67,7 +67,7 @@ class BrnScrollableTextDialog extends Dialog { class BrnScrollableText extends StatelessWidget { /// 标题 - final String title; + final String? title; /// 是否可关闭 final bool isClose; @@ -76,37 +76,37 @@ class BrnScrollableText extends StatelessWidget { final String contentText; /// 文字颜色 - final Color textColor; + final Color? textColor; /// 文字字体 - final double textFontSize; + final double? textFontSize; /// 提交按钮文字 - final String submitText; + final String? submitText; /// 提交操作 - final VoidCallback onSubmitClick; + final VoidCallback? onSubmitClick; /// 操作按钮背景色 - final Color submitBgColor; + final Color? submitBgColor; /// 富文本超链接点击回调 - final BrnHyperLinkCallback linksCallback; + final BrnHyperLinkCallback? linksCallback; /// 是否展示底部操作区域 final bool isShowOperateWidget; const BrnScrollableText( {this.title, - this.isClose, - this.contentText, + this.isClose = true, + required this.contentText, this.textColor, this.textFontSize, this.submitText, this.onSubmitClick, this.submitBgColor, this.linksCallback, - this.isShowOperateWidget}); + this.isShowOperateWidget = true}); @override Widget build(BuildContext context) { @@ -131,8 +131,9 @@ class BrnScrollableText extends StatelessWidget { submitText: submitText, submitBgColor: submitBgColor, onSubmit: () { - onSubmitClick(); - Navigator.pop(context); + if (onSubmitClick != null) { + onSubmitClick!(); + } }, isShowOperateWidget: isShowOperateWidget, ); diff --git a/lib/src/components/dialog/brn_share_dialog.dart b/lib/src/components/dialog/brn_share_dialog.dart index 8e58eb68..8e282877 100644 --- a/lib/src/components/dialog/brn_share_dialog.dart +++ b/lib/src/components/dialog/brn_share_dialog.dart @@ -13,11 +13,11 @@ typedef BrnShareDialogItemClickCallBack(int shareChannel, int customIndex); /// 获取自定义分享item标题 /// index为自定义分享item索引 -typedef String BrnShareDialogGetCustomShareItemTitle(int index); +typedef String? BrnShareDialogGetCustomShareItemTitle(int index); /// 获取自定义分享item图标 /// index为自定义分享item索引 -typedef Widget BrnShareDialogGetCustomShareItemIcon(int index); +typedef Widget? BrnShareDialogGetCustomShareItemIcon(int index); // ignore: must_be_immutable class BrnShareDialog extends StatelessWidget { @@ -27,10 +27,10 @@ class BrnShareDialog extends StatelessWidget { final String titleText; /// 弹框辅助信息文案,为空则不显示辅助信息 - final String descText; + final String? descText; /// 文案与分享渠道图标间的分割线内嵌文案 - final String separatorText; + final String? separatorText; /// 分享渠道列表 final List shareChannels; @@ -48,23 +48,23 @@ class BrnShareDialog extends StatelessWidget { final Color separatorLineColor; /// 点击事件 - final BrnShareDialogItemClickCallBack clickCallBack; + final BrnShareDialogItemClickCallBack? clickCallBack; /// 回调获取名称 - final BrnShareDialogGetCustomShareItemTitle getCustomChannelTitle; + final BrnShareDialogGetCustomShareItemTitle? getCustomChannelTitle; /// 回调获取图片(Widget) - final BrnShareDialogGetCustomShareItemIcon getCustomChannelWidget; + final BrnShareDialogGetCustomShareItemIcon? getCustomChannelWidget; /// dialog配置 - BrnDialogConfig themeData; + BrnDialogConfig? themeData; BrnShareDialog({ - @required this.context, - this.titleText, + required this.context, + required this.titleText, this.descText, this.separatorText, - this.shareChannels, + required this.shareChannels, this.clickCallBack, this.getCustomChannelTitle, this.getCustomChannelWidget, @@ -76,7 +76,7 @@ class BrnShareDialog extends StatelessWidget { }) { this.themeData ??= BrnDialogConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: themeData!.configId) .dialogConfig .merge(themeData); } @@ -117,7 +117,9 @@ class BrnShareDialog extends StatelessWidget { if (value != null) { List info = value; if (info.length >= 2) { - clickCallBack(info[0], info[1]); + if (clickCallBack != null) { + clickCallBack!(info[0], info[1]); + } } } }); @@ -125,7 +127,7 @@ class BrnShareDialog extends StatelessWidget { /// 构建widgets框架 List _configDialogWidgets() { - List widgets = List(); + List widgets = []; widgets.add(_configDialogseparator()); //分割 widgets.add(Padding( @@ -145,7 +147,7 @@ class BrnShareDialog extends StatelessWidget { padding: EdgeInsets.only(top: 28), child: Text( titleText, - style: BrnDialogUtils.getDialogTitleStyle(themeData), + style: BrnDialogUtils.getDialogTitleStyle(themeData!), ), ), Positioned( @@ -157,7 +159,7 @@ class BrnShareDialog extends StatelessWidget { child: Container( width: 30, height: 30, - child: BrunoTools.getAssetImage(BrnAsset.ICON_PICKER_CLOSE), + child: BrunoTools.getAssetImage(BrnAsset.iconPickerClose), ), onTap: () { Navigator.of(context).pop(); @@ -184,7 +186,7 @@ class BrnShareDialog extends StatelessWidget { color: Color(0xffffffff), padding: EdgeInsets.only(left: 6, right: 6), child: Text( - (separatorText != null) ? separatorText : "你可以通过以下方式分享给客户", + separatorText ?? "你可以通过以下方式分享给客户", style: TextStyle(fontSize: 12, color: shareTextColor), ), ), @@ -195,16 +197,20 @@ class BrnShareDialog extends StatelessWidget { /// 构建分享途径部分 Widget _configDialogShareItems() { - List shareItems = List(); - String title; // 标题 - Widget image; // 图片路径 + List shareItems = []; + String? title; // 标题 + Widget? image; // 图片路径 for (int index = 0; index < shareChannels.length; index++) { title = null; image = null; - if (shareChannels[index] == BrnShareItemConstants.SHARE_CUSTOM) { + if (shareChannels[index] == BrnShareItemConstants.shareCustom) { // 获取自定义channel信息 - title = getCustomChannelTitle(index); - image = getCustomChannelWidget(index); + if (getCustomChannelTitle != null) { + title = getCustomChannelTitle!(index); + } + if (getCustomChannelTitle != null) { + image = getCustomChannelWidget!(index); + } } else { // 获取自预设channel信息 title = BrnShareItemConstants.shareItemTitleList[shareChannels[index]]; diff --git a/lib/src/components/dialog/brn_single_select.dart b/lib/src/components/dialog/brn_single_select.dart index e466f6e4..96d5726b 100644 --- a/lib/src/components/dialog/brn_single_select.dart +++ b/lib/src/components/dialog/brn_single_select.dart @@ -6,7 +6,7 @@ import 'package:bruno/src/theme/configs/brn_dialog_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; -typedef BrnSingleSelectOnSubmitCallback = Function(String data); +typedef BrnSingleSelectOnSubmitCallback = Function(String? data); typedef BrnSingleSelectOnItemClickCallback = void Function( BuildContext dialogContext, int index); @@ -25,19 +25,19 @@ class BrnSingleSelectDialog extends Dialog { final String submitText; /// 提交按钮点击回调 - final BrnSingleSelectOnSubmitCallback onSubmitClick; + final BrnSingleSelectOnSubmitCallback? onSubmitClick; /// item 点击回调 - final BrnSingleSelectOnItemClickCallback onItemClick; + final BrnSingleSelectOnItemClickCallback? onItemClick; /// 提交按钮背景颜色 - final Color submitBgColor; + final Color? submitBgColor; /// 选中的选项名称 - final String checkedItem; + final String? checkedItem; /// 单选列表底部自定义 Widget - final Widget customWidget; + final Widget? customWidget; /// 内容是否可滑动。默认为 true final bool isCustomFollowScroll; @@ -48,7 +48,7 @@ class BrnSingleSelectDialog extends Dialog { const BrnSingleSelectDialog( {this.isClose: true, this.title: "", - this.conditions, + required this.conditions, this.submitText: "提交", this.submitBgColor, this.onSubmitClick, @@ -79,26 +79,26 @@ class BrnSingleSelectDialog extends Dialog { class BrnSingleSelectDialogWidget extends StatefulWidget { final bool isClose; final String title; - final List conditions; + final List? conditions; final String submitText; - final BrnSingleSelectOnSubmitCallback onSubmitClick; - final BrnSingleSelectOnItemClickCallback onItemClick; //可供埋点需求用 - final Color submitBgColor; - String checkedItem; // 选择项目 + final BrnSingleSelectOnSubmitCallback? onSubmitClick; + final BrnSingleSelectOnItemClickCallback? onItemClick; //可供埋点需求用 + final Color? submitBgColor; + String? checkedItem; // 选择项目 - final Widget customWidget; + final Widget? customWidget; final bool isCustomFollowScroll; final bool canDismissOnConfirmClick; - BrnDialogConfig themeData; + BrnDialogConfig? themeData; BrnSingleSelectDialogWidget( - {this.isClose, - this.title, + {this.isClose = true, + this.title = "", this.conditions, - this.submitText, + this.submitText = "", this.submitBgColor, this.onSubmitClick, this.onItemClick, @@ -109,7 +109,7 @@ class BrnSingleSelectDialogWidget extends StatefulWidget { this.themeData}) { this.themeData ??= BrnDialogConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: themeData!.configId) .dialogConfig .merge(themeData); } @@ -135,7 +135,7 @@ class BrnSingleSelectDialogWidgetState color: widget.themeData?.backgroundColor, borderRadius: BorderRadius.all(Radius.circular( BrnDialogUtils.getDialogRadius( - widget.themeData))), //设置四周圆角 角度 + widget.themeData!))), //设置四周圆角 角度 ), child: Stack( children: [ @@ -148,7 +148,7 @@ class BrnSingleSelectDialogWidgetState child: Text( widget.title, style: BrnDialogUtils.getDialogTitleStyle( - widget.themeData), + widget.themeData!), ), ), Container( @@ -226,7 +226,7 @@ class BrnSingleSelectDialogWidgetState Navigator.of(context).pop(); } if (widget.onSubmitClick != null) { - widget.onSubmitClick(widget.checkedItem); + widget.onSubmitClick!(widget.checkedItem); } }, )) @@ -242,7 +242,7 @@ class BrnSingleSelectDialogWidgetState child: Padding( padding: EdgeInsets.all(15), child: BrunoTools.getAssetImage( - BrnAsset.ICON_PICKER_CLOSE), + BrnAsset.iconPickerClose), ))) : Container() ], @@ -251,7 +251,7 @@ class BrnSingleSelectDialogWidgetState } Widget _buildItem(BuildContext context, int index) { - if (widget.conditions == null || widget.conditions[index] == null) { + if (widget.conditions == null) { return Container(); } else { return Container( @@ -265,11 +265,11 @@ class BrnSingleSelectDialogWidgetState child: InkWell( onTap: () { setState(() { - for (dynamic item in widget.conditions) { - if (widget.conditions[index] == item) { + for (dynamic item in widget.conditions!) { + if (widget.conditions![index] == item) { if (widget.onItemClick != null && widget.checkedItem != item) { - widget.onItemClick(context, index); + widget.onItemClick!(context, index); } widget.checkedItem = item; break; @@ -277,14 +277,14 @@ class BrnSingleSelectDialogWidgetState } }); }, - child: Text(widget.conditions[index], + child: Text(widget.conditions![index], style: TextStyle( fontWeight: - widget.conditions[index] == widget.checkedItem + widget.conditions![index] == widget.checkedItem ? FontWeight.w600 : FontWeight.normal, fontSize: 16, - color: widget.conditions[index] == widget.checkedItem + color: widget.conditions![index] == widget.checkedItem ? BrnThemeConfigurator.instance .getConfig() .commonConfig @@ -298,24 +298,24 @@ class BrnSingleSelectDialogWidgetState child: Container( alignment: Alignment.center, height: 44, - child: widget.checkedItem == widget.conditions[index] + child: widget.checkedItem == widget.conditions![index] ? BrunoTools.getAssetImageWithBandColor( BrnAsset.iconSingleSelected) : BrunoTools.getAssetImage(BrnAsset.iconUnSelect), ), onTap: () { if (widget.onItemClick != null) { - widget.onItemClick(context, index); + widget.onItemClick!(context, index); } setState(() { - widget.checkedItem = widget.conditions[index]; + widget.checkedItem = widget.conditions![index]; }); }, ) ], ), ), - index != widget.conditions.length - 1 + index != widget.conditions!.length - 1 ? Padding( padding: EdgeInsets.fromLTRB(20, 0, 20, 0), child: BrnLine()) : Container() diff --git a/lib/src/components/empty/brn_empty_status.dart b/lib/src/components/empty/brn_empty_status.dart index bdcfd48c..2522c917 100644 --- a/lib/src/components/empty/brn_empty_status.dart +++ b/lib/src/components/empty/brn_empty_status.dart @@ -25,8 +25,8 @@ class BrnAbnormalStateUtils { /// 通过状态获取对应空页面widget /// status: 页面状态类型为[EmptyState] static Widget getEmptyWidgetByState(BuildContext context, - AbnormalState status, BrnEmptyStatusIndexedActionClickCallback action, - {Image img}) { + AbnormalState status, + {Image? img,BrnEmptyStatusIndexedActionClickCallback? action}) { if (AbnormalState.getDataFailed == status) { return BrnAbnormalStateWidget( img: img ?? BrunoTools.getAssetImage(BrnAsset.emptyState), @@ -55,13 +55,13 @@ class BrnAbnormalStateUtils { /// 操作区域按钮类型 enum OperateAreaType { /// 单按钮 - SingleButton, + singleButton, /// 双按钮 - DoubleButton, + doubleButton, /// 文本按钮 - TextButton + textButton } /// 空页面操作区域按钮的点击回调 @@ -72,22 +72,22 @@ typedef BrnEmptyStatusIndexedActionClickCallback = void Function(int index); // ignore: must_be_immutable class BrnAbnormalStateWidget extends StatelessWidget { /// 图片 - final Image img; + final Image? img; /// 标题 - final String title; + final String? title; /// 内容 - final String content; + final String? content; /// 操作区类型 final OperateAreaType operateAreaType; /// 操作区文案 - final List operateTexts; + final List? operateTexts; /// 点击事件回调 - final BrnEmptyStatusIndexedActionClickCallback action; + final BrnEmptyStatusIndexedActionClickCallback? action; /// 是否可点击页面回调配合[action]使用 /// 当为true时调用[action]回调,当为false时不做处理 @@ -96,7 +96,7 @@ class BrnAbnormalStateWidget extends StatelessWidget { /// 顶部距离走自动计算逻辑:父视图高度的8%,可自己指定高度 /// 默认为null - final double topOffset; + final double? topOffset; /// 背景色设置 /// 默认Colors.white @@ -109,13 +109,13 @@ class BrnAbnormalStateWidget extends StatelessWidget { /// 默认 false final bool isCenterVertical; - BrnAbnormalStateConfig themeData; + BrnAbnormalStateConfig? themeData; BrnAbnormalStateWidget({ this.img, this.title, this.content, - this.operateAreaType: OperateAreaType.TextButton, + this.operateAreaType: OperateAreaType.textButton, this.operateTexts, this.action, this.enablePageTap: false, @@ -127,7 +127,7 @@ class BrnAbnormalStateWidget extends StatelessWidget { }) { this.themeData ??= BrnAbnormalStateConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .abnormalStateConfig .merge(this.themeData); } @@ -136,12 +136,12 @@ class BrnAbnormalStateWidget extends StatelessWidget { Widget build(BuildContext context) { return GestureDetector( onTap: () { - if (this.enablePageTap) { - action(0); + if (this.enablePageTap && action!=null) { + action!(0); } }, child: Container( - color: bgColor ?? Colors.white, + color: bgColor, child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: isCenterVertical @@ -169,7 +169,7 @@ class BrnAbnormalStateWidget extends StatelessWidget { : EdgeInsets.only(top: topOffset ?? height * topPercent), child: img, ) - : Container(); + : SizedBox.shrink(); } ///文案区域:标题 @@ -178,11 +178,11 @@ class BrnAbnormalStateWidget extends StatelessWidget { ? Container( alignment: Alignment.center, padding: EdgeInsets.fromLTRB(60, 24, 60, 0), - child: Text(title, + child: Text(title!, textAlign: TextAlign.center, - style: themeData?.titleTextStyle?.generateTextStyle()), + style: themeData!.titleTextStyle.generateTextStyle()), ) - : Container(); + : SizedBox.shrink(); } ///文案区域:内容 @@ -191,11 +191,11 @@ class BrnAbnormalStateWidget extends StatelessWidget { ? Container( alignment: Alignment.center, padding: EdgeInsets.fromLTRB(60, 12, 60, 0), - child: Text(content, + child: Text(content!, textAlign: TextAlign.center, - style: themeData?.contentTextStyle?.generateTextStyle()), + style: themeData!.contentTextStyle.generateTextStyle()), ) - : Container(); + : SizedBox.shrink(); } ///操作区域 @@ -205,42 +205,46 @@ class BrnAbnormalStateWidget extends StatelessWidget { padding: EdgeInsets.only(top: 36), child: _buildOperateContentWidget(), ) - : Container(); + : SizedBox.shrink(); } ///操作区按钮 _buildOperateContentWidget() { - if (OperateAreaType.SingleButton == operateAreaType) { + if (OperateAreaType.singleButton == operateAreaType) { return GestureDetector( - onTap: () => action(0), + onTap: () { + if (action != null) action!(0); + }, child: Container( - constraints: BoxConstraints(minWidth: themeData.singleMinWidth), + constraints: BoxConstraints(minWidth: themeData!.singleMinWidth), padding: EdgeInsets.fromLTRB(48, 16, 48, 16), decoration: BoxDecoration( - color: themeData.commonConfig.brandPrimary, + color: themeData!.commonConfig.brandPrimary, borderRadius: - BorderRadius.all(Radius.circular(themeData?.btnRadius))), - child: Text(operateTexts[0] ?? "", + BorderRadius.all(Radius.circular(themeData!.btnRadius))), + child: Text(operateTexts![0], textAlign: TextAlign.center, - style: themeData?.singleBrnTextStyle?.generateTextStyle()), + style: themeData!.singleTextStyle.generateTextStyle()), ), ); - } else if (OperateAreaType.DoubleButton == operateAreaType) { + } else if (OperateAreaType.doubleButton == operateAreaType) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: [ GestureDetector( - onTap: () => action(0), + onTap: () { + if (action != null) action!(0); + }, child: Container( - constraints: BoxConstraints(minWidth: themeData.doubleMinWidth), + constraints: BoxConstraints(minWidth: themeData!.doubleMinWidth), padding: EdgeInsets.fromLTRB(36, 16, 36, 16), decoration: BoxDecoration( - color: themeData.commonConfig.brandPrimary.withAlpha(0x14), + color: themeData!.commonConfig.brandPrimary.withAlpha(0x14), borderRadius: - BorderRadius.all(Radius.circular(themeData?.btnRadius))), - child: Text(operateTexts[0] ?? "", + BorderRadius.all(Radius.circular(themeData!.btnRadius))), + child: Text(operateTexts![0], textAlign: TextAlign.center, - style: themeData?.doubleBrnTextStyle?.generateTextStyle()), + style: themeData!.doubleTextStyle.generateTextStyle()), ), ), Container( @@ -248,26 +252,30 @@ class BrnAbnormalStateWidget extends StatelessWidget { color: Colors.transparent, ), GestureDetector( - onTap: () => action(1), + onTap: () { + if (action != null) action!(1); + }, child: Container( - constraints: BoxConstraints(minWidth: themeData.doubleMinWidth), + constraints: BoxConstraints(minWidth: themeData!.doubleMinWidth), padding: EdgeInsets.fromLTRB(36, 16, 36, 16), decoration: BoxDecoration( - color: themeData.commonConfig.brandPrimary.withAlpha(0x14), + color: themeData!.commonConfig.brandPrimary.withAlpha(0x14), borderRadius: - BorderRadius.all(Radius.circular(themeData?.btnRadius))), - child: Text(operateTexts[1] ?? "", + BorderRadius.all(Radius.circular(themeData!.btnRadius))), + child: Text(operateTexts![1], textAlign: TextAlign.center, - style: themeData?.doubleBrnTextStyle?.generateTextStyle()), + style: themeData!.doubleTextStyle.generateTextStyle()), ), ), ], ); - } else if (OperateAreaType.TextButton == operateAreaType) { + } else if (OperateAreaType.textButton == operateAreaType) { return GestureDetector( - onTap: () => action(0), - child: Text(operateTexts[0] ?? "", - style: themeData?.operateTextStyle?.generateTextStyle())); + onTap: () { + if (action != null) action!(0); + }, + child: Text(operateTexts![0], + style: themeData!.operateTextStyle.generateTextStyle())); } return Container(); } diff --git a/lib/src/components/form/base/brn_form_item_type.dart b/lib/src/components/form/base/brn_form_item_type.dart index 1335a8a9..08e1cf60 100644 --- a/lib/src/components/form/base/brn_form_item_type.dart +++ b/lib/src/components/form/base/brn_form_item_type.dart @@ -1,59 +1,61 @@ + + class BrnPrefixIconType { - static const String TYPE_NORMAL = "type_normal"; - static const String TYPE_ADD = "type_add"; - static const String TYPE_REMOVE = "type_remove"; + static const String normal = "type_normal"; + static const String add = "type_add"; + static const String remove = "type_remove"; } /// 用于描述表单项的类型 class BrnInputItemType { /// appbar 类型 - static const String HEADER_NORMAL_TYPE = "header_normal_type"; + static const String headerNormalType = "header_normal_type"; /// 表单项类型 - static const String TEXT_INPUT_TYPE = "text_input_type"; - static const String TEXT_FORMAT_INPUT_TYPE = "text_format_input_type"; - static const String TEXT_ARRAY_INPUT_TYPE = "text_array_input_type"; - static const String TEXT_SELECT_INPUT_TYPE = "text_select_input_type"; - static const String TEXT_BLOCK_INPUT_TYPE = "text_block_input_type"; - static const String TEXT_INPUT_TITLE_SELECT_TYPE = + static const String textInputType = "text_input_type"; + static const String textFormatInputType = "text_format_input_type"; + static const String textArrayInputType = "text_array_input_type"; + static const String textSelectInputType = "text_select_input_type"; + static const String textBlockInputType = "text_block_input_type"; + static const String textInputTitleSelectType = "text_input_title_select_type"; - static const String TEXT_RANGE_INPUT_TYPE = "text_range_input_type"; - static const String TEXT_STEP_INPUT_TYPE = "text_step_input_type"; - static const String RADIO_INPUT_TYPE = "radio_input_type"; - static const String RADIO_PORTRAIT_INPUT_TYPE = "radio_column_input_type"; - static const String MULTI_CHOICE_INPUT_TYPE = "multi_choice_input_type"; - static const String MULTI_CHOICE_PORTRAIT_INPUT_TYPE = + static const String textRangeInputType = "text_range_input_type"; + static const String textStepInputType = "text_step_input_type"; + static const String radioInputType = "radio_input_type"; + static const String radioPortraitInputType = "radio_column_input_type"; + static const String multiChoiceInputType = "multi_choice_input_type"; + static const String multiChoicePortraitInputType = "multi_choice_column_input_type"; - static const String SWITCH_TYPE = "switch_type"; + static const String switchType = "switch_type"; - static const String STAR_INPUT_TYPE = "star_input_type"; - static const String PHOTO_PICKER_TYPE = "photo_picker_type"; - static const String EXPAND_GROUP_TYPE = "expand_group_type"; - static const String NORMAL_GROUP_TYPE = "normal_group_type"; - static const String TEXT_INPUT_RATIO_TYPE = "text_input_ratio_type"; + static const String starInputType = "star_input_type"; + static const String photoPickerType = "photo_picker_type"; + static const String expandGroupType = "expand_group_type"; + static const String normalGroupType = "normal_group_type"; + static const String textInputRatioType = "text_input_ratio_type"; - static const String TEXT_QUICK_SELECT_INPUT_TYPE = + static const String textQuickSelectInputType = "text_quick_select_input_type"; /// bottom类型 - static const String BOTTOM_BTN_TYPE = "bottom_btn_type"; + static const String bottomBtnType = "bottom_btn_type"; - static const String BTN_TYPE = "btn_type"; - static const String BTN_MULTI_TYPE = "btn_multi_type"; - static const String BTN_MULTI_STATE_TYPE = "btn_multi_state_type"; + static const String btnType = "btn_type"; + static const String btnMultiType = "btn_multi_type"; + static const String btnMultiStateType = "btn_multi_state_type"; - static const String LABEL_TITLE = "label_title"; - static const String LABEL_ADD = "label_add"; + static const String labelTitle = "label_title"; + static const String labelAdd = "label_add"; } class BrnInputType { - static const String TEXT = "text"; - static const String MULTI_LINE = "multiline"; - static const String NUMBER = "number"; - static const String DECIMAL = "decimal"; - static const String PHONE = "phone"; - static const String DATE = "datetime"; - static const String EMAIL = "emailAddress"; - static const String URL = "url"; - static const String PWD = "visiblePassword"; + static const String text = "text"; + static const String multiLine = "multiline"; + static const String number = "number"; + static const String decimal = "decimal"; + static const String phone = "phone"; + static const String date = "datetime"; + static const String email = "emailAddress"; + static const String url = "url"; + static const String pwd = "visiblePassword"; } diff --git a/lib/src/components/form/base/input_item_interface.dart b/lib/src/components/form/base/input_item_interface.dart index 7bfd14e5..757f960a 100644 --- a/lib/src/components/form/base/input_item_interface.dart +++ b/lib/src/components/form/base/input_item_interface.dart @@ -1,10 +1,13 @@ /// 用于model兼容回调 /// 主要用于各种点击事件 + + + typedef OnBrnFormSelectAll = void Function(int index, bool isSelect); /// 主要用于各种输入值变化 typedef OnBrnFormRadioValueChanged = void Function( - String oldStr, String newStr); + String? oldStr, String? newStr); typedef OnBrnFormSwitchChanged = void Function(bool oldValue, bool newValue); typedef OnBrnFormValueChanged = void Function(int oldValue, int newValue); typedef OnBrnFormMultiChoiceValueChanged = void Function( diff --git a/lib/src/components/form/items/general/brn_multi_choice_input_item.dart b/lib/src/components/form/items/general/brn_multi_choice_input_item.dart index 047176ef..1c632b54 100644 --- a/lib/src/components/form/items/general/brn_multi_choice_input_item.dart +++ b/lib/src/components/form/items/general/brn_multi_choice_input_item.dart @@ -1,8 +1,7 @@ -import 'package:bruno/bruno.dart'; import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; -import 'package:bruno/src/components/radio/brn_radio_core.dart'; +import 'package:bruno/src/components/radio/brn_checkbox.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:flutter/material.dart'; @@ -17,23 +16,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnMultiChoiceInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.MULTI_CHOICE_INPUT_TYPE; + final String type = BrnInputItemType.multiChoiceInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -48,51 +47,51 @@ class BrnMultiChoiceInputFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 特殊字段 - List value; + final List value; /// 内容 - List options; + final List options; /// 局部禁用list - List enableList; + final List enableList; /// 选项选中状态变化回调 - final OnBrnFormMultiChoiceValueChanged onChanged; + final OnBrnFormMultiChoiceValueChanged? onChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnMultiChoiceInputFormItem( - {Key key, + {Key? key, this.label, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: true, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = true, this.onAddTap, this.onRemoveTap, this.onTip, - this.value, - this.options, - this.enableList, + this.value = const [], + this.options = const [], + this.enableList = const [], this.onChanged, this.themeData}) - : super() { + : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -106,11 +105,10 @@ class BrnMultiChoiceInputFormItem extends StatefulWidget { class BrnMultiChoiceInputFormItemState extends State { // 标记选项的选中状态,内部变量无须初始化。初始化选中状态通过设置value字段设置 - List _selectStatus; + List _selectStatus = []; @override void initState() { - _initSpecialParams(); _initSelectedStatus(); super.initState(); } @@ -119,7 +117,7 @@ class BrnMultiChoiceInputFormItemState Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -132,7 +130,7 @@ class BrnMultiChoiceInputFormItemState ), child: Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -143,9 +141,9 @@ class BrnMultiChoiceInputFormItemState widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -160,16 +158,16 @@ class BrnMultiChoiceInputFormItemState ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); } - List getCheckboxList(List options) { - List result = List(); + List getCheckboxList(List? options) { + List result = []; if (options == null || options.isEmpty) { result.add(Container()); return result; @@ -179,7 +177,7 @@ class BrnMultiChoiceInputFormItemState final int pos = index; result.add( Container( - padding: BrnFormUtil.optionsMiddlePadding(widget.themeData), + padding: BrnFormUtil.optionsMiddlePadding(widget.themeData!), child: Row( children: [ BrnCheckbox( @@ -194,12 +192,12 @@ class BrnMultiChoiceInputFormItemState radioIndex: index, disable: getRadioEnableState(index), isSelected: - (_selectStatus != null && pos < _selectStatus.length) + (pos < _selectStatus.length) ? _selectStatus[pos] : false, onValueChangedAtIndex: (position, value) { _selectStatus[position] = value; - List oldValue = List()..addAll(widget.value); + List oldValue = []..addAll(widget.value); setState(() { widget.value.clear(); @@ -225,24 +223,23 @@ class BrnMultiChoiceInputFormItemState } TextStyle getOptionTextStyle(int index) { - TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData); + TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData!); if (index < 0 || index >= _selectStatus.length) { return result; } if (_selectStatus[index]) { - result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData); + result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData!); } if (!widget.isEdit) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit); + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit); } - if (widget.enableList != null && - widget.enableList.isNotEmpty && + if (widget.enableList.isNotEmpty && widget.enableList.length > index && !widget.enableList[index]) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, false); + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, false); } return result; @@ -253,41 +250,23 @@ class BrnMultiChoiceInputFormItemState return true; } - if (widget.enableList == null || - widget.enableList.isEmpty || - widget.enableList.length < index) { + if (widget.enableList.isEmpty || widget.enableList.length < index) { return false; } return !widget.enableList[index]; } - void _initSpecialParams() { - if (widget.value == null) { - widget.value = List(); - } - - if (widget.options == null) { - widget.options = List(); - } - - if (widget.enableList == null) { - widget.enableList = List(); - } - } - void _initSelectedStatus() { - if (widget.options != null && widget.options.isNotEmpty) { - _selectStatus = List(widget.options.length); - } else { - _selectStatus = List(); + if (widget.options.isNotEmpty) { + _selectStatus = List.filled(widget.options.length, false); } for (int index = 0; index < _selectStatus.length; ++index) { _selectStatus[index] = false; } - if (widget.value == null || widget.value.isEmpty) { + if (widget.value.isEmpty) { return; } diff --git a/lib/src/components/form/items/general/brn_multi_choice_portrait_input_item.dart b/lib/src/components/form/items/general/brn_multi_choice_portrait_input_item.dart index c3a535a5..8ed2e616 100644 --- a/lib/src/components/form/items/general/brn_multi_choice_portrait_input_item.dart +++ b/lib/src/components/form/items/general/brn_multi_choice_portrait_input_item.dart @@ -3,7 +3,6 @@ import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/components/line/brn_line.dart'; import 'package:bruno/src/components/radio/brn_checkbox.dart'; -import 'package:bruno/src/components/radio/brn_radio_core.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:flutter/material.dart'; @@ -18,23 +17,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnMultiChoicePortraitInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.MULTI_CHOICE_PORTRAIT_INPUT_TYPE; + String type = BrnInputItemType.multiChoicePortraitInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -49,51 +48,51 @@ class BrnMultiChoicePortraitInputFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 特殊字段 - List value; + final List value; /// 内容 - List options; + final List options; /// 局部禁用list - List enableList; + final List enableList; /// 选项选中状态变化回调 - final OnBrnFormMultiChoiceValueChanged onChanged; + final OnBrnFormMultiChoiceValueChanged? onChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnMultiChoicePortraitInputFormItem( - {Key key, + {Key? key, this.label, - this.title: "", - this.subTitle, + this.title = "", + this.subTitle = "", this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: false, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = false, this.onAddTap, this.onRemoveTap, this.onTip, - this.value, - this.options, - this.enableList, + this.value = const [], + this.options = const [], + this.enableList = const [], this.onChanged, this.themeData}) - : super() { + : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -107,11 +106,10 @@ class BrnMultiChoicePortraitInputFormItem extends StatefulWidget { class BrnMultiChoicePortraitInputFormItemState extends State { // 标记选项的选中状态,内部变量无须初始化。初始化选中状态通过设置value字段设置 - List _selectStatus; + List _selectStatus = []; @override void initState() { - _initSpecialParams(); _initSelectedStatus(); super.initState(); } @@ -120,7 +118,7 @@ class BrnMultiChoicePortraitInputFormItemState Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -133,7 +131,7 @@ class BrnMultiChoicePortraitInputFormItemState children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -144,9 +142,9 @@ class BrnMultiChoicePortraitInputFormItemState widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -155,9 +153,9 @@ class BrnMultiChoicePortraitInputFormItemState ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData), + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!), Container( padding: EdgeInsets.only(left: 20, top: 14), @@ -170,8 +168,8 @@ class BrnMultiChoicePortraitInputFormItemState ); } - List getCheckboxList(List options) { - List result = List(); + List getCheckboxList(List? options) { + List result = []; if (options == null || options.isEmpty) { result.add(Container()); return result; @@ -190,12 +188,12 @@ class BrnMultiChoicePortraitInputFormItemState mainAxisSize: MainAxisSize.max, radioIndex: index, disable: getRadioEnableState(index), - isSelected: (_selectStatus != null && index < _selectStatus.length) + isSelected: (index < _selectStatus.length) ? _selectStatus[index] : false, onValueChangedAtIndex: (position, value) { _selectStatus[position] = value; - List oldValue = List()..addAll(widget.value); + List oldValue = []..addAll(widget.value); setState(() { widget.value.clear(); @@ -219,69 +217,50 @@ class BrnMultiChoicePortraitInputFormItemState } TextStyle getOptionTextStyle(int index) { - TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData); + TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData!); if (index < 0 || index >= _selectStatus.length) { return result; } if (_selectStatus[index]) { - result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData); + result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData!); } - if (widget.isEdit != null && !widget.isEdit) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit); + if (!widget.isEdit) { + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit); } - if (widget.enableList != null && - widget.enableList.isNotEmpty && + if (widget.enableList.isNotEmpty && widget.enableList.length > index && !widget.enableList[index]) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, false); + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, false); } return result; } bool getRadioEnableState(int index) { - if (widget.isEdit != null && !widget.isEdit) { + if (!widget.isEdit) { return true; } - if (widget.enableList == null || - widget.enableList.isEmpty || - widget.enableList.length < index) { + if (widget.enableList.isEmpty || widget.enableList.length < index) { return false; } return !widget.enableList[index]; } - void _initSpecialParams() { - if (widget.value == null) { - widget.value = List(); - } - - if (widget.options == null) { - widget.options = List(); - } - - if (widget.enableList == null) { - widget.enableList = List(); - } - } - void _initSelectedStatus() { - if (widget.options != null && widget.options.isNotEmpty) { - _selectStatus = List(widget.options.length); - } else { - _selectStatus = List(); + if (widget.options.isNotEmpty) { + _selectStatus = List.filled(widget.options.length, false); } for (int index = 0; index < _selectStatus.length; ++index) { _selectStatus[index] = false; } - if (widget.value == null || widget.value.isEmpty) { + if (widget.value.isEmpty) { return; } diff --git a/lib/src/components/form/items/general/brn_quick_select_input_item.dart b/lib/src/components/form/items/general/brn_quick_select_input_item.dart index beb94a87..dd594699 100644 --- a/lib/src/components/form/items/general/brn_quick_select_input_item.dart +++ b/lib/src/components/form/items/general/brn_quick_select_input_item.dart @@ -1,8 +1,10 @@ + + import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -17,23 +19,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnTextQuickSelectFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_QUICK_SELECT_INPUT_TYPE; + String type = BrnInputItemType.textQuickSelectInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -48,49 +50,49 @@ class BrnTextQuickSelectFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 点击录入区回调 - final VoidCallback onTap; + final VoidCallback? onTap; - final ValueChanged onBtnSelectChanged; + final ValueChanged? onBtnSelectChanged; /// 录入项 hint 提示 final String hint; /// 录入项 值 - String value; + String? value; /// 快捷操作按钮选项文案列表 - List btnsTxt; + List? btnsTxt; /// 快捷按钮区的初始选中状态,可不传,则内部自动生成并维护 - List selectBtnList; + List? selectBtnList; /// 快捷按钮区的是否可用状态,可不传,内部生成并维护 - List enableBtnList; + List? enableBtnList; /// 用户自定义快捷按钮视图 - Widget btns; + Widget? btns; /// 快捷按钮较多时是否可滑动,默认为 fasle,不可滑动 final bool isBtnsScroll; - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnTextQuickSelectFormItem( - {Key key, + {Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -110,7 +112,7 @@ class BrnTextQuickSelectFormItem extends StatefulWidget { : super(key: key) { themeData ??= BrnFormItemConfig(); themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: themeData!.configId) .formItemConfig .merge(themeData); } @@ -127,7 +129,7 @@ class BrnTextQuickSelectFormItemState Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -139,7 +141,7 @@ class BrnTextQuickSelectFormItemState children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -154,11 +156,11 @@ class BrnTextQuickSelectFormItemState // 主标题 BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), // 问号提示 BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -172,7 +174,7 @@ class BrnTextQuickSelectFormItemState } if (widget.onTap != null) { - widget.onTap(); + widget.onTap!(); } }, child: Row( @@ -191,7 +193,7 @@ class BrnTextQuickSelectFormItemState ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), /// 快捷按钮区 Container( @@ -208,24 +210,24 @@ class BrnTextQuickSelectFormItemState )), /// 错误提示 - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); } Widget buildText() { - if (widget.value != null && widget.value.isNotEmpty) { + if (widget.value != null && widget.value!.isNotEmpty) { return Text( - widget.value, + widget.value!, textAlign: TextAlign.end, - style: BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit), + style: BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit), ); } else { return Text( widget.hint, textAlign: TextAlign.end, - style: BrnFormUtil.getHintTextStyle(widget.themeData), + style: BrnFormUtil.getHintTextStyle(widget.themeData!), ); } } @@ -233,23 +235,23 @@ class BrnTextQuickSelectFormItemState // ignore: must_be_immutable class QuickButtonsWidget extends StatefulWidget { - List btnsTxt; - List selectBtnList; - List enableBtnList; - Widget btns; - bool isBtnsScroll; + List? btnsTxt; + List? selectBtnList; + List? enableBtnList; + Widget? btns; + bool? isBtnsScroll; bool isEdit; - ValueChanged onBtnSelectChanged; + ValueChanged? onBtnSelectChanged; QuickButtonsWidget({ - Key key, + Key? key, this.btnsTxt, this.selectBtnList, this.enableBtnList, this.btns, this.isBtnsScroll, - this.isEdit: true, + this.isEdit = true, this.onBtnSelectChanged, }); @@ -287,16 +289,16 @@ class QuickButtonsState extends State { } if (widget.btnsTxt == null) { - widget.btnsTxt = List(); + widget.btnsTxt = []; } if (widget.selectBtnList == null) { _useInnerStatus = true; - widget.selectBtnList = List.filled(widget.btnsTxt.length, false); + widget.selectBtnList = List.filled(widget.btnsTxt!.length, false); } if (widget.enableBtnList == null) { - widget.enableBtnList = List.filled(widget.btnsTxt.length, true); + widget.enableBtnList = List.filled(widget.btnsTxt!.length, true); } } @@ -306,9 +308,9 @@ class QuickButtonsState extends State { } if (widget.btns != null) { - return widget.btns; + return widget.btns!; } else if (widget.btnsTxt != null) { - if (widget.isBtnsScroll) { + if (widget.isBtnsScroll!) { return ListView( scrollDirection: Axis.horizontal, children: getBtnsByText(), @@ -320,20 +322,15 @@ class QuickButtonsState extends State { ); } } else { - return Container(); + return SizedBox.shrink(); } } List getBtnsByText() { - List result = List(); - - for (int index = 0; index < widget.btnsTxt.length; ++index) { - String str = widget.btnsTxt[index]; - - if (str == null) { - continue; - } + List result = []; + for (int index = 0; index < widget.btnsTxt!.length; ++index) { + String? str = widget.btnsTxt![index]; result.add(Container( padding: EdgeInsets.fromLTRB(6, 0, 6, 0), child: FlatButton( @@ -344,22 +341,22 @@ class QuickButtonsState extends State { child: Text( str, style: TextStyle( - fontSize: BrnFont.FONT_12, + fontSize: BrnFonts.f12, ), ), onPressed: () { if (!widget.isEdit || (widget.enableBtnList != null && - !widget.enableBtnList[index])) { + !widget.enableBtnList![index])) { return; } if (widget.onBtnSelectChanged != null) { - widget.onBtnSelectChanged(index); + widget.onBtnSelectChanged!(index); } if (_useInnerStatus) { // 如果是内部维护的状态,需要改变按钮的状态 - widget.selectBtnList[index] = - widget.selectBtnList[index] ? false : true; + widget.selectBtnList![index] = + widget.selectBtnList![index] ? false : true; } setState(() {}); /* @@ -384,20 +381,20 @@ class QuickButtonsState extends State { } Color getButtonColor(int index) { - if (widget.btnsTxt != null && widget.btnsTxt.isEmpty) { + if (widget.btnsTxt != null && widget.btnsTxt!.isEmpty) { return Color(0xFFF8F8F8); } /// 这个按钮不可点击 if (widget.enableBtnList != null && - index < widget.enableBtnList.length && - !widget.enableBtnList[index]) { + index < widget.enableBtnList!.length && + !widget.enableBtnList![index]) { return Color(0xFFF8F8F8); } if (widget.selectBtnList != null && - index < widget.selectBtnList.length && - widget.selectBtnList[index]) { + index < widget.selectBtnList!.length && + widget.selectBtnList![index]) { return Color(0x1F0984F9); } else { return Color(0xFFF8F8F8); @@ -405,25 +402,25 @@ class QuickButtonsState extends State { } Color getBtnTextColor(int index) { - if (widget.btnsTxt != null && widget.btnsTxt.isEmpty) { + if (widget.btnsTxt != null && widget.btnsTxt!.isEmpty) { return Color(0xFF222222); } /// 这个按钮不可点击 if (widget.enableBtnList != null && - index < widget.enableBtnList.length && - !widget.enableBtnList[index]) { + index < widget.enableBtnList!.length && + !widget.enableBtnList![index]) { return Color(0xFF999999); } if (widget.selectBtnList == null || - widget.selectBtnList.length != widget.btnsTxt.length) { + widget.selectBtnList!.length != widget.btnsTxt!.length) { return Color(0xFF222222); } if (widget.selectBtnList != null && - index < widget.selectBtnList.length && - widget.selectBtnList[index]) { + index < widget.selectBtnList!.length && + widget.selectBtnList![index]) { return Color(0xFF0984F9); } else { return Color(0xFF222222); diff --git a/lib/src/components/form/items/general/brn_radio_input_item.dart b/lib/src/components/form/items/general/brn_radio_input_item.dart index de7bdffc..b13c7eba 100644 --- a/lib/src/components/form/items/general/brn_radio_input_item.dart +++ b/lib/src/components/form/items/general/brn_radio_input_item.dart @@ -1,9 +1,11 @@ + + import 'dart:math'; -import 'package:bruno/bruno.dart'; import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; +import 'package:bruno/src/components/radio/brn_radio_button.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:flutter/material.dart'; @@ -15,25 +17,26 @@ import 'package:flutter/widgets.dart'; /// 包括"标题"、"副标题"、"错误信息提示"、"必填项提示"、"添加/删除按钮"、"消息提示"、 /// "单选项"等元素 /// -// ignore: must_be_immutable2 + +// ignore: must_be_immutable class BrnRadioInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.RADIO_INPUT_TYPE; + final String type = BrnInputItemType.radioInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项,默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -48,46 +51,46 @@ class BrnRadioInputFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 录入项 值 - String value; + String? value; /// 选项 - List options; + List? options; /// 局部禁用list - List enableList; + List? enableList; /// 选项选中状态变化回调 - final OnBrnFormRadioValueChanged onChanged; + final OnBrnFormRadioValueChanged? onChanged; /// 标题显示的最大行数,默认值 1 - final int titleMaxLines; + final int? titleMaxLines; /// 左边标题部分/右边选项部分的宽度比例。例如 1/2 显示就传 0.5。 /// 右边选项部分的显示宽度 = min(选项部分的实际宽度, 选项部分的比例计算宽度) - double layoutRatio; + double? layoutRatio; /// 是否自动布局 - bool _isAutoLayout; + bool? _isAutoLayout; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnRadioInputFormItem({ - Key key, + Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -103,19 +106,19 @@ class BrnRadioInputFormItem extends StatefulWidget { }) : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); this._isAutoLayout = false; } BrnRadioInputFormItem.autoLayout({ - Key key, + Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -133,7 +136,7 @@ class BrnRadioInputFormItem extends StatefulWidget { this._isAutoLayout = true; this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -146,13 +149,13 @@ class BrnRadioInputFormItem extends StatefulWidget { class BrnRadioInputFormItemState extends State { double _kRadioTitleLeftPadding = 6; - double _kRadionIconWidth = 16; + double _kRadioIconWidth = 16; @override Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -160,10 +163,10 @@ class BrnRadioInputFormItemState extends State { ? _buildAutoLayoutTitleWidget(context) : _buildTitleWidget(context), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), // 错误提示 - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -172,7 +175,7 @@ class BrnRadioInputFormItemState extends State { double _getTitleMaxWidth(BuildContext context, BoxConstraints constraints) { // 计算表单右边部分的宽度 double contentRatio = BrnFormUtil.getAutoLayoutContentRatio( - tipLabelHidden: widget.tipLabel == null || widget.tipLabel.isEmpty, + tipLabelHidden: widget.tipLabel == null || widget.tipLabel!.isEmpty, layoutRatio: widget.layoutRatio); double ratioWidth = constraints.maxWidth * contentRatio; double maxWidth = min(ratioWidth, _calculateTextWidth(context)); @@ -189,7 +192,7 @@ class BrnRadioInputFormItemState extends State { Flexible( child: Container( padding: BrnFormUtil.titleEdgeInsets( - widget.prefixIconType, widget.isRequire, widget.themeData), + widget.prefixIconType, widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -224,7 +227,7 @@ class BrnRadioInputFormItemState extends State { child: GestureDetector( onTap: () { if (widget.onTip != null) { - widget.onTip(); + widget.onTip!(); } }, child: Row( @@ -241,7 +244,7 @@ class BrnRadioInputFormItemState extends State { child: Text( widget.tipLabel ?? "", overflow: TextOverflow.ellipsis, - style: BrnFormUtil.getTipsTextStyle(widget.themeData), + style: BrnFormUtil.getTipsTextStyle(widget.themeData!), ), ), ], @@ -260,22 +263,14 @@ class BrnRadioInputFormItemState extends State { /// 计算Text所占宽度 double _calculateTextWidth(BuildContext context) { - List options; - if (widget.options.isNotEmpty ?? false) { - // 模型里边的数据 - options = widget.options; - } else if (widget.options.isNotEmpty ?? false) { - // widget 里边的数据 - options = widget.options; - } - + List? options = widget.options; // 计算所有备选文案的文字长度 double totalTextWidth = 0; - if (options.isNotEmpty ?? false) { + if (options != null && options.isNotEmpty) { int idx = -1; - for (String item in options) { + for (String? item in options) { idx += 1; - TextStyle optionStyle = getOptionTextStyle(item, idx); + TextStyle? optionStyle = getOptionTextStyle(item, idx); TextPainter painter = TextPainter( locale: Localizations.localeOf(context), textAlign: TextAlign.start, @@ -286,9 +281,9 @@ class BrnRadioInputFormItemState extends State { // 6 是备选文案和单选按钮之间的间距 // 16 是 radio 按钮的宽度 double optionWidth = painter.width + - BrnFormUtil.optionsMiddlePadding(widget.themeData).left + + BrnFormUtil.optionsMiddlePadding(widget.themeData!)!.left + _kRadioTitleLeftPadding + - _kRadionIconWidth; + _kRadioIconWidth; totalTextWidth += optionWidth; } } @@ -296,12 +291,12 @@ class BrnRadioInputFormItemState extends State { } Widget _buildTitleTextWidget() { - return Text(widget.title ?? "", + return Text(widget.title , overflow: widget.titleMaxLines == null ? TextOverflow.clip : TextOverflow.ellipsis, maxLines: widget.titleMaxLines, - style: BrnFormUtil.getTitleTextStyle(widget.themeData)); + style: BrnFormUtil.getTitleTextStyle(widget.themeData!)); } Row _buildTitleWidget(BuildContext context) { @@ -314,7 +309,7 @@ class BrnRadioInputFormItemState extends State { ), child: Container( padding: BrnFormUtil.titleEdgeInsets( - widget.prefixIconType, widget.isRequire, widget.themeData), + widget.prefixIconType, widget.isRequire, widget.themeData!), child: Row( children: [ // 添加/删除图标 @@ -345,9 +340,9 @@ class BrnRadioInputFormItemState extends State { ); } - List getRadioList(List options) { - List result = List(); - String option; + List getRadioList(List? options) { + List result = []; + String? option; if (options == null || options.isEmpty) { result.add(Container()); return result; @@ -358,7 +353,7 @@ class BrnRadioInputFormItemState extends State { result.add( Container( - padding: BrnFormUtil.optionsMiddlePadding(widget.themeData), + padding: BrnFormUtil.optionsMiddlePadding(widget.themeData!), child: Row( children: [ BrnRadioButton( @@ -371,13 +366,13 @@ class BrnRadioInputFormItemState extends State { )), disable: getRadioEnableState(index), radioIndex: index, - isSelected: index == widget.options.indexOf(widget.value), + isSelected: index == widget.options!.indexOf(widget.value ?? ''), onValueChangedAtIndex: (int position, bool selected) { if (getRadioEnableState(position)) { return; } - String oldValue = widget.value; + String? oldValue = widget.value; widget.value = options[index]; BrnFormUtil.notifyRadioStatusChanged( widget.onChanged, context, oldValue, widget.value); @@ -393,25 +388,25 @@ class BrnRadioInputFormItemState extends State { return result; } - TextStyle getOptionTextStyle(String opt, int index) { - TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData); + TextStyle getOptionTextStyle(String? opt, int index) { + TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData!); if (opt == null) { return result; } if (opt == widget.value) { - result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData); + result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData!); } if (!widget.isEdit) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit); + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit); } if (widget.enableList != null && - widget.enableList.isNotEmpty && - widget.enableList.length > index && - !widget.enableList[index]) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, false); + widget.enableList!.isNotEmpty && + widget.enableList!.length > index && + !widget.enableList![index]) { + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, false); } return result; @@ -423,11 +418,11 @@ class BrnRadioInputFormItemState extends State { } if (widget.enableList == null || - widget.enableList.isEmpty || - widget.enableList.length < index) { + widget.enableList!.isEmpty || + widget.enableList!.length < index) { return false; } - return !widget.enableList[index]; + return !widget.enableList![index]; } } diff --git a/lib/src/components/form/items/general/brn_radio_portrait_input_item.dart b/lib/src/components/form/items/general/brn_radio_portrait_input_item.dart index 7d9f2ecb..3a446f72 100644 --- a/lib/src/components/form/items/general/brn_radio_portrait_input_item.dart +++ b/lib/src/components/form/items/general/brn_radio_portrait_input_item.dart @@ -1,9 +1,10 @@ + + import 'package:bruno/bruno.dart'; import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/components/line/brn_line.dart'; -import 'package:bruno/src/components/radio/brn_radio_core.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -17,23 +18,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnRadioPortraitInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.RADIO_INPUT_TYPE; + String type = BrnInputItemType.radioInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -48,36 +49,36 @@ class BrnRadioPortraitInputFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 录入项 值 - String value; + String? value; /// 选项 - List options; + List? options; /// 局部禁用list - List enableList; + List? enableList; /// 选项选中状态变化回调 - final OnBrnFormRadioValueChanged onChanged; + final OnBrnFormRadioValueChanged? onChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnRadioPortraitInputFormItem( - {Key key, + {Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -92,7 +93,7 @@ class BrnRadioPortraitInputFormItem extends StatefulWidget { : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -109,7 +110,7 @@ class BrnRadioPortraitInputFormItemState Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -122,7 +123,7 @@ class BrnRadioPortraitInputFormItemState children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -133,9 +134,9 @@ class BrnRadioPortraitInputFormItemState widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -144,9 +145,9 @@ class BrnRadioPortraitInputFormItemState ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData), + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!), Container( padding: EdgeInsets.only(left: 20, top: 14), @@ -159,9 +160,9 @@ class BrnRadioPortraitInputFormItemState ); } - List getRadioList(List options) { - List result = List(); - String option; + List getRadioList(List? options) { + List result = []; + String? option; if (options == null || options.isEmpty) { result.add(Container()); return result; @@ -176,7 +177,7 @@ class BrnRadioPortraitInputFormItemState padding: EdgeInsets.only(top: 14, bottom: 14), child: BrnRadioButton( child: Text( - option, + option!, style: getOptionTextStyle(option, index), ), childOnRight: false, @@ -184,12 +185,12 @@ class BrnRadioPortraitInputFormItemState mainAxisSize: MainAxisSize.max, disable: getRadioEnableState(index), radioIndex: index, - isSelected: index == widget.options.indexOf(widget.value), + isSelected: index == widget.options!.indexOf(widget.value ?? ''), onValueChangedAtIndex: (int position, bool isSelected) { if (getRadioEnableState(position)) { return; } - String oldValue = widget.value; + String? oldValue = widget.value; widget.value = options[position]; BrnFormUtil.notifyRadioStatusChanged( widget.onChanged, context, oldValue, widget.value); @@ -205,25 +206,25 @@ class BrnRadioPortraitInputFormItemState return result; } - TextStyle getOptionTextStyle(String opt, int index) { - TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData); - if (opt == null /*|| widget.value == null*/) { + TextStyle getOptionTextStyle(String? opt, int index) { + TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData!); + if (opt == null) { return result; } if (opt == widget.value) { - result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData); + result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData!); } - if (widget.isEdit != null && !widget.isEdit) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit); + if (!widget.isEdit) { + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit); } if (widget.enableList != null && - widget.enableList.isNotEmpty && - widget.enableList.length > index && - !widget.enableList[index]) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, false); + widget.enableList!.isNotEmpty && + widget.enableList!.length > index && + !widget.enableList![index]) { + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, false); } return result; @@ -235,11 +236,11 @@ class BrnRadioPortraitInputFormItemState } if (widget.enableList == null || - widget.enableList.isEmpty || - widget.enableList.length < index) { + widget.enableList!.isEmpty || + widget.enableList!.length < index) { return false; } - return !widget.enableList[index]; + return !widget.enableList![index]; } } diff --git a/lib/src/components/form/items/general/brn_range_input_item.dart b/lib/src/components/form/items/general/brn_range_input_item.dart index 8f6eb958..00d4d1ea 100644 --- a/lib/src/components/form/items/general/brn_range_input_item.dart +++ b/lib/src/components/form/items/general/brn_range_input_item.dart @@ -1,12 +1,12 @@ + + import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; -import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; /// /// 范围输入型录入项 @@ -14,25 +14,26 @@ import 'package:flutter/widgets.dart'; /// 包括"标题"、"副标题"、"错误信息提示"、"必填项提示"、"添加/删除按钮"、"消息提示"、 /// "输入框"等元素 /// +// ignore: must_be_immutable class BrnRangeInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_RANGE_INPUT_TYPE; + String type = BrnInputItemType.textRangeInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -52,13 +53,13 @@ class BrnRangeInputFormItem extends StatefulWidget { final bool isPrefixIconEnabled; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 最小值提示语 final String hintMin; @@ -67,41 +68,41 @@ class BrnRangeInputFormItem extends StatefulWidget { final String hintMax; /// 最小值单位 - final String minUnit; + final String? minUnit; /// 最大值单位 - final String maxUnit; + final String? maxUnit; /// 最小值输入框最大字符数 - final int leftMaxCount; + final int? leftMaxCount; /// 最大值输入框最大字符数 - final int rightMaxCount; + final int? rightMaxCount; /// 输入内容类型,参见[BrnInputType] - final String inputType; + final String? inputType; - final TextEditingController minController; - final TextEditingController maxController; - List minInputFormatters; - List maxInputFormatters; + final TextEditingController? minController; + final TextEditingController? maxController; + List? minInputFormatters; + List? maxInputFormatters; /// 最小值输入回调 - final ValueChanged onMinChanged; + final ValueChanged? onMinChanged; /// 最大值输入回调 - final ValueChanged onMaxChanged; + final ValueChanged? onMaxChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnRangeInputFormItem( - {Key key, + {Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -109,8 +110,8 @@ class BrnRangeInputFormItem extends StatefulWidget { this.onAddTap, this.onRemoveTap, this.onTip, - this.hintMin: "请输入", - this.hintMax: "请输入", + this.hintMin: '最小', + this.hintMax: '最大', this.minUnit, this.maxUnit, this.leftMaxCount, @@ -126,7 +127,7 @@ class BrnRangeInputFormItem extends StatefulWidget { : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -138,15 +139,13 @@ class BrnRangeInputFormItem extends StatefulWidget { } class BrnRangeInputFormItemState extends State { - TextEditingController _minController; - TextEditingController _maxController; - - BrnFormItemConfig config; + late TextEditingController _minController; + late TextEditingController _maxController; + late BrnFormItemConfig config; @override void initState() { config = BrnThemeConfigurator.instance.getConfig().formItemConfig; - _minController = widget.minController ?? TextEditingController(); _maxController = widget.maxController ?? TextEditingController(); @@ -157,7 +156,7 @@ class BrnRangeInputFormItemState extends State { Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -170,7 +169,7 @@ class BrnRangeInputFormItemState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -181,9 +180,9 @@ class BrnRangeInputFormItemState extends State { widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -202,12 +201,12 @@ class BrnRangeInputFormItemState extends State { maxLines: 1, maxLength: widget.leftMaxCount, style: BrnFormUtil.getIsEditTextStyle( - widget.themeData, widget.isEdit), + widget.themeData!, widget.isEdit), decoration: InputDecoration( border: InputBorder.none, hintStyle: - BrnFormUtil.getHintTextStyle(widget.themeData), - hintText: widget.hintMin ?? '最小', + BrnFormUtil.getHintTextStyle(widget.themeData!), + hintText: widget.hintMin, counterText: "", contentPadding: EdgeInsets.all(0), isDense: true, @@ -233,7 +232,7 @@ class BrnRangeInputFormItemState extends State { widget.minUnit ?? "", style: TextStyle( color: Color(0xFF101010), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), )), Container( @@ -242,7 +241,7 @@ class BrnRangeInputFormItemState extends State { "—", style: TextStyle( color: Color(0xFF101010), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), )), Container( @@ -257,12 +256,12 @@ class BrnRangeInputFormItemState extends State { maxLines: 1, maxLength: widget.rightMaxCount, style: BrnFormUtil.getIsEditTextStyle( - widget.themeData, widget.isEdit), + widget.themeData!, widget.isEdit), decoration: InputDecoration( border: InputBorder.none, hintStyle: - BrnFormUtil.getHintTextStyle(widget.themeData), - hintText: widget.hintMax ?? '最大', + BrnFormUtil.getHintTextStyle(widget.themeData!), + hintText: widget.hintMax, counterText: "", contentPadding: EdgeInsets.all(0), isDense: true, @@ -288,7 +287,7 @@ class BrnRangeInputFormItemState extends State { widget.maxUnit ?? "", style: TextStyle( color: Color(0xFF101010), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), )), ], @@ -298,9 +297,9 @@ class BrnRangeInputFormItemState extends State { ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -310,11 +309,7 @@ class BrnRangeInputFormItemState extends State { void dispose() { super.dispose(); // 如果controller由外部创建不需要销毁, 若由内部创建则需要销毁 - if (widget.minController == null) { - _minController?.dispose(); - } - if (widget.maxController == null) { - _maxController?.dispose(); - } + _minController.dispose(); + _maxController.dispose(); } } diff --git a/lib/src/components/form/items/general/brn_ratio_input_item.dart b/lib/src/components/form/items/general/brn_ratio_input_item.dart index 266f70aa..2a5c1293 100644 --- a/lib/src/components/form/items/general/brn_ratio_input_item.dart +++ b/lib/src/components/form/items/general/brn_ratio_input_item.dart @@ -1,5 +1,6 @@ + + import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; -import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; @@ -16,23 +17,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnRatioInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_INPUT_RATIO_TYPE; + String type = BrnInputItemType.textInputRatioType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -52,35 +53,35 @@ class BrnRatioInputFormItem extends StatefulWidget { final bool isPrefixIconEnabled; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; ///内容 final String hint; /// 输入内容类型 - final String inputType; - final TextEditingController controller; - List inputFormatters; + final String? inputType; + final TextEditingController? controller; + List? inputFormatters; /// 输入回调 - final ValueChanged onChanged; + final ValueChanged? onChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnRatioInputFormItem( - {Key key, + {Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -97,7 +98,7 @@ class BrnRatioInputFormItem extends StatefulWidget { : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -109,12 +110,11 @@ class BrnRatioInputFormItem extends StatefulWidget { } class BrnRatioInputFormItemState extends State { - TextEditingController _controller; + late TextEditingController _controller; @override void initState() { _controller = widget.controller ?? TextEditingController(); - super.initState(); } @@ -122,7 +122,7 @@ class BrnRatioInputFormItemState extends State { Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -135,7 +135,7 @@ class BrnRatioInputFormItemState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -146,9 +146,9 @@ class BrnRatioInputFormItemState extends State { widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -159,7 +159,7 @@ class BrnRatioInputFormItemState extends State { child: Text( "1 : ", style: - BrnFormUtil.getTitleTextStyle(widget.themeData), + BrnFormUtil.getTitleTextStyle(widget.themeData!), )), Container( width: 60, @@ -169,13 +169,13 @@ class BrnRatioInputFormItemState extends State { enabled: widget.isEdit, maxLines: 1, style: BrnFormUtil.getIsEditTextStyle( - widget.themeData, widget.isEdit), + widget.themeData!, widget.isEdit), inputFormatters: widget.inputFormatters, decoration: InputDecoration( border: InputBorder.none, hintStyle: - BrnFormUtil.getHintTextStyle(widget.themeData), - hintText: widget.hint ?? '请输入', + BrnFormUtil.getHintTextStyle(widget.themeData!), + hintText: widget.hint, counterText: "", contentPadding: EdgeInsets.all(0), isDense: true, @@ -201,9 +201,9 @@ class BrnRatioInputFormItemState extends State { ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -213,8 +213,6 @@ class BrnRatioInputFormItemState extends State { void dispose() { super.dispose(); // 如果controller由外部创建不需要销毁, 若由内部创建则需要销毁 - if (widget.controller == null) { - _controller?.dispose(); - } + _controller.dispose(); } } diff --git a/lib/src/components/form/items/general/brn_star_input_item.dart b/lib/src/components/form/items/general/brn_star_input_item.dart index 6b15bf7d..b19cf5ab 100644 --- a/lib/src/components/form/items/general/brn_star_input_item.dart +++ b/lib/src/components/form/items/general/brn_star_input_item.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; @@ -17,23 +19,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnStarsFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.STAR_INPUT_TYPE; + String type = BrnInputItemType.starInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -48,13 +50,13 @@ class BrnStarsFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 特有字段 int value; @@ -63,18 +65,18 @@ class BrnStarsFormItem extends StatefulWidget { final int sumStar; /// 星值数量变化回调 - final OnBrnFormValueChanged onChanged; + final OnBrnFormValueChanged? onChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnStarsFormItem( - {Key key, + {Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -85,10 +87,10 @@ class BrnStarsFormItem extends StatefulWidget { this.value: 0, this.onChanged, this.themeData}) - : super() { + : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -100,13 +102,13 @@ class BrnStarsFormItem extends StatefulWidget { } class BrnStarsFormItemState extends State { - List _result = List(); + List _result = []; @override Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -115,7 +117,7 @@ class BrnStarsFormItemState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: ConstrainedBox( constraints: BoxConstraints( maxHeight: 25, @@ -130,9 +132,9 @@ class BrnStarsFormItemState extends State { widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ))), Row( @@ -143,9 +145,9 @@ class BrnStarsFormItemState extends State { ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -182,22 +184,18 @@ class BrnStarsFormItemState extends State { } bool isEnable() { - if (widget.isEdit == null) { - return true; - } - return widget.isEdit; } Image getStar(int index, int selectCount, int sum) { if (selectCount <= 0) { - return BrunoTools.getAssetImage(BrnAsset.ICON_STAR_UNSELECT); + return BrunoTools.getAssetImage(BrnAsset.iconStarUnSelect); } if (index < selectCount) { - return BrunoTools.getAssetImage(BrnAsset.ICON_STAR_SELECT); + return BrunoTools.getAssetImage(BrnAsset.iconStarSelect); } - return BrunoTools.getAssetImage(BrnAsset.ICON_STAR_UNSELECT); + return BrunoTools.getAssetImage(BrnAsset.iconStarUnSelect); } } diff --git a/lib/src/components/form/items/general/brn_step_input_item.dart b/lib/src/components/form/items/general/brn_step_input_item.dart index 8af51c31..f6c48048 100644 --- a/lib/src/components/form/items/general/brn_step_input_item.dart +++ b/lib/src/components/form/items/general/brn_step_input_item.dart @@ -5,7 +5,7 @@ import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -15,25 +15,26 @@ import 'package:flutter/widgets.dart'; /// 包括"标题"、"副标题"、"错误信息提示"、"必填项提示"、"添加/删除按钮"、"消息提示"、 /// "递增/递减按钮"等元素 /// +// ignore: must_be_immutable class BrnStepInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_STEP_INPUT_TYPE; + final String type = BrnInputItemType.textStepInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -48,16 +49,16 @@ class BrnStepInputFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 特有字段 - int value; + final int? value; /// 单步上限值 final int maxLimit; @@ -66,33 +67,34 @@ class BrnStepInputFormItem extends StatefulWidget { final int minLimit; /// 当前值变化回调 - final OnBrnFormValueChanged onChanged; + final OnBrnFormValueChanged? onChanged; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnStepInputFormItem({ - Key key, + Key? key, this.label, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: false, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = false, this.onAddTap, this.onRemoveTap, this.onTip, - this.value: 0, - this.maxLimit: 10, - this.minLimit: 0, + this.value, + this.maxLimit = 10, + this.minLimit = 0, this.onChanged, this.themeData, - }) : super(key: key) { + }) : assert(value == null || value >= minLimit && value <= maxLimit), + super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -104,11 +106,19 @@ class BrnStepInputFormItem extends StatefulWidget { } class BrnStepInputFormItemState extends State { + late int _value; + + @override + void initState() { + super.initState(); + _value = widget.value ?? widget.minLimit; + } + @override Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -121,7 +131,7 @@ class BrnStepInputFormItemState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -132,9 +142,9 @@ class BrnStepInputFormItemState extends State { widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -151,18 +161,10 @@ class BrnStepInputFormItemState extends State { return; } - if (widget.value == null) { - widget.value = 1; - BrnFormUtil.notifyValueChanged(widget.onChanged, - context, widget.value + 1, widget.value); - setState(() {}); - return; - } - if (!isReachMinLevel()) { - widget.value = widget.value - 1; - BrnFormUtil.notifyValueChanged(widget.onChanged, - context, widget.value + 1, widget.value); + _value = _value - 1; + BrnFormUtil.notifyValueChanged( + widget.onChanged, context, _value + 1, _value); setState(() {}); } }, @@ -174,10 +176,10 @@ class BrnStepInputFormItemState extends State { alignment: Alignment.center, width: 50, child: Text( - "${widget.value}", + "$_value", style: TextStyle( color: Color(0xFF222222), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), ), ), @@ -191,18 +193,10 @@ class BrnStepInputFormItemState extends State { return; } - if (widget.value == null) { - widget.value = 1; - BrnFormUtil.notifyValueChanged(widget.onChanged, - context, widget.value - 1, widget.value); - setState(() {}); - return; - } - if (!isReachMaxLevel()) { - widget.value = widget.value + 1; - BrnFormUtil.notifyValueChanged(widget.onChanged, - context, widget.value - 1, widget.value); + _value = _value + 1; + BrnFormUtil.notifyValueChanged( + widget.onChanged, context, _value - 1, _value); setState(() {}); } }, @@ -217,71 +211,53 @@ class BrnStepInputFormItemState extends State { ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); } bool isEnable() { - if (widget.isEdit == null) { - return true; - } - return widget.isEdit; } Image getAddIcon() { - if (widget.isEdit != null && !widget.isEdit) { - return BrunoTools.getAssetImage(BrnAsset.ICON_ADD_DISABLE); + if (!widget.isEdit) { + return BrunoTools.getAssetImage(BrnAsset.iconAddDisable); } if (isReachMaxLevel()) { - return BrunoTools.getAssetImage(BrnAsset.ICON_ADD_DISABLE); + return BrunoTools.getAssetImage(BrnAsset.iconAddDisable); } - return BrunoTools.getAssetImage(BrnAsset.ICON_ADD_ENABLE); + return BrunoTools.getAssetImage(BrnAsset.iconAddEnable); } bool isReachMaxLevel() { - int value = widget.value; - - if (widget.value == null) { - return false; - } - - if (value >= widget.maxLimit) { + if (_value >= widget.maxLimit) { return true; } - return false; } Image getMinusIcon() { - if (widget.isEdit != null && !widget.isEdit) { - return BrunoTools.getAssetImage(BrnAsset.ICON_MINUS_DISABLE); + if (!widget.isEdit) { + return BrunoTools.getAssetImage(BrnAsset.iconMinusDisable); } if (isReachMinLevel()) { - return BrunoTools.getAssetImage(BrnAsset.ICON_MINUS_DISABLE); + return BrunoTools.getAssetImage(BrnAsset.iconMinusDisable); } - return BrunoTools.getAssetImage(BrnAsset.ICON_MINUS_ENABLE); + return BrunoTools.getAssetImage(BrnAsset.iconMinusEnable); } bool isReachMinLevel() { - int value = widget.value; - - if (widget.value == null) { - return false; - } - - if (value <= widget.minLimit) { + if (_value <= widget.minLimit) { return true; } - return false; } } diff --git a/lib/src/components/form/items/general/brn_text_block_input_item.dart b/lib/src/components/form/items/general/brn_text_block_input_item.dart index c0f85bb4..7fbc70b2 100644 --- a/lib/src/components/form/items/general/brn_text_block_input_item.dart +++ b/lib/src/components/form/items/general/brn_text_block_input_item.dart @@ -1,5 +1,4 @@ import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; -import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; @@ -15,23 +14,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnTextBlockInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_BLOCK_INPUT_TYPE; + final String type = BrnInputItemType.textBlockInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -51,30 +50,30 @@ class BrnTextBlockInputFormItem extends StatefulWidget { final bool isPrefixIconEnabled; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 输入字符数上限 - final int maxCharCount; + final int? maxCharCount; /// 录入项 hint 提示 final String hint; /// 输入内容类型 - final String inputType; + final String? inputType; /// 指定对输入数据的格式化要求 - List inputFormatters; + final List? inputFormatters; /// 输入回调 - final ValueChanged onChanged; + final ValueChanged? onChanged; - final TextEditingController controller; + final TextEditingController? controller; /// 最小行数,默认值4 final int minLines; @@ -83,25 +82,24 @@ class BrnTextBlockInputFormItem extends StatefulWidget { final int maxLines; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnTextBlockInputFormItem( - {Key key, + {Key? key, this.label, - this.type: BrnInputItemType.TEXT_BLOCK_INPUT_TYPE, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: false, - this.isPrefixIconEnabled: false, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = false, + this.isPrefixIconEnabled = false, this.onAddTap, this.onRemoveTap, this.onTip, this.onChanged, - this.hint: "请选择", + this.hint = "请输入", this.maxCharCount, this.inputType, this.inputFormatters, @@ -112,7 +110,7 @@ class BrnTextBlockInputFormItem extends StatefulWidget { : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -124,7 +122,7 @@ class BrnTextBlockInputFormItem extends StatefulWidget { } class BrnTextBlockInputFormItemState extends State { - TextEditingController _controller; + late TextEditingController _controller; @override void initState() { @@ -136,7 +134,7 @@ class BrnTextBlockInputFormItemState extends State { Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -146,7 +144,7 @@ class BrnTextBlockInputFormItemState extends State { ), child: Container( padding: BrnFormUtil.titleEdgeInsets( - widget.prefixIconType, widget.isRequire, widget.themeData), + widget.prefixIconType, widget.isRequire, widget.themeData!), child: Row( children: [ // 添加/删除 按钮 @@ -160,39 +158,39 @@ class BrnTextBlockInputFormItemState extends State { BrnFormUtil.buildRequireWidget(widget.isRequire), // title - BrnFormUtil.buildTitleWidget(widget.title, widget.themeData), + BrnFormUtil.buildTitleWidget(widget.title, widget.themeData!), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), // 错误提示 - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData), + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!), // 输入框 Container( - padding: BrnFormUtil.errorEdgeInsets(widget.themeData), + padding: BrnFormUtil.errorEdgeInsets(widget.themeData!), child: TextField( keyboardType: BrnFormUtil.getInputType(widget.inputType), controller: _controller, maxLength: widget.maxCharCount, - maxLengthEnforced: true, - maxLines: widget.maxLines ?? 20, - minLines: widget.minLines ?? 4, + maxLengthEnforcement: MaxLengthEnforcement.enforced, + maxLines: widget.maxLines, + minLines: widget.minLines, textAlign: TextAlign.left, enabled: widget.isEdit, style: BrnFormUtil.getIsEditTextStyle( - widget.themeData, widget.isEdit), + widget.themeData!, widget.isEdit), inputFormatters: widget.inputFormatters, decoration: InputDecoration( - hintText: widget.hint ?? "请输入", - hintStyle: BrnFormUtil.getHintTextStyle(widget.themeData), + hintText: widget.hint , + hintStyle: BrnFormUtil.getHintTextStyle(widget.themeData!), contentPadding: EdgeInsets.all(0), border: InputBorder.none, isDense: true, @@ -215,7 +213,7 @@ class BrnTextBlockInputFormItemState extends State { void dispose() { super.dispose(); if (widget.controller == null) { - _controller?.dispose(); + _controller.dispose(); } } } diff --git a/lib/src/components/form/items/general/brn_text_input_item.dart b/lib/src/components/form/items/general/brn_text_input_item.dart index 4018cb4d..02058a33 100644 --- a/lib/src/components/form/items/general/brn_text_input_item.dart +++ b/lib/src/components/form/items/general/brn_text_input_item.dart @@ -1,12 +1,10 @@ import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; -import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; /// /// 文本输入型录入项 @@ -17,23 +15,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnTextInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_INPUT_TYPE; + final String type = BrnInputItemType.textInputType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 [BrnPrefixIconType] 类 final String prefixIconType; @@ -53,55 +51,54 @@ class BrnTextInputFormItem extends StatefulWidget { final bool isPrefixIconEnabled; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 固定内容 - final String prefixText; + final String? prefixText; /// 提示文案 final String hint; /// 单位 - final String unit; + final String? unit; /// 输入内容类型 - final String inputType; + final String? inputType; /// 最大可输入字符数 - final int maxCharCount; - List inputFormatters; + final int? maxCharCount; + final List? inputFormatters; /// 输入变化回调 - final ValueChanged onChanged; + final ValueChanged? onChanged; - final TextEditingController controller; + final TextEditingController? controller; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnTextInputFormItem({ - Key key, + Key? key, this.label, - this.type: BrnInputItemType.TEXT_INPUT_TYPE, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: false, - this.isPrefixIconEnabled: false, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = false, + this.isPrefixIconEnabled = false, this.onAddTap, this.onRemoveTap, this.onTip, this.prefixText, - this.hint: "请输入", + this.hint = "请输入", this.unit, this.maxCharCount, this.inputType, @@ -112,7 +109,7 @@ class BrnTextInputFormItem extends StatefulWidget { }) : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -124,7 +121,7 @@ class BrnTextInputFormItem extends StatefulWidget { } class BrnTextInputFormItemState extends State { - TextEditingController _controller; + late TextEditingController _controller; @override void initState() { @@ -136,7 +133,7 @@ class BrnTextInputFormItemState extends State { Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -148,7 +145,7 @@ class BrnTextInputFormItemState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon( @@ -159,7 +156,7 @@ class BrnTextInputFormItemState extends State { widget.onRemoveTap), BrnFormUtil.buildRequireWidget(widget.isRequire), BrnFormUtil.buildTitleWidget( - widget.title, widget.themeData), + widget.title, widget.themeData!), Offstage( offstage: (widget.prefixText == null), child: Container( @@ -167,11 +164,11 @@ class BrnTextInputFormItemState extends State { child: Text( widget.prefixText ?? "", style: BrnFormUtil.getTitleTextStyle( - widget.themeData), + widget.themeData!), )), ), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -182,11 +179,11 @@ class BrnTextInputFormItemState extends State { maxLines: 1, maxLength: widget.maxCharCount, style: BrnFormUtil.getIsEditTextStyle( - widget.themeData, widget.isEdit), + widget.themeData!, widget.isEdit), decoration: InputDecoration( border: InputBorder.none, - hintStyle: BrnFormUtil.getHintTextStyle(widget.themeData), - hintText: widget.hint ?? '请输入', + hintStyle: BrnFormUtil.getHintTextStyle(widget.themeData!), + hintText: widget.hint, counterText: "", contentPadding: EdgeInsets.all(0), isDense: true, @@ -211,15 +208,15 @@ class BrnTextInputFormItemState extends State { widget.unit ?? "", style: TextStyle( color: Color(0xFF101010), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), )), ), ], ), ), - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -231,7 +228,7 @@ class BrnTextInputFormItemState extends State { // 如果controller由外部创建不需要销毁, 若由内部创建则需要销毁 if (widget.controller == null) { - _controller?.dispose(); + _controller.dispose(); } } } diff --git a/lib/src/components/form/items/general/brn_text_select_item.dart b/lib/src/components/form/items/general/brn_text_select_item.dart index 3c400269..1678b5c8 100644 --- a/lib/src/components/form/items/general/brn_text_select_item.dart +++ b/lib/src/components/form/items/general/brn_text_select_item.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; @@ -5,7 +7,7 @@ import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -19,19 +21,19 @@ import 'package:flutter/widgets.dart'; /// // ignore: must_be_immutable class BrnTextSelectFormItem extends StatefulWidget { - final String label; + final String? label; /// 录入项的唯一标识,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_SELECT_INPUT_TYPE; + final String type = BrnInputItemType.textSelectInputType; /// 录入项类型,主要用于录入类型页面框架中 final String title; /// 录入项标题 - final String subTitle; + final String? subTitle; /// 录入项子标题 - final String tipLabel; + final String? tipLabel; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, @@ -51,46 +53,46 @@ class BrnTextSelectFormItem extends StatefulWidget { final bool isEdit; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 点击录入区回调 - final VoidCallback onTap; + final VoidCallback? onTap; /// 录入项 hint 提示 final String hint; /// 录入项 值 - final String value; + final String? value; /// 选中文本最大行数 final int valueMaxLines; /// title最大行数 - final int titleMaxLines; + final int? titleMaxLines; ///是否自动布局 - bool _isAutoLayout; + bool? _isAutoLayout; /// 行布局比例值 左边「标题+问号+提示语」 右边「选项值」 /// 左:右 比例值 例如 左:右 = 6:4 则 ratio = 1.5 - double layoutRatio; + double? layoutRatio; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnTextSelectFormItem({ - Key key, + Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -107,18 +109,18 @@ class BrnTextSelectFormItem extends StatefulWidget { this._isAutoLayout = false; this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } BrnTextSelectFormItem.autoLayout( - {Key key, + {Key? key, this.label, this.title: "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, + this.prefixIconType: BrnPrefixIconType.normal, this.error: "", this.isEdit: true, this.isRequire: false, @@ -136,7 +138,7 @@ class BrnTextSelectFormItem extends StatefulWidget { this._isAutoLayout = true; this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -147,7 +149,7 @@ class BrnTextSelectFormItem extends StatefulWidget { } } -double _fontSize = BrnFont.FONT_16; +double _fontSize = BrnFonts.f16; StrutStyle _contentStructStyle = StrutStyle( forceStrutHeight: true, height: 1, leading: 0.5, fontSize: _fontSize); @@ -166,10 +168,10 @@ class BrnTextSelectFormItemState extends State { : _buildTitleWidget(context), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), // 错误提示 - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -177,7 +179,7 @@ class BrnTextSelectFormItemState extends State { double _getTitleMaxWidth(BuildContext context, BoxConstraints constraints) { double contentRatio = BrnFormUtil.getAutoLayoutContentRatio( - tipLabelHidden: widget.tipLabel == null || widget.tipLabel.isEmpty, + tipLabelHidden: widget.tipLabel == null || widget.tipLabel!.isEmpty, layoutRatio: widget.layoutRatio); double maxWidth = min( constraints.maxWidth * contentRatio, @@ -235,7 +237,7 @@ class BrnTextSelectFormItemState extends State { GestureDetector _buildRightWidget(BuildContext context) { return GestureDetector( onTap: () { - if (widget.isEdit != null && !widget.isEdit) { + if (!widget.isEdit) { return; } @@ -267,7 +269,7 @@ class BrnTextSelectFormItemState extends State { child: GestureDetector( onTap: () { if (widget.onTip != null) { - widget.onTip(); + widget.onTip!(); } }, child: Row( @@ -289,8 +291,8 @@ class BrnTextSelectFormItemState extends State { forceStrutHeight: true, height: 1, leading: 0.5, - fontSize: BrnFont.FONT_14), - style: BrnFormUtil.getTipsTextStyle(widget.themeData), + fontSize: BrnFonts.f14), + style: BrnFormUtil.getTipsTextStyle(widget.themeData!), ), ), ], @@ -302,13 +304,13 @@ class BrnTextSelectFormItemState extends State { // 标题widget Widget _buildTitleTextWidget() { return Text( - widget.title ?? "", + widget.title, overflow: widget.titleMaxLines == null ? TextOverflow.clip : TextOverflow.ellipsis, maxLines: widget.titleMaxLines, strutStyle: _contentStructStyle, - style: BrnFormUtil.getTitleTextStyle(widget.themeData, height: 1), + style: BrnFormUtil.getTitleTextStyle(widget.themeData!, height: 1), ); } @@ -342,7 +344,7 @@ class BrnTextSelectFormItemState extends State { // 计算Text所占宽度 double _calculateTextWidth(BuildContext context) { TextPainter painter; - if (widget.value != null && widget.value.isNotEmpty) { + if (widget.value != null && widget.value!.isNotEmpty) { painter = TextPainter( locale: Localizations.localeOf(context), textAlign: TextAlign.end, @@ -351,7 +353,7 @@ class BrnTextSelectFormItemState extends State { text: TextSpan( text: widget.value, style: BrnFormUtil.getIsEditTextStyle( - widget.themeData, widget.isEdit, + widget.themeData!, widget.isEdit, height: 1), )); } else { @@ -362,7 +364,7 @@ class BrnTextSelectFormItemState extends State { strutStyle: _contentStructStyle, text: TextSpan( text: widget.hint, - style: BrnFormUtil.getHintTextStyle(widget.themeData, height: 1), + style: BrnFormUtil.getHintTextStyle(widget.themeData!, height: 1), )); } painter.layout(); @@ -372,14 +374,14 @@ class BrnTextSelectFormItemState extends State { } Widget buildText() { - if (widget.value != null && widget.value.isNotEmpty) { + if (widget.value != null && widget.value!.isNotEmpty) { return Text( - widget.value, + widget.value!, overflow: TextOverflow.ellipsis, - maxLines: widget.valueMaxLines ?? 1, + maxLines: widget.valueMaxLines , textAlign: TextAlign.end, strutStyle: _contentStructStyle, - style: BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit, + style: BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit, height: 1), ); } else { @@ -387,7 +389,7 @@ class BrnTextSelectFormItemState extends State { widget.hint, textAlign: TextAlign.end, strutStyle: _contentStructStyle, - style: BrnFormUtil.getHintTextStyle(widget.themeData, height: 1), + style: BrnFormUtil.getHintTextStyle(widget.themeData!, height: 1), ); } } @@ -395,7 +397,7 @@ class BrnTextSelectFormItemState extends State { String getCalculateText() { String value = '请选择'; if (!BrunoTools.isEmpty(widget.value)) { - value = widget.value; + value = widget.value!; } else if (!BrunoTools.isEmpty(widget.hint)) { value = widget.hint; } @@ -406,7 +408,7 @@ class BrnTextSelectFormItemState extends State { // fontSize : 文字的大小; // maxLines:文本支持最大多少行 static double calculateTextHeight( - BuildContext context, String value, double fontSize, int maxLines) { + BuildContext context, String? value, double fontSize, int maxLines) { TextPainter painter = TextPainter( // AUTO:华为手机如果不指定locale的时候,该方法算出来的文字高度是比系统计算偏小的。 diff --git a/lib/src/components/form/items/general/brn_title_select_input_item.dart b/lib/src/components/form/items/general/brn_title_select_input_item.dart index ad23341b..4410cb96 100644 --- a/lib/src/components/form/items/general/brn_title_select_input_item.dart +++ b/lib/src/components/form/items/general/brn_title_select_input_item.dart @@ -8,7 +8,7 @@ import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -21,23 +21,23 @@ import 'package:flutter/services.dart'; // ignore: must_be_immutable class BrnTitleSelectInputFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.TEXT_INPUT_TITLE_SELECT_TYPE; + final String type = BrnInputItemType.textInputTitleSelectType; /// 录入项标题 - String title; + final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -57,19 +57,19 @@ class BrnTitleSelectInputFormItem extends StatefulWidget { final bool isPrefixIconEnabled; /// 点击"+"图标回调 - final VoidCallback onAddTap; + final VoidCallback? onAddTap; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 提示文案 final String hint; /// 最大可输入字符数 - final int maxCount; + final int? maxCount; /// 输入类型 final String inputType; @@ -78,38 +78,38 @@ class BrnTitleSelectInputFormItem extends StatefulWidget { final int selectedIndex; /// title选择列表 - List selectList; - List inputFormatters; + final List selectList; + final List? inputFormatters; /// 输入文本变化回调 - final ValueChanged onChanged; + final ValueChanged? onChanged; /// title文案选中回调 - final OnBrnFormTitleSelected onTitleSelected; - final TextEditingController controller; + final OnBrnFormTitleSelected? onTitleSelected; + final TextEditingController? controller; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnTitleSelectInputFormItem( - {Key key, + {Key? key, + required this.selectList, this.label, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: false, - this.isPrefixIconEnabled: false, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = false, + this.isPrefixIconEnabled = false, this.onAddTap, this.onRemoveTap, this.onTip, - this.hint: "请输入", + this.hint = "请输入", this.maxCount, - this.inputType: BrnInputType.TEXT, - this.selectedIndex: -1, - this.selectList, + this.inputType = BrnInputType.text, + this.selectedIndex = -1, this.inputFormatters, this.onChanged, this.onTitleSelected, @@ -118,7 +118,7 @@ class BrnTitleSelectInputFormItem extends StatefulWidget { : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -130,10 +130,11 @@ class BrnTitleSelectInputFormItem extends StatefulWidget { class BrnTitleSelectInputFormItemState extends State { - TextEditingController _controller; - StreamController _showController; - StreamController _textController; - GlobalKey _globalKey; + late TextEditingController _controller; + late StreamController _showController; + late StreamController _textController; + late GlobalKey _globalKey; + String _title = ""; @override void initState() { @@ -145,7 +146,7 @@ class BrnTitleSelectInputFormItemState Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -165,8 +166,8 @@ class BrnTitleSelectInputFormItemState ], ), ), - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!), ], ), ); @@ -175,7 +176,7 @@ class BrnTitleSelectInputFormItemState Widget _buildLeftMenu() { return Container( padding: BrnFormUtil.titleEdgeInsets( - widget.prefixIconType, widget.isRequire, widget.themeData), + widget.prefixIconType, widget.isRequire, widget.themeData!), child: Row( children: [ BrnFormUtil.buildPrefixIcon(widget.prefixIconType, widget.isEdit, @@ -187,7 +188,7 @@ class BrnTitleSelectInputFormItemState _buildTriangle(), BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ); @@ -199,15 +200,16 @@ class BrnTitleSelectInputFormItemState padding: EdgeInsets.only(right: 4), child: GestureDetector( onTap: () { - if (widget.isEdit != null && !widget.isEdit) { + if (!widget.isEdit) { return; } - RenderBox trigle = _globalKey.currentContext?.findRenderObject(); - Offset offset = trigle?.localToGlobal(Offset.zero); - final RenderBox button = context.findRenderObject(); + RenderBox? trigle = + _globalKey.currentContext?.findRenderObject() as RenderBox?; + Offset? offset = trigle?.localToGlobal(Offset.zero); + final RenderBox button = context.findRenderObject() as RenderBox; final RenderBox overlay = - Overlay.of(context).context.findRenderObject(); + Overlay.of(context)!.context.findRenderObject() as RenderBox; final RelativeRect position = RelativeRect.fromRect( Rect.fromPoints( button.localToGlobal(Offset.zero, ancestor: overlay), @@ -217,9 +219,9 @@ class BrnTitleSelectInputFormItemState ); var relativeRect = RelativeRect.fromLTRB( - position.left + offset?.dx ?? 16, + position.left + (offset?.dx ?? 0.0), position.top + 44, - position.right + offset?.dx ?? 16, + position.right + (offset?.dx ?? 0.0), position.bottom + 44); _showController.add(true); Navigator.push( @@ -234,10 +236,10 @@ class BrnTitleSelectInputFormItemState selectList: widget.selectList, selectedIndex: widget.selectedIndex, selectCallback: (item, index) { - widget.title = item; + _title = item; _textController.add(item); if (widget.onTitleSelected != null) { - widget.onTitleSelected(item, index); + widget.onTitleSelected!(item, index); } }, themeData: widget.themeData, @@ -252,11 +254,11 @@ class BrnTitleSelectInputFormItemState }, child: StreamBuilder( stream: _textController.stream, - initialData: widget.title ?? "", + initialData: _title, builder: (context, AsyncSnapshot snapshot) { return Text( - snapshot.data, - style: BrnFormUtil.getTitleTextStyle(widget.themeData), + snapshot.data!, + style: BrnFormUtil.getTitleTextStyle(widget.themeData!), ); }, ), @@ -271,10 +273,10 @@ class BrnTitleSelectInputFormItemState stream: _showController.stream, initialData: false, builder: (BuildContext context, AsyncSnapshot snapshot) { - return snapshot.data + return snapshot.data! ? BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_SELECTED_UP_TRIANGLE) - : BrunoTools.getAssetImage(BrnAsset.ICON_UNSELECT_DOWN_TRIANGLE); + BrnAsset.iconSelectedUpTriangle) + : BrunoTools.getAssetImage(BrnAsset.iconUnSelectDownTriangle); }, ), ); @@ -287,7 +289,7 @@ class BrnTitleSelectInputFormItemState controller: _controller, enabled: widget.isEdit, maxLength: widget.maxCount, - style: BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit), + style: BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit), onChanged: (text) { BrnFormUtil.notifyInputChanged(widget.onChanged, text); }, @@ -296,9 +298,9 @@ class BrnTitleSelectInputFormItemState border: InputBorder.none, hintStyle: TextStyle( color: Color(0xFFCCCCCC), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, textBaseline: TextBaseline.alphabetic), - hintText: widget.hint ?? '请输入', + hintText: widget.hint, counterText: "", contentPadding: EdgeInsets.all(0), isDense: true, @@ -315,7 +317,7 @@ class BrnTitleSelectInputFormItemState super.dispose(); // 如果controller由外部创建不需要销毁, 若由内部创建则需要销毁 if (widget.controller == null) { - _controller?.dispose(); + _controller.dispose(); } } @@ -325,19 +327,21 @@ class BrnTitleSelectInputFormItemState _controller = widget.controller ?? TextEditingController(); _globalKey = GlobalKey(); + _title = widget.title; } } +// ignore: must_be_immutable class TitleSelectPopWidget extends StatefulWidget { List selectList; - int selectedIndex; + int? selectedIndex; final Function(String item, int index) selectCallback; - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; TitleSelectPopWidget( - {this.selectList, + {required this.selectList, this.selectedIndex, - this.selectCallback, + required this.selectCallback, this.themeData}); @override @@ -347,7 +351,7 @@ class TitleSelectPopWidget extends StatefulWidget { class _TitleSelectPopWidgetState extends State { @override Widget build(BuildContext context) { - List showList = List(); + List showList = []; for (int i = 0, n = widget.selectList.length; i < n; ++i) { showList.add(selectItem(widget.selectList[i], i, i == n - 1)); } @@ -363,7 +367,7 @@ class _TitleSelectPopWidgetState extends State { ], color: Colors.white, border: Border.all( - color: widget.themeData.commonConfig.dividerColorBase, width: 0.5), + color: widget.themeData!.commonConfig.dividerColorBase, width: 0.5), borderRadius: BorderRadius.all(Radius.circular(4)), ), child: Column( @@ -398,7 +402,7 @@ class _TitleSelectPopWidgetState extends State { bottom: BorderSide( color: isLast ? Colors.transparent - : widget.themeData.commonConfig.dividerColorBase, + : widget.themeData!.commonConfig.dividerColorBase, width: 0.5)), // 也可控件一边圆角大小 ), child: Text( @@ -406,8 +410,8 @@ class _TitleSelectPopWidgetState extends State { style: TextStyle( decoration: TextDecoration.none, color: isSelected - ? widget.themeData.commonConfig.brandPrimary - : widget.themeData.commonConfig.colorTextBase, + ? widget.themeData!.commonConfig.brandPrimary + : widget.themeData!.commonConfig.colorTextBase, fontWeight: FontWeight.w500, fontSize: 16, ), diff --git a/lib/src/components/form/undetermined/brn_expandable_group.dart b/lib/src/components/form/items/group/brn_expandable_group.dart similarity index 88% rename from lib/src/components/form/undetermined/brn_expandable_group.dart rename to lib/src/components/form/items/group/brn_expandable_group.dart index 63f05eb1..0c56bd95 100644 --- a/lib/src/components/form/undetermined/brn_expandable_group.dart +++ b/lib/src/components/form/items/group/brn_expandable_group.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + + import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; @@ -31,19 +33,18 @@ class BrnExpandableGroup extends StatefulWidget { /// the tile to reveal or hide the [children]. The [initiallyExpanded] property must /// be non-null. BrnExpandableGroup({ - Key key, - @required this.title, + Key? key, + required this.title, this.subtitle, this.backgroundColor, this.onExpansionChanged, this.children = const [], this.initiallyExpanded = false, this.themeData, - }) : assert(initiallyExpanded != null), - super(key: key) { + }) : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -57,15 +58,14 @@ class BrnExpandableGroup extends StatefulWidget { /// /// Typically a [Text] widget. - @Deprecated('message') - final String subtitle; + final String? subtitle; /// Called when the tile expands or collapses. /// /// When the tile starts expanding, this function is called with the value /// true. When the tile starts collapsing, this function is called with /// the value false. - final ValueChanged onExpansionChanged; + final ValueChanged? onExpansionChanged; /// The widgets that are displayed when the tile expands. /// @@ -73,12 +73,12 @@ class BrnExpandableGroup extends StatefulWidget { final List children; /// The color to display behind the sublist when expanded. - final Color backgroundColor; + final Color? backgroundColor; /// Specifies if the list tile is initially expanded (true) or collapsed (false, the default). final bool initiallyExpanded; - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; @override _BrnExpansionElementState createState() => _BrnExpansionElementState(); @@ -97,13 +97,13 @@ class _BrnExpansionElementState extends State final ColorTween _iconColorTween = ColorTween(); final ColorTween _backgroundColorTween = ColorTween(); - AnimationController _controller; - Animation _iconTurns; - Animation _heightFactor; + late AnimationController _controller; + late Animation _iconTurns; + late Animation _heightFactor; bool _isExpanded = false; - Widget arrowIcon; + Widget? arrowIcon; @override void initState() { @@ -127,9 +127,9 @@ class _BrnExpansionElementState extends State if (_isExpanded) { arrowIcon = - BrunoTools.getAssetSizeImage(BrnAsset.ICON_DOWN_ARROW, 12, 12); + BrunoTools.getAssetSizeImage(BrnAsset.iconDownArrow, 12, 12); } else { - arrowIcon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_UP_ARROW, 12, 12); + arrowIcon = BrunoTools.getAssetSizeImage(BrnAsset.iconUpArrow, 12, 12); } } @@ -152,10 +152,10 @@ class _BrnExpansionElementState extends State PageStorage.of(context)?.writeState(context, _isExpanded); }); if (widget.onExpansionChanged != null) - widget.onExpansionChanged(_isExpanded); + widget.onExpansionChanged!(_isExpanded); } - Widget _buildHeader(BuildContext context, Widget child) { + Widget _buildHeader(BuildContext context, Widget? child) { final Color backgroundColor = Colors.transparent; return Container( @@ -181,9 +181,9 @@ class _BrnExpansionElementState extends State Container( padding: EdgeInsets.only(right: 6), child: Text( - widget.title ?? "", + widget.title, style: BrnFormUtil.getHeadTitleTextStyle( - widget.themeData, + widget.themeData!, isBold: true), )), // 副标题 @@ -194,12 +194,12 @@ class _BrnExpansionElementState extends State child: Offstage( // ignore: deprecated_member_use_from_same_package offstage: (widget.subtitle == null || - widget.subtitle.isEmpty), + widget.subtitle!.isEmpty), child: Text( // ignore: deprecated_member_use_from_same_package widget.subtitle ?? "", style: BrnFormUtil.getSubTitleTextStyle( - widget.themeData), + widget.themeData!), ), ), ), @@ -236,8 +236,8 @@ class _BrnExpansionElementState extends State /// title 文字颜色 _headerColorTween - ..begin = theme.textTheme.subtitle1.color - ..end = theme.textTheme.subtitle1.color; + ..begin = theme.textTheme.subtitle1!.color + ..end = theme.textTheme.subtitle1!.color; /// 展开收起图标颜色 _iconColorTween diff --git a/lib/src/components/form/items/group/brn_expand_group.dart b/lib/src/components/form/items/group/brn_expandable_group_with_opreate.dart similarity index 79% rename from lib/src/components/form/items/group/brn_expand_group.dart rename to lib/src/components/form/items/group/brn_expandable_group_with_opreate.dart index 770a8191..13a06eab 100644 --- a/lib/src/components/form/items/group/brn_expand_group.dart +++ b/lib/src/components/form/items/group/brn_expandable_group_with_opreate.dart @@ -14,23 +14,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnExpandFormGroup extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.NORMAL_GROUP_TYPE; + final String type = BrnInputItemType.normalGroupType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项错误提示 final String error; @@ -42,35 +42,35 @@ class BrnExpandFormGroup extends StatefulWidget { final bool isEdit; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 初始是否为展开状态 final bool isExpand; /// 右侧文案 - final String deleteLabel; + final String? deleteLabel; /// 内部子项 - List children; + final List children; BrnExpandFormGroup({ - Key key, + Key? key, this.label, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.error: "", - this.isEdit: true, - this.isRequire: false, + this.error = "", + this.isEdit = true, + this.isRequire = false, this.onRemoveTap, this.onTip, - this.isExpand: true, + this.isExpand = true, this.deleteLabel, - this.children, - }); + required this.children, + }) : super(key: key); @override BrnExpandFormGroupState createState() { @@ -83,7 +83,7 @@ class BrnExpandFormGroupState extends State { Widget build(BuildContext context) { return Container( child: ExpansionElementWidget( - title: widget.title ?? "", + title: widget.title, subtitle: widget.subTitle, deleteText: widget.deleteLabel, initiallyExpanded: widget.isExpand, @@ -100,17 +100,15 @@ class BrnExpandFormGroupState extends State { } List getSubItem() { - List result = List(); + List result = []; - if (widget.children == null || widget.children.isEmpty) { + if (widget.children.isEmpty) { return result; } for (Widget w in widget.children) { - if (w != null) { - result.add(BrnLine()); - result.add(w); - } + result.add(BrnLine()); + result.add(w); } return result; diff --git a/lib/src/components/form/items/group/brn_normal_group.dart b/lib/src/components/form/items/group/brn_normal_group.dart index 59bfcc76..af71d4b8 100644 --- a/lib/src/components/form/items/group/brn_normal_group.dart +++ b/lib/src/components/form/items/group/brn_normal_group.dart @@ -3,9 +3,8 @@ import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/components/line/brn_line.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; /// /// 可展开收起组类型录入项 @@ -13,25 +12,26 @@ import 'package:flutter/widgets.dart'; /// /// 包括"标题"、"副标题"、"错误信息提示"、"必填项提示"、"添加/删除按钮"、"消息提示" /// +// ignore: must_be_immutable class BrnNormalFormGroup extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - final String type = BrnInputItemType.NORMAL_GROUP_TYPE; + final String type = BrnInputItemType.normalGroupType; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项错误提示 final String error; @@ -43,37 +43,37 @@ class BrnNormalFormGroup extends StatefulWidget { final bool isEdit; /// 点击"-"图标回调 - final VoidCallback onRemoveTap; + final VoidCallback? onRemoveTap; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 右侧文案 - final String deleteLabel; + final String? deleteLabel; /// 内部子项 - List children; + final List children; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnNormalFormGroup({ - Key key, + Key? key, this.label, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.error: "", - this.isEdit: true, - this.isRequire: false, + this.error = "", + this.isEdit = true, + this.isRequire = false, this.onRemoveTap, this.onTip, this.deleteLabel, - this.children, - }) : super() { + required this.children, + }) : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -103,16 +103,16 @@ class BrnNormalFormGroupState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Offstage( - offstage: (widget.title == null || widget.title.isEmpty), + offstage: (widget.title.isEmpty), child: Container( child: Row( children: [ Container( padding: EdgeInsets.only(left: 20, right: 6), child: Text( - widget.title ?? "", + widget.title, style: BrnFormUtil.getHeadTitleTextStyle( - widget.themeData, + widget.themeData!, isBold: true), )), ], @@ -135,7 +135,7 @@ class BrnNormalFormGroupState extends State { widget.deleteLabel ?? "", style: TextStyle( color: Color(0xFFFA3F3F), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), ), ), @@ -148,12 +148,12 @@ class BrnNormalFormGroupState extends State { // 副标题 Container( alignment: Alignment.centerLeft, - padding: BrnFormUtil.subTitleEdgeInsets(widget.themeData), + padding: BrnFormUtil.subTitleEdgeInsets(widget.themeData!), child: Offstage( - offstage: (widget.subTitle == null || widget.subTitle.isEmpty), + offstage: (widget.subTitle == null || widget.subTitle!.isEmpty), child: Text( widget.subTitle ?? "", - style: BrnFormUtil.getSubTitleTextStyle(widget.themeData), + style: BrnFormUtil.getSubTitleTextStyle(widget.themeData!), ), ), ), @@ -169,17 +169,15 @@ class BrnNormalFormGroupState extends State { } List getSubItem() { - List result = List(); + List result = []; - if (widget.children == null || widget.children.isEmpty) { + if (widget.children.isEmpty) { return result; } for (Widget w in widget.children) { - if (w != null) { - result.add(BrnLine()); - result.add(w); - } + result.add(BrnLine()); + result.add(w); } return result; diff --git a/lib/src/components/form/undetermined/brn_portrait_radio_group.dart b/lib/src/components/form/items/group/brn_portrait_radio_group.dart similarity index 74% rename from lib/src/components/form/undetermined/brn_portrait_radio_group.dart rename to lib/src/components/form/items/group/brn_portrait_radio_group.dart index 36504d9c..88ecbf44 100644 --- a/lib/src/components/form/undetermined/brn_portrait_radio_group.dart +++ b/lib/src/components/form/items/group/brn_portrait_radio_group.dart @@ -1,7 +1,6 @@ -import 'package:bruno/bruno.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/components/line/brn_line.dart'; -import 'package:bruno/src/components/radio/brn_radio_core.dart'; +import 'package:bruno/src/components/radio/brn_radio_button.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:flutter/material.dart'; @@ -9,7 +8,7 @@ import 'package:flutter/widgets.dart'; /// 备选项点击时的回调。[oldStr] 旧的选项,如果初始没有选中项,该参数为null,[newStr] 新选中的选项。 typedef BrnPortraitRadioGroupOnChanged = void Function( - BrnPortraitRadioGroupOption oldStr, BrnPortraitRadioGroupOption newStr); + BrnPortraitRadioGroupOption? oldStr, BrnPortraitRadioGroupOption newStr); /// 纵向放置的单选 radio 视图。选项可为单行字符串,也可是标题+说明两部分。具体参见 [BrnPortraitRadioGroupOption]。 /// 选项的标题/子标题文字样式分别通过 [BrnFormItemConfig.optionTextStyle] 和 [BrnFormItemConfig.subTitleTextStyle] 控 @@ -20,16 +19,16 @@ class BrnPortraitRadioGroup extends StatefulWidget { final bool isEdit; /// 初始化时默认选中的项,匹配逻辑是 [BrnPortraitRadioGroupOption.title] 和 [BrnPortraitRadioGroupOption.subTitle] 都相等。 - BrnPortraitRadioGroupOption selectedOption; + final BrnPortraitRadioGroupOption? selectedOption; /// 备选项数组,参数类型为 [BrnPortraitRadioGroupOption] - List options; + final List? options; /// 备选项可用状态数组 - final List enableList; + final List? enableList; /// 选项变化回调 - final BrnPortraitRadioGroupOnChanged onChanged; + final BrnPortraitRadioGroupOnChanged? onChanged; /// [options] 中 title subTitle 是否换行展示。 /// false: 换行展示 @@ -38,38 +37,36 @@ class BrnPortraitRadioGroup extends StatefulWidget { final bool isCollapseContent; /// 主题配置数据 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; /// 通过传入一个字符串数组 [options],快捷构造出单行选项文案的纵向单选视图。 BrnPortraitRadioGroup.withSimpleList({ - Key key, + Key? key, this.isEdit = true, - String selectedOption, - List options, + String selectedOption = "", + required List options, this.enableList, this.onChanged, this.themeData, this.isCollapseContent = false, - }) { - this.options = options - ?.map((item) => BrnPortraitRadioGroupOption(title: item)) - ?.toList() ?? - List(); - int selectedIndex = options.indexOf(selectedOption); - if (selectedIndex > -1) { - this.selectedOption = this.options[selectedIndex]; - } - + }) : this.options = options + .map((item) => BrnPortraitRadioGroupOption(title: item)) + .toList(), + this.selectedOption = options.indexOf(selectedOption) > -1 + ? BrnPortraitRadioGroupOption( + title: options[options.indexOf(selectedOption)]) + : BrnPortraitRadioGroupOption(), + super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } /// 通过 [BrnPortraitRadioGroupOption] 类型的数组 [options],构造纵向单选视图。 BrnPortraitRadioGroup.withOptions({ - Key key, + Key? key, this.isEdit = true, this.selectedOption, this.options, @@ -77,10 +74,10 @@ class BrnPortraitRadioGroup extends StatefulWidget { this.onChanged, this.isCollapseContent = false, this.themeData, - }) { + }) :super(key: key){ this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -92,9 +89,12 @@ class BrnPortraitRadioGroup extends StatefulWidget { } class BrnPortraitRadioGroupState extends State { + late BrnPortraitRadioGroupOption? _selectedOption; + @override void initState() { super.initState(); + _selectedOption = widget.selectedOption; } @override @@ -108,8 +108,8 @@ class BrnPortraitRadioGroupState extends State { ); } - List getRadioList(List options) { - List result = List(); + List getRadioList(List? options) { + List result = []; BrnPortraitRadioGroupOption option; if (options == null || options.isEmpty) { result.add(Container()); @@ -149,16 +149,16 @@ class BrnPortraitRadioGroupState extends State { if (getRadioEnableState(position)) { return; } - BrnPortraitRadioGroupOption oldValue = widget.selectedOption; - widget.selectedOption = options[position]; + BrnPortraitRadioGroupOption? oldValue = _selectedOption; + _selectedOption = options[position]; if (widget.onChanged != null) { - widget.onChanged(oldValue, options[position]); + widget.onChanged!(oldValue, options[position]); } setState(() {}); }, ), Visibility( - visible: option.subTitle != null && option.subTitle.length > 0, + visible: option.subTitle != null && option.subTitle!.length > 0, child: Padding( padding: EdgeInsets.only(top: 4, right: 20), child: Text( @@ -166,7 +166,7 @@ class BrnPortraitRadioGroupState extends State { overflow: widget.isCollapseContent ? TextOverflow.ellipsis : null, maxLines: widget.isCollapseContent ? 1 : null, - style: BrnFormUtil.getSubTitleTextStyle(widget.themeData), + style: BrnFormUtil.getSubTitleTextStyle(widget.themeData!), ), ), ) @@ -186,8 +186,8 @@ class BrnPortraitRadioGroupState extends State { int getGroupValue() { int selectedIndex = -1; - for (int index = 0; index < widget.options.length; index++) { - if (isSameOption(widget.options[index], widget.selectedOption)) { + for (int index = 0; index < widget.options!.length; index++) { + if (isSameOption(widget.options![index], _selectedOption)) { selectedIndex = index; break; } @@ -196,57 +196,54 @@ class BrnPortraitRadioGroupState extends State { } bool isSameOption( - BrnPortraitRadioGroupOption src, BrnPortraitRadioGroupOption dst) { - if (src == null || dst == null) return false; + BrnPortraitRadioGroupOption src, BrnPortraitRadioGroupOption? dst) { + if (dst == null) return false; return src.title == dst.title && src.subTitle == dst.subTitle; } TextStyle getOptionTextStyle(BrnPortraitRadioGroupOption opt, int index) { - TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData); - if (opt == null /*|| widget.value == null*/) { - return result; - } + TextStyle result = BrnFormUtil.getOptionTextStyle(widget.themeData!); - if (isSameOption(opt, widget.selectedOption)) { - result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData); + if (isSameOption(opt, _selectedOption)) { + result = BrnFormUtil.getOptionSelectedTextStyle(widget.themeData!); } - if (widget.isEdit != null && !widget.isEdit) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit); + if (!widget.isEdit) { + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit); } if (widget.enableList != null && - widget.enableList.isNotEmpty && - widget.enableList.length > index && - !widget.enableList[index]) { - result = BrnFormUtil.getIsEditTextStyle(widget.themeData, false); + widget.enableList!.isNotEmpty && + widget.enableList!.length > index && + !widget.enableList![index]) { + result = BrnFormUtil.getIsEditTextStyle(widget.themeData!, false); } return result; } bool getRadioEnableState(int index) { - if (widget.isEdit != null && !widget.isEdit) { + if (!widget.isEdit) { return true; } if (widget.enableList == null || - widget.enableList.isEmpty || - widget.enableList.length < index) { + widget.enableList!.isEmpty || + widget.enableList!.length < index) { return false; } - return !widget.enableList[index]; + return !widget.enableList![index]; } } /// 纵置单选视图的选项模型。文字样式见 [BrnPortraitRadioGroup] 说明。 class BrnPortraitRadioGroupOption { /// 标题 - String title; + String? title; /// 子标题说明文案 - String subTitle; + String? subTitle; BrnPortraitRadioGroupOption({this.title, this.subTitle}); } diff --git a/lib/src/components/form/items/group/element_expand_widget.dart b/lib/src/components/form/items/group/element_expand_widget.dart index dac9e2f7..72164ba6 100644 --- a/lib/src/components/form/items/group/element_expand_widget.dart +++ b/lib/src/components/form/items/group/element_expand_widget.dart @@ -2,11 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + + import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -31,8 +33,8 @@ class ExpansionElementWidget extends StatefulWidget { /// the tile to reveal or hide the [children]. The [initiallyExpanded] property must /// be non-null. ExpansionElementWidget({ - Key key, - @required this.title, + Key? key, + this.title = "", this.subtitle, this.backgroundColor, this.onExpansionChanged, @@ -41,11 +43,10 @@ class ExpansionElementWidget extends StatefulWidget { this.deleteText, this.callback, this.themeData, - }) : assert(initiallyExpanded != null), - super(key: key) { + }) : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -55,19 +56,19 @@ class ExpansionElementWidget extends StatefulWidget { /// Typically a [Text] widget. final String title; - final String deleteText; + final String? deleteText; /// Additional content displayed below the title. /// /// Typically a [Text] widget. - final String subtitle; + final String? subtitle; /// Called when the tile expands or collapses. /// /// When the tile starts expanding, this function is called with the value /// true. When the tile starts collapsing, this function is called with /// the value false. - final ValueChanged onExpansionChanged; + final ValueChanged? onExpansionChanged; /// The widgets that are displayed when the tile expands. /// @@ -75,14 +76,14 @@ class ExpansionElementWidget extends StatefulWidget { final List children; /// The color to display behind the sublist when expanded. - final Color backgroundColor; + final Color? backgroundColor; /// Specifies if the list tile is initially expanded (true) or collapsed (false, the default). final bool initiallyExpanded; - final VoidCallback callback; + final VoidCallback? callback; - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; @override _ExpansionElementState createState() => _ExpansionElementState(); @@ -103,13 +104,13 @@ class _ExpansionElementState extends State final ColorTween _iconColorTween = ColorTween(); final ColorTween _backgroundColorTween = ColorTween(); - AnimationController _controller; - Animation _iconTurns; - Animation _heightFactor; + late AnimationController _controller; + late Animation _iconTurns; + late Animation _heightFactor; bool _isExpanded = false; - Widget arrowIcon; + late Widget arrowIcon; @override void initState() { @@ -163,10 +164,10 @@ class _ExpansionElementState extends State PageStorage.of(context)?.writeState(context, _isExpanded); }); if (widget.onExpansionChanged != null) - widget.onExpansionChanged(_isExpanded); + widget.onExpansionChanged!(_isExpanded); } - Widget _buildHeader(BuildContext context, Widget child) { + Widget _buildHeader(BuildContext context, Widget? child) { final Color borderSideColor = /*_borderColor.value ??*/ Colors.transparent; final Color backgroundColor = /*_backgroundColor.value ??*/ Colors .transparent; @@ -198,9 +199,9 @@ class _ExpansionElementState extends State Container( padding: EdgeInsets.only(right: 6), child: Text( - widget.title ?? "", + widget.title, style: BrnFormUtil.getHeadTitleTextStyle( - widget.themeData, + widget.themeData!, isBold: true), )), RotationTransition( @@ -216,7 +217,7 @@ class _ExpansionElementState extends State child: GestureDetector( onTap: () { if (widget.callback != null) { - widget.callback(); + widget.callback!(); } }, child: Container( @@ -225,7 +226,7 @@ class _ExpansionElementState extends State widget.deleteText ?? "", style: TextStyle( color: Color(0xFFFA3F3F), - fontSize: BrnFont.FONT_16, + fontSize: BrnFonts.f16, ), ), ), @@ -241,10 +242,10 @@ class _ExpansionElementState extends State alignment: Alignment.centerLeft, padding: EdgeInsets.only(left: 20, top: 4, bottom: 14), child: Offstage( - offstage: (widget.subtitle == null || widget.subtitle.isEmpty), + offstage: (widget.subtitle == null || widget.subtitle!.isEmpty), child: Text( widget.subtitle ?? "", - style: BrnFormUtil.getSubTitleTextStyle(widget.themeData), + style: BrnFormUtil.getSubTitleTextStyle(widget.themeData!), ), ), ), @@ -271,8 +272,8 @@ class _ExpansionElementState extends State /// title 文字颜色 _headerColorTween - ..begin = theme.textTheme.subtitle1.color - ..end = theme.textTheme.subtitle1.color; + ..begin = theme.textTheme.subtitle1!.color + ..end = theme.textTheme.subtitle1!.color; /// 展开收起图标颜色 _iconColorTween diff --git a/lib/src/components/form/items/misc/brn_add_label_item.dart b/lib/src/components/form/items/misc/brn_add_label_item.dart index 87981746..731c179d 100644 --- a/lib/src/components/form/items/misc/brn_add_label_item.dart +++ b/lib/src/components/form/items/misc/brn_add_label_item.dart @@ -1,19 +1,19 @@ + + import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; -import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; /// 添加组类型录入项所使用的Widget // ignore: must_be_immutable class BrnAddLabel extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.LABEL_ADD; + final String type = BrnInputItemType.labelAdd; /// 标题文案 final String title; @@ -22,15 +22,15 @@ class BrnAddLabel extends StatefulWidget { final bool isEdit; /// 点击录入区回调 - final VoidCallback onTap; + final VoidCallback? onTap; BrnAddLabel({ - Key key, + Key? key, this.label, - this.title: "", - this.isEdit: true, + this.title = "", + this.isEdit = true, this.onTap, - }); + }) : super(key: key); @override BrnAddLabelState createState() { @@ -53,13 +53,13 @@ class BrnAddLabelState extends State { color: Colors.white, padding: EdgeInsets.fromLTRB(20, 15, 0, 15), child: Text( - widget.title ?? "", + widget.title, style: TextStyle( color: BrnThemeConfigurator.instance .getConfig() .commonConfig .brandPrimary, - fontSize: BrnFont.FONT_18, + fontSize: BrnFonts.f18, ), ), ), diff --git a/lib/src/components/form/items/misc/brn_title_item.dart b/lib/src/components/form/items/misc/brn_title_item.dart index fe024075..a3d77a21 100644 --- a/lib/src/components/form/items/misc/brn_title_item.dart +++ b/lib/src/components/form/items/misc/brn_title_item.dart @@ -2,7 +2,7 @@ import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -10,23 +10,23 @@ import 'package:flutter/widgets.dart'; // ignore: must_be_immutable class BrnTitleFormItem extends StatefulWidget { /// 录入项的唯一标识,主要用于录入类型页面框架中 - final String label; + final String? label; /// 录入项类型,主要用于录入类型页面框架中 - String type = BrnInputItemType.LABEL_TITLE; + final String type = BrnInputItemType.labelTitle; /// 录入项标题 final String title; /// 录入项子标题 - final String subTitle; + final String? subTitle; /// 录入项提示(问号图标&文案) 用户点击时触发onTip回调。 /// 1. 若赋值为 空字符串("")时仅展示"问号"图标, /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 录入项前缀图标样式 "添加项" "删除项" 详见 PrefixIconType类 final String prefixIconType; @@ -41,27 +41,27 @@ class BrnTitleFormItem extends StatefulWidget { final bool isRequire; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 点击操作区标识 - final String operationLabel; + final String? operationLabel; /// 点击回调 - final VoidCallback onTap; + final VoidCallback? onTap; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnTitleFormItem( - {Key key, + {Key? key, this.label, - this.title: "", + this.title = "", this.subTitle, this.tipLabel, - this.prefixIconType: BrnPrefixIconType.TYPE_NORMAL, - this.error: "", - this.isEdit: true, - this.isRequire: false, + this.prefixIconType = BrnPrefixIconType.normal, + this.error = "", + this.isEdit = true, + this.isRequire = false, this.onTip, this.operationLabel, this.onTap, @@ -69,7 +69,7 @@ class BrnTitleFormItem extends StatefulWidget { : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -85,7 +85,7 @@ class BrnTitleFormItemState extends State { Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -98,20 +98,20 @@ class BrnTitleFormItemState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsets(widget.prefixIconType, - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ // 主标题 Container( child: Text( - widget.title ?? "", + widget.title, style: - BrnFormUtil.getHeadTitleTextStyle(widget.themeData), + BrnFormUtil.getHeadTitleTextStyle(widget.themeData!), )), // 问号提示 BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -132,8 +132,8 @@ class BrnTitleFormItemState extends State { child: Text( widget.operationLabel ?? "", style: TextStyle( - color: widget.themeData.commonConfig.brandPrimary, - fontSize: BrnFont.FONT_16, + color: widget.themeData!.commonConfig.brandPrimary, + fontSize: BrnFonts.f16, ), )), ), @@ -143,10 +143,10 @@ class BrnTitleFormItemState extends State { ), // 副标题 - BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData), + BrnFormUtil.buildSubTitleWidget(widget.subTitle, widget.themeData!), // 错误提示 - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); diff --git a/lib/src/components/form/items/title/brn_base_title_item.dart b/lib/src/components/form/items/title/brn_base_title_item.dart index b03187ac..90a1ba0a 100644 --- a/lib/src/components/form/items/title/brn_base_title_item.dart +++ b/lib/src/components/form/items/title/brn_base_title_item.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; @@ -16,7 +18,7 @@ class BrnBaseTitle extends StatefulWidget { final String title; /// 子标题 - final String subTitle; + final String? subTitle; /// 是否必填项 final bool isRequire; @@ -32,40 +34,40 @@ class BrnBaseTitle extends StatefulWidget { /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 标题Widget - final Widget titleWidget; + final Widget? titleWidget; /// 子标题Widget - final Widget subTitleWidget; + final Widget? subTitleWidget; /// 右侧自定义操作区 - final Widget customActionWidget; + final Widget? customActionWidget; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnBaseTitle({ - Key key, - this.title: "", + Key? key, + this.title= "", this.subTitle, - this.isRequire: false, - this.isEdit: true, - this.error: "", + this.isRequire= false, + this.isEdit= true, + this.error= "", this.tipLabel, this.titleWidget, this.subTitleWidget, this.customActionWidget, this.onTip, this.themeData, - }) { + }) : super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -86,7 +88,7 @@ class BrnTitleState extends State { Widget build(BuildContext context) { return Container( color: Colors.white, - padding: BrnFormUtil.itemEdgeInsets(widget.themeData), + padding: BrnFormUtil.itemEdgeInsets(widget.themeData!), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -99,7 +101,7 @@ class BrnTitleState extends State { children: [ Container( padding: BrnFormUtil.titleEdgeInsetsForHead( - widget.isRequire, widget.themeData), + widget.isRequire, widget.themeData!), child: Row( children: [ // 必填项符号 @@ -110,7 +112,7 @@ class BrnTitleState extends State { // 问号提示 BrnFormUtil.buildTipLabelWidget( - widget.tipLabel, widget.onTip, widget.themeData), + widget.tipLabel, widget.onTip, widget.themeData!), ], ), ), @@ -126,12 +128,12 @@ class BrnTitleState extends State { // 副标题 Offstage( - offstage: (widget.subTitle == null || widget.subTitle.isEmpty), + offstage: (widget.subTitle == null || widget.subTitle!.isEmpty), child: getSubTitleWidget(), ), // 错误提示 - BrnFormUtil.buildErrorWidget(widget.error, widget.themeData) + BrnFormUtil.buildErrorWidget(widget.error, widget.themeData!) ], ), ); @@ -139,24 +141,24 @@ class BrnTitleState extends State { Widget getTitleWidget() { if (widget.titleWidget != null) { - return widget.titleWidget; + return widget.titleWidget!; } else { - return BrnFormUtil.buildTitleWidget(widget.title, widget.themeData); + return BrnFormUtil.buildTitleWidget(widget.title, widget.themeData!); } } Widget getSubTitleWidget() { if (widget.subTitleWidget != null) { return Container( - padding: BrnFormUtil.subTitleEdgeInsets(widget.themeData), + padding: BrnFormUtil.subTitleEdgeInsets(widget.themeData!), child: widget.subTitleWidget, ); } else { return Container( - padding: BrnFormUtil.subTitleEdgeInsets(widget.themeData), + padding: BrnFormUtil.subTitleEdgeInsets(widget.themeData!), child: Text( widget.subTitle ?? "", - style: BrnFormUtil.getSubTitleTextStyle(widget.themeData), + style: BrnFormUtil.getSubTitleTextStyle(widget.themeData!), )); } } diff --git a/lib/src/components/form/items/title/brn_select_all_title_item.dart b/lib/src/components/form/items/title/brn_select_all_title_item.dart index 36a45110..9f1c804b 100644 --- a/lib/src/components/form/items/title/brn_select_all_title_item.dart +++ b/lib/src/components/form/items/title/brn_select_all_title_item.dart @@ -2,7 +2,6 @@ import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/components/form/items/title/brn_base_title_item.dart'; import 'package:bruno/src/components/form/utils/brn_form_util.dart'; import 'package:bruno/src/components/radio/brn_checkbox.dart'; -import 'package:bruno/src/components/radio/brn_radio_core.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/widgets.dart'; @@ -17,7 +16,7 @@ class BrnSelectAllTitle extends StatefulWidget { final String title; /// 子标题 - final String subTitle; + final String? subTitle; /// 是否必填项 final bool isRequire; @@ -33,42 +32,42 @@ class BrnSelectAllTitle extends StatefulWidget { /// 2. 若赋值为非空字符串时 展示"问号图标&文案", /// 3. 若不赋值或赋值为null时 不显示提示项 /// 默认值为 3 - final String tipLabel; + final String? tipLabel; /// 标题Widget - final Widget titleWidget; + final Widget? titleWidget; /// 子标题Widget - final Widget subTitleWidget; + final Widget? subTitleWidget; /// 右侧自定义操作区 - final Widget customActionWidget; + final Widget? customActionWidget; /// 点击"?"图标回调 - final VoidCallback onTip; + final VoidCallback? onTip; /// 全选状态回调 - final OnBrnFormSelectAll onSelectAll; + final OnBrnFormSelectAll? onSelectAll; /// 选中项文案 - final String selectText; + final String? selectText; /// 选中项Widget - final Widget selectTextWidget; + final Widget? selectTextWidget; /// 选中项状态 - bool selectState; + final bool selectState; /// form配置 - BrnFormItemConfig themeData; + BrnFormItemConfig? themeData; BrnSelectAllTitle({ - Key key, - this.title: "", + Key? key, + this.title = "", this.subTitle, - this.isRequire: false, - this.isEdit: true, - this.error: "", + this.isRequire = false, + this.isEdit = true, + this.error = "", this.tipLabel, this.titleWidget, this.subTitleWidget, @@ -76,13 +75,13 @@ class BrnSelectAllTitle extends StatefulWidget { this.onSelectAll, this.selectText, this.selectTextWidget, - this.selectState: true, + this.selectState = true, this.themeData, this.customActionWidget, - }) { + }):super(key: key) { this.themeData ??= BrnFormItemConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .formItemConfig .merge(this.themeData); } @@ -94,16 +93,18 @@ class BrnSelectAllTitle extends StatefulWidget { } class BrnSelectAllTitleState extends State { + late bool _selectState; + @override void initState() { super.initState(); + _selectState = widget.selectState; } @override void didUpdateWidget(BrnSelectAllTitle oldWidget) { super.didUpdateWidget(oldWidget); - - widget.selectState = oldWidget.selectState; + _selectState = oldWidget.selectState; } @override @@ -121,16 +122,16 @@ class BrnSelectAllTitleState extends State { child: getSelectTextWidget(), radioIndex: 0, disable: !widget.isEdit, - isSelected: widget.selectState, + isSelected: _selectState, onValueChangedAtIndex: (position, value) { - if (widget.isEdit != null && !widget.isEdit) { + if (!widget.isEdit) { return; } - widget.selectState = value; + _selectState = value; if (widget.onSelectAll != null) { - widget.onSelectAll(position, value); + widget.onSelectAll!(position, value); } }, ), @@ -138,7 +139,7 @@ class BrnSelectAllTitleState extends State { ); } - Widget getSelectTextWidget() { + Widget? getSelectTextWidget() { if (widget.selectTextWidget != null) { return widget.selectTextWidget; } else { @@ -151,13 +152,13 @@ class BrnSelectAllTitleState extends State { } } - TextStyle getOptionTextStyle(BrnFormItemConfig themeData) { - if (widget.selectState) { - return BrnFormUtil.getOptionSelectedTextStyle(widget.themeData); + TextStyle getOptionTextStyle(BrnFormItemConfig? themeData) { + if (_selectState) { + return BrnFormUtil.getOptionSelectedTextStyle(widget.themeData!); } - if (widget.isEdit != null && !widget.isEdit) { - return BrnFormUtil.getIsEditTextStyle(widget.themeData, widget.isEdit); + if (!widget.isEdit) { + return BrnFormUtil.getIsEditTextStyle(widget.themeData!, widget.isEdit); } - return BrnFormUtil.getOptionTextStyle(widget.themeData); + return BrnFormUtil.getOptionTextStyle(widget.themeData!); } } diff --git a/lib/src/components/form/utils/brn_form_util.dart b/lib/src/components/form/utils/brn_form_util.dart index b15c7c33..5ae9d8c7 100644 --- a/lib/src/components/form/utils/brn_form_util.dart +++ b/lib/src/components/form/utils/brn_form_util.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/form/base/brn_form_item_type.dart'; import 'package:bruno/src/components/form/base/input_item_interface.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; @@ -12,9 +14,9 @@ class BrnFormUtil { /// 获取添加、删除图标 static Widget buildPrefixIcon(String prefixIconType, bool isEdit, - BuildContext context, VoidCallback onAddTap, VoidCallback onRemoveTap) { + BuildContext context, VoidCallback? onAddTap, VoidCallback? onRemoveTap) { return Offstage( - offstage: prefixIconType == BrnPrefixIconType.TYPE_NORMAL, + offstage: prefixIconType == BrnPrefixIconType.normal, child: Container( padding: EdgeInsets.only(right: 6), child: GestureDetector( @@ -37,9 +39,9 @@ class BrnFormUtil { return Container( padding: errorEdgeInsets(themeData), child: Offstage( - offstage: (error == null || error.isEmpty), + offstage: (error.isEmpty), child: Text( - error ?? "", + error, style: getErrorTextStyle(themeData), )), ); @@ -47,7 +49,7 @@ class BrnFormUtil { /// 获取子标题Widget static Widget buildSubTitleWidget( - String subTitle, BrnFormItemConfig themeData) { + String? subTitle, BrnFormItemConfig themeData) { return Offstage( offstage: (subTitle == null || subTitle.isEmpty), child: Container( @@ -62,14 +64,14 @@ class BrnFormUtil { /// 获取必填项 static Widget buildRequireWidget(bool isRequire) { return Offstage( - offstage: (isRequire == null || !isRequire), + offstage: (!isRequire), child: BrnFormUtil.getRequireIcon(isRequire), ); } /// 获取问号 static Widget buildTipLabelWidget( - String tipLabel, VoidCallback onTip, BrnFormItemConfig themeData) { + String? tipLabel, VoidCallback? onTip, BrnFormItemConfig themeData) { return Offstage( offstage: (tipLabel == null), child: GestureDetector( @@ -100,31 +102,28 @@ class BrnFormUtil { static Widget buildTitleWidget(String title, BrnFormItemConfig themeData) { return Container( child: Text( - title ?? "", + title, style: BrnFormUtil.getTitleTextStyle(themeData), )); } /// 录入项是否可编辑 static bool isEdit(bool isEdit) { - if (isEdit == null) { - return true; - } return isEdit; } static Widget getPrefixIcon(String type) { - if (type == BrnPrefixIconType.TYPE_ADD) { - return BrunoTools.getAssetImageWithBandColor(BrnAsset.ICON_ADD_FORM_ITEM); - } else if (type == BrnPrefixIconType.TYPE_REMOVE) { - return BrunoTools.getAssetImage(BrnAsset.ICON_REMOVE_FORM_ITEM); + if (type == BrnPrefixIconType.add) { + return BrunoTools.getAssetImageWithBandColor(BrnAsset.iconAddFormItem); + } else if (type == BrnPrefixIconType.remove) { + return BrunoTools.getAssetImage(BrnAsset.iconRemoveFormItem); } else { return Container(); } } static Widget getPrefixIconWithDisable(String type, bool isEnabled) { - return (isEnabled ?? true) + return (isEnabled) ? BrnFormUtil.getPrefixIcon(type) : ColorFiltered( colorFilter: ColorFilter.mode( @@ -138,13 +137,12 @@ class BrnFormUtil { } static Widget getRequireIcon(bool isRequire) { - isRequire ??= false; return Container( padding: isRequire ? EdgeInsets.only(right: 2) : EdgeInsets.only(right: 0), child: isRequire - ? BrunoTools.getAssetSizeImage(BrnAsset.ICON_REQUIRE_RED, 8, 8, + ? BrunoTools.getAssetSizeImage(BrnAsset.iconRequireRed, 8, 8, color: Color(0xFFFA3F3F)) : null, ); @@ -153,23 +151,21 @@ class BrnFormUtil { /// 视觉同学要求修改右箭头图标 static Image getRightArrowIcon() { return BrunoTools.getAssetSizeImage( - BrnAsset.ICON_RIGHT_ARROW, rightArrowSize, rightArrowSize); + BrnAsset.iconRightArrow, rightArrowSize, rightArrowSize); } static Image getQuestionMarkIcon() { - return BrunoTools.getAssetImage(BrnAsset.ICON_QUESTION); + return BrunoTools.getAssetImage(BrnAsset.iconQuestion); } /// 设置录入项总的padding, 不包括顶部和底部padding static EdgeInsets computeItemEdgeInsets2(String type, bool isRequire) { - isRequire ??= false; return EdgeInsets.fromLTRB(0, 0, 20, 14); } /// 设置内容行padding, 包括顶部和底部padding static EdgeInsets computeEdgeInsets2(String type, bool isRequire) { - isRequire ??= false; - if (isRequire && type == BrnPrefixIconType.TYPE_NORMAL) { + if (isRequire && type == BrnPrefixIconType.normal) { return EdgeInsets.only(left: 10, top: 14); } @@ -177,14 +173,13 @@ class BrnFormUtil { } static EdgeInsets computeErrorEdgeInsets(String type, bool isRequire) { - isRequire ??= false; return EdgeInsets.only( left: 20, top: 4, ); } - static TextInputType getInputType(String type) { + static TextInputType getInputType(String? type) { TextInputType inputType = TextInputType.text; if (type == null || type.isEmpty) { @@ -192,31 +187,31 @@ class BrnFormUtil { } switch (type) { - case BrnInputType.TEXT: + case BrnInputType.text: inputType = TextInputType.text; break; - case BrnInputType.MULTI_LINE: + case BrnInputType.multiLine: inputType = TextInputType.multiline; break; - case BrnInputType.NUMBER: + case BrnInputType.number: inputType = TextInputType.number; break; - case BrnInputType.DECIMAL: + case BrnInputType.decimal: inputType = TextInputType.numberWithOptions(decimal: true); break; - case BrnInputType.PHONE: + case BrnInputType.phone: inputType = TextInputType.phone; break; - case BrnInputType.DATE: + case BrnInputType.date: inputType = TextInputType.datetime; break; - case BrnInputType.EMAIL: + case BrnInputType.email: inputType = TextInputType.emailAddress; break; - case BrnInputType.URL: + case BrnInputType.url: inputType = TextInputType.url; break; - case BrnInputType.PWD: + case BrnInputType.pwd: inputType = TextInputType.visiblePassword; break; default: @@ -232,12 +227,12 @@ class BrnFormUtil { /// 处理点击"添加/删除"按钮动作 static void notifyAddRemoveTap(BuildContext context, String prefixIconType, - VoidCallback onAddTap, VoidCallback onRemoveTap) { - if (BrnPrefixIconType.TYPE_ADD == prefixIconType) { + VoidCallback? onAddTap, VoidCallback? onRemoveTap) { + if (BrnPrefixIconType.add == prefixIconType) { if (onAddTap != null) { onAddTap(); } - } else if (BrnPrefixIconType.TYPE_REMOVE == prefixIconType) { + } else if (BrnPrefixIconType.remove == prefixIconType) { if (onRemoveTap != null) { onRemoveTap(); } @@ -245,21 +240,21 @@ class BrnFormUtil { } /// 处理点击"添加/删除"按钮动作 - static void notifyAddTap(BuildContext context, VoidCallback onAddTap) { + static void notifyAddTap(BuildContext context, VoidCallback? onAddTap) { if (onAddTap != null) { onAddTap(); } } /// 处理点击"添加/删除"按钮动作 - static void notifyRemoveTap(BuildContext context, VoidCallback onRemoveTap) { + static void notifyRemoveTap(BuildContext context, VoidCallback? onRemoveTap) { if (onRemoveTap != null) { onRemoveTap(); } } /// 处理点击"按钮"动作 - static void notifyTap(BuildContext context, VoidCallback onWidgetTap) { + static void notifyTap(BuildContext context, VoidCallback? onWidgetTap) { if (onWidgetTap != null) { onWidgetTap(); } @@ -267,14 +262,14 @@ class BrnFormUtil { /// 处理 输入状态 变化 static void notifyInputChanged( - ValueChanged onTextChanged, String newStr) { + ValueChanged? onTextChanged, String newStr) { if (onTextChanged != null) { onTextChanged(/*oldStr, */ newStr); } } /// 处理 开关 变化 - static void notifySwitchChanged(OnBrnFormSwitchChanged onSwitchChanged, + static void notifySwitchChanged(OnBrnFormSwitchChanged? onSwitchChanged, BuildContext context, bool oldValue, bool newValue) { if (onSwitchChanged != null) { onSwitchChanged(oldValue, newValue); @@ -282,7 +277,7 @@ class BrnFormUtil { } /// 处理 数字值 变化 - static void notifyValueChanged(OnBrnFormValueChanged onValueChanged, + static void notifyValueChanged(OnBrnFormValueChanged? onValueChanged, BuildContext context, int oldVal, int newVal) { if (onValueChanged != null) { onValueChanged(oldVal, newVal); @@ -290,19 +285,19 @@ class BrnFormUtil { } /// 处理 单选选中状态变化 - static void notifyRadioStatusChanged(OnBrnFormRadioValueChanged onTextChanged, - BuildContext context, Object oldVal, Object newVal) { + static void notifyRadioStatusChanged(OnBrnFormRadioValueChanged? onTextChanged, + BuildContext context, Object? oldVal, Object? newVal) { if (onTextChanged != null) { - onTextChanged(oldVal, newVal); + onTextChanged(oldVal as String?, newVal as String?); } } /// 处理 多选选中状态变化 static void notifyMultiChoiceStatusChanged( - OnBrnFormMultiChoiceValueChanged onChoiceChanged, + OnBrnFormMultiChoiceValueChanged? onChoiceChanged, BuildContext context, - Object oldVal, - Object newVal, + List oldVal, + List newVal, ) { if (onChoiceChanged != null) { onChoiceChanged(oldVal, newVal); @@ -314,45 +309,43 @@ class BrnFormUtil { /// /// 选项之间的间距 - static EdgeInsets optionsMiddlePadding(BrnFormItemConfig themeData) { - return themeData?.optionsMiddlePadding; + static EdgeInsets? optionsMiddlePadding(BrnFormItemConfig themeData) { + return themeData.optionsMiddlePadding; } /// 走主题配置 上下右间距 static EdgeInsets itemEdgeInsets(BrnFormItemConfig themeData) { - return themeData?.formPadding; + return themeData.formPadding; } /// 标题行的左间距 static EdgeInsets titleEdgeInsets( String type, bool isRequire, BrnFormItemConfig themeData) { - isRequire ??= false; - if (isRequire && type == BrnPrefixIconType.TYPE_NORMAL) { - return themeData?.titlePaddingSm; + if (isRequire && type == BrnPrefixIconType.normal) { + return themeData.titlePaddingSm; } - return themeData?.titlePaddingLg; + return themeData.titlePaddingLg; } /// 标题行的左间距 static EdgeInsets titleEdgeInsetsForHead( bool isRequire, BrnFormItemConfig themeData) { - isRequire ??= false; - return isRequire ? themeData?.titlePaddingSm : themeData?.titlePaddingLg; + return isRequire ? themeData.titlePaddingSm : themeData.titlePaddingLg; } /// 子标题的右上间距 static EdgeInsets subTitleEdgeInsets(BrnFormItemConfig themeData) { - return themeData?.subTitlePadding; + return themeData.subTitlePadding; } /// error的右上间距 static EdgeInsets errorEdgeInsets(BrnFormItemConfig themeData) { - return themeData?.errorPadding; + return themeData.errorPadding; } /// 提示文本样式 static TextStyle getTipsTextStyle(BrnFormItemConfig themeData) { - return themeData?.tipsTextStyle?.generateTextStyle(); + return themeData.tipsTextStyle.generateTextStyle(); } /// 获取 右侧 输入、选择默认文本样式 @@ -360,28 +353,27 @@ class BrnFormUtil { {double height = 0}) { if (height > 0) { return BrnTextStyle(height: height) - .merge(themeData?.hintTextStyle) - ?.generateTextStyle(); + .merge(themeData.hintTextStyle) + .generateTextStyle(); } - return themeData?.hintTextStyle?.generateTextStyle(); + return themeData.hintTextStyle.generateTextStyle(); } /// 获取是否可编辑的字体 static TextStyle getIsEditTextStyle(BrnFormItemConfig themeData, bool isEdit, {double height = 0}) { - isEdit ??= true; if (height > 0) { return isEdit ? BrnTextStyle(height: height) - .merge(themeData?.contentTextStyle) - ?.generateTextStyle() + .merge(themeData.contentTextStyle) + .generateTextStyle() : BrnTextStyle(height: height) - .merge(themeData?.disableTextStyle) - ?.generateTextStyle(); + .merge(themeData.disableTextStyle) + .generateTextStyle(); } return isEdit - ? themeData?.contentTextStyle?.generateTextStyle() - : themeData?.disableTextStyle?.generateTextStyle(); + ? themeData.contentTextStyle.generateTextStyle() + : themeData.disableTextStyle.generateTextStyle(); } /// 获取标题文本样式 @@ -389,41 +381,41 @@ class BrnFormUtil { {double height = 0}) { if (height > 0) { return BrnTextStyle(height: height) - .merge(themeData?.titleTextStyle) - ?.generateTextStyle(); + .merge(themeData.titleTextStyle) + .generateTextStyle(); } - return themeData?.titleTextStyle?.generateTextStyle(); + return themeData.titleTextStyle.generateTextStyle(); } /// 获取标题文本样式 static TextStyle getHeadTitleTextStyle(BrnFormItemConfig themeData, {bool isBold = false}) { if (isBold) { - return themeData?.headTitleTextStyle - ?.merge(BrnTextStyle(fontWeight: FontWeight.w600)) - ?.generateTextStyle(); + return themeData.headTitleTextStyle + .merge(BrnTextStyle(fontWeight: FontWeight.w600)) + .generateTextStyle(); } - return themeData?.headTitleTextStyle?.generateTextStyle(); + return themeData.headTitleTextStyle.generateTextStyle(); } /// 获取左侧辅助样式 static TextStyle getSubTitleTextStyle(BrnFormItemConfig themeData) { - return themeData?.subTitleTextStyle?.generateTextStyle(); + return themeData.subTitleTextStyle.generateTextStyle(); } /// 获取error 文本样式 static TextStyle getErrorTextStyle(BrnFormItemConfig themeData) { - return themeData?.errorTextStyle?.generateTextStyle(); + return themeData.errorTextStyle.generateTextStyle(); } /// 获取选项文本样式 static TextStyle getOptionTextStyle(BrnFormItemConfig themeData) { - return themeData?.optionTextStyle?.generateTextStyle(); + return themeData.optionTextStyle.generateTextStyle(); } /// 获取选中选项文本样式 static TextStyle getOptionSelectedTextStyle(BrnFormItemConfig themeData) { - return themeData?.optionSelectedTextStyle?.generateTextStyle(); + return themeData.optionSelectedTextStyle.generateTextStyle(); } /// @@ -443,7 +435,7 @@ class BrnFormUtil { /// 当左右内容超出默认比例且「无」提示语,则按比例 4:6 布局 /// 有用户自定义比例时用用户自定义比例 static double getAutoLayoutContentRatio( - {bool tipLabelHidden, double layoutRatio}) { + {required bool tipLabelHidden, double? layoutRatio}) { double defaultRatio = tipLabelHidden ? BrnFormUtil.contentRatio : 1 - BrnFormUtil.contentRatio; diff --git a/lib/src/components/gallery/config/brn_basic_gallery_config.dart b/lib/src/components/gallery/config/brn_basic_gallery_config.dart index 73e00487..f7eb3871 100644 --- a/lib/src/components/gallery/config/brn_basic_gallery_config.dart +++ b/lib/src/components/gallery/config/brn_basic_gallery_config.dart @@ -1,27 +1,27 @@ import 'package:flutter/material.dart'; abstract class BrnBasicGroupConfig { - //每一个组的标题 - String title; + /// 每一个组的标题 + String? title; - List configList; + List? configList; - BrnBasicGroupConfig({this.title, @required this.configList}); + BrnBasicGroupConfig({this.title, required this.configList}); } -//每一个item的配置接口,定制化的需求可以自己实现相关接口 +/// 每一个 item 的配置接口,定制化的需求可以自己实现相关接口 abstract class BrnBasicItemConfig { - //该配置的groupIndex - int groupIndex; + /// 该配置的 groupIndex + int? groupIndex; - //改配置的type信息 - String type; + /// 该配置的 type 信息 + String? type; - //构建查看详情页的widget + /// 构建查看详情页的 widget Widget buildDetailWidget(BuildContext context, List allConfig, int groupId, int index); - //构建简略页的widget + /// 构建简略页的 widget Widget buildSummaryWidget(BuildContext context, List allConfig, int groupId, int index); } diff --git a/lib/src/components/gallery/config/brn_bottom_card.dart b/lib/src/components/gallery/config/brn_bottom_card.dart index ca8ff2ea..e811c5bb 100644 --- a/lib/src/components/gallery/config/brn_bottom_card.dart +++ b/lib/src/components/gallery/config/brn_bottom_card.dart @@ -5,21 +5,21 @@ import 'package:bruno/src/theme/configs/brn_gallery_detail_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; -/// fold 收起状态 -/// unfold 展开状态 -/// cantFold 不可折叠的状态,描述信息直接展开 +/// [fold] 收起状态 +/// [unfold] 展开状态 +/// [cantFold] 不可折叠的状态,描述信息直接展开 enum PhotoBottomCardState { fold, unFold, cantFold } // ignore: must_be_immutable class BrnPhotoBottomCard extends StatefulWidget { - final String name; - final String des; + final String? name; + final String? des; final PhotoBottomCardState model; final double contentHeight; - BrnGalleryDetailConfig themeData; + BrnGalleryDetailConfig? themeData; BrnPhotoBottomCard( - {Key key, + {Key? key, this.name, this.des, this.model = PhotoBottomCardState.cantFold, @@ -33,7 +33,7 @@ class BrnPhotoBottomCard extends StatefulWidget { class _BrnPhotoBottomCardState extends State with TickerProviderStateMixin { - PhotoBottomCardState state; + PhotoBottomCardState? state; @override void initState() { @@ -45,14 +45,14 @@ class _BrnPhotoBottomCardState extends State Widget build(BuildContext context) { return Container( width: double.infinity, - color: widget.themeData.bottomBackgroundColor, + color: widget.themeData!.bottomBackgroundColor, child: state == PhotoBottomCardState.cantFold ? buildCantFoldWidget() : buildFoldableWidget(), ); } - //构建可折叠的card + /// 构建可折叠的card Widget buildFoldableWidget() { if (state == PhotoBottomCardState.fold) { return Container( @@ -62,7 +62,7 @@ class _BrnPhotoBottomCardState extends State mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(widget.name ?? "", - style: widget.themeData.titleStyle?.generateTextStyle()), + style: widget.themeData!.titleStyle.generateTextStyle()), GestureDetector( onTap: () { setState(() { @@ -76,12 +76,12 @@ class _BrnPhotoBottomCardState extends State padding: EdgeInsets.only(right: 4), child: Text('展开', style: - widget.themeData.actionStyle?.generateTextStyle()), + widget.themeData!.actionStyle.generateTextStyle()), ), Transform.rotate( angle: pi, child: BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_UPARROW, widget.themeData.iconColor), + BrnAsset.iconUpArrow, widget.themeData!.iconColor), ) ], ), @@ -100,7 +100,7 @@ class _BrnPhotoBottomCardState extends State mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text(widget.name ?? "", - style: widget.themeData.titleStyle?.generateTextStyle()), + style: widget.themeData!.titleStyle.generateTextStyle()), GestureDetector( onTap: () { setState(() { @@ -113,11 +113,11 @@ class _BrnPhotoBottomCardState extends State Padding( padding: EdgeInsets.only(right: 4), child: Text('收起', - style: widget.themeData.actionStyle - ?.generateTextStyle()), + style: widget.themeData!.actionStyle + .generateTextStyle()), ), BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_UPARROW, widget.themeData.iconColor) + BrnAsset.iconUpArrow, widget.themeData!.iconColor) ], ), ) @@ -126,7 +126,7 @@ class _BrnPhotoBottomCardState extends State ), Text( widget.des ?? "", - style: widget.themeData.contentStyle?.generateTextStyle(), + style: widget.themeData!.contentStyle.generateTextStyle(), ) ], ), @@ -134,7 +134,7 @@ class _BrnPhotoBottomCardState extends State } } - //构建不可折叠的card,content是一个ScrollView + /// 构建不可折叠的 card, content 是一个 ScrollView Widget buildCantFoldWidget() { return Column( mainAxisAlignment: MainAxisAlignment.start, @@ -146,18 +146,18 @@ class _BrnPhotoBottomCardState extends State padding: EdgeInsets.only(top: 16, bottom: 12, left: 20, right: 20), child: Text( widget.name ?? "", - style: widget.themeData.titleStyle?.generateTextStyle(), + style: widget.themeData!.titleStyle.generateTextStyle(), ), ), ), Container( - height: widget.contentHeight ?? 150, + height: widget.contentHeight, child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: Padding( child: Text( widget.des ?? "", - style: widget.themeData.contentStyle?.generateTextStyle(), + style: widget.themeData!.contentStyle.generateTextStyle(), ), padding: EdgeInsets.only(left: 20, right: 20)), )) diff --git a/lib/src/components/gallery/config/brn_controller.dart b/lib/src/components/gallery/config/brn_controller.dart index 685de414..fffb4c9f 100644 --- a/lib/src/components/gallery/config/brn_controller.dart +++ b/lib/src/components/gallery/config/brn_controller.dart @@ -1,3 +1,5 @@ + + import 'package:flutter/material.dart'; /// 控制页面刷新,并跳转到指定的 index @@ -9,7 +11,6 @@ class BrnGalleryController extends ChangeNotifier { /// [groupId] 第几组图片 /// [indexId] 组内的第几张 void refresh(int groupId, int indexId) { - assert(groupId != null && indexId != null); this.groupId = groupId; this.indexId = indexId; notifyListeners(); diff --git a/lib/src/components/gallery/config/brn_photo_gallery_config.dart b/lib/src/components/gallery/config/brn_photo_gallery_config.dart index e7c1542f..0a7f8e9a 100644 --- a/lib/src/components/gallery/config/brn_photo_gallery_config.dart +++ b/lib/src/components/gallery/config/brn_photo_gallery_config.dart @@ -8,61 +8,71 @@ import 'package:flutter/material.dart'; import 'package:photo_view/photo_view.dart'; class BrnPhotoGroupConfig extends BrnBasicGroupConfig { - final List urls; - final String title; - List configList; - final BrnGalleryDetailConfig themeData; - - //通过url列表生成配置 - BrnPhotoGroupConfig.url({this.title, @required this.urls, this.themeData}) { - configList = List(); - urls.forEach((item) => - configList.add(BrnPhotoItemConfig(url: item, themeData: themeData))); - } - - //自定义配置列表 - BrnPhotoGroupConfig({this.urls, this.title, this.configList, this.themeData}); + final List? urls; + final String? title; + final BrnGalleryDetailConfig? themeData; + + /// 通过 [urls] 列表生成配置 + BrnPhotoGroupConfig.url( + {this.title, + required this.urls, + this.themeData, + List? configList}) + : super( + title: title, + configList: urls + ?.map((item) => + BrnPhotoItemConfig(url: item, themeData: themeData)) + .toList()); + + /// 自定义配置列表 + BrnPhotoGroupConfig( + {this.urls, + this.title, + List? configList, + this.themeData}) + : super(title: title, configList: configList); } -//图片类的配置 +/// 图片类的配置 class BrnPhotoItemConfig extends BrnBasicItemConfig { - //图片url + /// 图片url final String url; - //图片的展示模式 + /// 图片的展示模式 final BoxFit fit; - //展位图 + /// 占位图 final String placeHolder; - //图片名称 用于详情页展示 - final String name; + /// 图片名称 用于详情页展示 + final String? name; - //图片描述公 用于详情页展示 - final String des; + /// 图片描述公 用于详情页展示 + final String? des; - //详情页图片点击回调 - final VoidCallback onTap; + /// 详情页图片点击回调 + final VoidCallback? onTap; - //详情页双击回调 - final VoidCallback onDoubleTap; + /// 详情页双击回调 + final VoidCallback? onDoubleTap; - //详情页长按回调 - final VoidCallback onLongPress; + /// 详情页长按回调 + final VoidCallback? onLongPress; - //详情页是否展示底部卡片,需要提供name和des信息 + /// 详情页是否展示底部卡片,需要提供name和des信息 final bool showBottom; - //底部展示卡片的模式// 0 表示 展开不可收起 1 收起可展开 2、 展开可收起 + /// [PhotoBottomCardState] 底部展示卡片的模式 final PhotoBottomCardState bottomCardModel; - //指定展开不可收起下 content的高度 + /// 指定展开不可收起下 content的高度 final double bottomContentHeight; - BrnGalleryDetailConfig themeData; + BrnGalleryDetailConfig? themeData; BrnPhotoItemConfig({ - @required this.url, + required this.url, this.fit = BoxFit.cover, this.placeHolder = "packages/${BrnStrings.flutterPackageName}/assets/icons/grey_place_holder.png", @@ -78,7 +88,7 @@ class BrnPhotoItemConfig extends BrnBasicItemConfig { }) { this.themeData ??= BrnGalleryDetailConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .galleryDetailConfig .merge(this.themeData); } @@ -115,23 +125,23 @@ class BrnPhotoItemConfig extends BrnBasicItemConfig { bottom: 0, child: GestureDetector( onTap: () { - if (onTap != null) onTap(); + onTap?.call(); }, onDoubleTap: () { - if (onDoubleTap != null) onDoubleTap(); + onDoubleTap?.call(); }, onLongPress: () { - if (onLongPress != null) onLongPress(); + onLongPress?.call(); }, child: Container( color: Colors.white, child: PhotoView( backgroundDecoration: - BoxDecoration(color: themeData.pageBackgroundColor), + BoxDecoration(color: themeData!.pageBackgroundColor), loadingBuilder: (context, event) { return Container( child: BrnLoadingDialog(), - color: themeData.pageBackgroundColor, + color: themeData!.pageBackgroundColor, ); }, imageProvider: NetworkImage(url), diff --git a/lib/src/components/gallery/page/brn_gallery_detail_page.dart b/lib/src/components/gallery/page/brn_gallery_detail_page.dart index 78701edf..829bb00f 100644 --- a/lib/src/components/gallery/page/brn_gallery_detail_page.dart +++ b/lib/src/components/gallery/page/brn_gallery_detail_page.dart @@ -31,17 +31,17 @@ class BrnGalleryDetailPage extends StatefulWidget { final bool fromSummary; /// 右上角自定义设置按钮,若为空,则展示 "全部图片" - final Widget Function(int groupId, int indexId) detailRightAction; + final Widget Function(int? groupId, int? indexId)? detailRightAction; /// 控制图片查看刷新 - final BrnGalleryController controller; + final BrnGalleryController? controller; /// 主题配置 - BrnGalleryDetailConfig themeData; + BrnGalleryDetailConfig? themeData; BrnGalleryDetailPage( - {Key key, - @required this.allConfig, + {Key? key, + required this.allConfig, this.initGroupId = 0, this.initIndexId = 0, this.fromSummary = false, @@ -51,7 +51,7 @@ class BrnGalleryDetailPage extends StatefulWidget { : super(key: key) { this.themeData ??= BrnGalleryDetailConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .galleryDetailConfig .merge(this.themeData); } @@ -63,24 +63,24 @@ class BrnGalleryDetailPage extends StatefulWidget { class _BrnGalleryDetailPageState extends State with TickerProviderStateMixin { /// title 关联的通知,因为 title 与图片所处的位置关联 - ValueNotifier _titleNotifier; - TabController _tabController; - List _allConfig = List(); - int _curTab; - int _curIndex; + ValueNotifier? _titleNotifier; + TabController? _tabController; + List _allConfig = []; + int? _curTab; + int? _curIndex; bool _assorted = false; - List _columnViews = List(); - List _tabs = List(); + List _columnViews = []; + List _tabs = []; String _groupTitle = ""; String _indexTitle = ""; - PageController _pageController; - List _pageViews = List(); + PageController? _pageController; + List _pageViews = []; Map _groupStartPosition = Map(); Map _groupCount = Map(); int _allCount = 0; - BrnAppBarConfig _appBarConfig; + BrnAppBarConfig? _appBarConfig; - BrnTabBarConfig _tabBarConfig; + late BrnTabBarConfig _tabBarConfig; @override void initState() { @@ -88,27 +88,27 @@ class _BrnGalleryDetailPageState extends State // 打平 appbar _appBarConfig = BrnThemeConfigurator.instance - .getConfig(configId: widget.themeData.configId) + .getConfig(configId: widget.themeData!.configId) .appBarConfig .merge(BrnAppBarConfig( - titleStyle: widget.themeData.appbarTitleStyle, - backgroundColor: widget.themeData.appbarBackgroundColor, - actionsStyle: widget.themeData.appbarActionStyle)); + titleStyle: widget.themeData!.appbarTitleStyle, + backgroundColor: widget.themeData!.appbarBackgroundColor, + actionsStyle: widget.themeData!.appbarActionStyle)); // 打平 tabBar _tabBarConfig = BrnThemeConfigurator.instance - .getConfig(configId: widget.themeData.configId) + .getConfig(configId: widget.themeData!.configId) .tabBarConfig .merge(BrnTabBarConfig( - unselectedLabelStyle: widget.themeData.tabBarUnSelectedLabelStyle, - labelStyle: widget.themeData.tabBarLabelStyle, - backgroundColor: widget.themeData.tabBarBackgroundColor, + unselectedLabelStyle: widget.themeData!.tabBarUnSelectedLabelStyle, + labelStyle: widget.themeData!.tabBarLabelStyle, + backgroundColor: widget.themeData!.tabBarBackgroundColor, )); _curIndex = widget.initIndexId; _curTab = widget.initGroupId; if (widget.controller != null) { - widget.controller.addListener(_refreshByController); + widget.controller!.addListener(_refreshByController); } } @@ -118,31 +118,31 @@ class _BrnGalleryDetailPageState extends State if (widget.controller != null && oldWidget.controller != widget.controller) { oldWidget.controller?.removeListener(_refreshByController); - widget.controller.addListener(_refreshByController); + widget.controller!.addListener(_refreshByController); } } void _refreshByController() { if (mounted) { - _curIndex = widget.controller.indexId; - _curTab = widget.controller.groupId; + _curIndex = widget.controller!.indexId; + _curTab = widget.controller!.groupId; setState(() {}); } } /// 根据groupIndex和index查page的位置 - int _getPagePosition(int groupIndex, int index) { + int? _getPagePosition(int? groupIndex, int? index) { return _groupStartPosition[groupIndex] + index; } /// 根据page的位置反查groupIndex和index List _getGroupIndexAndIndex(int pagePosition) { - List result = List(); + List result = []; MapEntry entry = _groupStartPosition.entries.toList().firstWhere((entry) { return (entry.value > pagePosition); }); result.add(entry.key - 1); - result.add(pagePosition - (_groupStartPosition[entry.key - 1])); + result.add(pagePosition - (_groupStartPosition[entry.key - 1]) as int); return result; } @@ -152,13 +152,12 @@ class _BrnGalleryDetailPageState extends State _columnViews.clear(); _allConfig.clear(); // 过滤 config 中内容为空的选项 - if (widget.allConfig != null) { - widget.allConfig.forEach((e) { - if (e.configList != null && e.configList.isNotEmpty) { - _allConfig.add(e); - } - }); - } + widget.allConfig.forEach((e) { + if (e.configList != null && e.configList!.isNotEmpty) { + _allConfig.add(e); + } + }); + _allCount = 0; _groupCount.clear(); _groupStartPosition.clear(); @@ -168,57 +167,55 @@ class _BrnGalleryDetailPageState extends State void _buildViews() { _reset(); - _titleNotifier = ValueNotifier(null); + _titleNotifier = ValueNotifier(''); _tabController = TabController( - length: _allConfig.length, vsync: this, initialIndex: _curTab) + length: _allConfig.length, vsync: this, initialIndex: _curTab!) ..addListener(() { - _curTab = _tabController.index; + _curTab = _tabController!.index; }); - if (_allConfig != null) { - int i = 0; - for (; i < _allConfig.length; i++) { - _groupStartPosition[i] = _allCount; - _allCount += _allConfig[i].configList.length; - _groupCount[i] = _allConfig[i].configList.length; - } + int i = 0; + for (; i < _allConfig.length; i++) { _groupStartPosition[i] = _allCount; + _allCount += _allConfig[i].configList!.length; + _groupCount[i] = _allConfig[i].configList!.length; } + _groupStartPosition[i] = _allCount; + _pageController = - PageController(initialPage: _getPagePosition(_curTab, _curIndex)); - if (_allConfig != null) { - _assorted = _allConfig.length > 1; + PageController(initialPage: _getPagePosition(_curTab, _curIndex)!); + _assorted = _allConfig.length > 1; - _allConfig.forEach((item) => _tabs.add( - BadgeTab(text: '${item.title ?? ""}(${item.configList.length})'))); - if (_allConfig.length > 1) - _columnViews.add(BrnTabBar( - backgroundcolor: _tabBarConfig.backgroundColor, - unselectedLabelStyle: - _tabBarConfig.unselectedLabelStyle?.generateTextStyle(), - unselectedLabelColor: _tabBarConfig.unselectedLabelStyle?.color, - labelColor: _tabBarConfig.labelStyle?.color, - indicatorColor: _tabBarConfig.labelStyle?.color, - labelStyle: _tabBarConfig.labelStyle?.generateTextStyle(), - tabs: _tabs, - controller: _tabController, - onTap: (state, index) { - _pageController.animateToPage(_getPagePosition(index, 0), - duration: Duration(microseconds: 100), curve: Curves.linear); - }, - )); + _allConfig.forEach((item) => _tabs.add( + BadgeTab(text: '${item.title ?? ""}(${item.configList!.length})'))); + if (_allConfig.length > 1) + _columnViews.add(BrnTabBar( + backgroundcolor: _tabBarConfig.backgroundColor, + unselectedLabelStyle: + _tabBarConfig.unselectedLabelStyle.generateTextStyle(), + unselectedLabelColor: _tabBarConfig.unselectedLabelStyle.color, + labelColor: _tabBarConfig.labelStyle.color, + indicatorColor: _tabBarConfig.labelStyle.color, + labelStyle: _tabBarConfig.labelStyle.generateTextStyle(), + tabs: _tabs, + controller: _tabController, + onTap: (state, index) { + _pageController!.animateToPage(_getPagePosition(index, 0)!, + duration: Duration(microseconds: 100), curve: Curves.linear); + }, + )); - for (int i = 0; i < _allConfig.length; i++) { - for (int j = 0; j < _allConfig[i].configList.length; j++) { - _pageViews.add(_allConfig[i] - .configList[j] - .buildDetailWidget(context, _allConfig, i, j)); - } + for (int i = 0; i < _allConfig.length; i++) { + for (int j = 0; j < _allConfig[i].configList!.length; j++) { + _pageViews.add(_allConfig[i] + .configList![j] + .buildDetailWidget(context, _allConfig, i, j)); } } - _groupTitle = _allConfig[_curTab].title ?? ""; - _indexTitle = "${_curIndex + 1}/${_allConfig[_curTab].configList.length}"; - _titleNotifier.value = + _groupTitle = _allConfig[_curTab!].title ?? ""; + _indexTitle = + "${_curIndex! + 1}/${_allConfig[_curTab!].configList!.length}"; + _titleNotifier?.value = _assorted ? "$_groupTitle($_indexTitle)" : "$_indexTitle"; _columnViews.add(Expanded( @@ -233,7 +230,7 @@ class _BrnGalleryDetailPageState extends State )); } - Future _moveToIndex(index) { + Future? _moveToIndex(index) { // 改变 title List pos = _getGroupIndexAndIndex(index); _indexTitle = "${pos[1] + 1}/${_groupCount[pos[0]]}"; @@ -242,9 +239,9 @@ class _BrnGalleryDetailPageState extends State // 处理是是否需要切换 tab if (_curTab != pos[0]) { _curTab = pos[0]; - _tabController.animateTo(pos[0]); + _tabController!.animateTo(pos[0]); } - _titleNotifier.value = + _titleNotifier?.value = _assorted ? "$_groupTitle($_indexTitle)" : "$_indexTitle"; return null; } @@ -255,24 +252,24 @@ class _BrnGalleryDetailPageState extends State return Scaffold( key: GlobalKey(), appBar: BrnAppBar( - brightness: widget.themeData.appbarBrightness, - backgroundColor: _appBarConfig.backgroundColor, + brightness: widget.themeData!.appbarBrightness, + backgroundColor: _appBarConfig!.backgroundColor, showDefaultBottom: false, themeData: _appBarConfig, title: ValueListenableBuilder( - valueListenable: _titleNotifier, - builder: (c, v, _) { + valueListenable: _titleNotifier!, + builder: (c, String v, _) { return Text( - v ?? "", - style: _appBarConfig.titleStyle?.generateTextStyle(), + v, + style: _appBarConfig!.titleStyle.generateTextStyle(), ); }, ), actions: widget.detailRightAction != null ? ValueListenableBuilder( builder: (c, v, _) => - widget.detailRightAction(_curTab, _curIndex), - valueListenable: _titleNotifier, + widget.detailRightAction!(_curTab, _curIndex), + valueListenable: _titleNotifier!, ) : BrnTextAction( '全部图片', @@ -289,10 +286,10 @@ class _BrnGalleryDetailPageState extends State fromDetail: true, ); })).then((result) { - if (result is List && result != null) { - _tabController.animateTo(result[0]); - _pageController - .jumpToPage(_getPagePosition(result[0], result[1])); + if (result is List) { + _tabController!.animateTo(result[0]); + _pageController!.jumpToPage( + _getPagePosition(result[0], result[1])!); } }); } @@ -304,10 +301,10 @@ class _BrnGalleryDetailPageState extends State } Widget _body() { - if (_allConfig == null || _allConfig.isEmpty) return Row(); + if (_allConfig.isEmpty) return Row(); return NotificationListener( child: Container( - color: widget.themeData.pageBackgroundColor, + color: widget.themeData!.pageBackgroundColor, child: Column( children: _columnViews, ), diff --git a/lib/src/components/gallery/page/brn_gallery_summary_page.dart b/lib/src/components/gallery/page/brn_gallery_summary_page.dart index bc81ebe0..2e7d7c93 100644 --- a/lib/src/components/gallery/page/brn_gallery_summary_page.dart +++ b/lib/src/components/gallery/page/brn_gallery_summary_page.dart @@ -22,13 +22,13 @@ class BrnGallerySummaryPage extends StatefulWidget { final bool fromDetail; /// 图片详情页右上角自定义设置按钮,若为空,则展示 "全部图片" - final Widget Function(int groupId, int indexId) detailRightAction; + final Widget Function(int? groupId, int? indexId)? detailRightAction; /// 控制图片查看刷新 - final BrnGalleryController controller; + final BrnGalleryController? controller; BrnGallerySummaryPage( - {@required this.allConfig, + {required this.allConfig, this.rowCount = 4, this.fromDetail = false, this.detailRightAction, @@ -43,7 +43,7 @@ class _BrnGallerySummaryPageState extends State { void initState() { super.initState(); if (widget.controller != null) { - widget.controller.addListener(() { + widget.controller!.addListener(() { if (mounted) { setState(() {}); } @@ -56,7 +56,7 @@ class _BrnGallerySummaryPageState extends State { super.didUpdateWidget(oldWidget); if (widget.controller != null && oldWidget.controller != widget.controller) { - widget.controller.addListener(() { + widget.controller!.addListener(() { if (mounted) { setState(() {}); } @@ -76,40 +76,36 @@ class _BrnGallerySummaryPageState extends State { } Widget _body() { - if (widget?.allConfig != null) { - List allConfig = widget.allConfig; - if (allConfig.length == 1) { - return SingleChildScrollView(child: _buildItem(allConfig[0], 0)); - } else { - return Padding( - padding: EdgeInsets.only(bottom: 20), - child: BrnAnchorTab( - widgetIndexedBuilder: (c, i) { - return _buildItem(allConfig[i], i); - }, - tabIndexedBuilder: (c, i) { - return BadgeTab( - text: - '${allConfig[i].title}(${allConfig[i].configList.length})'); - }, - itemCount: allConfig.length), - ); - } + List allConfig = widget.allConfig; + if (allConfig.length == 1) { + return SingleChildScrollView(child: _buildItem(allConfig[0], 0)); } else { - return Row(); + return Padding( + padding: EdgeInsets.only(bottom: 20), + child: BrnAnchorTab( + widgetIndexedBuilder: (c, i) { + return _buildItem(allConfig[i], i); + }, + tabIndexedBuilder: (c, i) { + return BadgeTab( + text: + '${allConfig[i].title ?? ""}(${allConfig[i].configList?.length ?? 0})'); + }, + itemCount: allConfig.length), + ); } } - Widget _buildItem(BrnBasicGroupConfig groupConfig, int groupId) { + Widget _buildItem(BrnBasicGroupConfig? groupConfig, int groupId) { if (groupConfig == null) return Row(); - List columnViews = List(); + List columnViews = []; if (groupConfig.title != null) columnViews.add(Container( height: 53, child: Padding( padding: EdgeInsets.only(top: 16, bottom: 12, left: 20, right: 20), child: Text( - '${groupConfig.title}(${groupConfig.configList.length})', + '${groupConfig.title}(${groupConfig.configList?.length ?? 0})', style: TextStyle( color: Color(0xFF222222), fontSize: 18, @@ -118,8 +114,8 @@ class _BrnGallerySummaryPageState extends State { ), )); if (groupConfig.configList != null) { - List gridViews = List(); - for (int i = 0; i < groupConfig.configList.length; i++) + List gridViews = []; + for (int i = 0; i < groupConfig.configList!.length; i++) gridViews.add(GestureDetector( onTap: () { //页面的跳转不应该交个子Widget处理 @@ -137,7 +133,7 @@ class _BrnGallerySummaryPageState extends State { ); })); }, - child: groupConfig.configList[i] + child: groupConfig.configList![i] .buildSummaryWidget(context, widget.allConfig, groupId, i), )); columnViews.add(GridView.count( diff --git a/lib/src/components/guide/brn_delay_rendered_widget.dart b/lib/src/components/guide/brn_delay_rendered_widget.dart index 364b8cae..0c8bc91b 100644 --- a/lib/src/components/guide/brn_delay_rendered_widget.dart +++ b/lib/src/components/guide/brn_delay_rendered_widget.dart @@ -15,10 +15,10 @@ class _DelayRenderedWidget extends StatefulWidget { final bool removed; const _DelayRenderedWidget({ - Key key, + Key? key, this.removed = false, this.duration = const Duration(milliseconds: 200), - this.child, + required this.child, this.childPersist = false, }) : super(key: key); @@ -28,8 +28,8 @@ class _DelayRenderedWidget extends StatefulWidget { class _DelayRenderedWidgetState extends State<_DelayRenderedWidget> { double opacity = 0; - Widget child; - Timer timer; + late Widget child; + late Timer timer; /// Time interval between animations final Duration durationInterval = Duration(milliseconds: 100); @@ -49,8 +49,8 @@ class _DelayRenderedWidgetState extends State<_DelayRenderedWidget> { @override void dispose() { - super.dispose(); timer.cancel(); + super.dispose(); } @override diff --git a/lib/src/components/guide/brn_flutter_guide.dart b/lib/src/components/guide/brn_flutter_guide.dart index 672cd925..5eac9e50 100644 --- a/lib/src/components/guide/brn_flutter_guide.dart +++ b/lib/src/components/guide/brn_flutter_guide.dart @@ -32,18 +32,18 @@ class BrnTipInfoBean { /// 支持 强引导:界面变灰,引导框高亮| 弱引导:直接在界面浮现提示框两种 class BrnGuide { bool _removed = false; - double _widgetWidth; - double _widgetHeight; - Offset _widgetOffset; - OverlayEntry _overlayEntry; + late double _widgetWidth; + late double _widgetHeight; + late Offset _widgetOffset; + OverlayEntry? _overlayEntry; int _currentStepIndex = 0; - Widget _stepWidget; + late Widget _stepWidget; List _configMap = []; List _globalKeys = []; final Color _maskColor = Colors.black.withOpacity(.6); final Duration _animationDuration = Duration(milliseconds: 300); final _th = _Throttling(duration: Duration(milliseconds: 500)); - Size _lastScreenSize; + late Size _lastScreenSize; /// 当前处于第几步 int get currentStepIndex => _currentStepIndex; @@ -61,15 +61,15 @@ class BrnGuide { final int stepCount; /// 每次点击的下一步的时候的回调 - final void Function(int nextIndex) onNextClick; + final void Function(int nextIndex)? onNextClick; /// 引导交互的模式 GuideMode introMode; BrnGuide( - {@required this.introMode, - @required this.widgetBuilder, - @required this.stepCount, + {required this.introMode, + required this.widgetBuilder, + required this.stepCount, this.borderRadius = const BorderRadius.all(Radius.circular(4)), this.padding = const EdgeInsets.all(10), this.onNextClick}) @@ -89,8 +89,8 @@ class BrnGuide { /// [borderRadius] BorderRadius setting void setStepConfig( int stepIndex, { - EdgeInsets padding, - BorderRadiusGeometry borderRadius, + EdgeInsets? padding, + BorderRadiusGeometry? borderRadius, }) { assert(stepIndex >= 0 && stepIndex < stepCount); _configMap[stepIndex] = { @@ -106,8 +106,8 @@ class BrnGuide { /// [borderRadius] BorderRadius setting void setStepsConfig( List stepsIndex, { - EdgeInsets padding, - BorderRadiusGeometry borderRadius, + EdgeInsets? padding, + BorderRadiusGeometry? borderRadius, }) { assert(stepsIndex .every((stepIndex) => stepIndex >= 0 && stepIndex < stepCount)); @@ -122,9 +122,9 @@ class BrnGuide { void _getWidgetInfo(GlobalKey globalKey) { try { - EdgeInsets currentConfig = _configMap[_currentStepIndex]['padding']; - RenderBox renderBox; - renderBox = globalKey.currentContext.findRenderObject(); + EdgeInsets? currentConfig = _configMap[_currentStepIndex]['padding']; + RenderBox renderBox = + globalKey.currentContext?.findRenderObject() as RenderBox; _widgetWidth = renderBox.size.width + (currentConfig?.horizontal ?? padding.horizontal); _widgetHeight = @@ -139,20 +139,20 @@ class BrnGuide { _widgetWidth = 0; _widgetHeight = 0; _widgetOffset = Offset.zero; - debugPrint('获取组件尺寸信息异常'); + debugPrint('获取组件尺寸信息异常${e.toString()}'); } } Widget _maskBuilder({ - double width, - double height, - BlendMode backgroundBlendMode, - @required double left, - @required double top, - double bottom, - double right, - BorderRadiusGeometry borderRadiusGeometry, - Widget child, + double? width, + double? height, + BlendMode? backgroundBlendMode, + required double left, + required double top, + double? bottom, + double? right, + BorderRadiusGeometry? borderRadiusGeometry, + Widget? child, }) { final decoration = BoxDecoration( color: Colors.white, @@ -189,7 +189,7 @@ class BrnGuide { _lastScreenSize = screenSize; _th.throttle(() { _createStepWidget(context); - _overlayEntry.markNeedsBuild(); + _overlayEntry?.markNeedsBuild(); }); } @@ -239,14 +239,14 @@ class BrnGuide { ); }, ); - Overlay.of(context).insert(_overlayEntry); + Overlay.of(context)?.insert(_overlayEntry!); } void _onNext(BuildContext context) { _currentStepIndex++; if (_currentStepIndex < stepCount) { if (onNextClick != null) { - onNextClick(currentStepIndex); + onNextClick!(currentStepIndex); } _renderStep(context); } @@ -255,9 +255,9 @@ class BrnGuide { void _onFinish() { if (_overlayEntry == null) return; _removed = true; - _overlayEntry.markNeedsBuild(); + _overlayEntry!.markNeedsBuild(); Timer(_animationDuration, () { - _overlayEntry.remove(); + _overlayEntry?.remove(); _overlayEntry = null; }); } @@ -272,12 +272,8 @@ class BrnGuide { screenSize: screenSize, size: widgetSize, onNext: _currentStepIndex == stepCount - 1 - ? () { - _onFinish(); - } - : () { - _onNext(context); - }, + ? () => _onFinish() + : () => _onNext(context), offset: _widgetOffset, currentStepIndex: _currentStepIndex, stepCount: stepCount, @@ -287,7 +283,7 @@ class BrnGuide { void _renderStep(BuildContext context) { _createStepWidget(context); - if (_overlayEntry != null) _overlayEntry.markNeedsBuild(); + _overlayEntry?.markNeedsBuild(); } /// 触发引导操作 [context]当前环境[BuildContext]的启动方法 diff --git a/lib/src/components/guide/brn_pulse_widget.dart b/lib/src/components/guide/brn_pulse_widget.dart index b03d9581..86181202 100644 --- a/lib/src/components/guide/brn_pulse_widget.dart +++ b/lib/src/components/guide/brn_pulse_widget.dart @@ -6,7 +6,8 @@ class PulseWidget extends StatefulWidget { final double width; final double height; - const PulseWidget({Key key, this.width, this.height}) : super(key: key); + const PulseWidget({Key? key, required this.width, required this.height}) + : super(key: key); @override _PulseWidgetState createState() => _PulseWidgetState(); @@ -14,9 +15,9 @@ class PulseWidget extends StatefulWidget { class _PulseWidgetState extends State with TickerProviderStateMixin { - AnimationController _scaleController; - AnimationController _fadeController; - Animation _alphaAnimation; + late AnimationController _scaleController; + late AnimationController _fadeController; + late Animation _alphaAnimation; @override void initState() { diff --git a/lib/src/components/guide/brn_step_widget_builder.dart b/lib/src/components/guide/brn_step_widget_builder.dart index a6a25747..32b95f36 100644 --- a/lib/src/components/guide/brn_step_widget_builder.dart +++ b/lib/src/components/guide/brn_step_widget_builder.dart @@ -6,7 +6,10 @@ enum GuideDirection { left, right, topLeft, bottomLeft, topRight, bottomRight } /// 单步引导组件 class StepWidgetBuilder { static Map _smartGetPosition( - {Size size, Size screenSize, Offset offset, GuideMode introMode}) { + {required Size size, + required Size screenSize, + required Offset offset, + required GuideMode introMode}) { double height = size.height; double width = size.width; double screenWidth = screenSize.width; @@ -164,8 +167,8 @@ class StepWidgetBuilder { //showSkipLabel表示是否展示跳过按钮 //showClose表示是否展示关闭按钮 static Widget Function(StepWidgetParams params) useDefaultTheme( - {@required List tipInfo, - String Function(int currentStepIndex, int stepCount) buttonTextBuilder, + {required List tipInfo, + String Function(int currentStepIndex, int stepCount)? buttonTextBuilder, bool showStepLabel = true, bool showSkipLabel = true, bool showClose = true}) { diff --git a/lib/src/components/guide/brn_step_widget_params.dart b/lib/src/components/guide/brn_step_widget_params.dart index f8120379..d5c56cd7 100644 --- a/lib/src/components/guide/brn_step_widget_params.dart +++ b/lib/src/components/guide/brn_step_widget_params.dart @@ -3,20 +3,20 @@ part of brn_intro; /// Highlight component parameters class WidgetParams { /// Padding of highlighted area - EdgeInsets padding; + EdgeInsets? padding; /// Border radius of the highlighted area - BorderRadiusGeometry borderRadius; + BorderRadiusGeometry? borderRadius; } /// The data passed in when the system calls [GuideStep.widgetBuilder] when the guide page is generated /// class StepWidgetParams { /// Enter the next guide page method, or null if there is no - final VoidCallback onNext; + final VoidCallback? onNext; /// End all guide page methods - final VoidCallback onFinish; + final VoidCallback? onFinish; /// Which guide page is currently displayed, starting from 0 final int currentStepIndex; @@ -35,14 +35,14 @@ class StepWidgetParams { final GuideMode introMode; StepWidgetParams({ - this.introMode, + required this.introMode, this.onNext, this.onFinish, - @required this.screenSize, - @required this.size, - @required this.currentStepIndex, - @required this.stepCount, - @required this.offset, + required this.screenSize, + required this.size, + required this.currentStepIndex, + required this.stepCount, + required this.offset, }); @override diff --git a/lib/src/components/guide/brn_throttling.dart b/lib/src/components/guide/brn_throttling.dart index 9ebfcb7c..f4055c84 100644 --- a/lib/src/components/guide/brn_throttling.dart +++ b/lib/src/components/guide/brn_throttling.dart @@ -3,11 +3,11 @@ part of brn_intro; /// Throttling /// Have method [throttle] class _Throttling { - Duration _duration; - Timer _timer; + late Duration _duration; + Timer? _timer; _Throttling({Duration duration = const Duration(seconds: 1)}) - : assert(duration is Duration && !duration.isNegative) { + : assert(!duration.isNegative) { _duration = duration; } diff --git a/lib/src/components/guide/brn_tip_widget.dart b/lib/src/components/guide/brn_tip_widget.dart index 6fa23b68..d8e1f094 100644 --- a/lib/src/components/guide/brn_tip_widget.dart +++ b/lib/src/components/guide/brn_tip_widget.dart @@ -10,12 +10,12 @@ enum GuideMode { force, soft } /// 默认的引导组件包含,强和弱两种交互模式 class BrnTipInfoWidget extends StatelessWidget { final GuideDirection direction; - final void Function() onClose; - final void Function() onNext; - final void Function() onSkip; + final void Function()? onClose; + final void Function()? onNext; + final void Function()? onSkip; final double width; - final double height; + final double? height; final BrnTipInfoBean info; final GuideMode mode; @@ -24,21 +24,21 @@ class BrnTipInfoWidget extends StatelessWidget { /// Total number of guide pages final int stepCount; - final num arrowPadding; - final String nextTip; + final double? arrowPadding; + final String? nextTip; const BrnTipInfoWidget( - {Key key, + {Key? key, this.onClose, this.onNext, this.onSkip, - @required this.width, - @required this.height, - this.currentStepIndex, - this.stepCount, - this.info, + required this.width, + this.height, + this.currentStepIndex = 0, + required this.stepCount, + required this.info, this.mode = GuideMode.force, - this.direction, + required this.direction, this.arrowPadding, this.nextTip}) : super(key: key); @@ -160,7 +160,7 @@ class BrnTipInfoWidget extends StatelessWidget { } Widget buildImage() { - if (info.imgUrl == null || info.imgUrl.isEmpty) return Row(); + if (info.imgUrl.isEmpty) return Row(); double imageSize = width - 16; return Padding( padding: EdgeInsets.only(top: 14), @@ -195,10 +195,10 @@ class BrnTipInfoWidget extends StatelessWidget { ? Row() : GestureDetector( onTap: () { - onClose(); + onClose!(); }, child: BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_CLOSE, Colors.black), + BrnAsset.iconClose, Colors.black), ), ), ], @@ -207,7 +207,7 @@ class BrnTipInfoWidget extends StatelessWidget { } Widget buildMessage() { - if (info.message == null) return Row(); + if (info.message.isEmpty) return Row(); return Padding( padding: EdgeInsets.only(top: 6), child: Text('${info.message}', @@ -234,7 +234,7 @@ class BrnTipInfoWidget extends StatelessWidget { alignment: Alignment.centerLeft, child: GestureDetector( onTap: () { - onSkip(); + onSkip!(); }, child: Text( '跳过 (${currentStepIndex + 1}/$stepCount)', @@ -264,12 +264,13 @@ class BrnTipInfoWidget extends StatelessWidget { ), child: GestureDetector( onTap: () { - onNext(); + onNext!(); }, child: Text( - nextTip ?? stepCount == currentStepIndex + 1 - ? '我知道了' - : '下一步', + nextTip ?? + (stepCount == currentStepIndex + 1 + ? '我知道了' + : '下一步'), style: TextStyle(color: Colors.white, fontSize: 14), ), ), @@ -300,7 +301,7 @@ class BrnTipInfoWidget extends StatelessWidget { alignment: Alignment.centerLeft, child: GestureDetector( onTap: () { - onSkip(); + onSkip!(); }, child: Text( '跳过 (${currentStepIndex + 1}/$stepCount)', @@ -322,12 +323,13 @@ class BrnTipInfoWidget extends StatelessWidget { alignment: Alignment.centerLeft, child: GestureDetector( onTap: () { - onNext(); + onNext!(); }, child: Text( - nextTip ?? stepCount == currentStepIndex + 1 - ? '我知道了' - : '下一步', + nextTip ?? + (stepCount == currentStepIndex + 1 + ? '我知道了' + : '下一步'), style: TextStyle( color: BrnThemeConfigurator.instance .getConfig() @@ -357,7 +359,7 @@ class CustomTrianglePainter extends CustomPainter { CustomTrianglePainter( {this.color = Colors.white, this.borderColor = const Color(0XFFCCCCCC), - @required this.direction}); + required this.direction}); @override void paint(Canvas canvas, Size size) { diff --git a/lib/src/components/input/brn_input_text.dart b/lib/src/components/input/brn_input_text.dart index f1e2b352..8642af4b 100644 --- a/lib/src/components/input/brn_input_text.dart +++ b/lib/src/components/input/brn_input_text.dart @@ -19,10 +19,10 @@ typedef BrnInputTextEditingCompleteCallback = Function(String input); class BrnInputText extends StatelessWidget { /// 搜索框输入内容改变时候的回调函数 - final BrnInputTextChangeCallback onTextChange; + final BrnInputTextChangeCallback? onTextChange; /// 点击确定后的回调 - final BrnInputTextSubmitCallback onSubmit; + final BrnInputTextSubmitCallback? onSubmit; /// 容器的最大高度,默认 200 final double maxHeight; @@ -37,10 +37,11 @@ class BrnInputText extends StatelessWidget { final String hint; /// 输入框的初始值,默认为"" + /// 不能定义为String,兼容example调用的传值 final String textString; /// 用于对 TextField 更精细的控制,若传入该字段,[textString] 参数将失效,可使用 TextEditingController.text 进行赋值。 - final TextEditingController textEditingController; + final TextEditingController? textEditingController; /// 最大字数,默认200 final int maxLength; @@ -52,22 +53,22 @@ class BrnInputText extends StatelessWidget { final EdgeInsetsGeometry padding; /// 最大hint行数 - final int maxHintLines; + final int? maxHintLines; /// 搜索框的焦点控制器 - final FocusNode focusNode; + final FocusNode? focusNode; /// 键盘输入行为, 默认为 TextInputAction.done final TextInputAction textInputAction; /// 光标展示 - final bool autoFocus; + final bool? autoFocus; /// 背景圆角 - final double borderRadius; + final double? borderRadius; /// 边框颜色 - final Color borderColor; + final Color? borderColor; BrnInputText({ this.onTextChange, @@ -96,13 +97,13 @@ class BrnInputText extends StatelessWidget { Widget _inputText(BuildContext context) { String textData = textString; - if (textData != null && textString.runes.length > maxLength) { + if (textString.runes.length > maxLength) { var sRunes = textData.runes; textData = String.fromCharCodes(sRunes, 0, maxLength); } var _controller = textEditingController; if (_controller == null) { - if (textData != null && textData.length > 0) { + if (textData.isNotEmpty) { _controller = TextEditingController.fromValue(TextEditingValue( text: textData, selection: TextSelection.fromPosition(TextPosition( @@ -128,7 +129,7 @@ class BrnInputText extends StatelessWidget { controller: _controller, keyboardType: TextInputType.multiline, maxLength: maxLength, - maxLengthEnforced: true, + maxLengthEnforcement: MaxLengthEnforcement.enforced, maxLines: null, autofocus: autoFocus ?? true, focusNode: focusNode, @@ -141,8 +142,12 @@ class BrnInputText extends StatelessWidget { .getConfig() .commonConfig .colorTextBase), - buildCounter: (BuildContext context, - {int currentLength, int maxLength, bool isFocused}) { + buildCounter: ( + BuildContext context, { + required int currentLength, + required int? maxLength, + required bool isFocused, + }) { return Row( mainAxisAlignment: MainAxisAlignment.end, children: [ @@ -182,12 +187,13 @@ class BrnInputText extends StatelessWidget { ), onSubmitted: (text) { if (onSubmit != null) { - onSubmit(text); + onSubmit!(text); } }, + onChanged: (text) { if (onTextChange != null) { - onTextChange(text); + onTextChange!(text); } }, ), diff --git a/lib/src/components/line/brn_dashed_line.dart b/lib/src/components/line/brn_dashed_line.dart index c952f449..c7a2abe4 100644 --- a/lib/src/components/line/brn_dashed_line.dart +++ b/lib/src/components/line/brn_dashed_line.dart @@ -11,33 +11,29 @@ import 'package:flutter/material.dart'; /// 分割线所在位置 enum BrnDashedLinePosition { /// 头部 - DashedLineTrailing, + trailing, /// 尾部 - DashedLineLeading, + leading, } -/// 虚线分割线 -class BrnDashedLine extends StatelessWidget { - /// 默认虚线方向 - static const Axis _normalAxis = Axis.horizontal; +/// 默认虚线方向 +const Axis _normalAxis = Axis.horizontal; - /// 默认虚线长度 - static const double _normalDashedLength = 8; +/// 默认虚线长度 +const double _normalDashedLength = 8; - /// 默认虚线厚度 - static const double _normalDashedThickness = 1; +/// 默认虚线厚度 +const double _normalDashedThickness = 1; - /// 默认间距 - static const double _normalDashedSpacing = 4; +/// 默认间距 +const double _normalDashedSpacing = 4; - /// 默认颜色 - static Color _normalColor = - BrnThemeConfigurator.instance.getConfig().commonConfig.dividerColorBase; +/// 默认位置,头部 +const BrnDashedLinePosition _normalPosition = BrnDashedLinePosition.leading; - /// 默认位置,头部 - static const BrnDashedLinePosition _normalPosition = - BrnDashedLinePosition.DashedLineLeading; +/// 虚线分割线 +class BrnDashedLine extends StatelessWidget { /// 虚线方向,默认值[_normalAxis] final Axis axis; @@ -52,7 +48,7 @@ class BrnDashedLine extends StatelessWidget { final double dashedSpacing; /// 颜色,默认值[_normalColor] - final Color color; + final Color? color; /// 虚线的Widget final Widget contentWidget; @@ -64,28 +60,28 @@ class BrnDashedLine extends StatelessWidget { final BrnDashedLinePosition position; BrnDashedLine({ - Key key, - @required this.contentWidget, - this.axis, - this.dashedLength, - this.dashedThickness, - this.dashedSpacing, + Key? key, + required this.contentWidget, + this.axis = _normalAxis, + this.dashedLength = _normalDashedLength, + this.dashedThickness = _normalDashedThickness, + this.dashedSpacing = _normalDashedSpacing, this.color, - this.dashedOffset, - this.position, + this.dashedOffset = 0.0, + this.position = _normalPosition, }); @override Widget build(BuildContext context) { return CustomPaint( painter: BrnDashedPainter( - axis: this.axis ?? _normalAxis, - dashedLength: this.dashedLength ?? _normalDashedLength, - dashedThickness: this.dashedThickness ?? _normalDashedThickness, - dashedSpacing: this.dashedSpacing ?? _normalDashedSpacing, - color: this.color ?? _normalColor, - dashedOffset: this.dashedOffset ?? 0, - position: this.position ?? _normalPosition), + axis: this.axis, + dashedLength: this.dashedLength , + dashedThickness: this.dashedThickness, + dashedSpacing: this.dashedSpacing , + color: this.color , + dashedOffset: this.dashedOffset, + position: this.position), child: this.contentWidget, ); } @@ -105,22 +101,22 @@ class BrnDashedPainter extends CustomPainter { final double dashedSpacing; /// 颜色 - final Color color; + final Color? color; /// 距离边缘的位置 - final double dashedOffset; + final double? dashedOffset; /// 分割线所在位置 - final BrnDashedLinePosition position; + final BrnDashedLinePosition? position; BrnDashedPainter({ - this.axis, - this.dashedLength, - this.dashedThickness, - this.dashedSpacing, + this.axis = _normalAxis, + this.dashedLength = _normalDashedLength, + this.dashedThickness = _normalDashedThickness, + this.dashedSpacing = _normalDashedSpacing, this.color, - this.dashedOffset, - this.position, + this.dashedOffset = 0.0, + this.position = _normalPosition, }); @override @@ -128,7 +124,7 @@ class BrnDashedPainter extends CustomPainter { var paint = Paint() // 创建一个画笔并配置其属性 ..strokeWidth = this.dashedThickness // 画笔的宽度 ..isAntiAlias = true // 是否抗锯齿 - ..color = this.color; // 画笔颜色 + ..color = this.color?? BrnThemeConfigurator.instance.getConfig().commonConfig.dividerColorBase; // 画笔颜色 var maxWidth = size.width; // size获取到宽度 var maxHeight = size.height; // size获取到宽度 @@ -137,12 +133,12 @@ class BrnDashedPainter extends CustomPainter { double startX = 0; final space = (this.dashedSpacing + this.dashedLength); double height = 0; - if (this.position == BrnDashedLinePosition.DashedLineLeading) { + if (this.position == BrnDashedLinePosition.leading) { // 头部 - height = dashedOffset + this.dashedThickness / 2; + height = dashedOffset! + this.dashedThickness / 2; } else { // 尾部 - height = size.height - dashedOffset - this.dashedThickness / 2; + height = size.height - dashedOffset! - this.dashedThickness / 2; } while (startX < maxWidth) { if ((maxWidth - startX) < this.dashedLength) { @@ -159,12 +155,12 @@ class BrnDashedPainter extends CustomPainter { double startY = 0; final space = (this.dashedSpacing + this.dashedLength); double width = 0; - if (this.position == BrnDashedLinePosition.DashedLineLeading) { + if (this.position == BrnDashedLinePosition.leading) { // 头部 - width = dashedOffset + this.dashedThickness / 2; + width = dashedOffset! + this.dashedThickness / 2; } else { // 尾部 - width = size.width - dashedOffset - this.dashedThickness / 2; + width = size.width - dashedOffset! - this.dashedThickness / 2; } while (startY < maxHeight) { if ((maxHeight - startY) < this.dashedLength) { diff --git a/lib/src/components/line/brn_line.dart b/lib/src/components/line/brn_line.dart index b1573a41..ef7a14d4 100644 --- a/lib/src/components/line/brn_line.dart +++ b/lib/src/components/line/brn_line.dart @@ -19,7 +19,7 @@ import 'package:flutter/material.dart'; /// class BrnLine extends StatelessWidget { /// 分割线的或者分割条的颜色 可以通过[BrnThemeConfigurator]配置默认颜色 - final Color color; + final Color? color; /// 分割线的或者分割条的高度 默认0.5 final double height; @@ -31,7 +31,7 @@ class BrnLine extends StatelessWidget { final double rightInset; BrnLine({ - Key key, + Key? key, this.color, this.height = 0.5, this.leftInset = 0, @@ -45,11 +45,8 @@ class BrnLine extends StatelessWidget { child: Divider( thickness: this.height, height: this.height, - color: this.color ?? - BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .dividerColorBase, + color: + this.color ?? BrnThemeConfigurator.instance.getConfig().commonConfig.dividerColorBase, ), ); } diff --git a/lib/src/components/loading/brn_loading.dart b/lib/src/components/loading/brn_loading.dart index 5bfca09e..9e83fdd7 100644 --- a/lib/src/components/loading/brn_loading.dart +++ b/lib/src/components/loading/brn_loading.dart @@ -1,3 +1,4 @@ +import 'package:bruno/src/constants/brn_strings_constants.dart'; import 'package:flutter/material.dart'; /// 页面或者弹窗中间的圆形加载框,左侧是可定制的加载文案[content],比如:加载中、提交中等等 @@ -29,7 +30,7 @@ import 'package:flutter/material.dart'; class BrnPageLoading extends StatelessWidget { final String content; - BrnPageLoading({this.content}); + const BrnPageLoading({this.content = BrnStrings.loadingContent}); @override Widget build(BuildContext context) { @@ -38,9 +39,7 @@ class BrnPageLoading extends StatelessWidget { height: 50, width: 130, decoration: BoxDecoration( - color: Color(0xff222222), - border: null, - borderRadius: BorderRadius.circular(5)), + color: Color(0xff222222), borderRadius: BorderRadius.circular(5)), child: Center( child: Row( mainAxisSize: MainAxisSize.min, @@ -56,7 +55,7 @@ class BrnPageLoading extends StatelessWidget { Container( margin: EdgeInsets.only(left: 8), child: Text( - content ?? "加载中...", + content, style: TextStyle( fontSize: 15, fontWeight: FontWeight.w600, @@ -78,7 +77,8 @@ class BrnLoadingDialog extends Dialog { /// 加载时的提示文案,默认为 `加载中...` final String content; - BrnLoadingDialog({Key key, this.content = "加载中..."}) : super(key: key); + const BrnLoadingDialog({Key? key, this.content = BrnStrings.loadingContent}) + : super(key: key); @override Widget build(BuildContext context) { @@ -92,13 +92,13 @@ class BrnLoadingDialog extends Dialog { /// * [barrierDismissible] 点击蒙层背景是否关闭弹窗,默认为 true,可关闭,详见 [showDialog] 中的 [barrierDismissible] /// * [useRootNavigator] 把弹窗添加到 [context] 中的 rootNavigator 还是最近的 [Navigator],默认为 true,添加到 /// rootNavigator,详见 [showDialog] 中的 [useRootNavigator]。 - static void show( + static Future show( BuildContext context, { - String content, + String content = BrnStrings.loadingContent, bool barrierDismissible = true, bool useRootNavigator = true, }) { - showDialog( + return showDialog( context: context, barrierDismissible: barrierDismissible, useRootNavigator: useRootNavigator, @@ -110,7 +110,7 @@ class BrnLoadingDialog extends Dialog { /// 关闭弹窗。 /// /// * [context] 上下文。 - static void dismiss(BuildContext context) { - Navigator.pop(context); + static void dismiss(BuildContext context, [T? result]) { + Navigator.pop(context, result); } } diff --git a/lib/src/components/navbar/brn_appbar.dart b/lib/src/components/navbar/brn_appbar.dart index 7630350b..93ee65b5 100644 --- a/lib/src/components/navbar/brn_appbar.dart +++ b/lib/src/components/navbar/brn_appbar.dart @@ -5,7 +5,6 @@ import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_appbar_config.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:flutter/widgets.dart'; /// AppBar组件,基于[AppBar]封装。为了解决原生的AppBar对Leading宽度的限制 /// 在1.21版本之后,Flutter放开了宽度的限制[https://github.com/flutter/flutter/blob/flutter-1.21-candidate.0/packages/flutter/lib/src/material/app_bar.dart] @@ -97,7 +96,7 @@ import 'package:flutter/widgets.dart'; class BrnAppBar extends PreferredSize { /// 导航栏左侧活动区域,在为null且 /// [automaticallyImplyLeading]为true时默认赋值为[BrnBackLeading] - final Widget leading; + final Widget? leading; /// AppBar标题,必须是String或者Widget类型 /// 为String时,会使用[BrnAppBarTitle]来加载title @@ -113,43 +112,43 @@ class BrnAppBar extends PreferredSize { /// 以下属性都对应于[AppBar]中的属性 /// 详细介绍可以查阅[AppBar]的文档 - final Color backgroundColor; - final PreferredSizeWidget bottom; + final Color? backgroundColor; + final PreferredSizeWidget? bottom; final double elevation; - final Brightness brightness; + final Brightness? brightness; final double toolbarOpacity; final double bottomOpacity; final Alignment titleAlignment; - final Widget flexibleSpace; - final double leadingWidth; - final Color shadowColor; - final ShapeBorder shape; - final IconThemeData iconTheme; - final IconThemeData actionsIconTheme; - final TextTheme textTheme; + final Widget? flexibleSpace; + final double? leadingWidth; + final Color? shadowColor; + final ShapeBorder? shape; + final IconThemeData? iconTheme; + final IconThemeData? actionsIconTheme; + final TextTheme? textTheme; final bool primary; final bool excludeHeaderSemantics; - final double titleSpacing; + final double? titleSpacing; /// 默认处理了返回按钮,flutter的pop,如果是native打开的话,可能需要单独处理,否则会出现白屏 /// backLeadCallback是默认的处理回调 /// DefaultLeadingCallBack 也可以通过改方法参数 设置统一的返回处理,该参数是静态的 - final VoidCallback backLeadCallback; + final VoidCallback? backLeadCallback; /// 是否显示默认的eeeeee分割线,默认显示,可以设置为不显示 final bool showDefaultBottom; final bool showLeadingDivider; - final BrnAppBarConfig themeData; + final BrnAppBarConfig? themeData; BrnAppBar( - {Key key, + {Key? key, this.leading, this.showLeadingDivider = false, this.title, this.actions, this.backgroundColor, this.bottom, - this.elevation, + this.elevation = 0, this.automaticallyImplyLeading = true, this.brightness, this.toolbarOpacity = 1.0, @@ -164,18 +163,18 @@ class BrnAppBar extends PreferredSize { this.shape, this.iconTheme, this.actionsIconTheme, - this.excludeHeaderSemantics, - this.primary, + this.excludeHeaderSemantics = false, + this.primary = true, this.textTheme, this.titleSpacing}) : assert( actions == null || actions is Widget || (actions is List)), assert(title == null || title is String || title is Widget), - super(key: key, child: null, preferredSize: null); + super(key: key, child: Container(), preferredSize: Size(0, 0)); BrnAppBar.buildSearchResultStyle( - {Key key, - String title, + {Key? key, + String? title, this.backgroundColor, this.bottom, this.brightness, @@ -189,8 +188,8 @@ class BrnAppBar extends PreferredSize { this.shape, this.iconTheme, this.actionsIconTheme, - this.excludeHeaderSemantics, - this.primary, + this.excludeHeaderSemantics = false, + this.primary = true, this.textTheme, this.titleSpacing}) : this.actions = null, @@ -211,7 +210,7 @@ class BrnAppBar extends PreferredSize { backLeadCallback: backLeadCallback, showDefaultBottom: showDefaultBottom, ), - super(key: key, child: null, preferredSize: null); + super(key: key, child: Container(), preferredSize: const Size(0, 0)); @override Size get preferredSize { @@ -221,7 +220,7 @@ class BrnAppBar extends PreferredSize { .appBarConfig .merge(_defaultConfig); return Size.fromHeight( - _defaultConfig.appBarHeight + (bottom?.preferredSize?.height ?? 0.0)); + _defaultConfig.appBarHeight + (bottom?.preferredSize.height ?? 0.0)); } @override @@ -241,13 +240,13 @@ class BrnAppBar extends PreferredSize { .appBarConfig .merge(_defaultConfig); - WidgetsBinding.instance.addPostFrameCallback((_) { + WidgetsBinding.instance?.addPostFrameCallback((_) { SystemChrome.setSystemUIOverlayStyle(_defaultConfig.systemUiOverlayStyle); }); return super.build(context); } - Widget _buildBarBottom() { + PreferredSizeWidget? _buildBarBottom() { if (brightness == null || brightness == Brightness.light) { if (bottom == null && showDefaultBottom) { return BrnBarBottomDivider(); @@ -273,13 +272,12 @@ class BrnAppBar extends PreferredSize { .appBarConfig .merge(_defaultConfig); - Widget flexibleSpace; - if (_defaultConfig.flexibleSpace != null) { + Widget? flexibleSpace; + if (this.flexibleSpace != null) { flexibleSpace = Container( height: _defaultConfig.appBarHeight + - MediaQueryData.fromWindow(window)?.padding?.top ?? - 0, - child: _defaultConfig.flexibleSpace, + MediaQueryData.fromWindow(window).padding.top, + child: this.flexibleSpace, ); } @@ -291,28 +289,28 @@ class BrnAppBar extends PreferredSize { automaticallyImplyLeading: false, title: _buildAppBarTitle(_defaultConfig), centerTitle: true, - elevation: elevation ?? 0, + elevation: elevation, backgroundColor: _defaultConfig.backgroundColor, actions: _wrapActions(_defaultConfig), bottom: _buildBarBottom(), brightness: brightness ?? Brightness.light, - toolbarOpacity: toolbarOpacity ?? 1.0, - bottomOpacity: bottomOpacity ?? 1.0, + toolbarOpacity: toolbarOpacity, + bottomOpacity: bottomOpacity, flexibleSpace: flexibleSpace, shadowColor: shadowColor, shape: shape, iconTheme: iconTheme, actionsIconTheme: actionsIconTheme, textTheme: textTheme, - primary: primary ?? true, - excludeHeaderSemantics: excludeHeaderSemantics ?? false, + primary: primary, + excludeHeaderSemantics: excludeHeaderSemantics, ); } // 根据输入的leading 设置默认的leadingWidth double _culLeadingSize(BrnAppBarConfig themeData) { if (leadingWidth != null) { - return leadingWidth; + return leadingWidth!; } if (leading is BrnDoubleLeading) { return themeData.leftAndRightPadding + @@ -328,7 +326,7 @@ class BrnAppBar extends PreferredSize { // 对[actions]进行包装: 单一的Widget会添加右边距 // List在添加右边距的 并 添加action中的间距 - List _wrapActions(BrnAppBarConfig themeData) { + List? _wrapActions(BrnAppBarConfig themeData) { if (actions == null || !(actions is List || actions is Widget)) { return null; } @@ -338,9 +336,9 @@ class BrnAppBar extends PreferredSize { if (actions.isEmpty) { return actionList; } - List tmp = (actions as List)?.map((_) { + List tmp = (actions as List).map((_) { return (_ is BrnTextAction) ? _warpRealAction(_) : _; - })?.toList(); + }).toList(); for (int i = 0, n = tmp.length; i < n; i++) { actionList.add(tmp[i]); @@ -364,10 +362,10 @@ class BrnAppBar extends PreferredSize { } // 详情请参考_ToolbarLayout的布局方法 - Widget _buildAppBarTitle( + Widget? _buildAppBarTitle( BrnAppBarConfig themeData, ) { - Widget realTitle; + Widget? realTitle; if (title is Widget) { return title; } @@ -382,8 +380,8 @@ class BrnAppBar extends PreferredSize { } // 如果leading是BrnBackLeading 需要添加左边距 - Widget _wrapLeading(BrnAppBarConfig barConfig) { - Widget realLeading = leading; + Widget? _wrapLeading(BrnAppBarConfig barConfig) { + Widget? realLeading = leading; if (leading == null && automaticallyImplyLeading) { realLeading = BrnBackLeading( iconPressed: backLeadCallback, @@ -403,12 +401,12 @@ class BrnAppBar extends PreferredSize { /// [BrnAppBar]中leading的默认实现 /// 宽度范围是40 class BrnBackLeading extends StatelessWidget { - final Widget child; - final VoidCallback iconPressed; - final BrnAppBarConfig themeData; + final Widget? child; + final VoidCallback? iconPressed; + final BrnAppBarConfig? themeData; BrnBackLeading({ - Key key, + Key? key, this.iconPressed, this.child, this.themeData, @@ -453,9 +451,10 @@ class BrnBackLeading extends StatelessWidget { class BrnDoubleLeading extends StatelessWidget { final Widget first; final Widget second; - final BrnAppBarConfig themeData; + final BrnAppBarConfig? themeData; - BrnDoubleLeading({Key key, this.first, this.second, this.themeData}) + BrnDoubleLeading( + {Key? key, required this.first, required this.second, this.themeData}) : super(key: key); @override @@ -485,15 +484,15 @@ class BrnDoubleLeading extends StatelessWidget { /// 标题文字个数限制在8个以内,并且单行展示 class BrnAppBarTitle extends StatelessWidget { final String title; - final BrnAppBarConfig themeData; + final BrnAppBarConfig? themeData; - BrnAppBarTitle(this.title, {Key key, this.themeData}) : super(key: key); + BrnAppBarTitle(this.title, {Key? key, this.themeData}) : super(key: key); @override Widget build(BuildContext context) { BrnAppBarConfig _defaultThemeData = themeData ?? BrnAppBarConfig(); _defaultThemeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: _defaultThemeData.configId) .appBarConfig .merge(this.themeData); @@ -504,7 +503,7 @@ class BrnAppBarTitle extends StatelessWidget { overflow: TextOverflow.ellipsis, ), constraints: BoxConstraints.loose(Size.fromWidth( - _defaultThemeData.titleStyle.generateTextStyle().fontSize * + (_defaultThemeData.titleStyle.generateTextStyle().fontSize ?? 18) * (_defaultThemeData.titleMaxLength + 1))), ); } @@ -515,17 +514,16 @@ class BrnAppBarTitle extends StatelessWidget { class BrnIconAction extends StatelessWidget { final Widget child; final VoidCallback iconPressed; - final double size; - final BrnAppBarConfig themeData; + final double? size; + final BrnAppBarConfig? themeData; BrnIconAction({ - Key key, - this.iconPressed, - this.child, + Key? key, + required this.iconPressed, + required this.child, this.size, this.themeData, - }) : assert(child != null && iconPressed != null), - super(key: key); + }) : super(key: key); @override Widget build(BuildContext context) { @@ -552,10 +550,10 @@ class BrnIconAction extends StatelessWidget { /// 此Widget中实现了大小约束,和点击实现,添加文本action时必须使用此类包裹 class BrnTextAction extends StatelessWidget { final String text; - final VoidCallback iconPressed; - final BrnAppBarConfig themeData; + final VoidCallback? iconPressed; + final BrnAppBarConfig? themeData; - BrnTextAction(this.text, {Key key, this.iconPressed, this.themeData}) + BrnTextAction(this.text, {Key? key, this.iconPressed, this.themeData}) : super(key: key); @override @@ -581,6 +579,9 @@ class BrnTextAction extends StatelessWidget { /// AppBar底部分割线,将实例传入[BrnAppBar.bottom]属性即可 class BrnBarBottomDivider extends PreferredSize { + BrnBarBottomDivider() + : super(child: Container(), preferredSize: const Size(0, 0)); + @override Size get preferredSize => Size.fromHeight(0.5); @@ -589,8 +590,8 @@ class BrnBarBottomDivider extends PreferredSize { } class _BrnSearchResultAppBar extends StatelessWidget { - final BrnAppBarConfig appBarConfig; - final String title; + final BrnAppBarConfig? appBarConfig; + final String? title; final backgroundColor; final bottom; final brightness; diff --git a/lib/src/components/navbar/brn_appbar_theme.dart b/lib/src/components/navbar/brn_appbar_theme.dart index 50cea13d..204e81a7 100644 --- a/lib/src/components/navbar/brn_appbar_theme.dart +++ b/lib/src/components/navbar/brn_appbar_theme.dart @@ -1,8 +1,8 @@ -import 'dart:ui'; - import 'package:flutter/material.dart'; class BrnAppBarTheme { + const BrnAppBarTheme._(); + /// [BrnAppBar] 高度固定值 static const double appBarHeight = 44; diff --git a/lib/src/components/navbar/brn_empty_appbar.dart b/lib/src/components/navbar/brn_empty_appbar.dart deleted file mode 100644 index 141e27c1..00000000 --- a/lib/src/components/navbar/brn_empty_appbar.dart +++ /dev/null @@ -1,19 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; - -class BrnEmptyAppBar extends PreferredSize { - final double height; - final Color color; - - BrnEmptyAppBar(this.height, {this.color}); - - @override - Size get preferredSize => Size.fromHeight(height); - - @override - Widget build(BuildContext context) { - return Container( - color: color ?? Colors.white, - ); - } -} diff --git a/lib/src/components/navbar/brn_search_bar.dart b/lib/src/components/navbar/brn_search_bar.dart index 06cec3f3..802ab87e 100644 --- a/lib/src/components/navbar/brn_search_bar.dart +++ b/lib/src/components/navbar/brn_search_bar.dart @@ -1,5 +1,3 @@ -import 'dart:ui'; - import 'package:bruno/src/components/navbar/brn_appbar.dart'; import 'package:bruno/src/components/navbar/brn_appbar_theme.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; @@ -35,37 +33,37 @@ typedef BrnSearchBarInputSubmitCallback = Function(String input); /// 更多信息 请查看[BrnAppBar] class BrnSearchAppbar extends PreferredSize { /// 搜索框的文本输入控制器 - final TextEditingController controller; + final TextEditingController? controller; /// 搜索框的焦点控制器 - final FocusNode focusNode; + final FocusNode? focusNode; /// 搜索框的左侧leading - final BrnSearchBarLeadClickCallback leadClickCallback; + final BrnSearchBarLeadClickCallback? leadClickCallback; /// 可以是字符串也可以是widget final dynamic leading; /// 取消点击的回调 - final BrnSearchBarDismissClickCallback dismissClickCallback; + final BrnSearchBarDismissClickCallback? dismissClickCallback; /// 输入变化的监听 - final BrnSearchBarInputChangeCallback searchBarInputChangeCallback; + final BrnSearchBarInputChangeCallback? searchBarInputChangeCallback; /// 输入框提交的监听 - final BrnSearchBarInputSubmitCallback searchBarInputSubmitCallback; + final BrnSearchBarInputSubmitCallback? searchBarInputSubmitCallback; /// 输入框的hint文字 - final String hint; + final String? hint; /// 输入框的hint的Style - final TextStyle hintStyle; + final TextStyle? hintStyle; /// 输入框的文本Style - final TextStyle inputTextStyle; + final TextStyle? inputTextStyle; /// 右侧取消的文本Style - final TextStyle dismissStyle; + final TextStyle? dismissStyle; /// 左侧的leading和搜索的分割线 final bool showDivider; @@ -77,7 +75,7 @@ class BrnSearchAppbar extends PreferredSize { final Brightness brightness; /// 清空回调 - final VoidCallback onClearTap; + final VoidCallback? onClearTap; const BrnSearchAppbar( {this.controller, @@ -94,7 +92,8 @@ class BrnSearchAppbar extends PreferredSize { this.autoFocus = true, this.brightness = Brightness.dark, this.onClearTap, - this.inputTextStyle}); + this.inputTextStyle}) + : super(child: const Center(), preferredSize: const Size(0, 0)); @override Widget get child => BrnAppBar( @@ -107,7 +106,7 @@ class BrnSearchAppbar extends PreferredSize { Size get preferredSize => Size.fromHeight(BrnAppBarTheme.appBarHeight); Widget build(BuildContext context) { - WidgetsBinding.instance.addPostFrameCallback((_) { + WidgetsBinding.instance?.addPostFrameCallback((_) { SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light); }); return super.build(context); @@ -144,21 +143,21 @@ class BrnSearchAppbar extends PreferredSize { } class _SearchInputWidget extends StatefulWidget { - final FocusNode focusNode; - final TextEditingController textEditingController; - final BrnSearchBarLeadClickCallback leadClickCallback; - final BrnSearchBarDismissClickCallback dismissClickCallback; + final FocusNode? focusNode; + final TextEditingController? textEditingController; + final BrnSearchBarLeadClickCallback? leadClickCallback; + final BrnSearchBarDismissClickCallback? dismissClickCallback; final dynamic leading; - final BrnSearchBarInputChangeCallback searchBarInputChangeCallback; - final BrnSearchBarInputSubmitCallback searchBarInputSubmitCallback; - final String hint; - final TextStyle hintStyle; - final TextStyle inputTextStyle; - final TextStyle dismissStyle; + final BrnSearchBarInputChangeCallback? searchBarInputChangeCallback; + final BrnSearchBarInputSubmitCallback? searchBarInputSubmitCallback; + final String? hint; + final TextStyle? hintStyle; + final TextStyle? inputTextStyle; + final TextStyle? dismissStyle; final bool showDivider; final bool autoFocus; - final VoidCallback clearTapCallback; - final Brightness brightness; + final VoidCallback? clearTapCallback; + final Brightness? brightness; _SearchInputWidget( {this.focusNode, @@ -168,7 +167,7 @@ class _SearchInputWidget extends StatefulWidget { this.textEditingController, this.searchBarInputChangeCallback, this.searchBarInputSubmitCallback, - this.hint, + this.hint= '请输入搜索内容', this.hintStyle, this.inputTextStyle, this.showDivider = true, @@ -182,14 +181,14 @@ class _SearchInputWidget extends StatefulWidget { } class __SearchInputWidgetState extends State<_SearchInputWidget> { - FocusNode _focusNode; - ValueNotifier valueNotifier; - TextEditingController _controller; - Color _defaultInputTextColor; - Color _defaultCancelTextColor; - Color _defaultDividerColor; - Color _defaultHintTextColor; - Color _defaultClearIconColor; + late FocusNode _focusNode; + late ValueNotifier valueNotifier; + late TextEditingController _controller; + late Color _defaultInputTextColor; + late Color _defaultCancelTextColor; + late Color _defaultDividerColor; + late Color _defaultHintTextColor; + late Color _defaultClearIconColor; @override void initState() { @@ -226,7 +225,7 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { @override void dispose() { super.dispose(); - _focusNode?.removeListener(_handleFocusChangeListenerTick); + _focusNode.removeListener(_handleFocusChangeListenerTick); } void _handleFocusChangeListenerTick() { @@ -243,7 +242,7 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { GestureDetector( onTap: () { if (widget.leadClickCallback != null) { - widget.leadClickCallback(_controller, () { + widget.leadClickCallback!(_controller, () { setState(() {}); }); } @@ -268,7 +267,7 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { Padding( padding: EdgeInsets.only(right: 8.0), child: - BrunoTools.getAssetSizeImage(BrnAsset.ICON_SEARCH, 16, 16), + BrunoTools.getAssetSizeImage(BrnAsset.iconSearch, 16, 16), ), Expanded( child: TextField( @@ -309,20 +308,20 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { color: _defaultHintTextColor, ), // 提示文本属性,提示字段接受哪种输入的文本。 - hintText: widget.hint ?? "请输入搜索内容", + hintText: widget.hint, ), // 在改变属性,当正在编辑的文本发生更改时调用。 onChanged: (content) { valueNotifier.value = true; if (widget.searchBarInputChangeCallback != null) { - widget.searchBarInputChangeCallback(content); + widget.searchBarInputChangeCallback!(content); } setState(() {}); }, onSubmitted: (content) { valueNotifier.value = false; if (widget.searchBarInputSubmitCallback != null) { - widget.searchBarInputSubmitCallback(content); + widget.searchBarInputSubmitCallback!(content); } }), ), @@ -330,7 +329,7 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { onTap: () { _controller.clear(); if (widget.clearTapCallback != null) { - widget.clearTapCallback(); + widget.clearTapCallback!(); } setState(() {}); }, @@ -341,7 +340,7 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { right: valueNotifier.value ? 24 : 20, left: valueNotifier.value ? 24 : 20), child: Image.asset( - 'assets/${BrnAsset.ICON_DELETE_TEXT}', + 'assets/${BrnAsset.iconDeleteText}', color: _defaultClearIconColor, scale: 3.0, height: 16, @@ -356,12 +355,12 @@ class __SearchInputWidgetState extends State<_SearchInputWidget> { ), ValueListenableBuilder( valueListenable: valueNotifier, - builder: (context, value, child) { + builder: (context, bool value, child) { return value ? GestureDetector( onTap: () { if (widget.dismissClickCallback != null) { - widget.dismissClickCallback(_controller, () { + widget.dismissClickCallback!(_controller, () { setState(() {}); }); } diff --git a/lib/src/components/noticebar/brn_marquee_text.dart b/lib/src/components/noticebar/brn_marquee_text.dart index 0dc6a9f6..4b6b3435 100644 --- a/lib/src/components/noticebar/brn_marquee_text.dart +++ b/lib/src/components/noticebar/brn_marquee_text.dart @@ -8,7 +8,7 @@ class BrnMarqueeText extends StatefulWidget { final String text; /// 文字样式 - final TextStyle textStyle; + final TextStyle? textStyle; ///滚动方向,水平或者垂直 final Axis scrollAxis; @@ -25,16 +25,14 @@ class BrnMarqueeText extends StatefulWidget { double height; BrnMarqueeText({ - @required this.text, + required this.text, this.width: 0, this.height: 0, this.timerRest: 100, this.textStyle, this.scrollAxis: Axis.horizontal, this.ratioOfBlankToScreen: 0.25, - }) : assert( - text != null, - ); + }); @override State createState() { @@ -44,26 +42,26 @@ class BrnMarqueeText extends StatefulWidget { class BrnMarqueeTextState extends State with SingleTickerProviderStateMixin { - ScrollController scroController; + late ScrollController scroController; double blankWidth = 1; double blankHeight = 1; double position = 0.0; - Timer timer; + Timer? timer; final double _moveDistance = 3.0; - GlobalKey _key = null; + GlobalKey? _key; @override void initState() { super.initState(); scroController = new ScrollController(); - WidgetsBinding.instance.addPostFrameCallback((callback) { - var size = context?.findRenderObject()?.paintBounds?.size; + WidgetsBinding.instance?.addPostFrameCallback((callback) { + var size = context.findRenderObject()!.paintBounds.size; widget.width = (widget.width) > 0 ? widget.width : size.width; widget.height = (widget.height) > 0 ? widget.height : size.height; _key = GlobalKey(); - if (calculateTextWith(widget.text, widget.textStyle.fontSize, - widget.textStyle.fontWeight, double.infinity, 1, context) > + if (calculateTextWith(widget.text, widget.textStyle?.fontSize, + widget.textStyle?.fontWeight, double.infinity, 1, context) > widget.width) { blankWidth = widget.width * widget.ratioOfBlankToScreen; blankHeight = widget.height * widget.ratioOfBlankToScreen; @@ -136,10 +134,8 @@ class BrnMarqueeTextState extends State @override void dispose() { - if (timer != null) { - timer.cancel(); - } - scroController = null; + timer?.cancel(); + scroController.dispose(); super.dispose(); } @@ -162,8 +158,13 @@ class BrnMarqueeTextState extends State ); } - double calculateTextWith(String value, double fontSize, FontWeight fontWeight, - double maxWidth, int maxLines, BuildContext context) { + double calculateTextWith( + String value, + double? fontSize, + FontWeight? fontWeight, + double maxWidth, + int maxLines, + BuildContext context) { TextPainter painter = TextPainter( ///AUTO:华为手机如果不指定locale的时候,该方法算出来的文字高度是比系统计算偏小的。 diff --git a/lib/src/components/noticebar/brn_notice_bar.dart b/lib/src/components/noticebar/brn_notice_bar.dart index 78e0e1fe..637a20d6 100644 --- a/lib/src/components/noticebar/brn_notice_bar.dart +++ b/lib/src/components/noticebar/brn_notice_bar.dart @@ -10,7 +10,7 @@ import 'package:flutter/material.dart'; class BrnNoticeBar extends StatelessWidget { /// 自定义左边的图标 - final Widget leftWidget; + final Widget? leftWidget; /// 是否显示左边的图标 final bool showLeftIcon; @@ -19,30 +19,30 @@ class BrnNoticeBar extends StatelessWidget { final String content; /// 通知的文字颜色 - final Color textColor; + final Color? textColor; /// 背景颜色 - final Color backgroundColor; + final Color? backgroundColor; /// 右边的图标 - final Widget rightWidget; + final Widget? rightWidget; /// 是否显示右边的图标 /// 默认值true final bool showRightIcon; /// 默认样式,取[NoticeStyles]里面的值 - final NoticeStyle noticeStyle; + final NoticeStyle? noticeStyle; /// 是否跑马灯 /// 默认值false final bool marquee; /// 通知钮点击的回调 - final VoidCallback onNoticeTap; + final VoidCallback? onNoticeTap; /// 右侧图标点击的回调 - final VoidCallback onRightIconTap; + final VoidCallback? onRightIconTap; /// 最小高度。leftWidget、rightWidget 都为空时,限制的最小高度。 /// 可以通过该属性控制组件高度,内容会自动垂直居中。 @@ -50,13 +50,13 @@ class BrnNoticeBar extends StatelessWidget { final double minHeight; /// 内容的内边距 - final EdgeInsets padding; + final EdgeInsets? padding; const BrnNoticeBar( - {Key key, + {Key? key, this.leftWidget, this.showLeftIcon = true, - @required this.content, + required this.content, this.textColor, this.backgroundColor, this.rightWidget, @@ -67,8 +67,7 @@ class BrnNoticeBar extends StatelessWidget { this.marquee = false, this.padding, this.minHeight = 36}) - : assert(content != null), - super(key: key); + : super(key: key); @override Widget build(BuildContext context) { @@ -80,7 +79,7 @@ class BrnNoticeBar extends StatelessWidget { tempRightWidget = GestureDetector( child: tempRightWidget, onTap: () { - onRightIconTap(); + onRightIconTap!(); }, ); } @@ -89,7 +88,7 @@ class BrnNoticeBar extends StatelessWidget { if (marquee) { contentWidget = BrnMarqueeText( height: 36, - text: content ?? '', + text: content, textStyle: TextStyle( color: textColor ?? (noticeStyle?.textColor ?? defaultStyle.textColor), @@ -98,7 +97,7 @@ class BrnNoticeBar extends StatelessWidget { ); } else { contentWidget = Text( - content ?? '', + content, overflow: TextOverflow.ellipsis, style: TextStyle( color: @@ -111,14 +110,14 @@ class BrnNoticeBar extends StatelessWidget { return Container( color: backgroundColor ?? (noticeStyle != null - ? noticeStyle.backgroundColor + ? noticeStyle!.backgroundColor : defaultStyle.backgroundColor), padding: this.padding ?? EdgeInsets.symmetric(horizontal: 20), constraints: BoxConstraints(minHeight: this.minHeight), child: GestureDetector( onTap: () { if (onNoticeTap != null) { - onNoticeTap(); + onNoticeTap!(); } }, child: Row( @@ -152,73 +151,73 @@ class BrnNoticeBar extends StatelessWidget { class NoticeStyles { ///红色+失败+箭头 static NoticeStyle failWithArrow = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_FAIL), + BrunoTools.getAssetImage(BrnAsset.iconNoticeFail), Color(0xFFFA3F3F), Color(0xFFFEEDED), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_ARROW_RED)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeArrowRed)); ///红色+失败+关闭 static NoticeStyle failWithClose = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_FAIL), + BrunoTools.getAssetImage(BrnAsset.iconNoticeFail), Color(0xFFFA3F3F), Color(0xFFFEEDED), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_CLOSE_RED)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeCloseRed)); ///蓝色+进行中+箭头 static NoticeStyle runningWithArrow = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_RUNNING), + BrunoTools.getAssetImage(BrnAsset.iconNoticeRunning), Color(0xFF0984F9), Color(0xFFE0EDFF), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_ARROW_BLUE)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeArrowBlue)); ///蓝色+进行中+关闭 static NoticeStyle runningWithClose = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_RUNNING), + BrunoTools.getAssetImage(BrnAsset.iconNoticeRunning), Color(0xFF0984F9), Color(0xFFE0EDFF), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_CLOSE_BLUE)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeCloseBlue)); ///绿色+完成+箭头 static NoticeStyle succeedWithArrow = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_SUCCEED), + BrunoTools.getAssetImage(BrnAsset.iconNoticeSucceed), Color(0xFF00AE66), Color(0xFFEBFFF7), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_ARROW_GREEN)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeArrowGreen)); ///绿色+完成+关闭 static NoticeStyle succeedWithClose = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_SUCCEED), + BrunoTools.getAssetImage(BrnAsset.iconNoticeSucceed), Color(0xFF00AE66), Color(0xFFEBFFF7), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_CLOSE_GREEN)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeCloseGreen)); ///橘色+警告+箭头 static NoticeStyle warningWithArrow = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_WARNING), + BrunoTools.getAssetImage(BrnAsset.iconNoticeWarning), Color(0xFFFAAD14), Color(0xFFFDFCEC), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_ARROW_ORANGE)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeArrowOrange)); ///橘色+警告+关闭 static NoticeStyle warningWithClose = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_WARNING), + BrunoTools.getAssetImage(BrnAsset.iconNoticeWarning), Color(0xFFFAAD14), Color(0xFFFDFCEC), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_CLOSE_ORANGE)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeCloseOrange)); ///橘色+通知+箭头 static NoticeStyle normalNoticeWithArrow = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE), + BrunoTools.getAssetImage(BrnAsset.iconNotice), Color(0xFFFAAD14), Color(0xFFFDFCEC), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_ARROW_ORANGE)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeArrowOrange)); ///橘色+通知+关闭 static NoticeStyle normalNoticeWithClose = NoticeStyle( - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE), + BrunoTools.getAssetImage(BrnAsset.iconNotice), Color(0xFFFAAD14), Color(0xFFFDFCEC), - BrunoTools.getAssetImage(BrnAsset.ICON_NOTICE_CLOSE_ORANGE)); + BrunoTools.getAssetImage(BrnAsset.iconNoticeCloseOrange)); } /// 通知样式 diff --git a/lib/src/components/noticebar/brn_notice_bar_with_button.dart b/lib/src/components/noticebar/brn_notice_bar_with_button.dart index c21b7055..7e1e59fd 100644 --- a/lib/src/components/noticebar/brn_notice_bar_with_button.dart +++ b/lib/src/components/noticebar/brn_notice_bar_with_button.dart @@ -11,52 +11,52 @@ class BrnNoticeBarWithButton extends StatelessWidget { final String content; /// 通知的背景色 - final Color backgroundColor; + final Color? backgroundColor; /// 通知的文字颜色 - final Color contentTextColor; + final Color? contentTextColor; /// 左边标签的文字 - final String leftTagText; + final String? leftTagText; /// 左边标签的文字颜色 - final Color leftTagTextColor; + final Color? leftTagTextColor; /// 左边标签的背景颜色 - final Color leftTagBackgroundColor; + final Color? leftTagBackgroundColor; /// 自定义左边的控件 - final Widget leftWidget; + final Widget? leftWidget; ///右边按钮的文字 - final String rightButtonText; + final String? rightButtonText; ///右边按钮的文字颜色 - final Color rightButtonTextColor; + final Color? rightButtonTextColor; ///右边按钮的边框颜色 - final Color rightButtonBorderColor; + final Color? rightButtonBorderColor; /// 自定义右边的控件 - final Widget rightWidget; + final Widget? rightWidget; /// 是否跑马灯 /// 默认值false final bool marquee; /// 右边按钮点击回调 - final VoidCallback onRightButtonTap; + final VoidCallback? onRightButtonTap; /// 最小高度。leftWidget、rightWidget 都为空时,限制的最小高度。 /// 可以通过该属性控制组件高度,内容会自动垂直居中。默认值 54。 final double minHeight; /// 内容的内边距 - final EdgeInsets padding; + final EdgeInsets? padding; const BrnNoticeBarWithButton( - {Key key, - @required this.content, + {Key? key, + required this.content, this.backgroundColor, this.contentTextColor, this.leftTagText, @@ -71,8 +71,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { this.rightWidget, this.padding, this.minHeight = 54}) - : assert(content != null), - super(key: key); + : super(key: key); @override Widget build(BuildContext context) { @@ -97,7 +96,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { /// 左边的标签 Widget _buildLeftTag() { if (leftWidget != null) { - return leftWidget; + return leftWidget!; } if (leftTagText?.isEmpty ?? true) { @@ -113,7 +112,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { borderRadius: BorderRadius.circular(2), ), child: Text( - leftTagText, + leftTagText!, style: TextStyle( color: leftTagTextColor ?? Colors.white, fontSize: 11, @@ -125,14 +124,14 @@ class BrnNoticeBarWithButton extends StatelessWidget { } Widget _buildContent() { - if (content?.isEmpty ?? true) { + if (content.isEmpty) { return Container(); } if (marquee) { return BrnMarqueeText( height: 20, - text: content ?? '', + text: content, textStyle: TextStyle( color: contentTextColor ?? Color(0xFF333333), fontSize: 14, @@ -140,7 +139,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { ); } else { return Text( - content ?? '', + content, overflow: TextOverflow.ellipsis, style: TextStyle( color: contentTextColor ?? Color(0xFF333333), @@ -153,7 +152,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { /// 右边的按钮 Widget _buildRightBtn() { if (rightWidget != null) { - return rightWidget; + return rightWidget!; } if (rightButtonText?.isEmpty ?? true) { @@ -162,7 +161,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { return GestureDetector( onTap: () { if (onRightButtonTap != null) { - onRightButtonTap(); + onRightButtonTap!(); } }, child: Padding( @@ -181,7 +180,7 @@ class BrnNoticeBarWithButton extends StatelessWidget { borderRadius: BorderRadius.circular(4), ), child: Text( - rightButtonText, + rightButtonText!, style: TextStyle( color: rightButtonTextColor ?? Color(0xFFFA5741), fontSize: 12, diff --git a/lib/src/components/picker/base/brn_picker.dart b/lib/src/components/picker/base/brn_picker.dart index d23a3d10..2f4a01e9 100644 --- a/lib/src/components/picker/base/brn_picker.dart +++ b/lib/src/components/picker/base/brn_picker.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + + import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; @@ -10,7 +12,7 @@ import 'package:flutter/widgets.dart'; /// Color of the 'magnifier' lens border. const Color _kHighlighterBorder = Color(0xFFF0F0F0); -const Color _kDefaultBackground = Color(0xFFD2D4DB); +const Color _kDefaultBackground = Color(0xFFFFFFFF); // Eyeballed values comparing with a native picker to produce the right // curvatures and densities. const double _kDefaultDiameterRatio = 3; @@ -59,7 +61,7 @@ class BrnPicker extends StatefulWidget { /// will loop the list back to the beginning. If set to false, the list will /// stop scrolling when you reach the end or the beginning. BrnPicker({ - Key key, + Key? key, this.diameterRatio = _kDefaultDiameterRatio, this.backgroundColor = _kDefaultBackground, this.lineColor = _kHighlighterBorder, @@ -68,9 +70,9 @@ class BrnPicker extends StatefulWidget { this.magnification = 1.0, this.scrollController, this.squeeze = _kSqueeze, - @required this.itemExtent, - @required this.onSelectedItemChanged, - @required List children, + required this.itemExtent, + required this.onSelectedItemChanged, + required List children, bool looping = false, }) : assert(children != null), assert(diameterRatio != null), @@ -104,7 +106,7 @@ class BrnPicker extends StatefulWidget { /// disable the background painting entirely; this is mildly more efficient /// than using [Colors.transparent]. BrnPicker.builder({ - Key key, + Key? key, this.diameterRatio = _kDefaultDiameterRatio, this.backgroundColor = _kDefaultBackground, this.lineColor = _kHighlighterBorder, @@ -113,10 +115,10 @@ class BrnPicker extends StatefulWidget { this.magnification = 1.0, this.scrollController, this.squeeze = _kSqueeze, - @required this.itemExtent, - @required this.onSelectedItemChanged, - @required IndexedWidgetBuilder itemBuilder, - int childCount, + required this.itemExtent, + required this.onSelectedItemChanged, + required IndexedWidgetBuilder itemBuilder, + int? childCount, }) : assert(itemBuilder != null), assert(diameterRatio != null), assert(diameterRatio > 0.0, @@ -151,7 +153,7 @@ class BrnPicker extends StatefulWidget { final Color backgroundColor; ///分割线颜色 - final Color lineColor; + final Color? lineColor; /// {@macro flutter.rendering.wheelList.offAxisFraction} final double offAxisFraction; @@ -165,7 +167,7 @@ class BrnPicker extends StatefulWidget { /// A [FixedExtentScrollController] to read and control the current item. /// /// If null, an implicit one will be created internally. - final FixedExtentScrollController scrollController; + final FixedExtentScrollController? scrollController; /// The uniform height of all children. /// @@ -195,8 +197,8 @@ class BrnPicker extends StatefulWidget { } class _CupertinoPickerState extends State { - int _lastHapticIndex; - FixedExtentScrollController _controller; + int? _lastHapticIndex; + FixedExtentScrollController? _controller; @override void initState() { @@ -247,8 +249,7 @@ class _CupertinoPickerState extends State { if (widget.backgroundColor != null && widget.backgroundColor.alpha < 255) return Container(); - final Color widgetBackgroundColor = - widget.backgroundColor ?? const Color(0xFFFFFFFF); + final Color widgetBackgroundColor = widget.backgroundColor; return Positioned.fill( child: IgnorePointer( child: Container( @@ -286,7 +287,7 @@ class _CupertinoPickerState extends State { /// Makes the magnifier lens look so that the colors are normal through /// the lens and partially grayed out around it. Widget _buildMagnifierScreen() { - final Color foreground = widget.backgroundColor?.withAlpha( + final Color foreground = widget.backgroundColor.withAlpha( (widget.backgroundColor.alpha * _kForegroundScreenOpacityFraction) .toInt()); @@ -324,7 +325,7 @@ class _CupertinoPickerState extends State { } Widget _buildUnderMagnifierScreen() { - final Color foreground = widget.backgroundColor?.withAlpha( + final Color foreground = widget.backgroundColor.withAlpha( (widget.backgroundColor.alpha * _kForegroundScreenOpacityFraction) .toInt()); @@ -359,7 +360,7 @@ class _CupertinoPickerState extends State { children: [ Positioned.fill( child: _CupertinoPickerSemantics( - scrollController: widget.scrollController ?? _controller, + scrollController: widget.scrollController ?? _controller!, child: ListWheelScrollView.useDelegate( controller: widget.scrollController ?? _controller, physics: const FixedExtentScrollPhysics(), @@ -404,9 +405,9 @@ class _CupertinoPickerState extends State { // scroll controller. class _CupertinoPickerSemantics extends SingleChildRenderObjectWidget { const _CupertinoPickerSemantics({ - Key key, - Widget child, - @required this.scrollController, + Key? key, + Widget? child, + required this.scrollController, }) : super(key: key, child: child); final FixedExtentScrollController scrollController; @@ -431,16 +432,16 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { this.controller = controller; } - FixedExtentScrollController get controller => _controller; - FixedExtentScrollController _controller; + FixedExtentScrollController? get controller => _controller; + FixedExtentScrollController? _controller; - set controller(FixedExtentScrollController value) { + set controller(FixedExtentScrollController? value) { if (value == _controller) return; if (_controller != null) - _controller.removeListener(_handleScrollUpdate); + _controller!.removeListener(_handleScrollUpdate); else - _currentIndex = value.initialItem ?? 0; - value.addListener(_handleScrollUpdate); + _currentIndex = value!.initialItem; + value?.addListener(_handleScrollUpdate); _controller = value; } @@ -456,17 +457,17 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { int _currentIndex = 0; void _handleIncrease() { - controller.jumpToItem(_currentIndex + 1); + controller!.jumpToItem(_currentIndex + 1); } void _handleDecrease() { if (_currentIndex == 0) return; - controller.jumpToItem(_currentIndex - 1); + controller!.jumpToItem(_currentIndex - 1); } void _handleScrollUpdate() { - if (controller.selectedItem == _currentIndex) return; - _currentIndex = controller.selectedItem; + if (controller!.selectedItem == _currentIndex) return; + _currentIndex = controller!.selectedItem; markNeedsSemanticsUpdate(); } @@ -483,7 +484,7 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { if (children.isEmpty) return super.assembleSemanticsNode(node, config, children); final SemanticsNode scrollable = children.first; - final Map indexedChildren = {}; + final Map indexedChildren = {}; scrollable.visitChildren((SemanticsNode child) { assert(child.indexInParent != null); indexedChildren[child.indexInParent] = child; @@ -492,9 +493,9 @@ class _RenderCupertinoPickerSemantics extends RenderProxyBox { if (indexedChildren[_currentIndex] == null) { return node.updateWith(config: config); } - config.value = indexedChildren[_currentIndex].label; - final SemanticsNode previousChild = indexedChildren[_currentIndex - 1]; - final SemanticsNode nextChild = indexedChildren[_currentIndex + 1]; + config.value = indexedChildren[_currentIndex]!.label; + final SemanticsNode? previousChild = indexedChildren[_currentIndex - 1]; + final SemanticsNode? nextChild = indexedChildren[_currentIndex + 1]; if (nextChild != null) { config.increasedValue = nextChild.label; config.onIncrease = _handleIncrease; diff --git a/lib/src/components/picker/base/brn_picker_constants.dart b/lib/src/components/picker/base/brn_picker_constants.dart index bbc22b4d..9ed44cc5 100755 --- a/lib/src/components/picker/base/brn_picker_constants.dart +++ b/lib/src/components/picker/base/brn_picker_constants.dart @@ -1,26 +1,28 @@ -import 'dart:ui'; - import 'package:flutter/material.dart'; /// Default value of DatePicker's item [TextStyle]. -const TextStyle DATETIME_PICKER_ITEM_TEXT_STYLE = - const TextStyle(color: Color(0xFF222222), fontSize: 18.0); +const TextStyle datetimePickerItemTextStyle = TextStyle( + color: Color(0xFF222222), + fontSize: 18.0, +); /// Default value of DatePicker's background color. -const PICKER_BACKGROUND_COLOR = Colors.white; +const pickerBackgroundColor = Colors.white; /// Default value of whether show title widget or not. -const PICKER_SHOW_TITLE_DEFAULT = true; +const pickerShowTitleDefault = true; /// Default value of DatePicker's height. -const double PICKER_HEIGHT = 240.0; +const double pickerHeight = 240.0; /// Default value of DatePicker's title height. -const double PICKER_TITLE_HEIGHT = 48.0; +const double pickerTitleHeight = 48.0; /// Default value of DatePicker's column height. -const double PICKER_ITEM_HEIGHT = 48.0; +const double pickerItemHeight = 48.0; /// Default value of DatePicker's item [TextStyle]. -const TextStyle PICKER_ITEM_TEXT_STYLE = - const TextStyle(color: Color(0xFF222222), fontSize: 18.0); +const TextStyle pickerItemTextStyle = TextStyle( + color: Color(0xFF222222), + fontSize: 18.0, +); diff --git a/lib/src/components/picker/base/brn_picker_title.dart b/lib/src/components/picker/base/brn_picker_title.dart index 33cf3427..7079cbbf 100755 --- a/lib/src/components/picker/base/brn_picker_title.dart +++ b/lib/src/components/picker/base/brn_picker_title.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/time_picker/brn_date_picker_constants.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/theme/brn_theme.dart'; @@ -9,21 +11,21 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class BrnPickerTitle extends StatelessWidget { final BrnPickerTitleConfig pickerTitleConfig; - final DateTimePickerLocale locale; + final DateTimePickerLocale? locale; final DateVoidCallback onCancel, onConfirm; - BrnPickerConfig themeData; + BrnPickerConfig? themeData; BrnPickerTitle({ - Key key, + Key? key, this.locale, - @required this.onCancel, - @required this.onConfirm, - this.pickerTitleConfig, + required this.onCancel, + required this.onConfirm, + this.pickerTitleConfig = BrnPickerTitleConfig.Default, this.themeData, }) : super(key: key) { this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } @@ -31,16 +33,16 @@ class BrnPickerTitle extends StatelessWidget { @override Widget build(BuildContext context) { if (pickerTitleConfig.title != null) { - return pickerTitleConfig.title; + return pickerTitleConfig.title!; } return Container( - height: themeData.titleHeight, + height: themeData!.titleHeight, decoration: ShapeDecoration( - color: themeData.backgroundColor, + color: themeData!.backgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( - topLeft: Radius.circular(themeData.cornerRadius), - topRight: Radius.circular(themeData.cornerRadius), + topLeft: Radius.circular(themeData!.cornerRadius), + topRight: Radius.circular(themeData!.cornerRadius), ), ), ), @@ -49,7 +51,7 @@ class BrnPickerTitle extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ Container( - height: themeData.titleHeight - 0.5, + height: themeData!.titleHeight - 0.5, padding: EdgeInsets.symmetric(horizontal: 20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, @@ -62,7 +64,7 @@ class BrnPickerTitle extends StatelessWidget { ), Text( pickerTitleConfig.titleContent, - style: themeData.titleTextStyle.generateTextStyle(), + style: themeData!.titleTextStyle.generateTextStyle(), ), GestureDetector( child: _renderConfirmWidget(context), @@ -74,7 +76,7 @@ class BrnPickerTitle extends StatelessWidget { ), ), Divider( - color: themeData.dividerColor, + color: themeData!.dividerColor, indent: 0.0, height: 0.5, ), @@ -85,9 +87,9 @@ class BrnPickerTitle extends StatelessWidget { /// render cancel button widget Widget _renderCancelWidget(BuildContext context) { - Widget cancelWidget = pickerTitleConfig.cancel; + Widget? cancelWidget = pickerTitleConfig.cancel; if (cancelWidget == null) { - TextStyle textStyle = themeData.cancelTextStyle.generateTextStyle(); + TextStyle textStyle = themeData!.cancelTextStyle.generateTextStyle(); cancelWidget = Text( '取消', style: textStyle, @@ -99,9 +101,9 @@ class BrnPickerTitle extends StatelessWidget { /// render confirm button widget Widget _renderConfirmWidget(BuildContext context) { - Widget confirmWidget = pickerTitleConfig.confirm; + Widget? confirmWidget = pickerTitleConfig.confirm; if (confirmWidget == null) { - TextStyle textStyle = themeData.confirmTextStyle.generateTextStyle(); + TextStyle textStyle = themeData!.confirmTextStyle.generateTextStyle(); confirmWidget = Text( '完成', style: textStyle, diff --git a/lib/src/components/picker/base/brn_picker_title_config.dart b/lib/src/components/picker/base/brn_picker_title_config.dart index 0c57d664..84d0cafc 100755 --- a/lib/src/components/picker/base/brn_picker_title_config.dart +++ b/lib/src/components/picker/base/brn_picker_title_config.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/base/brn_picker_constants.dart'; import 'package:flutter/material.dart'; @@ -15,20 +17,20 @@ class BrnPickerTitleConfig { this.cancel, this.confirm, this.title, - this.showTitle: PICKER_SHOW_TITLE_DEFAULT, + this.showTitle: pickerShowTitleDefault, this.titleContent: "请选择", }); static const BrnPickerTitleConfig Default = const BrnPickerTitleConfig(); /// Custom cancel [Widget]. - final Widget cancel; + final Widget? cancel; /// Custom confirm [Widget]. - final Widget confirm; + final Widget? confirm; /// Custom title [Widget]. If specify a title widget, the cancel and confirm widgets will not display. - final Widget title; + final Widget? title; /// Whether display title widget or not. If set false, the default cancel and confirm widgets will not display, but the custom title widget will display if had specified one custom title widget. final bool showTitle; diff --git a/lib/src/components/picker/brn_bottom_picker.dart b/lib/src/components/picker/brn_bottom_picker.dart index 05fd0d8e..91a531c9 100644 --- a/lib/src/components/picker/brn_bottom_picker.dart +++ b/lib/src/components/picker/brn_bottom_picker.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; @@ -24,12 +26,12 @@ import 'package:flutter/rendering.dart'; class BrnBottomPicker { static void show( BuildContext context, { - @required contentWidget, + required contentWidget, String title = '请选择', dynamic confirm, dynamic cancel, - VoidCallback onConfirm, - VoidCallback onCancel, + VoidCallback? onConfirm, + VoidCallback? onCancel, bool barrierDismissible = true, bool showTitle = true, }) { @@ -48,7 +50,7 @@ class BrnBottomPicker { pickerTitleConfig: BrnPickerTitleConfig(titleContent: title, showTitle: showTitle), ); - return theme != null ? Theme(data: theme, child: pageChild) : pageChild; + return Theme(data: theme, child: pageChild); }, barrierDismissible: barrierDismissible, barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel, @@ -73,14 +75,14 @@ class BrnBottomPickerWidget extends StatefulWidget { final Widget contentWidget; final dynamic confirm; final dynamic cancel; - final Function() onConfirmPressed; - final Function() onCancelPressed; + final Function()? onConfirmPressed; + final Function()? onCancelPressed; final barrierDismissible; final BrnPickerTitleConfig pickerTitleConfig; const BrnBottomPickerWidget({ - Key key, - this.contentWidget, + Key? key, + required this.contentWidget, this.confirm, this.cancel, this.onConfirmPressed, @@ -97,8 +99,8 @@ class BrnBottomPickerWidget extends StatefulWidget { class BrnBottomPickerWidgetState extends State with TickerProviderStateMixin { - AnimationController _controller; - Animation _animation; + late AnimationController _controller; + late Animation _animation; @override void initState() { @@ -115,7 +117,7 @@ class BrnBottomPickerWidgetState extends State Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { - _controller?.reverse(); + _controller.reverse(); return true; }, child: Scaffold( @@ -134,12 +136,12 @@ class BrnBottomPickerWidgetState extends State @override void dispose() { super.dispose(); - _controller?.dispose(); + _controller.dispose(); } Widget _buildBottomWidget() { return SlideTransition( - position: _animation, + position: _animation as Animation, child: BrnPickerClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(BrnThemeConfigurator.instance @@ -175,14 +177,14 @@ class BrnBottomPickerWidgetState extends State if (widget.onCancelPressed == null) { _closeDialog(); } else { - widget.onCancelPressed(); + widget.onCancelPressed!(); } }, onConfirm: () { if (widget.onConfirmPressed == null) { _closeDialog(); } else { - widget.onConfirmPressed(); + widget.onConfirmPressed!(); } }, pickerTitleConfig: BrnPickerTitleConfig( @@ -192,8 +194,8 @@ class BrnBottomPickerWidgetState extends State ); } - Widget _buildConfirmWidget() { - Widget confirmWidget; + Widget? _buildConfirmWidget() { + Widget? confirmWidget; if (widget.confirm is Widget) { confirmWidget = widget.confirm; } else if (widget.confirm is String) { @@ -204,8 +206,8 @@ class BrnBottomPickerWidgetState extends State return confirmWidget; } - Widget _buildCancelWidget() { - Widget cancelWidget; + Widget? _buildCancelWidget() { + Widget? cancelWidget; if (widget.cancel is Widget) { cancelWidget = widget.cancel; } else if (widget.cancel is String) { @@ -229,7 +231,7 @@ class BrnBottomPickerWidgetState extends State ); } - Widget _buildDefaultCancel(String string) { + Widget _buildDefaultCancel(String? string) { return Text( string ?? '取消', style: TextStyle( diff --git a/lib/src/components/picker/brn_bottom_write_picker.dart b/lib/src/components/picker/brn_bottom_write_picker.dart index cbd9bbd3..c5a5cbaf 100644 --- a/lib/src/components/picker/brn_bottom_write_picker.dart +++ b/lib/src/components/picker/brn_bottom_write_picker.dart @@ -1,15 +1,17 @@ + + import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_bottom_picker.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; ///取消输入事件回调 -typedef BrnBottomWritePickerClickCallback = Future Function( - String content); +typedef BrnBottomWritePickerClickCallback = Future? Function( + String? content); ///确认输入事件回调 -typedef BrnBottomWritePickerConfirmClickCallback = Future Function( - BuildContext dialogContext, String content); +typedef BrnBottomWritePickerConfirmClickCallback = Future? Function( + BuildContext dialogContext, String? content); class BrnBottomWritePicker extends StatefulWidget { /// 弹窗左边自定义文案,默认 '取消' @@ -28,22 +30,22 @@ class BrnBottomWritePicker extends StatefulWidget { final int maxLength; /// 取消输入事件回调 - final BrnBottomWritePickerClickCallback onCancel; + final BrnBottomWritePickerClickCallback? onCancel; /// 确认输入内容事件回调 - final BrnBottomWritePickerConfirmClickCallback onConfirm; + final BrnBottomWritePickerConfirmClickCallback? onConfirm; /// 弹窗右边文案颜色 - final Color rightTextColor; + final Color? rightTextColor; /// 光标颜色 - final Color cursorColor; + final Color? cursorColor; /// 默认文本 - final String defaultText; + final String? defaultText; /// 用于对 TextField 更精细的控制,若传入该字段,[defaultText] 参数将失效,可使用 TextEditingController.text 进行赋值。 - final TextEditingController textEditingController; + final TextEditingController? textEditingController; const BrnBottomWritePicker( {this.maxLength = 200, @@ -69,14 +71,14 @@ class BrnBottomWritePicker extends StatefulWidget { String leftTag = "取消", String title = "", String rightTag = "确认", - BrnBottomWritePickerClickCallback onCancel, - BrnBottomWritePickerConfirmClickCallback onConfirm, + BrnBottomWritePickerClickCallback? onCancel, + BrnBottomWritePickerConfirmClickCallback? onConfirm, bool confirmDismiss = false, bool cancelDismiss = true, - Color rightTextColor, - Color cursorColor, - String defaultText, - TextEditingController textEditingController}) { + Color? rightTextColor, + Color? cursorColor, + String? defaultText, + TextEditingController? textEditingController}) { final ThemeData theme = Theme.of(context); showGeneralDialog( context: context, @@ -103,26 +105,24 @@ class BrnBottomWritePicker extends StatefulWidget { defaultText: defaultText, textEditingController: textEditingController, ); - return theme != null - ? Theme(data: theme, child: pageChild) - : pageChild; + return Theme(data: theme, child: pageChild); }); } } class _BottomWritePickerState extends State { - TextEditingController _controller; + TextEditingController? _controller; @override void initState() { super.initState(); if (_controller == null) { - if (widget.defaultText != null && widget.defaultText.length > 0) { + if (widget.defaultText != null && widget.defaultText!.length > 0) { _controller = TextEditingController.fromValue(TextEditingValue( - text: widget.defaultText, + text: widget.defaultText!, selection: TextSelection.fromPosition(TextPosition( affinity: TextAffinity.downstream, - offset: widget.defaultText.length)))); + offset: widget.defaultText!.length)))); } else { _controller = TextEditingController(); } @@ -171,12 +171,12 @@ class _BottomWritePickerState extends State { cancel: widget.leftTag, onConfirmPressed: () { if (widget.onConfirm != null) { - widget.onConfirm(context, _controller?.text); + widget.onConfirm!(context, _controller?.text); } }, onCancelPressed: () { if (widget.onCancel != null) { - widget.onCancel(_controller?.text); + widget.onCancel!(_controller?.text); } }, barrierDismissible: true, diff --git a/lib/src/components/picker/brn_mulit_select_tags_picker.dart b/lib/src/components/picker/brn_mulit_select_tags_picker.dart index 7326c839..d222640d 100644 --- a/lib/src/components/picker/brn_mulit_select_tags_picker.dart +++ b/lib/src/components/picker/brn_mulit_select_tags_picker.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_tags_common_picker.dart'; import 'package:bruno/src/components/picker/brn_tags_picker_config.dart'; @@ -23,14 +25,15 @@ typedef BrnMultiSelectTagOnItemClick = void Function( /// 多选标签弹框,适用于底部弹出 Picker,且选择样式为 Tag 的场景。 /// 功能:多选标签弹框,适用于从底部弹出的情况,属于 Picker; /// 可自定义标题、默认选中、字体大小等。 +// ignore: must_be_immutable class BrnMultiSelectTagsPicker extends CommonTagsPicker { BrnMultiSelectTagsPicker({ - Key key, - @required this.context, - @required this.onConfirm, + Key? key, + required this.context, + required this.onConfirm, this.onCancel, - @required this.tagPickerConfig, - @required this.onTagValueGetter, + required this.tagPickerConfig, + required this.onTagValueGetter, this.onMaxSelectClick, this.onItemClick, this.maxSelectItemCount = 0, @@ -38,7 +41,7 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { this.itemHeight = 34.0, this.layoutStyle = BrnMultiSelectTagsLayoutStyle.average, BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig.Default, - BrnPickerConfig themeData, + BrnPickerConfig? themeData, }) : super( key: key, context: context, @@ -54,16 +57,16 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { final ValueChanged onConfirm; /// 点击取消按钮 - final VoidCallback onCancel; + final VoidCallback? onCancel; /// 当点击到最大数目时的点击事件 - final VoidCallback onMaxSelectClick; + final VoidCallback? onMaxSelectClick; /// 点击某个按钮的回调 - final BrnMultiSelectTagOnItemClick onItemClick; + final BrnMultiSelectTagOnItemClick? onItemClick; /// 一行多少个数据,默认4个 - final int crossAxisCount; + final int? crossAxisCount; /// 最多选择多少个item,默认可以无限选 final int maxSelectItemCount; @@ -82,8 +85,8 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { final double itemHeight; /// 操作类型属性 - List _selectedTags; - List _sourceTags; + late List _selectedTags; + late List _sourceTags; @override void show() { @@ -97,8 +100,8 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { } @override - Widget createBuilder(BuildContext context, VoidCallback onUpdate) { - if (this.tagPickerConfig?.tagItemSource?.isNotEmpty ?? false) { + Widget createBuilder(BuildContext context, VoidCallback? onUpdate) { + if (this.tagPickerConfig.tagItemSource.isNotEmpty) { return _buildContent(context, onUpdate); } else { return Container( @@ -110,12 +113,12 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { } } - Widget _buildContent(BuildContext context, VoidCallback onUpdate) { + Widget _buildContent(BuildContext context, VoidCallback? onUpdate) { if (this.layoutStyle == BrnMultiSelectTagsLayoutStyle.average) { return LayoutBuilder( builder: (_, constraints) { - double maxwidth = constraints.maxWidth; - return _buildGridViewWidget(context, onUpdate, maxwidth); + double maxWidth = constraints.maxWidth; + return _buildGridViewWidget(context, onUpdate, maxWidth); }, ); } else { @@ -125,11 +128,11 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { ///等宽度的布局 Widget _buildGridViewWidget( - BuildContext context, VoidCallback onUpdate, double maxWidth) { + BuildContext context, VoidCallback? onUpdate, double maxWidth) { int brnCrossAxisCount = - (this.crossAxisCount == 0 || this.crossAxisCount == null) + (this.crossAxisCount == null || this.crossAxisCount == 0) ? 4 - : this.crossAxisCount; + : this.crossAxisCount!; double width = (maxWidth - (brnCrossAxisCount - 1) * 12 - 40) / brnCrossAxisCount; //计算宽高比 @@ -141,9 +144,9 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { .getConfig() .commonConfig .colorTextImportant; - Color tagBackgroudColor = + Color tagBackgroundColor = this.tagPickerConfig.tagBackgroudColor ?? Color(0xffF8F8F8); - Color selectedTagBackgroudColor = + Color selectedTagBackgroundColor = this.tagPickerConfig.selectedTagBackgroudColor ?? BrnThemeConfigurator.instance .getConfig() @@ -175,8 +178,8 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { selected: selected, padding: edgeInsets, pressElevation: 0, - backgroundColor: tagBackgroudColor, - selectedColor: selectedTagBackgroudColor, + backgroundColor: tagBackgroundColor, + selectedColor: selectedTagBackgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(2.0)), label: Container( @@ -199,12 +202,12 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { value == true) { if (this.onMaxSelectClick != null) { // ignore: unnecessary_statements - this.onMaxSelectClick(); + this.onMaxSelectClick!(); } return; } _clickTag(value, choice); - onUpdate(); + onUpdate!(); }, ); }).toList(), @@ -213,7 +216,7 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { } ///流式布局 - Widget _buildWrapViewWidget(BuildContext context, VoidCallback onUpdate) { + Widget _buildWrapViewWidget(BuildContext context, VoidCallback? onUpdate) { Color selectedTagTitleColor = this.tagPickerConfig.selectedTagTitleColor ?? BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary; Color tagTitleColor = this.tagPickerConfig.tagTitleColor ?? @@ -221,9 +224,9 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { .getConfig() .commonConfig .colorTextImportant; - Color tagBackgroudColor = + Color tagBackgroundColor = this.tagPickerConfig.tagBackgroudColor ?? Color(0xffF8F8F8); - Color selectedTagBackgroudColor = + Color selectedTagBackgroundColor = this.tagPickerConfig.selectedTagBackgroudColor ?? BrnThemeConfigurator.instance .getConfig() @@ -245,8 +248,8 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { selected: selected, padding: edgeInsets, pressElevation: 0, - backgroundColor: tagBackgroudColor, - selectedColor: selectedTagBackgroudColor, + backgroundColor: tagBackgroundColor, + selectedColor: selectedTagBackgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(2.0)), label: Text( @@ -266,12 +269,12 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { value == true) { if (this.onMaxSelectClick != null) { // ignore: unnecessary_statements - this.onMaxSelectClick(); + this.onMaxSelectClick!(); } return; } _clickTag(value, choice); - onUpdate(); + onUpdate!(); }, ); }).toList(), @@ -279,12 +282,12 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { } void _dataSetup() { - List tagItems = List(); - List tagSelectItems = List(); + List tagItems = []; + List tagSelectItems = []; for (BrnTagItemBean item in this.tagPickerConfig.tagItemSource) { tagItems.add(item); //选中的按钮 - if (item.isSelect == true && item.name != null) { + if (item.isSelect == true) { tagSelectItems.add(item); } } @@ -306,7 +309,7 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { ///点击tag if (this.onItemClick != null) { - this.onItemClick(tagName, selected); + this.onItemClick!(tagName, selected); } } } diff --git a/lib/src/components/picker/brn_multi_picker.dart b/lib/src/components/picker/brn_multi_picker.dart index 06ff4bec..e6ad7cc4 100644 --- a/lib/src/components/picker/brn_multi_picker.dart +++ b/lib/src/components/picker/brn_multi_picker.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/base/brn_picker.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; @@ -5,8 +7,7 @@ import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; import 'package:bruno/src/theme/brn_theme.dart'; import 'package:flutter/material.dart'; -///数据选择控件高度 -const pickerHeight = 240.0; +import 'base/brn_picker_constants.dart'; /// 可以自定义实现 item Widget样式,更灵活 /// [isSelect] 是否被选中 @@ -34,7 +35,7 @@ abstract class BrnMultiDataPickerDelegate { String titleForRowInComponent(int component, int index); /// 定义每列内容的高度 - double rowHeightForComponent(int component); + double? rowHeightForComponent(int component); /// 定义选择更改后的操作 void selectRowInComponent(int component, int row); @@ -50,7 +51,7 @@ class BrnMultiDataPicker extends StatefulWidget { final String title; ///多级数据选择标题文案样式 - final TextStyle titleTextStyle; + final TextStyle? titleTextStyle; /// 多级数据选择弹窗所要覆盖页面的context final BuildContext context; @@ -59,50 +60,50 @@ class BrnMultiDataPicker extends StatefulWidget { final BrnMultiDataPickerDelegate delegate; ///多级数据选择确认文案样式 - final TextStyle confirmTextStyle; + final TextStyle? confirmTextStyle; ///多级数据选择取消文案样式 - final TextStyle cancelTextStyle; + final TextStyle? cancelTextStyle; /// 多级数据选择每一级的默认标题 - final List pickerTitles; + final List? pickerTitles; /// 多级数据选择每一级默认标题的字体大小 - final double pickerTitleFontSize; + final double? pickerTitleFontSize; /// 多级数据选择每一级默认标题的文案颜色 - final Color pickerTitleColor; + final Color? pickerTitleColor; /// 多级数据选择数据字体大小 - final double textFontSize; + final double? textFontSize; /// 多级数据选择数据文案颜色 - final Color textColor; + final Color? textColor; /// 多级数据选择数据选中文案颜色 - final Color textSelectedColor; + final Color? textSelectedColor; /// 多级数据选择数据widget容器 - final List controllers = List(); + final List controllers = []; /// 多级数据选择确认点击回调 - final ConfirmButtonClick confirmClick; + final ConfirmButtonClick? confirmClick; /// 选择轮盘的滚动行为 - final ScrollBehavior behavior; + final ScrollBehavior? behavior; /// 返回自定义 itemWidget 的回调 - final BrnMultiDataPickerCreateWidgetCallback createItemWidget; + final BrnMultiDataPickerCreateWidgetCallback? createItemWidget; /// 是否复位数据位置。默认 true final bool sync; - BrnPickerConfig themeData; + BrnPickerConfig? themeData; BrnMultiDataPicker( - {Key key, - @required this.context, - @required this.delegate, + {Key? key, + required this.context, + required this.delegate, this.title = "", this.titleTextStyle, this.confirmTextStyle, @@ -117,10 +118,9 @@ class BrnMultiDataPicker extends StatefulWidget { this.confirmClick, this.createItemWidget, this.themeData, - this.sync = true}) - : assert(delegate != null) { + this.sync = true}) { this.themeData ??= BrnPickerConfig(); - this.themeData = this.themeData.merge(BrnPickerConfig( + this.themeData = this.themeData!.merge(BrnPickerConfig( cancelTextStyle: BrnTextStyle.withStyle(cancelTextStyle), confirmTextStyle: BrnTextStyle.withStyle(confirmTextStyle), titleTextStyle: BrnTextStyle.withStyle(titleTextStyle), @@ -130,7 +130,7 @@ class BrnMultiDataPicker extends StatefulWidget { )); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } @@ -153,7 +153,7 @@ class BrnMultiDataPicker extends StatefulWidget { } class _BrnMultiDataPickerState extends State { - List _selectedIndexList = List(); + List _selectedIndexList = []; @override void initState() { @@ -166,7 +166,7 @@ class _BrnMultiDataPickerState extends State { @override Widget build(BuildContext context) { return Container( - height: widget.themeData.pickerHeight + widget.themeData.titleHeight, + height: widget.themeData!.pickerHeight + widget.themeData!.titleHeight, child: Material( type: MaterialType.transparency, child: new Column( @@ -174,8 +174,8 @@ class _BrnMultiDataPickerState extends State { children: [ BrnPickerClipRRect( borderRadius: BorderRadius.only( - topLeft: Radius.circular(widget.themeData.cornerRadius), - topRight: Radius.circular(widget.themeData.cornerRadius), + topLeft: Radius.circular(widget.themeData!.cornerRadius), + topRight: Radius.circular(widget.themeData!.cornerRadius), ), child: _configHeaderWidget(), ), @@ -198,7 +198,8 @@ class _BrnMultiDataPickerState extends State { }, onConfirm: () { Navigator.of(context).pop(_selectedIndexList); - widget?.confirmClick(_selectedIndexList); + if (widget.confirmClick != null) + widget.confirmClick!(_selectedIndexList); }, ); } @@ -216,7 +217,7 @@ class _BrnMultiDataPickerState extends State { } List _pickersWithTitle() { - List pickersWithTitle = List(); + List pickersWithTitle = []; for (int i = 0; i < widget.delegate.numberOfComponent(); i++) { int initRow = widget.delegate.initSelectedRowForComponent(i); FixedExtentScrollController controller = @@ -234,7 +235,7 @@ class _BrnMultiDataPickerState extends State { child: Padding( padding: EdgeInsets.only(top: 25), child: Text( - widget.pickerTitles[i], + widget.pickerTitles == null ? '' : widget.pickerTitles![i], style: TextStyle( fontSize: widget.pickerTitleFontSize, color: widget.pickerTitleColor), @@ -250,7 +251,7 @@ class _BrnMultiDataPickerState extends State { //picker数据 List _pickers() { - List pickers = List(); + List pickers = []; for (int i = 0; i < widget.delegate.numberOfComponent(); i++) { int initRow = widget.delegate.initSelectedRowForComponent(i); FixedExtentScrollController controller = @@ -266,25 +267,25 @@ class _BrnMultiDataPickerState extends State { //构建单列数据 Widget _configSinglePicker(int component) { return MyPicker( - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, controller: widget.controllers[component], key: Key(component.toString()), createWidgetList: () { if (widget.createItemWidget != null) { - List widgetList = List(); + List widgetList = []; for (int i = 0; i < widget.delegate.numberOfRowsInComponent(component); i++) { bool isSelect = _selectedIndexList[component] == i; widgetList.add(widget.createItemWidget != null - ? widget.createItemWidget( + ? widget.createItemWidget!( isSelect, component, i, _selectedIndexList) : Container()); } return widgetList; } else { - List list = List(); + List list = []; for (int i = 0; i < widget.delegate.numberOfRowsInComponent(component); i++) { @@ -292,8 +293,8 @@ class _BrnMultiDataPickerState extends State { child: Text( widget.delegate.titleForRowInComponent(component, i), style: _selectedIndexList[component] == i - ? widget.themeData.itemTextSelectedStyle.generateTextStyle() - : widget.themeData.itemTextStyle.generateTextStyle(), + ? widget.themeData!.itemTextSelectedStyle.generateTextStyle() + : widget.themeData!.itemTextStyle.generateTextStyle(), ), )); } @@ -301,7 +302,7 @@ class _BrnMultiDataPickerState extends State { } }, itemExtent: widget.delegate.rowHeightForComponent(component) ?? - widget.themeData.itemHeight, + widget.themeData!.itemHeight, changed: (int index) { widget.delegate.selectRowInComponent(component, index); _selectedIndexList[component] = index; @@ -309,7 +310,7 @@ class _BrnMultiDataPickerState extends State { for (int i = component + 1; i < widget.delegate.numberOfComponent(); i++) { - List list = List(); + List list = []; for (int j = 0; j < widget.delegate.numberOfRowsInComponent(component); j++) { @@ -332,33 +333,31 @@ class _BrnMultiDataPickerState extends State { /// 一级数据选择widget class MyPicker extends StatefulWidget { ///创建数据widget列表 - final CreateWidgetList createWidgetList; + final CreateWidgetList? createWidgetList; ///数据选择改变回调 - final ValueChanged changed; - - final Key key; + final ValueChanged? changed; /// 数据显示高度 final double itemExtent; /// 滚动行为 - final ScrollBehavior scrollBehavior; + final ScrollBehavior? scrollBehavior; - final FixedExtentScrollController controller; + final FixedExtentScrollController? controller; final Color backgroundColor; - final Color lineColor; + final Color? lineColor; MyPicker({ + Key? key, this.createWidgetList, this.changed, - this.key, this.scrollBehavior, this.itemExtent = 45, this.controller, this.backgroundColor = Colors.white, this.lineColor, - }); + }) : super(key: key); @override State createState() { @@ -369,7 +368,7 @@ class MyPicker extends StatefulWidget { class _MyPickerState extends State { @override Widget build(BuildContext context) { - var children = widget.createWidgetList(); + var children = widget.createWidgetList!(); return Container( child: ScrollConfiguration( behavior: widget.scrollBehavior ?? _DefaultScrollBehavior(), @@ -381,7 +380,7 @@ class _MyPickerState extends State { lineColor: widget.lineColor, onSelectedItemChanged: (index) { if (widget.changed != null) { - widget.changed(index); + widget.changed!(index); } }, children: children.length > 0 diff --git a/lib/src/components/picker/brn_picker_cliprrect.dart b/lib/src/components/picker/brn_picker_cliprrect.dart index eed8707b..ca5ac7e3 100644 --- a/lib/src/components/picker/brn_picker_cliprrect.dart +++ b/lib/src/components/picker/brn_picker_cliprrect.dart @@ -6,12 +6,11 @@ import 'package:flutter/widgets.dart'; /// [borderRadius] 默认值为 BorderRadius.only(topLeft: Radius.circular(8.0), topRight: Radius.circular(8.0)), class BrnPickerClipRRect extends ClipRRect { const BrnPickerClipRRect({ - Key key, + Key? key, BorderRadius borderRadius = const BorderRadius.only( topLeft: Radius.circular(8.0), topRight: Radius.circular(8.0), ), - Widget child, - }) : assert(borderRadius != null), - super(key: key, borderRadius: borderRadius, child: child); + Widget? child, + }) : super(key: key, borderRadius: borderRadius, child: child); } diff --git a/lib/src/components/picker/brn_select_tags_with_input_picker.dart b/lib/src/components/picker/brn_select_tags_with_input_picker.dart index a3f9474e..bb39f13f 100644 --- a/lib/src/components/picker/brn_select_tags_with_input_picker.dart +++ b/lib/src/components/picker/brn_select_tags_with_input_picker.dart @@ -9,9 +9,9 @@ import 'package:flutter/rendering.dart'; typedef SelectTagWithInputValueGetter = String Function(V data); ///提交按钮事件回调 -typedef BrnTagInputConfirmClickCallback = Future Function( +typedef BrnTagInputConfirmClickCallback = Future? Function( BuildContext dialogContext, - List selectedTags, + List? selectedTags, String content); ///关闭 picker回调 @@ -29,19 +29,19 @@ class BrnSelectTagsWithInputPicker extends Dialog { final int maxLength; ///输入内容事件回调 - final BrnTagInputConfirmClickCallback confirm; + final BrnTagInputConfirmClickCallback? confirm; ///关闭 picker 回调 - final BrnTagInputCancelClickCallBack cancelCallBack; + final BrnTagInputCancelClickCallBack? cancelCallBack; ///光标颜色 - final Color cursorColor; + final Color? cursorColor; /// 默认文本 - final String defaultText; + final String? defaultText; /// 用于对 TextField 更精细的控制,若传入该字段,[defaultText] 参数将失效,可使用 TextEditingController.text 进行赋值。 - final TextEditingController textEditingController; + final TextEditingController? textEditingController; /// 强制显示文本框 final bool forceShowTextInput; @@ -66,8 +66,8 @@ class BrnSelectTagsWithInputPicker extends Dialog { this.multiSelect = false, this.defaultText, this.textEditingController, - @required this.tagPickerConfig, - @required this.onTagValueGetter}); + required this.tagPickerConfig, + required this.onTagValueGetter}); @override Widget build(BuildContext context) { @@ -89,29 +89,29 @@ class BrnSelectTagsWithInputPicker extends Dialog { } class BrnSelectTagsWithInputPickerWidget extends StatefulWidget { - final String title; - final BrnTagInputConfirmClickCallback confirm; - final BrnTagInputCancelClickCallBack cancelCallBack; - final int maxLength; - final String hintText; - final Color cursorColor; + final String? title; + final BrnTagInputConfirmClickCallback? confirm; + final BrnTagInputCancelClickCallBack? cancelCallBack; + final int? maxLength; + final String? hintText; + final Color? cursorColor; final bool forceShowTextInput; final bool multiSelect; - final String defaultText; - final TextEditingController textEditingController; - final BrnTagsInputPickerConfig tagPickerBean; - final SelectTagWithInputValueGetter onTagValueGetter; + final String? defaultText; + final TextEditingController? textEditingController; + final BrnTagsInputPickerConfig? tagPickerBean; + final SelectTagWithInputValueGetter? onTagValueGetter; const BrnSelectTagsWithInputPickerWidget( - {Key key, + {Key? key, this.title, this.confirm, this.cancelCallBack, this.maxLength, this.hintText, this.cursorColor, - this.forceShowTextInput, - this.multiSelect, + this.forceShowTextInput = false, + this.multiSelect = false, this.defaultText, this.textEditingController, this.tagPickerBean, @@ -126,13 +126,13 @@ class BrnSelectTagsWithInputPickerWidget extends StatefulWidget { class _BrnSelectTagsWithInputPickerWidgetState extends State with AutomaticKeepAliveClientMixin { - TextEditingController _textEditingController; + TextEditingController? _textEditingController; /// 暂定只支持两列标签 int brnCrossAxisCount = 2; - List _selectedTags; - List _sourceTags; + late List _selectedTags; + late List _sourceTags; @override void initState() { @@ -140,11 +140,11 @@ class _BrnSelectTagsWithInputPickerWidgetState _dataSetup(); _textEditingController = widget.textEditingController ?? TextEditingController.fromValue(TextEditingValue( - text: widget.defaultText == null ? "" : widget.defaultText, + text: widget.defaultText == null ? "" : widget.defaultText!, selection: TextSelection.fromPosition(TextPosition( affinity: TextAffinity.downstream, offset: widget.defaultText != null - ? widget.defaultText.length + ? widget.defaultText!.length : 0)))); } @@ -169,7 +169,7 @@ class _BrnSelectTagsWithInputPickerWidgetState ), child: Column( mainAxisSize: MainAxisSize.min, - children: (widget.tagPickerBean?.tagItemSource?.isNotEmpty ?? false) + children: (widget.tagPickerBean?.tagItemSource.isNotEmpty ?? false) ? _buildBody(context) : _buildNoTagsBody(context), ), @@ -216,16 +216,19 @@ class _BrnSelectTagsWithInputPickerWidgetState } void _dataSetup() { - List tagItems = List(); - List tagSelectedItems = List(); - for (BrnTagInputItemBean item in widget.tagPickerBean.tagItemSource) { - tagItems.add(item); - //选中的按钮 - if (item.isSelect == true && item.name != null) { - tagSelectedItems.add(item); + List tagItems = []; + List tagSelectedItems = []; + if (widget.tagPickerBean != null) { + for (BrnTagInputItemBean item in widget.tagPickerBean!.tagItemSource) { + tagItems.add(item); + //选中的按钮 + if (item.isSelect == true ) { + tagSelectedItems.add(item); + } } } + this._sourceTags = tagItems; // 重新排序,name 越长,越靠后 this._sourceTags.sort((left, right) { @@ -244,7 +247,7 @@ class _BrnSelectTagsWithInputPickerWidgetState mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - widget.title, + widget.title ?? '', style: TextStyle( color: BrnThemeConfigurator.instance .getConfig() @@ -257,13 +260,13 @@ class _BrnSelectTagsWithInputPickerWidgetState InkWell( onTap: () { if (widget.cancelCallBack != null) { - widget.cancelCallBack(context); + widget.cancelCallBack!(context); } Navigator.of(context).pop(); }, child: Padding( padding: EdgeInsets.all(4), - child: BrunoTools.getAssetImage(BrnAsset.ICON_PICKER_CLOSE), + child: BrunoTools.getAssetImage(BrnAsset.iconPickerClose), )) ], ), @@ -281,7 +284,7 @@ class _BrnSelectTagsWithInputPickerWidgetState double preferredWidthWithText(String content) { double originalTextWidth = paintWidthWithTextStyle( - content, TextStyle(fontSize: widget.tagPickerBean.tagTitleFontSize)); + content, TextStyle(fontSize: widget.tagPickerBean!.tagTitleFontSize)); double maxTextWidthInHalf = (MediaQuery.of(context).size.width - (brnCrossAxisCount - 1) * 12 - 20 * 2) / @@ -293,17 +296,17 @@ class _BrnSelectTagsWithInputPickerWidgetState } Widget _tagsArea(BuildContext context) { - Color selectedTagTitleColor = widget.tagPickerBean.selectedTagTitleColor ?? + Color selectedTagTitleColor = widget.tagPickerBean?.selectedTagTitleColor ?? BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary; - Color tagTitleColor = widget.tagPickerBean.tagTitleColor ?? + Color tagTitleColor = widget.tagPickerBean?.tagTitleColor ?? BrnThemeConfigurator.instance .getConfig() .commonConfig .colorTextImportant; - Color tagBackgroudColor = - widget.tagPickerBean.tagBackgroudColor ?? Color(0xffF8F8F8); - Color selectedTagBackgroudColor = - widget.tagPickerBean.selectedTagBackgroudColor ?? + Color tagBackgroundColor = + widget.tagPickerBean?.tagBackgroundColor ?? Color(0xffF8F8F8); + Color selectedTagBackgroundColor = + widget.tagPickerBean?.selectedTagBackgroundColor ?? BrnThemeConfigurator.instance .getConfig() .commonConfig @@ -318,11 +321,11 @@ class _BrnSelectTagsWithInputPickerWidgetState children: this._sourceTags.map((choice) { bool selected = choice.isSelect; Color titleColor = selected ? selectedTagTitleColor : tagTitleColor; - String textToDisplay = widget.onTagValueGetter(choice); + String textToDisplay = widget.onTagValueGetter!(choice); return ChoiceChip( selected: selected, - backgroundColor: tagBackgroudColor, - selectedColor: selectedTagBackgroudColor, + backgroundColor: tagBackgroundColor, + selectedColor: selectedTagBackgroundColor, pressElevation: 0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4.0)), @@ -331,7 +334,7 @@ class _BrnSelectTagsWithInputPickerWidgetState labelStyle: TextStyle( color: titleColor, fontWeight: selected ? FontWeight.w600 : FontWeight.w400, - fontSize: widget.tagPickerBean.tagTitleFontSize), + fontSize: widget.tagPickerBean!.tagTitleFontSize), label: Container( width: preferredWidthWithText(textToDisplay), child: Text( @@ -421,8 +424,8 @@ class _BrnSelectTagsWithInputPickerWidgetState onTap: () { if (!isCommitBtnEnable()) return; if (widget.confirm != null) { - widget.confirm( - context, this._selectedTags, _textEditingController.text); + widget.confirm!( + context, this._selectedTags, _textEditingController!.text); } }, child: Container( @@ -451,8 +454,16 @@ class _BrnSelectTagsWithInputPickerWidgetState } bool isCommitBtnEnable() { + bool needExpend = false; + for (int i = 0; i < this._selectedTags.length; i++) { + BrnTagInputItemBean brnTagInputItemBean = this._selectedTags[i]; + if (true == brnTagInputItemBean.needExpend) { + needExpend = true; + break; + } + } return this._selectedTags.length > 0 && - (isShowTextInput() ? _textEditingController.text.length > 0 : true); + (needExpend ? _textEditingController!.text.length > 0 : true); } bool isShowTextInput() { @@ -461,11 +472,11 @@ class _BrnSelectTagsWithInputPickerWidgetState } for (int i = 0; i < this._selectedTags.length; i++) { BrnTagInputItemBean brnTagInputItemBean = this._selectedTags[i]; - if (true == brnTagInputItemBean.needExplane) { + if (true == brnTagInputItemBean.needExpend) { return true; } } - _textEditingController.clear(); + _textEditingController!.clear(); return false; } @@ -482,19 +493,19 @@ class BrnTagInputItemBean { bool isSelect; ///选中tag的index - int index; + int? index; /// 选中后是否展示文本输入框 - bool needExplane; + bool needExpend; /// 附带的更多数据,方便在点击回调中取用。 - Map ext; + Map? ext; BrnTagInputItemBean({ - this.name, + this.name = '', this.isSelect = false, this.index, - this.needExplane = false, + this.needExpend = false, this.ext, }); } @@ -504,18 +515,18 @@ class BrnTagsInputPickerConfig { {this.tagTitleFontSize = 16.0, this.tagTitleColor, this.selectedTagTitleColor, - this.tagBackgroudColor, - this.selectedTagBackgroudColor, + this.tagBackgroundColor, + this.selectedTagBackgroundColor, this.tagItemSource = const []}) { this.tagTitleColor = BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase; } double tagTitleFontSize; - Color tagTitleColor; - Color selectedTagTitleColor; - Color tagBackgroudColor; - Color selectedTagBackgroudColor; + Color? tagTitleColor; + Color? selectedTagTitleColor; + Color? tagBackgroundColor; + Color? selectedTagBackgroundColor; List tagItemSource; } diff --git a/lib/src/components/picker/brn_tags_common_picker.dart b/lib/src/components/picker/brn_tags_common_picker.dart index 7a1fef20..d6cb4a5e 100644 --- a/lib/src/components/picker/brn_tags_common_picker.dart +++ b/lib/src/components/picker/brn_tags_common_picker.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; @@ -11,21 +13,22 @@ enum BrnCommonPickBackType { } typedef TagsPickerContentBuilder = Widget Function( - BuildContext context, VoidCallback onUpdate); + BuildContext context, VoidCallback? onUpdate); /// 创建时传入Builder 或者 子类实现 createBuilder 函数 +// ignore: must_be_immutable class CommonTagsPicker extends StatefulWidget { final BuildContext context; - final ValueChanged onConfirm; - final VoidCallback onCancel; - final TagsPickerContentBuilder contentBuilder; + final ValueChanged? onConfirm; + final VoidCallback? onCancel; + final TagsPickerContentBuilder? contentBuilder; final BrnPickerTitleConfig pickerTitleConfig; - BrnPickerConfig themeData; + BrnPickerConfig? themeData; CommonTagsPicker( - {Key key, - @required this.context, + {Key? key, + required this.context, this.onConfirm, this.onCancel, this.contentBuilder, @@ -34,7 +37,7 @@ class CommonTagsPicker extends StatefulWidget { : super(key: key) { this.themeData ??= BrnPickerConfig(); this.themeData = this - .themeData + .themeData! .merge(BrnThemeConfigurator.instance.getConfig().pickerConfig); } @@ -47,11 +50,11 @@ class CommonTagsPicker extends StatefulWidget { }).then((type) { if (type == BrnCommonPickBackType.confirm) { if (onConfirm != null) { - onConfirm(getConfirmData()); + onConfirm!(getConfirmData()); } } else { if (onCancel != null) { - onCancel(); + onCancel!(); } } }); @@ -59,7 +62,7 @@ class CommonTagsPicker extends StatefulWidget { /// 子类重写实现builder @protected - Widget createBuilder(BuildContext context, VoidCallback onUpdate) { + Widget? createBuilder(BuildContext context, VoidCallback? onUpdate) { return null; } @@ -78,7 +81,7 @@ class CommonTagsPicker extends StatefulWidget { } class _CommonPickerState extends State { - VoidCallback _onUpdate; + VoidCallback? _onUpdate; @override void initState() { @@ -133,9 +136,9 @@ class _CommonPickerState extends State { /// 创建内容视图 Widget _createContentWidget() { - Widget contentWidget; + Widget? contentWidget; if (widget.contentBuilder != null) { - contentWidget = widget.contentBuilder(context, _onUpdate); + contentWidget = widget.contentBuilder!(context, _onUpdate); } else { contentWidget = widget.createBuilder(context, _onUpdate); } @@ -148,7 +151,7 @@ class _CommonPickerState extends State { ); } return Container( - padding: EdgeInsets.only(top: widget.themeData.titleHeight), // 流出头部视图 + padding: EdgeInsets.only(top: widget.themeData!.titleHeight), // 流出头部视图 child: ListView( shrinkWrap: true, // 列表高度自适应 controller: ScrollController(keepScrollOffset: false), // 若视图小于弹窗则不滑动 diff --git a/lib/src/components/picker/brn_tags_picker_config.dart b/lib/src/components/picker/brn_tags_picker_config.dart index 76f82a7d..1303df3c 100644 --- a/lib/src/components/picker/brn_tags_picker_config.dart +++ b/lib/src/components/picker/brn_tags_picker_config.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; @@ -24,19 +26,19 @@ class BrnTagsPickerHeaderConfig { final double headerHeight; final String title; - Color titleColor; + Color? titleColor; final double titleFontSize; final String confirmTitle; - final Color confirmColor; + final Color? confirmColor; final double confirmFontSize; final String cancelTitle; - Color cancelColor; + Color? cancelColor; final double cancelFontSize; //分割线颜色 - final Color dividingLineColor; + final Color? dividingLineColor; } class BrnTagsPickerConfig { @@ -56,19 +58,19 @@ class BrnTagsPickerConfig { double tagTitleFontSize; ///tag 文字颜色 - Color tagTitleColor; + Color? tagTitleColor; ///选中的tag颜色 - Color selectedTagTitleColor; + Color? selectedTagTitleColor; ///tag 背景颜色 - Color tagBackgroudColor; + Color? tagBackgroudColor; ///选中的颜色 - Color selectedTagBackgroudColor; + Color? selectedTagBackgroudColor; ///内部item的边距 - EdgeInsets chipPadding; + EdgeInsets? chipPadding; ///数据源 List tagItemSource; @@ -82,13 +84,13 @@ class BrnTagItemBean { String code; ///code唯一标识 - int index; + int? index; ///是被选中 bool isSelect; ///自己添加的扩展 - Map ext; + Map? ext; BrnTagItemBean( {this.name = '', diff --git a/lib/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart b/lib/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart index c6368103..b64f03df 100644 --- a/lib/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart +++ b/lib/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart @@ -2,54 +2,50 @@ import 'package:bruno/src/constants/brn_constants.dart'; import 'package:bruno/src/utils/brn_tools.dart'; enum PickerFilterType { - None, //未设置 - UnLimit, // 不限类型,与其他所有类型互斥。 - Radio, //单选列表、单选项 type为radio - Checkbox, //多选列表、多选项 type为checkbox + none, //未设置 + unLimit, // 不限类型,与其他所有类型互斥。 + radio, //单选列表、单选项 type为radio + checkbox, //多选列表、多选项 type为checkbox } /// 筛选弹窗展示风格 enum PickerWindowType { - List, //列表类型,使用列表 Item 展示。 - Range, //值范围类型,使用 Tag + Range 的 Item 展示 + list, //列表类型,使用列表 Item 展示。 + range, //值范围类型,使用 Tag + Range 的 Item 展示 } class BrnPickerEntity { - String uniqueId; //唯一的id - String + String? uniqueId; //唯一的id + String? type; //类型 目前支持的类型有不限(unlimit)、单选(radio)、复选(checkbox), 最终被解析成 PickerFilterType 类型 - String key; //回传给服务器 - String value; //回传给服务器 + String? key; //回传给服务器 + String? value; //回传给服务器 String name; //显示的文案 - String defaultValue; + String? defaultValue; List children; //下级筛选项 - Map extMap; //扩展字段,目前只有min和max + Map? extMap; //扩展字段,目前只有min和max bool isSelected; //是否选中 int maxSelectedCount; - BrnPickerEntity parent; //上级筛选项 - PickerFilterType filterType; //筛选类型 + BrnPickerEntity? parent; //上级筛选项 + PickerFilterType? filterType; //筛选类型 BrnPickerEntity( {this.uniqueId, this.key, this.value, this.defaultValue, - this.name, - this.children, + this.name = '', + this.children = const [], this.isSelected = false, this.extMap, this.type, - this.maxSelectedCount}) { + this.maxSelectedCount = BrnSelectionConstant.maxSelectCount}) { this.filterType = this.parserFilterTypeWithType(this.type); - - /// 默认支持最大选中个数为 65535 - this.maxSelectedCount = - maxSelectedCount ?? BrnSelectionConstant.MAX_SELECT_COUNT; } - static BrnPickerEntity fromMap(Map map) { - if (map == null) return null; + static BrnPickerEntity fromMap(Map? map) { + if (map == null) return BrnPickerEntity(); BrnPickerEntity entity = BrnPickerEntity(); entity.uniqueId = map['id'] ?? ""; entity.name = map['name'] ?? ""; @@ -61,14 +57,15 @@ class BrnPickerEntity { entity.value = map['value'] ?? ""; if (map['maxSelectedCount'] != null && int.tryParse(map['maxSelectedCount']) != null) { - entity.maxSelectedCount = int.tryParse(map['maxSelectedCount']); + entity.maxSelectedCount = int.tryParse(map['maxSelectedCount']) ?? + BrnSelectionConstant.maxSelectCount; } else { - entity.maxSelectedCount = BrnSelectionConstant.MAX_SELECT_COUNT; + entity.maxSelectedCount = BrnSelectionConstant.maxSelectCount; } entity.extMap = map['ext'] ?? {}; // entity.children = map['children'] ?? []; - entity.children = List() - ..addAll((map['children'] as List ?? []) + entity.children = [] + ..addAll((map['children'] as List? ?? []) .map((o) => BrnPickerEntity.fromMap(o))); return entity; } @@ -79,11 +76,11 @@ class BrnPickerEntity { } void configDefaultValue() { - if (this.children != null && this.children.length > 0) { + if (this.children.length > 0) { for (BrnPickerEntity entity in this.children) { if (!BrunoTools.isEmpty(defaultValue)) { - List values = defaultValue.split(','); - entity.isSelected = values != null && values.contains(entity.value); + List values = defaultValue!.split(','); + entity.isSelected = values.contains(entity.value); } entity.configDefaultValue(); } @@ -93,7 +90,7 @@ class BrnPickerEntity { } void configRelationship() { - if (this.children != null && this.children.length > 0) { + if (this.children.length > 0) { for (BrnPickerEntity entity in this.children) { entity.parent = this; entity.configRelationship(); @@ -103,26 +100,26 @@ class BrnPickerEntity { PickerWindowType parserShowType(String showType) { if (showType == "list") { - return PickerWindowType.List; + return PickerWindowType.list; } else if (showType == "range") { - return PickerWindowType.Range; + return PickerWindowType.range; } - return PickerWindowType.List; + return PickerWindowType.list; } - PickerFilterType parserFilterTypeWithType(String type) { + PickerFilterType parserFilterTypeWithType(String? type) { if (type == "unlimit") { - return PickerFilterType.UnLimit; + return PickerFilterType.unLimit; } else if (type == "radio") { - return PickerFilterType.Radio; + return PickerFilterType.radio; } else if (type == "checkbox") { - return PickerFilterType.Checkbox; + return PickerFilterType.checkbox; } - return PickerFilterType.None; + return PickerFilterType.none; } void clearChildSelection() { - if (this.children != null && this.children.length > 0) { + if (this.children.length > 0) { for (BrnPickerEntity entity in this.children) { entity.isSelected = false; entity.clearChildSelection(); @@ -131,18 +128,14 @@ class BrnPickerEntity { } List selectedLastColumnList() { - List list = List(); - if (this.children != null && this.children.length > 0) { - List firstList = List(); + List list = []; + if (this.children.length > 0) { + List firstList = []; for (BrnPickerEntity firstEntity in this.children) { - if (firstEntity != null && - firstEntity.children != null && - firstEntity.children.length > 0) { - List secondList = List(); + if (firstEntity.children.length > 0) { + List secondList = []; for (BrnPickerEntity secondEntity in firstEntity.children) { - if (secondEntity != null && - secondEntity.children != null && - secondEntity.children.length > 0) { + if (secondEntity.children.length > 0) { List thirds = this.currentSelectListForEntity(secondEntity); if (thirds.length > 0) { @@ -150,12 +143,12 @@ class BrnPickerEntity { } else if (secondEntity.isSelected) { secondList.add(secondEntity); } - } else if (secondEntity != null && secondEntity.isSelected) { + } else if (secondEntity.isSelected) { secondList.add(secondEntity); } } list.addAll(secondList); - } else if (firstEntity != null && firstEntity.isSelected) { + } else if (firstEntity.isSelected) { firstList.add(firstEntity); } } @@ -166,27 +159,25 @@ class BrnPickerEntity { List selectedListWithoutUnlimit() { List selected = selectedList(); - return selected?.where((_) => !_.isUnLimit())?.toList() ?? List(); + return selected.where((_) => !_.isUnLimit()).toList() ; } List selectedList() { - List results = List(); + List results = []; List firstColumn = this.currentSelectListForEntity(this); results.addAll(firstColumn); - if (firstColumn != null && firstColumn.length > 0) { + if (firstColumn.length > 0) { for (BrnPickerEntity firstEntity in firstColumn) { - if (firstEntity != null) { List secondColumn = this.currentSelectListForEntity(firstEntity); results.addAll(secondColumn); - if (secondColumn != null && secondColumn.length > 0) { + if (secondColumn.length > 0) { for (BrnPickerEntity secondEntity in secondColumn) { List thirdColumn = this.currentSelectListForEntity(secondEntity); results.addAll(thirdColumn); } } - } } } return results; @@ -194,8 +185,8 @@ class BrnPickerEntity { /// 返回状态为选中的子节点 List currentSelectListForEntity(BrnPickerEntity entity) { - List list = List(); - if (entity.children != null && entity.children.length > 0) { + List list = []; + if (entity.children.length > 0) { for (BrnPickerEntity entity in entity.children) { if (entity.isSelected) { list.add(entity); @@ -221,13 +212,11 @@ class BrnPickerEntity { /// 判断当前的筛选 Item 是否为当前层次中第一个被选中的 Item。 /// 用于展开筛选弹窗时显示选中效果。 int getIndexInCurrentLevel() { - if (parent == null || - parent.children == null || - parent.children.length == 0) return -1; + if (parent == null || parent!.children.length == 0) return -1; - for (BrnPickerEntity entity in parent.children) { + for (BrnPickerEntity entity in parent!.children) { if (entity == this) { - return parent.children.indexOf(entity); + return parent!.children.indexOf(entity); } } return -1; @@ -235,11 +224,10 @@ class BrnPickerEntity { bool isInLastLevel() { if (parent == null || - parent.children == null || - parent.children.length == 0) return true; + parent!.children.length == 0) return true; - for (BrnPickerEntity entity in parent.children) { - if (entity.children != null && entity.children.length > 0) { + for (BrnPickerEntity entity in parent!.children) { + if (entity.children.length > 0) { return false; } } @@ -248,18 +236,18 @@ class BrnPickerEntity { /// 在这里简单认为 value 为空【null 或 ''】时为 unLimit. bool isUnLimit() { - return filterType == PickerFilterType.UnLimit || - (BrunoTools.isEmpty(value) && filterType == PickerFilterType.Radio); + return filterType == PickerFilterType.unLimit || + (BrunoTools.isEmpty(value) && filterType == PickerFilterType.radio); } void clearSelectedEntity() { - List tmp = List(); + List tmp = []; BrnPickerEntity node = this; tmp.add(node); while (tmp.isNotEmpty) { node = tmp.removeLast(); node.isSelected = false; - node.children?.forEach((data) { + node.children.forEach((data) { tmp.add(data); }); } diff --git a/lib/src/components/picker/multi_range_picker/brn_multi_column_converter.dart b/lib/src/components/picker/multi_range_picker/brn_multi_column_converter.dart index b29bcbaa..c4c60f41 100644 --- a/lib/src/components/picker/multi_range_picker/brn_multi_column_converter.dart +++ b/lib/src/components/picker/multi_range_picker/brn_multi_column_converter.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart'; import 'package:bruno/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart'; import 'package:bruno/src/utils/brn_tools.dart'; @@ -13,7 +15,7 @@ class BrnMultiRangeSelConverter { } Map> getSelectionParams( - List selectedResults, + List? selectedResults, {bool includeUnlimitSelection = false}) { Map> params = Map(); if (selectedResults == null) return params; @@ -26,19 +28,19 @@ class BrnMultiRangeSelConverter { } else if (levelCount == 2) { params.addAll(getCurrentSelectionEntityParams(menuItemEntity, includeUnlimitSelection: includeUnlimitSelection)); - menuItemEntity.children?.forEach((firstLevelItem) => mergeParams( + menuItemEntity.children.forEach((firstLevelItem) => mergeParams( params, getCurrentSelectionEntityParams(firstLevelItem, includeUnlimitSelection: includeUnlimitSelection))); } else if (levelCount == 3) { params.addAll(getCurrentSelectionEntityParams(menuItemEntity, includeUnlimitSelection: includeUnlimitSelection)); - menuItemEntity.children?.forEach((firstLevelItem) { + menuItemEntity.children.forEach((firstLevelItem) { mergeParams( params, getCurrentSelectionEntityParams(firstLevelItem, includeUnlimitSelection: includeUnlimitSelection)); - firstLevelItem.children?.forEach((secondLevelItem) { + firstLevelItem.children.forEach((secondLevelItem) { mergeParams( params, getCurrentSelectionEntityParams(secondLevelItem, @@ -50,14 +52,14 @@ class BrnMultiRangeSelConverter { return params; } - Map> mergeParams( - Map> params, - Map> selectedParams) { - selectedParams?.forEach((String key, List value) { - if (params != null && params.containsKey(key)) { + Map> mergeParams( + Map> params, + Map> selectedParams) { + selectedParams.forEach((String? key, List value) { + if ( params.containsKey(key)) { params[key]?.addAll(value); } else { - params?.addAll(selectedParams); + params.addAll(selectedParams); } }); return params; @@ -67,20 +69,19 @@ class BrnMultiRangeSelConverter { BrnPickerEntity selectionEntity, {bool includeUnlimitSelection = false}) { Map> params = Map(); - String parentKey = selectionEntity.key; + String parentKey = selectionEntity.key ?? ''; var selectedEntity = selectionEntity.children - ?.where((BrnPickerEntity f) => f.isSelected) - ?.where((BrnPickerEntity f) { + .where((BrnPickerEntity f) => f.isSelected) + .where((BrnPickerEntity f) { if (includeUnlimitSelection) { return true; } else { return !BrunoTools.isEmpty(f.value); } }) - ?.map((BrnPickerEntity f) => f) - ?.toList(); - List selectedParams = - selectedEntity == null ? [] : selectedEntity; + .map((BrnPickerEntity f) => f) + .toList(); + List selectedParams = selectedEntity; if (!BrunoTools.isEmpty(selectedParams) && !BrunoTools.isEmpty(parentKey)) { params[parentKey] = selectedParams; } diff --git a/lib/src/components/picker/multi_range_picker/brn_multi_column_list.dart b/lib/src/components/picker/multi_range_picker/brn_multi_column_list.dart index 1a4c6b83..1d6b7a55 100644 --- a/lib/src/components/picker/multi_range_picker/brn_multi_column_list.dart +++ b/lib/src/components/picker/multi_range_picker/brn_multi_column_list.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart'; import 'package:bruno/src/components/picker/multi_range_picker/brn_multi_column_picker.dart'; import 'package:bruno/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart'; @@ -10,48 +12,48 @@ import 'package:flutter/material.dart'; /// [index] 点击位置处于当前列的位置 /// [entity] 被点击位置的数据 typedef bool BrnOnSelectEntityInterceptor( - int listIndex, int index, BrnPickerEntity entity); + int? listIndex, int index, BrnPickerEntity entity); // ignore: must_be_immutable class BrnMultiColumnListWidget extends StatefulWidget { - List _selectedItems; - int focusedIndex = -1; - List items; + List? _selectedItems; + int? focusedIndex = -1; + List? items; Color normalColor; Color selectedColor; - Color backgroundColor; - Color selectedBackgroundColor; + Color? backgroundColor; + Color? selectedBackgroundColor; int flex; - BrnOnEntityTap singleListItemPick; - int currentListIndex; + BrnOnEntityTap? singleListItemPick; + int? currentListIndex; double maxHeight; - BrnOnSelectEntityInterceptor onSelectEntityInterceptor; + BrnOnSelectEntityInterceptor? onSelectEntityInterceptor; BrnMultiColumnListWidget({ - @required this.items, + required this.items, this.normalColor = const Color(0Xff4a4e59), this.selectedColor = const Color(0xff41bc6a), this.maxHeight = 0, this.backgroundColor, this.selectedBackgroundColor, - this.flex, + required this.flex, this.focusedIndex, this.singleListItemPick, this.onSelectEntityInterceptor, }) { if (items == null) { - items = List(); + items = []; } - items.forEach((element) { + items!.forEach((element) { element.configRelationship(); }); currentListIndex = BrnMultiColumnPickerUtil.getCurrentColumnIndex( - items.length > 0 ? items[0] : null); + items!.length > 0 ? items![0] : null); - _selectedItems = items?.where((f) => f.isSelected)?.toList(); + _selectedItems = items?.where((f) => f.isSelected).toList(); if (_selectedItems == null) { - _selectedItems = List(); + _selectedItems = []; } } @@ -59,7 +61,7 @@ class BrnMultiColumnListWidget extends StatefulWidget { _BrnMultiColumnListWidgetState createState() => _BrnMultiColumnListWidgetState(); - List getSelectedItems() { + List? getSelectedItems() { return _selectedItems; } } @@ -70,7 +72,7 @@ class _BrnMultiColumnListWidgetState extends State { return Expanded( flex: widget.flex, child: Container( - constraints: (widget.maxHeight == null || widget.maxHeight == 0) + constraints: (widget.maxHeight == 0) ? BoxConstraints.expand() : BoxConstraints(maxHeight: widget.maxHeight), color: widget.backgroundColor, @@ -78,10 +80,10 @@ class _BrnMultiColumnListWidgetState extends State { shrinkWrap: true, padding: EdgeInsets.only(top: 0), scrollDirection: Axis.vertical, - itemCount: widget.items.length, + itemCount: widget.items!.length, separatorBuilder: (BuildContext context, int index) => Container(), itemBuilder: (BuildContext context, int index) { - BrnPickerEntity item = widget.items[index]; + BrnPickerEntity item = widget.items![index]; /// 点击筛选,展开弹窗时,默认展示上次选中的筛选项。 bool isCurrentFocused = _isItemFocused(index, item); @@ -97,14 +99,16 @@ class _BrnMultiColumnListWidgetState extends State { isFirstLevel: (1 == widget.currentListIndex) ? true : false, itemSelectFunction: (BrnPickerEntity entity) { if (widget.onSelectEntityInterceptor != null && - widget.onSelectEntityInterceptor( + widget.onSelectEntityInterceptor!( widget.currentListIndex, index, entity) == false) { return; } _processFilterData(entity); - widget.singleListItemPick( - widget.currentListIndex, index, entity); + if(widget.singleListItemPick!=null){ + widget.singleListItemPick!( + widget.currentListIndex ?? 0, index, entity); + } }, ); }, @@ -122,12 +126,12 @@ class _BrnMultiColumnListWidgetState extends State { } /// Item 点击之后的数据处理 - void _processFilterData(BrnPickerEntity selectedEntity) { + void _processFilterData(BrnPickerEntity? selectedEntity) { if (null == selectedEntity) { return; } - if (selectedEntity.filterType == PickerFilterType.Checkbox && + if (selectedEntity.filterType == PickerFilterType.checkbox && !selectedEntity.isSelected) { if (!BrnMultiColumnPickerUtil.isSelectedCountExceed(selectedEntity)) { BrnToast.show("您选择的数量已达上限", context); @@ -137,8 +141,8 @@ class _BrnMultiColumnListWidgetState extends State { int totalLevel = BrnMultiColumnPickerUtil.getTotalColumnCount(selectedEntity); - if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + if (selectedEntity.isUnLimit() && selectedEntity.parent !=null) { + selectedEntity.parent!.clearChildSelection(); } /// 设置选中数据。 @@ -155,35 +159,37 @@ class _BrnMultiColumnListWidgetState extends State { /// Warning !!! /// (两列、三列时)第一列节点是否被选中取决于它的子节点是否被选中, /// 只有当它子节点被选中时才会认为第一列的节点相应被选中。 - if (widget.items != null && widget.items.length > 0) { - widget.items[0].parent?.isSelected = widget.items[0].parent.children + if (widget.items != null && + widget.items!.length > 0 && + widget.items![0].parent != null ) { + widget.items![0].parent?.isSelected = widget.items![0].parent!.children .where((BrnPickerEntity f) => f.isSelected) .length > 0; } - for (BrnPickerEntity item in widget.items) { + for (BrnPickerEntity item in widget.items!) { if (item.isSelected) { - if (!widget._selectedItems.contains(item)) { - widget._selectedItems.add(item); + if (!widget._selectedItems!.contains(item)) { + widget._selectedItems!.add(item); } } else { - if (widget._selectedItems.contains(item)) { - widget._selectedItems.remove(item); + if (widget._selectedItems!.contains(item)) { + widget._selectedItems!.remove(item); } } } } void _configFirstList(BrnPickerEntity selectedEntity) { - if (PickerFilterType.Radio == selectedEntity.filterType) { + if (PickerFilterType.radio == selectedEntity.filterType) { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; - } else if (PickerFilterType.Checkbox == selectedEntity.filterType) { + } else if (PickerFilterType.checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 @@ -191,7 +197,7 @@ class _BrnMultiColumnListWidgetState extends State { if (selectedEntity.parent == null) { brotherItems = widget.items; } else { - brotherItems = selectedEntity.parent.children; + brotherItems = selectedEntity.parent!.children; } for (BrnPickerEntity entity in brotherItems) { if (entity.isUnLimit()) { @@ -203,20 +209,20 @@ class _BrnMultiColumnListWidgetState extends State { } } - void _configSecondList(BrnPickerEntity selectedEntity, int currentListIndex) { + void _configSecondList(BrnPickerEntity selectedEntity, int? currentListIndex) { if (currentListIndex == 1) { - if (PickerFilterType.Checkbox != selectedEntity.filterType) { - selectedEntity.parent.clearChildSelection(); + if (PickerFilterType.checkbox != selectedEntity.filterType) { + selectedEntity.parent!.clearChildSelection(); } } else { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 - if (PickerFilterType.Radio == selectedEntity.filterType) { - selectedEntity.parent.clearChildSelection(); + if (PickerFilterType.radio == selectedEntity.filterType) { + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; - } else if (PickerFilterType.Checkbox == selectedEntity.filterType) { + } else if (PickerFilterType.checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 @@ -224,7 +230,7 @@ class _BrnMultiColumnListWidgetState extends State { if (selectedEntity.parent == null) { brotherItems = widget.items; } else { - brotherItems = selectedEntity.parent.children; + brotherItems = selectedEntity.parent!.children; } for (BrnPickerEntity entity in brotherItems) { if (entity.isUnLimit()) { @@ -237,20 +243,20 @@ class _BrnMultiColumnListWidgetState extends State { } } - void _configThirdList(BrnPickerEntity selectedEntity, int currentListIndex) { + void _configThirdList(BrnPickerEntity selectedEntity, int? currentListIndex) { if (currentListIndex == 1) { - if (PickerFilterType.Checkbox != selectedEntity.filterType) { - selectedEntity.parent.clearChildSelection(); + if (PickerFilterType.checkbox != selectedEntity.filterType) { + selectedEntity.parent!.clearChildSelection(); } } else { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 - if (PickerFilterType.Radio == selectedEntity.filterType) { - selectedEntity.parent.clearChildSelection(); + if (PickerFilterType.radio == selectedEntity.filterType) { + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; - } else if (PickerFilterType.Checkbox == selectedEntity.filterType) { + } else if (PickerFilterType.checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 @@ -258,7 +264,7 @@ class _BrnMultiColumnListWidgetState extends State { if (selectedEntity.parent == null) { brotherItems = widget.items; } else { - brotherItems = selectedEntity.parent.children; + brotherItems = selectedEntity.parent!.children; } for (BrnPickerEntity entity in brotherItems) { if (entity.isUnLimit()) { diff --git a/lib/src/components/picker/multi_range_picker/brn_multi_column_picker.dart b/lib/src/components/picker/multi_range_picker/brn_multi_column_picker.dart index 22bfd61e..e070c441 100644 --- a/lib/src/components/picker/multi_range_picker/brn_multi_column_picker.dart +++ b/lib/src/components/picker/multi_range_picker/brn_multi_column_picker.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; @@ -23,7 +25,7 @@ typedef void BrnOnEntityTap( /// [secondIndex] 第二列被选中数据的位置 /// [thirdIndex] 第三列被选中数据的位置 typedef void BrnOnPickerConfirm(Map> results, - int firstIndex, int secondIndex, int thirdIndex); + int? firstIndex, int? secondIndex, int? thirdIndex); /// 从屏幕下方弹起的多级筛选选择器 /// 可设置筛项的层级、多选、单选等筛选相关功能 @@ -33,7 +35,7 @@ class BrnMultiColumnPicker extends StatefulWidget { final BrnPickerEntity entity; /// 初始化时的选中选项 - final List defaultFocusedIndexes; + final List? defaultFocusedIndexes; /// Picker展示最大高度,默认 280 final double maxHeight; @@ -46,23 +48,23 @@ class BrnMultiColumnPicker extends StatefulWidget { final bool isIncludeUnLimit; /// 选择数据后回调函数 - final BrnOnPickerConfirm onConfirm; + final BrnOnPickerConfirm? onConfirm; /// 选择项目后回调函数 - final BrnOnEntityTap onEntityTap; + final BrnOnEntityTap? onEntityTap; /// 当前选项是否可以被选中:返回 true 可以被选中 false 不可以被选中 - final BrnOnSelectEntityInterceptor canSelectEntryInterceptor; + final BrnOnSelectEntityInterceptor? canSelectEntryInterceptor; /// 主题定制,只有 Picker Title 部分样式生效 - BrnPickerConfig themeData; + BrnPickerConfig? themeData; /// Picker Title 数据配置 final BrnPickerTitleConfig pickerTitleConfig; BrnMultiColumnPicker( - {Key key, - @required this.entity, + {Key? key, + required this.entity, this.maxHeight = 280.0, this.showSelectedCount = false, this.isIncludeUnLimit = false, @@ -75,7 +77,7 @@ class BrnMultiColumnPicker extends StatefulWidget { : super(key: key) { this.themeData ??= BrnPickerConfig(); this.themeData = this - .themeData + .themeData! .merge(BrnThemeConfigurator.instance.getConfig().pickerConfig); } @@ -86,23 +88,23 @@ class BrnMultiColumnPicker extends StatefulWidget { class _BrnSelectionGroupViewState extends State { static const BrnMultiRangeSelConverter defaultConverter = const BrnMultiRangeSelConverter(); - List _firstList = List(); - List _secondList = List(); - List _thirdList = List(); - List _originalSelectedItemsList = List(); - int _firstIndex; - int _secondIndex; - int _thirdIndex; + List _firstList = []; + List? _secondList = []; + List? _thirdList = []; + List _originalSelectedItemsList = []; + int? _firstIndex; + int? _secondIndex; + int? _thirdIndex; int get _columnCount { return BrnMultiColumnPickerUtil.getTotalColumnCount(widget.entity); } /// 未选中状态颜色,默认 Color(0Xff4a4e59) - Color _normalColor; + late Color _normalColor; /// 选中状态颜色,默认 Color(0xff41bc6a) - Color _selectedColor; + late Color _selectedColor; @override void initState() { @@ -121,8 +123,8 @@ class _BrnSelectionGroupViewState extends State { height: widget.maxHeight + 48, child: BrnPickerClipRRect( borderRadius: BorderRadius.only( - topLeft: Radius.circular(widget.themeData.cornerRadius), - topRight: Radius.circular(widget.themeData.cornerRadius), + topLeft: Radius.circular(widget.themeData!.cornerRadius), + topRight: Radius.circular(widget.themeData!.cornerRadius), ), child: Column( children: _configWidgets(), @@ -133,7 +135,7 @@ class _BrnSelectionGroupViewState extends State { //pragma mark -- config widgets List _configWidgets() { - List widgetList = List(); + List widgetList = []; widgetList.add( Offstage( offstage: !widget.pickerTitleConfig.showTitle, @@ -157,7 +159,7 @@ class _BrnSelectionGroupViewState extends State { } Widget _listWidget() { - List widgets = List(); + List widgets = []; if (!BrunoTools.isEmpty(_firstList) && BrunoTools.isEmpty(_secondList) && @@ -178,11 +180,11 @@ class _BrnSelectionGroupViewState extends State { (int listIndex, int index, BrnPickerEntity entity) { _setFirstIndex(index); if (_columnCount == 1 && - widget.entity.filterType == PickerFilterType.Radio) { + widget.entity.filterType == PickerFilterType.radio) { _confirmButtonClickEvent(); } if (widget.onEntityTap != null) { - widget.onEntityTap(0, index, entity); + widget.onEntityTap!(0, index, entity); } })); } else if (!BrunoTools.isEmpty(_firstList) && @@ -202,7 +204,7 @@ class _BrnSelectionGroupViewState extends State { (int listIndex, int index, BrnPickerEntity entity) { _setFirstIndex(index); if (widget.onEntityTap != null) { - widget.onEntityTap(0, index, entity); + widget.onEntityTap!(0, index, entity); } })); @@ -219,7 +221,7 @@ class _BrnSelectionGroupViewState extends State { (int listIndex, int index, BrnPickerEntity entity) { _setSecondIndex(index); if (widget.onEntityTap != null) { - widget.onEntityTap(1, index, entity); + widget.onEntityTap!(1, index, entity); } })); } else if (!BrunoTools.isEmpty(_firstList) && @@ -239,7 +241,7 @@ class _BrnSelectionGroupViewState extends State { (int listIndex, int index, BrnPickerEntity entity) { _setFirstIndex(index); if (widget.onEntityTap != null) { - widget.onEntityTap(0, index, entity); + widget.onEntityTap!(0, index, entity); } })); @@ -256,7 +258,7 @@ class _BrnSelectionGroupViewState extends State { (int listIndex, int index, BrnPickerEntity entity) { _setSecondIndex(index); if (widget.onEntityTap != null) { - widget.onEntityTap(1, index, entity); + widget.onEntityTap!(1, index, entity); } })); widgets.add(BrnMultiColumnListWidget( @@ -277,7 +279,7 @@ class _BrnSelectionGroupViewState extends State { } setState(() {}); if (widget.onEntityTap != null) { - widget.onEntityTap(2, index, entity); + widget.onEntityTap!(2, index, entity); } })); } @@ -302,7 +304,7 @@ class _BrnSelectionGroupViewState extends State { Map> result = defaultConverter .convertPickedData([widget.entity], includeUnlimitSelection: widget.isIncludeUnLimit); - widget.onConfirm(result, _firstIndex, _secondIndex, _thirdIndex); + widget.onConfirm!(result, _firstIndex, _secondIndex, _thirdIndex); } } @@ -341,10 +343,10 @@ class _BrnSelectionGroupViewState extends State { // 刷新3个ListView的数据源 void _refreshDataSource() { _firstList = widget.entity.children; - if (_firstIndex >= 0 && _firstList.length > _firstIndex) { - _secondList = _firstList[_firstIndex].children; - if (_secondIndex >= 0 && _secondList.length > _secondIndex) { - _thirdList = _secondList[_secondIndex].children; + if (_firstIndex! >= 0 && _firstList.length > _firstIndex!) { + _secondList = _firstList[_firstIndex!].children; + if (_secondIndex! >= 0 && _secondList!.length > _secondIndex!) { + _thirdList = _secondList![_secondIndex!].children; } else { _thirdList = null; } @@ -356,51 +358,41 @@ class _BrnSelectionGroupViewState extends State { void _configDefaultSelectedData() { _firstList = widget.entity.children; - //是否已选择的item里面有第一列的 - if (_firstList == null) { - _secondIndex = -1; - _secondList = null; - - _thirdIndex = -1; - _thirdList = null; - - return; - } _firstIndex = _getInitialSelectIndex(_firstList); if (_firstIndex == -1) { if (widget.defaultFocusedIndexes != null) { for (int index = 0; - index < widget.defaultFocusedIndexes.length; + index < widget.defaultFocusedIndexes!.length; index++) { - if (index == 0 && widget.defaultFocusedIndexes[index] >= 0) { - _firstIndex = widget.defaultFocusedIndexes[index]; + if (index == 0 && widget.defaultFocusedIndexes![index] >= 0) { + _firstIndex = widget.defaultFocusedIndexes![index]; } - if (index == 1 && _firstIndex >= 0) { - _secondIndex = widget.defaultFocusedIndexes[index]; + if (index == 1 && _firstIndex! >= 0) { + _secondIndex = widget.defaultFocusedIndexes![index]; } - if (index == 2 && _secondIndex >= 0) { - _thirdIndex = widget.defaultFocusedIndexes[index]; + if (index == 2 && _secondIndex! >= 0) { + _thirdIndex = widget.defaultFocusedIndexes![index]; } } } - if (_firstIndex >= 0 && _firstIndex < _firstList.length) { - _secondList = _firstList[_firstIndex].children; + if (_firstIndex! >= 0 && _firstIndex! < _firstList.length) { + _secondList = _firstList[_firstIndex!].children; } if (_secondList == null) { _thirdIndex = -1; _thirdList = null; return; } - if (_secondIndex >= 0 && _secondIndex < _secondList.length) { - _thirdList = _secondList[_secondIndex].children; + if (_secondIndex! >= 0 && _secondIndex! < _secondList!.length) { + _thirdList = _secondList![_secondIndex!].children; } } else { - if (_firstIndex >= 0 && _firstIndex < _firstList.length) { - _secondList = _firstList[_firstIndex].children; + if (_firstIndex! >= 0 && _firstIndex! < _firstList.length) { + _secondList = _firstList[_firstIndex!].children; if (_secondList != null) { _secondIndex = _getInitialSelectIndex(_secondList); } @@ -411,8 +403,8 @@ class _BrnSelectionGroupViewState extends State { _thirdList = null; return; } - if (_secondIndex >= 0 && _secondIndex < _secondList.length) { - _thirdList = _secondList[_secondIndex].children; + if (_secondIndex! >= 0 && _secondIndex! < _secondList!.length) { + _thirdList = _secondList![_secondIndex!].children; if (_thirdList != null) { _thirdIndex = _getInitialSelectIndex(_thirdList); } @@ -423,10 +415,8 @@ class _BrnSelectionGroupViewState extends State { //设置数据为未选中状态 void _resetSelectionDatas(BrnPickerEntity entity) { entity.isSelected = false; - if (entity.children != null) { - for (BrnPickerEntity subEntity in entity.children) { - _resetSelectionDatas(subEntity); - } + for (BrnPickerEntity subEntity in entity.children) { + _resetSelectionDatas(subEntity); } } @@ -435,15 +425,13 @@ class _BrnSelectionGroupViewState extends State { void _setFirstIndex(int firstIndex) { _firstIndex = firstIndex; _secondIndex = -1; - if (widget.entity.children.length > _firstIndex) { + if (widget.entity.children.length > _firstIndex!) { List seconds = - widget.entity.children[_firstIndex].children; - if (seconds != null) { - _secondIndex = _getInitialSelectIndex(seconds); + widget.entity.children[_firstIndex!].children; + _secondIndex = _getInitialSelectIndex(seconds); - if (_secondIndex >= 0) { - _setSecondIndex(_secondIndex); - } + if (_secondIndex! >= 0) { + _setSecondIndex(_secondIndex); } } setState(() { @@ -451,23 +439,21 @@ class _BrnSelectionGroupViewState extends State { }); } - void _setSecondIndex(int secondIndex) { + void _setSecondIndex(int? secondIndex) { _secondIndex = secondIndex; _thirdIndex = -1; List seconds = - widget.entity.children[_firstIndex].children; - if (seconds.length > _secondIndex) { - List thirds = seconds[_secondIndex].children; - if (thirds != null) { - _thirdIndex = _getInitialSelectIndex(thirds); - } + widget.entity.children[_firstIndex!].children; + if (seconds.length > _secondIndex!) { + List thirds = seconds[_secondIndex!].children; + _thirdIndex = _getInitialSelectIndex(thirds); } setState(() { _refreshDataSource(); }); } - int _getInitialSelectIndex(List levelList) { + int _getInitialSelectIndex(List? levelList) { int index = -1; if (levelList == null || levelList.length == 0) { return index; @@ -486,7 +472,7 @@ class _BrnSelectionGroupViewState extends State { // 例如1级为多选,不应该默认选中2级的不限 // 否则每选中任意一个1级选项,就默认有了一个2级的不限 if (entity.isUnLimit() && - entity.parent.filterType != PickerFilterType.Checkbox) { + entity.parent!.filterType != PickerFilterType.checkbox) { index = levelList.indexOf(entity); break; } diff --git a/lib/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart b/lib/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart index a719ca04..03a0d5d7 100644 --- a/lib/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart +++ b/lib/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart @@ -1,27 +1,25 @@ + + import 'package:bruno/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart'; -import 'package:bruno/src/utils/brn_tools.dart'; /// BrnMultiColumnPicker相关工具类 class BrnMultiColumnPickerUtil { /// 筛选项最多不超过三层,故直接写代码判断,本质为深度优先搜索。 - static int getTotalColumnCount(BrnPickerEntity entity) { + static int getTotalColumnCount(BrnPickerEntity? entity) { int count = 0; - BrnPickerEntity rootEntity = entity; - while (rootEntity.parent != null) { - rootEntity = rootEntity.parent; + BrnPickerEntity? rootEntity = entity; + while (rootEntity?.parent != null) { + rootEntity = rootEntity?.parent!; } - if (rootEntity != null && - rootEntity.children != null && + if (rootEntity != null && rootEntity.children.length > 0) { count = count > 1 ? count : 1; for (BrnPickerEntity firstLevelEntity in rootEntity.children) { - if (firstLevelEntity.children != null && - firstLevelEntity.children.length > 0) { + if (firstLevelEntity.children.length > 0) { count = count > 2 ? count : 2; for (BrnPickerEntity secondLevelEntity in firstLevelEntity.children) { - if (secondLevelEntity.children != null && - secondLevelEntity.children.length > 0) { + if (secondLevelEntity.children.length > 0) { count = 3; break; } @@ -33,7 +31,7 @@ class BrnMultiColumnPickerUtil { } /// 确定当前 Item 在第几层级 - static int getCurrentColumnIndex(BrnPickerEntity currentItem) { + static int getCurrentColumnIndex(BrnPickerEntity? currentItem) { int listIndex = -1; if (currentItem != null) { listIndex = 0; @@ -50,9 +48,9 @@ class BrnMultiColumnPickerUtil { /// [entity] 传入当前点击的 Item /// !!! 在设置 isSelected = true之前进行 check。 /// 返回 true 符合条件,false 不符合条件 - static bool isSelectedCountExceed(BrnPickerEntity entity) { - if (entity == null && entity.parent == null) return false; - return entity.parent.getSelectedChildCount() < - entity.parent.maxSelectedCount; + static bool isSelectedCountExceed(BrnPickerEntity? entity) { + if (entity == null || entity.parent == null) return false; + return entity.parent!.getSelectedChildCount() < + entity.parent!.maxSelectedCount; } } diff --git a/lib/src/components/picker/multi_range_picker/btn_multi_column_picker_item.dart b/lib/src/components/picker/multi_range_picker/btn_multi_column_picker_item.dart index 3310c1d0..55dbb9be 100644 --- a/lib/src/components/picker/multi_range_picker/btn_multi_column_picker_item.dart +++ b/lib/src/components/picker/multi_range_picker/btn_multi_column_picker_item.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/picker/multi_range_picker/bean/brn_multi_column_picker_entity.dart'; import 'package:bruno/src/components/picker/multi_range_picker/brn_multi_column_picker_util.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; @@ -10,17 +12,17 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { final BrnPickerEntity item; final Color normalColor; final Color selectColor; - final Color backgroundColor; - final Color selectedBackgroundColor; - final bool isCurrentFocused; + final Color? backgroundColor; + final Color? selectedBackgroundColor; + final bool? isCurrentFocused; final bool isFirstLevel; final bool isMoreSelectionListType; - final ItemSelectFunction itemSelectFunction; + final ItemSelectFunction? itemSelectFunction; BrnMultiRangePickerCommonItem({ - @required this.item, + required this.item, this.normalColor = const Color(0Xff4a4e59), this.selectColor = const Color(0xff41bc6a), this.backgroundColor, @@ -35,7 +37,7 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { Widget build(BuildContext context) { var checkbox; if (!item.isUnLimit() && - (item.children == null || item.children.length == 0)) { + (item.children.length == 0)) { if (item.isInLastLevel() && _hasCheckBoxBrother(item)) { checkbox = Container( padding: EdgeInsets.only(left: 6), @@ -55,7 +57,7 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { return GestureDetector( onTap: () { if (itemSelectFunction != null) { - itemSelectFunction(item); + itemSelectFunction!(item); } }, child: Container( @@ -88,8 +90,8 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { ); } - Color _getItemBGColor() { - if (isCurrentFocused) { + Color? _getItemBGColor() { + if (isCurrentFocused!) { return this.selectedBackgroundColor; } else { return this.backgroundColor; @@ -97,23 +99,23 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { } Color _getItemTextColor() { - Color itemColor = (item.isUnLimit() ? isCurrentFocused : item.isSelected) + Color itemColor = (item.isUnLimit() ? isCurrentFocused : item.isSelected)! ? selectColor : normalColor; if (!item.isInLastLevel()) { - itemColor = isCurrentFocused ? selectColor : normalColor; + itemColor = isCurrentFocused! ? selectColor : normalColor; } return itemColor; } FontWeight _getItemFontWeight() { FontWeight fontWeight = - (item.isUnLimit() ? isCurrentFocused : item.isSelected) + (item.isUnLimit() ? isCurrentFocused : item.isSelected)! ? FontWeight.w600 : FontWeight.normal; if (!item.isInLastLevel()) { - fontWeight = isCurrentFocused ? FontWeight.w600 : FontWeight.normal; + fontWeight = isCurrentFocused! ? FontWeight.w600 : FontWeight.normal; } return fontWeight; } @@ -121,8 +123,7 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { String _getSelectedItemCount(BrnPickerEntity item) { String itemCount = ""; if ((BrnMultiColumnPickerUtil.getTotalColumnCount(item) < 3 || - !isFirstLevel) && - item.children != null) { + !isFirstLevel)) { int count = item.children.where((f) => f.isSelected && !f.isUnLimit()).length; if (count > 1) { @@ -133,9 +134,12 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { } bool _hasCheckBoxBrother(BrnPickerEntity item) { - int count = item.parent.children - ?.where((f) => f.filterType == PickerFilterType.Checkbox) - ?.length; + int? count; + if (item.parent != null) { + count = item.parent!.children + .where((f) => f.filterType == PickerFilterType.checkbox) + .length; + } return count == null ? false : count > 0; } } diff --git a/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_data.dart b/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_data.dart index 9d9eebab..a48143db 100644 --- a/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_data.dart +++ b/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_data.dart @@ -1,3 +1,5 @@ + + class BrnMultiSelectBottomPickerItem { String code; //选项编号 diff --git a/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_list_picker.dart b/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_list_picker.dart index 6aee590e..c1427243 100644 --- a/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_list_picker.dart +++ b/lib/src/components/picker/multi_select_bottom_picker/brn_multi_select_list_picker.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/line/brn_line.dart'; import 'package:bruno/src/components/picker/base/brn_picker_constants.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; @@ -22,19 +24,19 @@ typedef BrnMultiSelectListPickerItemClick = void Function( /// 多选列表 Picker class BrnMultiSelectListPicker extends StatefulWidget { - final String title; + final String? title; final List items; - final BrnMultiSelectListPickerSubmit onSubmit; - final VoidCallback onCancel; - final BrnMultiSelectListPickerItemClick onItemClick; + final BrnMultiSelectListPickerSubmit? onSubmit; + final VoidCallback? onCancel; + final BrnMultiSelectListPickerItemClick? onItemClick; final BrnPickerTitleConfig pickerTitleConfig; static void show( BuildContext context, { - @required List items, - BrnMultiSelectListPickerSubmit onSubmit, - VoidCallback onCancel, - BrnMultiSelectListPickerItemClick onItemClick, + required List items, + BrnMultiSelectListPickerSubmit? onSubmit, + VoidCallback? onCancel, + BrnMultiSelectListPickerItemClick? onItemClick, BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig.Default, bool isDismissible = true, }) { @@ -55,9 +57,9 @@ class BrnMultiSelectListPicker extends StatefulWidget { } BrnMultiSelectListPicker({ - Key key, + Key? key, this.title, - this.items, + required this.items, this.pickerTitleConfig = BrnPickerTitleConfig.Default, this.onSubmit, this.onCancel, @@ -98,15 +100,15 @@ class MultiSelectDialogWidgetState extends State { pickerTitleConfig: widget.pickerTitleConfig, onConfirm: () { List selectedItems = - List(); + []; if (widget.onSubmit != null) { - for (int i = 0; i < widget.items?.length; i++) { + for (int i = 0; i < widget.items.length; i++) { if (widget.items[i].isChecked) { selectedItems.add(widget.items[i]); } } if (widget.onSubmit != null) { - widget.onSubmit(selectedItems); + widget.onSubmit!(selectedItems); } } }, @@ -118,12 +120,12 @@ class MultiSelectDialogWidgetState extends State { ), LimitedBox( maxWidth: double.infinity, - maxHeight: PICKER_HEIGHT, + maxHeight: pickerHeight, child: ListView.builder( shrinkWrap: true, itemBuilder: (context, index) => _buildItem(context, index), - itemCount: widget.items?.length)), + itemCount: widget.items.length)), ], ), ], @@ -133,9 +135,7 @@ class MultiSelectDialogWidgetState extends State { } Widget _buildItem(BuildContext context, int index) { - if (widget.items[index] == null) { - return Container(); - } else { + return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () { @@ -143,7 +143,7 @@ class MultiSelectDialogWidgetState extends State { widget.items[index].isChecked = !widget.items[index].isChecked; }); if (widget.onItemClick != null) { - widget.onItemClick(context, index); + widget.onItemClick!(context, index); } }, child: Column( @@ -178,13 +178,13 @@ class MultiSelectDialogWidgetState extends State { ], ), ), - index != widget.items.length - 1 + index != widget.items.length - 1 ? Padding( padding: EdgeInsets.fromLTRB(20, 0, 20, 0), child: BrnLine()) : Container() ], )); - } + } } diff --git a/lib/src/components/picker/time_picker/brn_date_picker_constants.dart b/lib/src/components/picker/time_picker/brn_date_picker_constants.dart index 04f36245..8c8dffe6 100755 --- a/lib/src/components/picker/time_picker/brn_date_picker_constants.dart +++ b/lib/src/components/picker/time_picker/brn_date_picker_constants.dart @@ -1,4 +1,7 @@ /// Selected value of DatePicker. + + + typedef DateValueCallback(DateTime dateTime, List selectedIndex); typedef DateRangeValueCallback(DateTime startDateTime, DateTime endDateTime, @@ -11,25 +14,25 @@ typedef DateRangeSideValueCallback( typedef DateVoidCallback(); /// Default value of minimum datetime. -const String DATE_PICKER_MIN_DATETIME = "1900-01-01 00:00:00"; +const String datePickerMinDatetime = "1900-01-01 00:00:00"; /// Default value of maximum datetime. -const String DATE_PICKER_MAX_DATETIME = "2100-12-31 23:59:59"; +const String datePickerMaxDatetime = "2100-12-31 23:59:59"; /// Default value of date format -const String DATETIME_PICKER_DATE_FORMAT = 'yyyy-MM-dd'; +const String datetimePickerDateFormat = 'yyyy-MM-dd'; /// Default value of time format -const String DATETIME_PICKER_TIME_FORMAT = 'HH:mm:ss'; +const String datetimePickerTimeFormat = 'HH:mm:ss'; /// Default value of datetime format -const String DATETIME_PICKER_DATETIME_FORMAT = 'yyyyMMdd HH:mm:ss'; +const String datetimePickerDatetimeFormat = 'yyyyMMdd HH:mm:ss'; /// Default value of date format -const String DATETIME_RANGE_PICKER_DATE_FORMAT = 'MM-dd'; +const String datetimeRangePickerDateFormat = 'MM-dd'; /// Default value of time format -const String DATETIME_RANGE_PICKER_TIME_FORMAT = 'HH:mm'; +const String datetimeRangePickerTimeFormat = 'HH:mm'; /// Default value of datetime format -const String DATETIME_RANGE_PICKER_DATETIME_FORMAT = 'MMdd HH:mm'; +const String datetimeRangePickerDatetimeFormat = 'MMdd HH:mm'; diff --git a/lib/src/components/picker/time_picker/brn_date_time_formatter.dart b/lib/src/components/picker/time_picker/brn_date_time_formatter.dart index ca584c9e..18bb9d78 100755 --- a/lib/src/components/picker/time_picker/brn_date_time_formatter.dart +++ b/lib/src/components/picker/time_picker/brn_date_time_formatter.dart @@ -10,49 +10,49 @@ import 'package:intl/intl.dart'; const String DATE_FORMAT_SEPARATOR = r'[|,-\._: ]+'; class DateTimeFormatter { - static DateTime convertStringToDate(String format, String date) { + static DateTime? convertStringToDate(String? format, String? date) { if (BrunoTools.isEmpty(format) || BrunoTools.isEmpty(date)) return null; - return DateFormat(format).parse(date); + return DateFormat(format).parse(date!); } - static DateTime convertIntValueToDateTime(String value) { + static DateTime? convertIntValueToDateTime(String? value) { if (value == null) { return null; } else { return int.tryParse(value) != null - ? DateTime.fromMillisecondsSinceEpoch(int.tryParse(value)) + ? DateTime.fromMillisecondsSinceEpoch(int.tryParse(value)!) : null; } } /// Get default value of date format. static String generateDateFormat( - String dateFormat, BrnDateTimePickerMode pickerMode) { + String? dateFormat, BrnDateTimePickerMode pickerMode) { if (dateFormat != null && dateFormat.length > 0) { return dateFormat; } switch (pickerMode) { case BrnDateTimePickerMode.date: - return DATETIME_PICKER_DATE_FORMAT; + return datetimePickerDateFormat; case BrnDateTimePickerMode.time: - return DATETIME_PICKER_TIME_FORMAT; + return datetimePickerTimeFormat; case BrnDateTimePickerMode.datetime: - return DATETIME_PICKER_DATETIME_FORMAT; + return datetimePickerDatetimeFormat; } return ''; } static String generateDateRangePickerFormat( - String dateFormat, BrnDateTimeRangePickerMode pickerMode) { + String? dateFormat, BrnDateTimeRangePickerMode pickerMode) { if (dateFormat != null && dateFormat.length > 0) { return dateFormat; } switch (pickerMode) { case BrnDateTimeRangePickerMode.date: - return DATETIME_RANGE_PICKER_DATE_FORMAT; + return datetimeRangePickerDateFormat; case BrnDateTimeRangePickerMode.time: - return DATETIME_RANGE_PICKER_TIME_FORMAT; + return datetimeRangePickerTimeFormat; } return ''; } @@ -68,15 +68,15 @@ class DateTimeFormatter { } /// Split date format to array. - static List splitDateFormat(String dateFormat, - {BrnDateTimePickerMode mode}) { + static List splitDateFormat(String? dateFormat, + {BrnDateTimePickerMode? mode}) { if (dateFormat == null || dateFormat.length == 0) { return []; } List result = dateFormat.split(RegExp(DATE_FORMAT_SEPARATOR)); if (mode == BrnDateTimePickerMode.datetime) { // datetime mode need join day format - List temp = List(); + List temp = []; StringBuffer dayFormat = StringBuffer(); for (int i = 0; i < result.length; i++) { String format = result[i]; @@ -99,7 +99,7 @@ class DateTimeFormatter { temp.insert(0, dayFormat.toString()); } else { // add default date format - temp.insert(0, DATETIME_PICKER_DATE_FORMAT); + temp.insert(0, datetimePickerDateFormat); } result = temp; } diff --git a/lib/src/components/picker/time_picker/date_picker/brn_date_picker.dart b/lib/src/components/picker/time_picker/date_picker/brn_date_picker.dart index 009af06f..a9680532 100755 --- a/lib/src/components/picker/time_picker/date_picker/brn_date_picker.dart +++ b/lib/src/components/picker/time_picker/date_picker/brn_date_picker.dart @@ -44,49 +44,49 @@ class BrnDatePicker { bool rootNavigator = false, /// 点击弹框外部区域能否消失 - bool canBarrierDismissible, + bool? canBarrierDismissible, /// 能滚动到的最小日期 - DateTime minDateTime, + DateTime? minDateTime, /// 能滚动到的最大日期 - DateTime maxDateTime, + DateTime? maxDateTime, /// 初始选择的时间。默认当前时间 - DateTime initialDateTime, + DateTime? initialDateTime, /// 时间格式化的格式 - String dateFormat, + String? dateFormat, /// 分钟间切换的差值 int minuteDivider: 1, - DateTimePickerLocale locale: DATETIME_PICKER_LOCALE_DEFAULT, + DateTimePickerLocale locale = datetimePickerLocaleDefault, /// 时间选择组件显示的时间类型 - BrnDateTimePickerMode pickerMode: BrnDateTimePickerMode.date, + BrnDateTimePickerMode pickerMode = BrnDateTimePickerMode.date, /// 时间选择组件的主题样式 - BrnPickerTitleConfig pickerTitleConfig, + BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig.Default, /// 点击【取消】回调给调用方的回调事件 - DateVoidCallback onCancel, + DateVoidCallback? onCancel, /// 点击【完成】回调给调用方的数据 - DateVoidCallback onClose, + DateVoidCallback? onClose, /// 时间滚动选择时候的回调事件 - DateValueCallback onChange, + DateValueCallback? onChange, /// 弹框点击外围消失的回调事件 - DateValueCallback onConfirm, - BrnPickerConfig themeData, + DateValueCallback? onConfirm, + BrnPickerConfig? themeData, }) { // handle the range of datetime if (minDateTime == null) { - minDateTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); + minDateTime = DateTime.parse(datePickerMinDatetime); } if (maxDateTime == null) { - maxDateTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + maxDateTime = DateTime.parse(datePickerMaxDatetime); } // handle initial DateTime @@ -129,37 +129,37 @@ class _DatePickerRoute extends PopupRoute { this.initialDateTime, this.minuteDivider, this.dateFormat, - this.locale, - this.pickerMode, - this.pickerTitleConfig, + this.locale = datetimePickerLocaleDefault, + this.pickerMode = BrnDateTimePickerMode.date, + this.pickerTitleConfig = BrnPickerTitleConfig.Default, this.onCancel, this.onChange, this.onConfirm, this.theme, this.barrierLabel, this.canBarrierDismissible, - RouteSettings settings, + RouteSettings? settings, this.themeData, }) : super(settings: settings) { this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } - final DateTime minDateTime, maxDateTime, initialDateTime; - final String dateFormat; + final DateTime? minDateTime, maxDateTime, initialDateTime; + final String? dateFormat; final DateTimePickerLocale locale; final BrnDateTimePickerMode pickerMode; final BrnPickerTitleConfig pickerTitleConfig; - final VoidCallback onCancel; - final DateValueCallback onChange; - final DateValueCallback onConfirm; - bool canBarrierDismissible; - final int minuteDivider; - final ThemeData theme; - BrnPickerConfig themeData; + final VoidCallback? onCancel; + final DateValueCallback? onChange; + final DateValueCallback? onConfirm; + bool? canBarrierDismissible; + final int? minuteDivider; + final ThemeData? theme; + BrnPickerConfig? themeData; @override Duration get transitionDuration => const Duration(milliseconds: 200); @@ -168,27 +168,27 @@ class _DatePickerRoute extends PopupRoute { bool get barrierDismissible => canBarrierDismissible ?? true; @override - final String barrierLabel; + final String? barrierLabel; @override Color get barrierColor => Colors.black54; - AnimationController _animationController; + AnimationController? _animationController; @override AnimationController createAnimationController() { assert(_animationController == null); _animationController = - BottomSheet.createAnimationController(navigator.overlay); - return _animationController; + BottomSheet.createAnimationController(navigator!.overlay!); + return _animationController!; } @override Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { - double height = themeData.pickerHeight; + double height = themeData!.pickerHeight; if (pickerTitleConfig.title != null || pickerTitleConfig.showTitle) { - height += themeData.titleHeight; + height += themeData!.titleHeight; } Widget bottomSheet = MediaQuery.removePadding( @@ -198,7 +198,7 @@ class _DatePickerRoute extends PopupRoute { ); if (theme != null) { - bottomSheet = Theme(data: theme, child: bottomSheet); + bottomSheet = Theme(data: theme!, child: bottomSheet); } return bottomSheet; } @@ -209,12 +209,12 @@ class _DatePickerComponent extends StatelessWidget { final _DatePickerRoute route; final double _pickerHeight; - _DatePickerComponent({@required this.route, @required pickerHeight}) + _DatePickerComponent({required this.route, required pickerHeight}) : this._pickerHeight = pickerHeight; @override Widget build(BuildContext context) { - Widget pickerWidget; + Widget? pickerWidget; switch (route.pickerMode) { case BrnDateTimePickerMode.date: pickerWidget = BrnDateWidget( @@ -263,16 +263,15 @@ class _DatePickerComponent extends StatelessWidget { } return GestureDetector( child: AnimatedBuilder( - animation: route.animation, - builder: (BuildContext context, Widget child) { + animation: route.animation!, + builder: (BuildContext context, Widget? child) { return ClipRect( child: CustomSingleChildLayout( - delegate: _BottomPickerLayout(route.animation.value, - contentHeight: _pickerHeight), + delegate: _BottomPickerLayout(route.animation!.value, _pickerHeight), child: BrnPickerClipRRect( borderRadius: BorderRadius.only( - topLeft: Radius.circular(route.themeData.cornerRadius), - topRight: Radius.circular(route.themeData.cornerRadius), + topLeft: Radius.circular(route.themeData!.cornerRadius), + topRight: Radius.circular(route.themeData!.cornerRadius), ), child: pickerWidget, ), @@ -285,7 +284,7 @@ class _DatePickerComponent extends StatelessWidget { } class _BottomPickerLayout extends SingleChildLayoutDelegate { - _BottomPickerLayout(this.progress, {this.contentHeight}); + _BottomPickerLayout(this.progress, this.contentHeight); final double progress; final double contentHeight; diff --git a/lib/src/components/picker/time_picker/date_picker/brn_date_widget.dart b/lib/src/components/picker/time_picker/date_picker/brn_date_widget.dart index 3c08e2dd..1d0b2a9f 100755 --- a/lib/src/components/picker/time_picker/date_picker/brn_date_widget.dart +++ b/lib/src/components/picker/time_picker/date_picker/brn_date_widget.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -9,7 +11,7 @@ import 'package:bruno/src/theme/brn_theme.dart'; import 'package:bruno/src/utils/i18n/brn_date_picker_i18n.dart'; import 'package:flutter/material.dart'; -enum ColumnType { Year, Month, Day } +enum ColumnType { year, month, day } /// Solar months of 31 days. const List _solarMonthsOf31Days = const [1, 3, 5, 7, 8, 10, 12]; @@ -19,38 +21,38 @@ const List _solarMonthsOf31Days = const [1, 3, 5, 7, 8, 10, 12]; // ignore: must_be_immutable class BrnDateWidget extends StatefulWidget { BrnDateWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.initialDateTime, - this.dateFormat: DATETIME_PICKER_DATE_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, - this.pickerTitleConfig: BrnPickerTitleConfig.Default, + this.dateFormat = datetimePickerDateFormat, + this.locale = datetimePickerLocaleDefault, + this.pickerTitleConfig= BrnPickerTitleConfig.Default, this.onCancel, this.onChange, this.onConfirm, this.canPop = true, this.themeData, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) < 0); this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } - final DateTime minDateTime, maxDateTime, initialDateTime; - final String dateFormat; + final DateTime? minDateTime, maxDateTime, initialDateTime; + final String? dateFormat; final DateTimePickerLocale locale; final BrnPickerTitleConfig pickerTitleConfig; - final DateVoidCallback onCancel; - final DateValueCallback onChange, onConfirm; + final DateVoidCallback? onCancel; + final DateValueCallback? onChange, onConfirm; final bool canPop; - BrnPickerConfig themeData; + BrnPickerConfig? themeData; @override State createState() => _BrnDateWidgetState( @@ -58,18 +60,18 @@ class BrnDateWidget extends StatefulWidget { } class _BrnDateWidgetState extends State { - DateTime _minDateTime, _maxDateTime; - int _currYear, _currMonth, _currDay; - List _yearRange, _monthRange, _dayRange; - FixedExtentScrollController _yearScrollCtrl, _monthScrollCtrl, _dayScrollCtrl; + late DateTime _minDateTime, _maxDateTime; + late int _currYear, _currMonth, _currDay; + late List _yearRange, _monthRange, _dayRange; + late FixedExtentScrollController? _yearScrollCtrl, _monthScrollCtrl, _dayScrollCtrl; - Map _scrollCtrlMap; - Map> _valueRangeMap; + late Map _scrollCtrlMap; + late Map?> _valueRangeMap; bool _isChangeDateRange = false; _BrnDateWidgetState( - DateTime minDateTime, DateTime maxDateTime, DateTime initialDateTime) { + DateTime? minDateTime, DateTime? maxDateTime, DateTime? initialDateTime) { // handle current selected year、month、day DateTime initDateTime = initialDateTime ?? DateTime.now(); this._currYear = initDateTime.year; @@ -77,8 +79,8 @@ class _BrnDateWidgetState extends State { this._currDay = initDateTime.day; // handle DateTime range - this._minDateTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - this._maxDateTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + this._minDateTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + this._maxDateTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); // limit the range of year this._yearRange = _calcYearRange(); @@ -139,7 +141,7 @@ class _BrnDateWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } if (widget.canPop) Navigator.pop(context); } @@ -148,7 +150,7 @@ class _BrnDateWidgetState extends State { void _onPressedConfirm() { if (widget.onConfirm != null) { DateTime dateTime = DateTime(_currYear, _currMonth, _currDay); - widget.onConfirm(dateTime, _calcSelectIndexList()); + widget.onConfirm!(dateTime, _calcSelectIndexList()); } if (widget.canPop) Navigator.pop(context); } @@ -157,13 +159,13 @@ class _BrnDateWidgetState extends State { void _onSelectedChange() { if (widget.onChange != null) { DateTime dateTime = DateTime(_currYear, _currMonth, _currDay); - widget.onChange(dateTime, _calcSelectIndexList()); + widget.onChange!(dateTime, _calcSelectIndexList()); } } /// find scroll controller by specified format - FixedExtentScrollController _findScrollCtrl(String format) { - FixedExtentScrollController scrollCtrl; + FixedExtentScrollController? _findScrollCtrl(String format) { + FixedExtentScrollController? scrollCtrl; _scrollCtrlMap.forEach((key, value) { if (format.contains(key)) { scrollCtrl = value; @@ -173,8 +175,8 @@ class _BrnDateWidgetState extends State { } /// find item value range by specified format - List _findPickerItemRange(String format) { - List valueRange; + List? _findPickerItemRange(String format) { + List? valueRange; _valueRangeMap.forEach((key, value) { if (format.contains(key)) { valueRange = value; @@ -185,11 +187,11 @@ class _BrnDateWidgetState extends State { /// render the picker widget of year、month and day Widget _renderDatePickerWidget() { - List pickers = List(); + List pickers = []; List formatArr = DateTimeFormatter.splitDateFormat(widget.dateFormat); formatArr.forEach((format) { - List valueRange = _findPickerItemRange(format); + List valueRange = _findPickerItemRange(format)!; Widget pickerColumn = _renderDatePickerColumnComponent( scrollCtrl: _findScrollCtrl(format), @@ -212,27 +214,27 @@ class _BrnDateWidgetState extends State { } Widget _renderDatePickerColumnComponent({ - @required FixedExtentScrollController scrollCtrl, - @required List valueRange, - @required String format, - @required ValueChanged valueChanged, + required FixedExtentScrollController? scrollCtrl, + required List valueRange, + required String format, + required ValueChanged valueChanged, }) { return Expanded( flex: 1, child: Container( - height: widget.themeData.pickerHeight, - decoration: BoxDecoration(color: widget.themeData.backgroundColor), + height: widget.themeData!.pickerHeight, + decoration: BoxDecoration(color: widget.themeData!.backgroundColor), child: BrnPicker.builder( - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, scrollController: scrollCtrl, - itemExtent: widget.themeData.itemHeight, + itemExtent: widget.themeData!.itemHeight, onSelectedItemChanged: valueChanged, childCount: valueRange.last - valueRange.first + 1, itemBuilder: (context, index) => _renderDatePickerItemComponent( format.contains("y") - ? ColumnType.Year - : (format.contains("M") ? ColumnType.Month : ColumnType.Day), + ? ColumnType.year + : (format.contains("M") ? ColumnType.month : ColumnType.day), index, valueRange.first + index, format), @@ -243,15 +245,15 @@ class _BrnDateWidgetState extends State { Widget _renderDatePickerItemComponent( ColumnType columnType, int index, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); - if ((ColumnType.Year == columnType && index == _calcSelectIndexList()[0]) || - (ColumnType.Month == columnType && + TextStyle textStyle = widget.themeData!.itemTextStyle.generateTextStyle(); + if ((ColumnType.year == columnType && index == _calcSelectIndexList()[0]) || + (ColumnType.month == columnType && index == _calcSelectIndexList()[1]) || - (ColumnType.Day == columnType && index == _calcSelectIndexList()[2])) { - textStyle = widget.themeData.itemTextSelectedStyle.generateTextStyle(); + (ColumnType.day == columnType && index == _calcSelectIndexList()[2])) { + textStyle = widget.themeData!.itemTextSelectedStyle.generateTextStyle(); } return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( DateTimeFormatter.formatDateTime(value, format, widget.locale), @@ -323,18 +325,18 @@ class _BrnDateWidgetState extends State { if (monthRangeChanged) { // CupertinoPicker refresh data not working (https://github.com/flutter/flutter/issues/22999) int currMonth = _currMonth; - _monthScrollCtrl.jumpToItem(monthRange.last - monthRange.first); + _monthScrollCtrl!.jumpToItem(monthRange.last - monthRange.first); if (currMonth < monthRange.last) { - _monthScrollCtrl.jumpToItem(currMonth - monthRange.first); + _monthScrollCtrl!.jumpToItem(currMonth - monthRange.first); } } if (dayRangeChanged) { // CupertinoPicker refresh data not working (https://github.com/flutter/flutter/issues/22999) int currDay = _currDay; - _dayScrollCtrl.jumpToItem(dayRange.last - dayRange.first); + _dayScrollCtrl!.jumpToItem(dayRange.last - dayRange.first); if (currDay < dayRange.last) { - _dayScrollCtrl.jumpToItem(currDay - dayRange.first); + _dayScrollCtrl!.jumpToItem(currDay - dayRange.first); } } diff --git a/lib/src/components/picker/time_picker/date_picker/brn_datetime_widget.dart b/lib/src/components/picker/time_picker/date_picker/brn_datetime_widget.dart index 34023ba7..b0f33a65 100755 --- a/lib/src/components/picker/time_picker/date_picker/brn_datetime_widget.dart +++ b/lib/src/components/picker/time_picker/date_picker/brn_datetime_widget.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -9,18 +11,18 @@ import 'package:bruno/src/theme/brn_theme.dart'; import 'package:bruno/src/utils/i18n/brn_date_picker_i18n.dart'; import 'package:flutter/material.dart'; -enum ColumnType { Year, Month, Day, Hour, Minute, Second } +enum ColumnType { year, month, day, hour, minute, second } /// DateTimePicker widget. Can display date and time picker // ignore: must_be_immutable class BrnDateTimeWidget extends StatefulWidget { BrnDateTimeWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.initDateTime, - this.dateFormat: DATETIME_PICKER_TIME_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, + this.dateFormat: datetimePickerTimeFormat, + this.locale: datetimePickerLocaleDefault, this.pickerTitleConfig: BrnPickerTitleConfig.Default, this.onCancel, this.onChange, @@ -28,25 +30,25 @@ class BrnDateTimeWidget extends StatefulWidget { this.minuteDivider, this.themeData, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) < 0); this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } - final DateTime minDateTime, maxDateTime, initDateTime; - final int minuteDivider; - final String dateFormat; + final DateTime? minDateTime, maxDateTime, initDateTime; + final int? minuteDivider; + final String? dateFormat; final DateTimePickerLocale locale; final BrnPickerTitleConfig pickerTitleConfig; - final DateVoidCallback onCancel; - final DateValueCallback onChange, onConfirm; - BrnPickerConfig themeData; + final DateVoidCallback? onCancel; + final DateValueCallback? onChange, onConfirm; + BrnPickerConfig? themeData; @override State createState() => _BrnDateTimeWidgetState( @@ -56,37 +58,37 @@ class BrnDateTimeWidget extends StatefulWidget { class _BrnDateTimeWidgetState extends State { final int _defaultMinuteDivider = 1; - DateTime _minTime, _maxTime; - int _currYear, _currMonth, _currDay, _currHour, _currMinute, _currSecond; - List _yearRange, + late DateTime _minTime, _maxTime; + late int _currYear, _currMonth, _currDay, _currHour, _currMinute, _currSecond; + late List _yearRange, _monthRange, _dayRange, _hourRange, _minuteRange, _secondRange; - FixedExtentScrollController _yearScrollCtrl, + late FixedExtentScrollController _yearScrollCtrl, _monthScrollCtrl, _dayScrollCtrl, _hourScrollCtrl, _minuteScrollCtrl, _secondScrollCtrl; - Map _scrollCtrlMap; - Map> _valueRangeMap; + late Map _scrollCtrlMap; + late Map?> _valueRangeMap; bool _isChangeTimeRange = false; - int _minuteDivider; + int? _minuteDivider; - _BrnDateTimeWidgetState(DateTime minTime, DateTime maxTime, DateTime initTime, - int minuteDivider) { + _BrnDateTimeWidgetState(DateTime? minTime, DateTime? maxTime, DateTime? initTime, + int? minuteDivider) { // check minTime value if (minTime == null) { - minTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); + minTime = DateTime.parse(datePickerMinDatetime); } // check maxTime value if (maxTime == null) { - maxTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + maxTime = DateTime.parse(datePickerMaxDatetime); } // check initTime value if (initTime == null) { @@ -132,7 +134,7 @@ class _BrnDateTimeWidgetState extends State { this._minuteRange = _calcMinuteRange(); this._currMinute = min(max(_minuteRange.first, _currMinute), _minuteRange.last); - _currMinute -= _currMinute % _minuteDivider; + _currMinute -= _currMinute % _minuteDivider!; // limit the range of second this._secondRange = _calcSecondRange(); @@ -149,7 +151,7 @@ class _BrnDateTimeWidgetState extends State { _hourScrollCtrl = FixedExtentScrollController(initialItem: _currHour - _hourRange.first); _minuteScrollCtrl = FixedExtentScrollController( - initialItem: (_currMinute - _minuteRange.first) ~/ _minuteDivider); + initialItem: (_currMinute - _minuteRange.first) ~/ _minuteDivider!); _secondScrollCtrl = FixedExtentScrollController( initialItem: _currSecond - _secondRange.first); @@ -200,7 +202,7 @@ class _BrnDateTimeWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -214,33 +216,33 @@ class _BrnDateTimeWidgetState extends State { /// 如果传入的时间格式不包含 月、天、小时、分钟、秒。则相对应的时间置为 1,1,0,0,0; DateTime dateTime = DateTime( _currYear, - (formatArr?.where((format) => format.contains('M'))?.toList() ?? List()) + (formatArr.where((format) => format.contains('M')).toList()) .length > 0 ? _currMonth : 1, - (formatArr?.where((format) => format.contains('d'))?.toList() ?? List()) + (formatArr.where((format) => format.contains('d')).toList()) .length > 0 ? _currDay : 1, - (formatArr?.where((format) => format.contains('H'))?.toList() ?? List()) + (formatArr.where((format) => format.contains('H')).toList()) .length > 0 ? _currHour : 0, - (formatArr?.where((format) => format.contains('m'))?.toList() ?? List()) + (formatArr.where((format) => format.contains('m')).toList()) .length > 0 ? _currMinute : 0, - (formatArr?.where((format) => format.contains('s'))?.toList() ?? List()) + (formatArr.where((format) => format.contains('s')).toList()) .length > 0 ? _currSecond : 0, ); - widget.onConfirm(dateTime, _calcSelectIndexList()); + widget.onConfirm!(dateTime, _calcSelectIndexList()); } Navigator.pop(context); } @@ -250,13 +252,13 @@ class _BrnDateTimeWidgetState extends State { if (widget.onChange != null) { DateTime dateTime = DateTime( _currYear, _currMonth, _currDay, _currHour, _currMinute, _currSecond); - widget.onChange(dateTime, _calcSelectIndexList()); + widget.onChange!(dateTime, _calcSelectIndexList()); } } /// find scroll controller by specified format - FixedExtentScrollController _findScrollCtrl(String format) { - FixedExtentScrollController scrollCtrl; + FixedExtentScrollController? _findScrollCtrl(String format) { + FixedExtentScrollController? scrollCtrl; _scrollCtrlMap.forEach((key, value) { if (format.contains(key)) { scrollCtrl = value; @@ -266,8 +268,8 @@ class _BrnDateTimeWidgetState extends State { } /// find item value range by specified format - List _findPickerItemRange(String format) { - List valueRange; + List? _findPickerItemRange(String format) { + List? valueRange; _valueRangeMap.forEach((key, value) { if (format.contains(key)) { valueRange = value; @@ -278,13 +280,13 @@ class _BrnDateTimeWidgetState extends State { /// render the picker widget of year、month and day Widget _renderDatePickerWidget() { - List pickers = List(); + List pickers = []; List formatArr = DateTimeFormatter.splitDateFormat(widget.dateFormat); // render time picker column formatArr.forEach((format) { - List valueRange = _findPickerItemRange(format); + List? valueRange = _findPickerItemRange(format); Widget pickerColumn = _renderDatePickerColumnComponent( scrollCtrl: _findScrollCtrl(format), @@ -314,31 +316,31 @@ class _BrnDateTimeWidgetState extends State { } Widget _renderDatePickerColumnComponent( - {@required FixedExtentScrollController scrollCtrl, - @required List valueRange, - @required String format, - @required ValueChanged valueChanged, - int flex, - IndexedWidgetBuilder itemBuilder}) { + {required FixedExtentScrollController? scrollCtrl, + required List? valueRange, + required String format, + required ValueChanged valueChanged, + required int flex, + IndexedWidgetBuilder? itemBuilder}) { Widget columnWidget = Container( width: double.infinity, - height: widget.themeData.pickerHeight, - decoration: BoxDecoration(color: widget.themeData.backgroundColor), + height: widget.themeData!.pickerHeight, + decoration: BoxDecoration(color: widget.themeData!.backgroundColor), child: BrnPicker.builder( - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, scrollController: scrollCtrl, - itemExtent: widget.themeData.itemHeight, + itemExtent: widget.themeData!.itemHeight, onSelectedItemChanged: valueChanged, childCount: format.contains('m') ? _calculateMinuteChildCount(valueRange, _minuteDivider) - : valueRange.last - valueRange.first + 1, + : valueRange!.last - valueRange.first + 1, itemBuilder: itemBuilder ?? (context, index) { - int value = valueRange.first + index; + int value = valueRange!.first + index; if (format.contains('m')) { - value = valueRange.first + _minuteDivider * index; + value = valueRange.first + _minuteDivider! * index; } return _renderDatePickerItemComponent( getColumnType(format), index, value, format); @@ -351,29 +353,29 @@ class _BrnDateTimeWidgetState extends State { ); } - _calculateMinuteChildCount(List valueRange, int divider) { + _calculateMinuteChildCount(List? valueRange, int? divider) { if (divider == 0 || divider == 1) { debugPrint("Cant devide by 0"); - return (valueRange.last - valueRange.first + 1); + return (valueRange!.last - valueRange.first + 1); } - return ((valueRange.last - valueRange.first) ~/ divider) + 1; + return ((valueRange!.last - valueRange.first) ~/ divider!) + 1; } // ignore: missing_return - ColumnType getColumnType(String format) { + ColumnType? getColumnType(String format) { if (format.contains('y')) { - return ColumnType.Year; + return ColumnType.year; } else if (format.contains('M')) { - return ColumnType.Month; + return ColumnType.month; } else if (format.contains('d')) { - return ColumnType.Day; + return ColumnType.day; } else if (format.contains('H')) { - return ColumnType.Hour; + return ColumnType.hour; } else if (format.contains('m')) { - return ColumnType.Minute; + return ColumnType.minute; } else if (format.contains('s')) { - return ColumnType.Second; + return ColumnType.second; } return null; } @@ -463,22 +465,22 @@ class _BrnDateTimeWidgetState extends State { /// render hour、minute、second picker item Widget _renderDatePickerItemComponent( - ColumnType columnType, int index, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); - if ((ColumnType.Year == columnType && index == _calcSelectIndexList()[0]) || - (ColumnType.Month == columnType && + ColumnType? columnType, int index, int value, String format) { + TextStyle textStyle = widget.themeData!.itemTextStyle.generateTextStyle(); + if ((ColumnType.year == columnType && index == _calcSelectIndexList()[0]) || + (ColumnType.month == columnType && index == _calcSelectIndexList()[1]) || - (ColumnType.Day == columnType && index == _calcSelectIndexList()[2]) || - (ColumnType.Hour == columnType && index == _calcSelectIndexList()[3]) || - (ColumnType.Minute == columnType && + (ColumnType.day == columnType && index == _calcSelectIndexList()[2]) || + (ColumnType.hour == columnType && index == _calcSelectIndexList()[3]) || + (ColumnType.minute == columnType && index == _calcSelectIndexList()[4]) || - (ColumnType.Second == columnType && + (ColumnType.second == columnType && index == _calcSelectIndexList()[5])) { - textStyle = widget.themeData.itemTextSelectedStyle.generateTextStyle(); + textStyle = widget.themeData!.itemTextSelectedStyle.generateTextStyle(); } return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( DateTimeFormatter.formatDateTime(value, format, widget.locale), @@ -508,7 +510,7 @@ class _BrnDateTimeWidgetState extends State { /// change the selection of month picker void _changeMinuteSelection(int index) { - int value = _minuteRange.first + index * _minuteDivider; + int value = _minuteRange.first + index * _minuteDivider!; _currMinute = value; _changeTimeRange(); _onSelectedChange(); @@ -574,10 +576,10 @@ class _BrnDateTimeWidgetState extends State { if (minuteRangeChanged) { // CupertinoPicker refresh data not working (https://github.com/flutter/flutter/issues/22999) _minuteScrollCtrl - .jumpToItem((minuteRange.last - minuteRange.first) ~/ _minuteDivider); + .jumpToItem((minuteRange.last - minuteRange.first) ~/ _minuteDivider!); if (_currMinute < minuteRange.last) { _minuteScrollCtrl - .jumpToItem((_currMinute - minuteRange.first) ~/ _minuteDivider); + .jumpToItem((_currMinute - minuteRange.first) ~/ _minuteDivider!); } } @@ -598,7 +600,7 @@ class _BrnDateTimeWidgetState extends State { int monthIndex = _currMonth - _monthRange.first; int dayIndex = _currDay - _dayRange.first; int hourIndex = _currHour - _hourRange.first; - int minuteIndex = (_currMinute - _minuteRange.first) ~/ _minuteDivider; + int minuteIndex = (_currMinute - _minuteRange.first) ~/ _minuteDivider!; int secondIndex = _currSecond - _secondRange.first; return [ yearIndex, @@ -687,10 +689,10 @@ class _BrnDateTimeWidgetState extends State { minHour = _minTime.hour; } - int modValue = _minTime.minute % _minuteDivider; + int modValue = _minTime.minute % _minuteDivider!; int minMinute = modValue == 0 ? _minTime.minute - : (_minTime.minute - modValue + _minuteDivider); + : (_minTime.minute - modValue + _minuteDivider!); if (minMinute == 60) { minHour = minHour + 1 > _maxTime.hour ? _maxTime.hour : minHour + 1; } @@ -715,10 +717,10 @@ class _BrnDateTimeWidgetState extends State { _currDay == _minTime.day && _currHour == _minTime.hour) { // selected minimum day、hour, limit minute range - int modValue = _minTime.minute % _minuteDivider; + int modValue = _minTime.minute % _minuteDivider!; minMinute = modValue == 0 ? _minTime.minute - : (_minTime.minute - modValue + _minuteDivider); + : (_minTime.minute - modValue + _minuteDivider!); if (minMinute == 60) { minMinute = 0; currHour = currHour + 1 > _maxTime.hour ? _maxTime.hour : currHour + 1; @@ -729,7 +731,7 @@ class _BrnDateTimeWidgetState extends State { _currDay == _maxTime.day && _currHour == _maxTime.hour) { // selected maximum day、hour, limit minute range - maxMinute = _maxTime.minute - _maxTime.minute % _minuteDivider; + maxMinute = _maxTime.minute - _maxTime.minute % _minuteDivider!; } return [minMinute, maxMinute]; } diff --git a/lib/src/components/picker/time_picker/date_picker/brn_time_widget.dart b/lib/src/components/picker/time_picker/date_picker/brn_time_widget.dart index d6dd6255..1e9e0491 100755 --- a/lib/src/components/picker/time_picker/date_picker/brn_time_widget.dart +++ b/lib/src/components/picker/time_picker/date_picker/brn_time_widget.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -11,17 +13,17 @@ import 'package:flutter/material.dart'; /// TimePicker widget. -enum ColumnType { Hour, Minute, Second } +enum ColumnType { hour, minute, second } // ignore: must_be_immutable class BrnTimeWidget extends StatefulWidget { BrnTimeWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.initDateTime, - this.dateFormat: DATETIME_PICKER_TIME_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, + this.dateFormat: datetimePickerTimeFormat, + this.locale: datetimePickerLocaleDefault, this.pickerTitleConfig: BrnPickerTitleConfig.Default, this.minuteDivider = 1, this.onCancel, @@ -29,25 +31,25 @@ class BrnTimeWidget extends StatefulWidget { this.onConfirm, this.themeData, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) < 0); this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } - final DateTime minDateTime, maxDateTime, initDateTime; - final String dateFormat; + final DateTime? minDateTime, maxDateTime, initDateTime; + final String? dateFormat; final DateTimePickerLocale locale; final BrnPickerTitleConfig pickerTitleConfig; - final DateVoidCallback onCancel; - final DateValueCallback onChange, onConfirm; - final int minuteDivider; + final DateVoidCallback? onCancel; + final DateValueCallback? onChange, onConfirm; + final int? minuteDivider; - BrnPickerConfig themeData; + BrnPickerConfig? themeData; @override State createState() => _BrnTimeWidgetState(this.minDateTime, @@ -57,26 +59,26 @@ class BrnTimeWidget extends StatefulWidget { class _BrnTimeWidgetState extends State { static int _defaultMinuteDivider = 1; - DateTime _minTime, _maxTime; - int _currHour, _currMinute, _currSecond; - int _minuteDivider; - List _hourRange, _minuteRange, _secondRange; - FixedExtentScrollController _hourScrollCtrl, + late DateTime _minTime, _maxTime; + late int _currHour, _currMinute, _currSecond; + late int _minuteDivider; + late List _hourRange, _minuteRange, _secondRange; + late FixedExtentScrollController _hourScrollCtrl, _minuteScrollCtrl, _secondScrollCtrl; - Map _scrollCtrlMap; - Map> _valueRangeMap; + late Map _scrollCtrlMap; + late Map> _valueRangeMap; bool _isChangeTimeRange = false; - _BrnTimeWidgetState(DateTime minTime, DateTime maxTime, DateTime initTime, - int minuteDivider) { + _BrnTimeWidgetState(DateTime? minTime, DateTime? maxTime, DateTime? initTime, + int? minuteDivider) { if (minTime == null) { - minTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); + minTime = DateTime.parse(datePickerMinDatetime); } if (maxTime == null) { - maxTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + maxTime = DateTime.parse(datePickerMaxDatetime); } if (initTime == null) { // init time is now @@ -153,7 +155,7 @@ class _BrnTimeWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -164,7 +166,7 @@ class _BrnTimeWidgetState extends State { DateTime now = DateTime.now(); DateTime dateTime = DateTime( now.year, now.month, now.day, _currHour, _currMinute, _currSecond); - widget.onConfirm(dateTime, _calcSelectIndexList()); + widget.onConfirm!(dateTime, _calcSelectIndexList()); } Navigator.pop(context); } @@ -175,13 +177,13 @@ class _BrnTimeWidgetState extends State { DateTime now = DateTime.now(); DateTime dateTime = DateTime( now.year, now.month, now.day, _currHour, _currMinute, _currSecond); - widget.onChange(dateTime, _calcSelectIndexList()); + widget.onChange!(dateTime, _calcSelectIndexList()); } } /// find scroll controller by specified format - FixedExtentScrollController _findScrollCtrl(String format) { - FixedExtentScrollController scrollCtrl; + FixedExtentScrollController? _findScrollCtrl(String format) { + FixedExtentScrollController? scrollCtrl; _scrollCtrlMap.forEach((key, value) { if (format.contains(key)) { scrollCtrl = value; @@ -191,8 +193,8 @@ class _BrnTimeWidgetState extends State { } /// find item value range by specified format - List _findPickerItemRange(String format) { - List valueRange; + List? _findPickerItemRange(String format) { + List? valueRange; _valueRangeMap.forEach((key, value) { if (format.contains(key)) { valueRange = value; @@ -203,11 +205,11 @@ class _BrnTimeWidgetState extends State { /// render the picker widget of year、month and day Widget _renderDatePickerWidget() { - List pickers = List(); + List pickers = []; List formatArr = DateTimeFormatter.splitDateFormat(widget.dateFormat); formatArr.forEach((format) { - List valueRange = _findPickerItemRange(format); + List? valueRange = _findPickerItemRange(format); Widget pickerColumn = _renderDatePickerColumnComponent( scrollCtrl: _findScrollCtrl(format), @@ -230,27 +232,27 @@ class _BrnTimeWidgetState extends State { } Widget _renderDatePickerColumnComponent({ - @required FixedExtentScrollController scrollCtrl, - @required List valueRange, - @required String format, - @required ValueChanged valueChanged, + required FixedExtentScrollController? scrollCtrl, + required List? valueRange, + required String format, + required ValueChanged valueChanged, }) { return Expanded( flex: 1, child: Container( - height: widget.themeData.pickerHeight, - decoration: BoxDecoration(color: widget.themeData.backgroundColor), + height: widget.themeData!.pickerHeight, + decoration: BoxDecoration(color: widget.themeData!.backgroundColor), child: BrnPicker.builder( - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, scrollController: scrollCtrl, - itemExtent: widget.themeData.itemHeight, + itemExtent: widget.themeData!.itemHeight, onSelectedItemChanged: valueChanged, childCount: format.contains('m') ? _calculateMinuteChildCount(valueRange, _minuteDivider) - : valueRange.last - valueRange.first + 1, + : valueRange!.last - valueRange.first + 1, itemBuilder: (context, index) { - int value = valueRange.first + index; + int value = valueRange!.first + index; if (format.contains('m')) { value = _minuteDivider * index; @@ -265,38 +267,38 @@ class _BrnTimeWidgetState extends State { } // ignore: missing_return - ColumnType getColumnType(String format) { + ColumnType? getColumnType(String format) { if (format.contains('H')) { - return ColumnType.Hour; + return ColumnType.hour; } else if (format.contains('m')) { - return ColumnType.Minute; + return ColumnType.minute; } else if (format.contains('s')) { - return ColumnType.Second; + return ColumnType.second; } return null; } - _calculateMinuteChildCount(List valueRange, int divider) { + _calculateMinuteChildCount(List? valueRange, int? divider) { if (divider == 0) { debugPrint("Cant devide by 0"); - return (valueRange.last - valueRange.first + 1); + return (valueRange!.last - valueRange.first + 1); } - return (valueRange.last - valueRange.first + 1) ~/ divider; + return (valueRange!.last - valueRange.first + 1) ~/ divider!; } Widget _renderDatePickerItemComponent( - ColumnType columnType, int index, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); - if ((ColumnType.Hour == columnType && index == _calcSelectIndexList()[0]) || - (ColumnType.Minute == columnType && + ColumnType? columnType, int index, int value, String format) { + TextStyle textStyle = widget.themeData!.itemTextStyle.generateTextStyle(); + if ((ColumnType.hour == columnType && index == _calcSelectIndexList()[0]) || + (ColumnType.minute == columnType && index == _calcSelectIndexList()[1]) || - (ColumnType.Second == columnType && + (ColumnType.second == columnType && index == _calcSelectIndexList()[2])) { - textStyle = widget.themeData.itemTextSelectedStyle.generateTextStyle(); + textStyle = widget.themeData!.itemTextSelectedStyle.generateTextStyle(); } return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( DateTimeFormatter.formatDateTime(value, format, widget.locale), diff --git a/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_picker.dart b/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_picker.dart index 9ad2b890..023aa757 100755 --- a/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_picker.dart +++ b/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_picker.dart @@ -37,28 +37,28 @@ class BrnDateRangePicker { static void showDatePicker( BuildContext context, { bool isDismissible = true, - DateTime minDateTime, - DateTime maxDateTime, + DateTime? minDateTime, + DateTime? maxDateTime, bool isLimitTimeRange = true, - DateTime initialStartDateTime, - DateTime initialEndDateTime, - String dateFormat, - int minuteDivider, - DateTimePickerLocale locale: DATETIME_PICKER_LOCALE_DEFAULT, - BrnDateTimeRangePickerMode pickerMode: BrnDateTimeRangePickerMode.date, - BrnPickerTitleConfig pickerTitleConfig: BrnPickerTitleConfig.Default, - DateVoidCallback onCancel, - DateVoidCallback onClose, - DateRangeValueCallback onChange, - DateRangeValueCallback onConfirm, - BrnPickerConfig themeData, + DateTime? initialStartDateTime, + DateTime? initialEndDateTime, + String? dateFormat, + int minuteDivider = 1, + DateTimePickerLocale locale = datetimePickerLocaleDefault, + BrnDateTimeRangePickerMode pickerMode = BrnDateTimeRangePickerMode.date, + BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig.Default, + DateVoidCallback? onCancel, + DateVoidCallback? onClose, + DateRangeValueCallback? onChange, + DateRangeValueCallback? onConfirm, + BrnPickerConfig? themeData, }) { // handle the range of datetime if (minDateTime == null) { - minDateTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); + minDateTime = DateTime.parse(datePickerMinDatetime); } if (maxDateTime == null) { - maxDateTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + maxDateTime = DateTime.parse(datePickerMaxDatetime); } // handle initial DateTime @@ -91,27 +91,27 @@ class BrnDateRangePicker { MaterialLocalizations.of(context).modalBarrierDismissLabel, themeData: themeData, ), - ).whenComplete(onClose); + ).whenComplete(onClose ?? () {}); } } class _DatePickerRoute extends PopupRoute { - final DateTime minDateTime, + final DateTime? minDateTime, maxDateTime, initialStartDateTime, initialEndDateTime; final bool isLimitTimeRange; - final String dateFormat; + final String? dateFormat; final DateTimePickerLocale locale; final BrnDateTimeRangePickerMode pickerMode; final BrnPickerTitleConfig pickerTitleConfig; - final VoidCallback onCancel; - final DateRangeValueCallback onChange; - final DateRangeValueCallback onConfirm; + final VoidCallback? onCancel; + final DateRangeValueCallback? onChange; + final DateRangeValueCallback? onConfirm; final int minuteDivider; - final ThemeData theme; - final bool isDismissible; - BrnPickerConfig themeData; + final ThemeData? theme; + final bool? isDismissible; + BrnPickerConfig? themeData; _DatePickerRoute({ this.minDateTime, @@ -121,9 +121,9 @@ class _DatePickerRoute extends PopupRoute { this.initialEndDateTime, this.minuteDivider = 1, this.dateFormat, - this.locale, - this.pickerMode, - this.pickerTitleConfig, + this.locale = datetimePickerLocaleDefault, + this.pickerMode = BrnDateTimeRangePickerMode.date, + this.pickerTitleConfig = BrnPickerTitleConfig.Default, this.onCancel, this.onChange, this.onConfirm, @@ -131,11 +131,11 @@ class _DatePickerRoute extends PopupRoute { this.barrierLabel, this.isDismissible, this.themeData, - RouteSettings settings, + RouteSettings? settings, }) : super(settings: settings) { this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } @@ -147,27 +147,27 @@ class _DatePickerRoute extends PopupRoute { bool get barrierDismissible => isDismissible ?? true; @override - final String barrierLabel; + final String? barrierLabel; @override Color get barrierColor => Colors.black54; - AnimationController _animationController; + AnimationController? _animationController; @override AnimationController createAnimationController() { assert(_animationController == null); _animationController = - BottomSheet.createAnimationController(navigator.overlay); - return _animationController; + BottomSheet.createAnimationController(navigator!.overlay!); + return _animationController!; } @override Widget buildPage(BuildContext context, Animation animation, Animation secondaryAnimation) { - double height = themeData.pickerHeight; + double height = themeData!.pickerHeight; if (pickerTitleConfig.title != null || pickerTitleConfig.showTitle) { - height += themeData.titleHeight; + height += themeData!.titleHeight; } Widget bottomSheet = MediaQuery.removePadding( @@ -180,7 +180,7 @@ class _DatePickerRoute extends PopupRoute { ); if (theme != null) { - bottomSheet = Theme(data: theme, child: bottomSheet); + bottomSheet = Theme(data: theme!, child: bottomSheet); } return bottomSheet; } @@ -190,12 +190,12 @@ class _DatePickerComponent extends StatelessWidget { final _DatePickerRoute route; final double _pickerHeight; - _DatePickerComponent({@required this.route, @required pickerHeight}) + _DatePickerComponent({required this.route, required pickerHeight}) : this._pickerHeight = pickerHeight; @override Widget build(BuildContext context) { - Widget pickerWidget; + Widget? pickerWidget; switch (route.pickerMode) { case BrnDateTimeRangePickerMode.date: pickerWidget = BrnDateRangeWidget( @@ -232,16 +232,15 @@ class _DatePickerComponent extends StatelessWidget { } return GestureDetector( child: AnimatedBuilder( - animation: route.animation, - builder: (BuildContext context, Widget child) { + animation: route.animation!, + builder: (BuildContext context, Widget? child) { return ClipRect( child: CustomSingleChildLayout( - delegate: _BottomPickerLayout(route.animation.value, - contentHeight: _pickerHeight), + delegate: _BottomPickerLayout(route.animation!.value, _pickerHeight), child: BrnPickerClipRRect( borderRadius: BorderRadius.only( - topLeft: Radius.circular(route.themeData.cornerRadius), - topRight: Radius.circular(route.themeData.cornerRadius), + topLeft: Radius.circular(route.themeData!.cornerRadius), + topRight: Radius.circular(route.themeData!.cornerRadius), ), child: pickerWidget, ), @@ -254,7 +253,7 @@ class _DatePickerComponent extends StatelessWidget { } class _BottomPickerLayout extends SingleChildLayoutDelegate { - _BottomPickerLayout(this.progress, {this.contentHeight}); + _BottomPickerLayout(this.progress, this.contentHeight); final double progress; final double contentHeight; diff --git a/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_side_widget.dart b/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_side_widget.dart index d6eb8871..fb3a4afb 100755 --- a/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_side_widget.dart +++ b/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_side_widget.dart @@ -10,49 +10,49 @@ import 'package:flutter/material.dart'; /// Solar months of 31 days. const List _solarMonthsOf31Days = const [1, 3, 5, 7, 8, 10, 12]; -enum ColumnType { Year, Month, Day } +enum ColumnType { year, month, day } /// one side widget of DateRangePicker // ignore: must_be_immutable class BrnDateRangeSideWidget extends StatefulWidget { /// 可选最小时间 - final DateTime minDateTime; + final DateTime? minDateTime; /// 可选最大时间 - final DateTime maxDateTime; + final DateTime? maxDateTime; /// 初始开始选中时间 - final DateTime initialStartDateTime; + final DateTime? initialStartDateTime; /// 时间展示格式 - final String dateFormat; + final String? dateFormat; final DateTimePickerLocale locale; /// 时间选择变化时回调 - final DateRangeSideValueCallback onChange; + final DateRangeSideValueCallback? onChange; /// 当前默认选择的时间变化时对外部回调,外部监听该事件同步修改默认初始选中的时间 - final DateRangeSideValueCallback onInitSelectChange; + final DateRangeSideValueCallback? onInitSelectChange; /// 主题定制 - BrnPickerConfig themeData; + BrnPickerConfig? themeData; BrnDateRangeSideWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.initialStartDateTime, - this.dateFormat: DATETIME_RANGE_PICKER_DATE_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, + this.dateFormat = datetimeRangePickerDateFormat, + this.locale = datetimePickerLocaleDefault, this.onInitSelectChange, this.onChange, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) <= 0); this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } @@ -66,36 +66,41 @@ class BrnDateRangeSideWidget extends StatefulWidget { } class _DatePickerWidgetState extends State { - DateTime _minDateTime, _maxDateTime; - int _currYear, _currMonth, _currDay; - List _yearRange, _monthRange, _dayRange; - FixedExtentScrollController _yearScrollCtrl, _monthScrollCtrl, _dayScrollCtrl; + late DateTime _minDateTime, _maxDateTime; + late int _currYear, _currMonth, _currDay; + late List _yearRange, _monthRange, _dayRange; + late FixedExtentScrollController _yearScrollCtrl, + _monthScrollCtrl, + _dayScrollCtrl; - Map _scrollCtrlMap; - Map> _valueRangeMap; + late Map _scrollCtrlMap; + late Map> _valueRangeMap; bool _isChangeDateRange = false; bool _scrolledNotDay = false; - DateRangeSideValueCallback _onInitSelectChange; + DateRangeSideValueCallback? _onInitSelectChange; - _DatePickerWidgetState(DateTime minDateTime, DateTime maxDateTime, - DateTime initialDateTime, DateRangeSideValueCallback onInitSelectChange) { + _DatePickerWidgetState( + DateTime? minDateTime, + DateTime? maxDateTime, + DateTime? initialDateTime, + DateRangeSideValueCallback? onInitSelectChange) { _onInitSelectChange = onInitSelectChange; _initData(initialDateTime, minDateTime, maxDateTime); } void _initData( - DateTime initialDateTime, DateTime minDateTime, DateTime maxDateTime) { + DateTime? initialDateTime, DateTime? minDateTime, DateTime? maxDateTime) { DateTime initDateTime = initialDateTime ?? DateTime.now(); this._currYear = initDateTime.year; this._currMonth = initDateTime.month; this._currDay = initDateTime.day; // handle DateTime range - this._minDateTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - this._maxDateTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + this._minDateTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + this._maxDateTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); // limit the range of year this._yearRange = _calcYearRange(); @@ -130,7 +135,7 @@ class _DatePickerWidgetState extends State { widget.initialStartDateTime, widget.minDateTime, widget.maxDateTime); return GestureDetector( child: Container( - color: widget.themeData.backgroundColor, + color: widget.themeData!.backgroundColor, child: _renderDatePickerWidget()), ); } @@ -139,7 +144,7 @@ class _DatePickerWidgetState extends State { void _onInitSelectedChange() { if (_onInitSelectChange != null) { DateTime dateTime = DateTime(_currYear, _currMonth, _currDay); - _onInitSelectChange(dateTime, _calcSelectIndexList()); + _onInitSelectChange!(dateTime, _calcSelectIndexList()); } } @@ -147,13 +152,13 @@ class _DatePickerWidgetState extends State { void _onSelectedChange() { if (widget.onChange != null) { DateTime dateTime = DateTime(_currYear, _currMonth, _currDay); - widget.onChange(dateTime, _calcSelectIndexList()); + widget.onChange!(dateTime, _calcSelectIndexList()); } } /// find scroll controller by specified format - FixedExtentScrollController _findScrollCtrl(String format) { - FixedExtentScrollController scrollCtrl; + FixedExtentScrollController? _findScrollCtrl(String format) { + FixedExtentScrollController? scrollCtrl; _scrollCtrlMap.forEach((key, value) { if (format.contains(key)) { scrollCtrl = value; @@ -163,8 +168,8 @@ class _DatePickerWidgetState extends State { } /// find item value range by specified format - List _findPickerItemRange(String format) { - List valueRange; + List? _findPickerItemRange(String format) { + List? valueRange; _valueRangeMap.forEach((key, value) { if (format.contains(key)) { valueRange = value; @@ -175,11 +180,11 @@ class _DatePickerWidgetState extends State { /// render the picker widget of year、month and day Widget _renderDatePickerWidget() { - List pickers = List(); + List pickers = []; List formatArr = DateTimeFormatter.splitDateFormat(widget.dateFormat); formatArr.forEach((format) { - List valueRange = _findPickerItemRange(format); + List valueRange = _findPickerItemRange(format)!; Widget pickerColumn = _renderDatePickerColumnComponent( scrollCtrl: _findScrollCtrl(format), @@ -202,10 +207,10 @@ class _DatePickerWidgetState extends State { } Widget _renderDatePickerColumnComponent({ - @required FixedExtentScrollController scrollCtrl, - @required List valueRange, - @required String format, - @required ValueChanged valueChanged, + required FixedExtentScrollController? scrollCtrl, + required List valueRange, + required String format, + required ValueChanged valueChanged, }) { var globalKey; if (_scrolledNotDay && format.contains("d")) { @@ -215,14 +220,14 @@ class _DatePickerWidgetState extends State { return Expanded( flex: 1, child: Container( - height: widget.themeData.pickerHeight, - decoration: BoxDecoration(color: widget.themeData.backgroundColor), + height: widget.themeData!.pickerHeight, + decoration: BoxDecoration(color: widget.themeData!.backgroundColor), child: BrnPicker.builder( key: globalKey, - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, scrollController: scrollCtrl, - itemExtent: widget.themeData.itemHeight, + itemExtent: widget.themeData!.itemHeight, onSelectedItemChanged: (int index) { if (!format.contains("d")) { _scrolledNotDay = true; @@ -232,8 +237,8 @@ class _DatePickerWidgetState extends State { childCount: valueRange.last - valueRange.first + 1, itemBuilder: (context, index) => _renderDatePickerItemComponent( format.contains("y") - ? ColumnType.Year - : (format.contains("M") ? ColumnType.Month : ColumnType.Day), + ? ColumnType.year + : (format.contains("M") ? ColumnType.month : ColumnType.day), index, valueRange.first + index, format), @@ -244,15 +249,15 @@ class _DatePickerWidgetState extends State { Widget _renderDatePickerItemComponent( ColumnType columnType, int index, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); - if ((ColumnType.Year == columnType && index == _calcSelectIndexList()[0]) || - (ColumnType.Month == columnType && + TextStyle textStyle = widget.themeData!.itemTextStyle.generateTextStyle(); + if ((ColumnType.year == columnType && index == _calcSelectIndexList()[0]) || + (ColumnType.month == columnType && index == _calcSelectIndexList()[1]) || - (ColumnType.Day == columnType && index == _calcSelectIndexList()[2])) { - textStyle = widget.themeData.itemTextSelectedStyle.generateTextStyle(); + (ColumnType.day == columnType && index == _calcSelectIndexList()[2])) { + textStyle = widget.themeData!.itemTextSelectedStyle.generateTextStyle(); } return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( DateTimeFormatter.formatDateTime(value, format, widget.locale), diff --git a/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_widget.dart b/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_widget.dart index cacab725..e5f311b1 100755 --- a/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_widget.dart +++ b/lib/src/components/picker/time_picker/date_range_picker/brn_date_range_widget.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -16,56 +18,56 @@ const List _solarMonthsOf31Days = const [1, 3, 5, 7, 8, 10, 12]; // ignore: must_be_immutable class BrnDateRangeWidget extends StatefulWidget { /// 可选最小时间 - final DateTime minDateTime; + final DateTime? minDateTime; /// 可选最大时间 - final DateTime maxDateTime; + final DateTime? maxDateTime; /// 初始选中的开始时间 - final DateTime initialStartDateTime; + final DateTime? initialStartDateTime; /// 初始选中的结束时间 - final DateTime initialEndDateTime; + final DateTime? initialEndDateTime; /// 时间展示格式 - final String dateFormat; + final String? dateFormat; final DateTimePickerLocale locale; /// cancel 回调 - final DateVoidCallback onCancel; + final DateVoidCallback? onCancel; /// 选中时间变化时的回调,返回选中的开始、结束时间 - final DateRangeValueCallback onChange; + final DateRangeValueCallback? onChange; /// 确定回调,返回选中的开始、结束时间 - final DateRangeValueCallback onConfirm; + final DateRangeValueCallback? onConfirm; /// Picker title 相关内容配置 final BrnPickerTitleConfig pickerTitleConfig; /// Picker 主题配置 - BrnPickerConfig themeData; + BrnPickerConfig? themeData; BrnDateRangeWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.initialStartDateTime, this.initialEndDateTime, - this.dateFormat: DATETIME_RANGE_PICKER_DATE_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, + this.dateFormat: datetimeRangePickerDateFormat, + this.locale: datetimePickerLocaleDefault, this.pickerTitleConfig: BrnPickerTitleConfig.Default, this.onCancel, this.onChange, this.onConfirm, this.themeData, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) < 0); this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } @@ -79,28 +81,28 @@ class BrnDateRangeWidget extends StatefulWidget { } class _DatePickerWidgetState extends State { - DateTime _minDateTime, _maxDateTime; - int _currStartYear, _currStartMonth, _currStartDay; - int _currEndYear, _currEndMonth, _currEndDay; + late DateTime _minDateTime, _maxDateTime; + late int _currStartYear, _currStartMonth, _currStartDay; + late int _currEndYear, _currEndMonth, _currEndDay; - List _monthRange, _startDayRange, _endDayRange; - List _startSelectedIndex; - List _endSelectedIndex; - DateTime _startSelectedDateTime; - DateTime _endSelectedDateTime; + late List _monthRange, _startDayRange, _endDayRange; + late List _startSelectedIndex; + late List _endSelectedIndex; + late DateTime _startSelectedDateTime; + late DateTime _endSelectedDateTime; bool _isFirstScroll = false; bool _isSecondScroll = false; - _DatePickerWidgetState(DateTime minDateTime, DateTime maxDateTime, - DateTime initialStartDateTime, DateTime initialEndDateTime) { + _DatePickerWidgetState(DateTime? minDateTime, DateTime? maxDateTime, + DateTime? initialStartDateTime, DateTime? initialEndDateTime) { // handle current selected year、month、day _initData( initialStartDateTime, initialEndDateTime, minDateTime, maxDateTime); } - void _initData(DateTime initialStartDateTime, DateTime initialEndDateTime, - DateTime minDateTime, DateTime maxDateTime) { + void _initData(DateTime? initialStartDateTime, DateTime? initialEndDateTime, + DateTime? minDateTime, DateTime? maxDateTime) { DateTime initStartDateTime = initialStartDateTime ?? DateTime.now(); DateTime initEndDateTime = initialEndDateTime ?? DateTime.now(); @@ -113,8 +115,8 @@ class _DatePickerWidgetState extends State { this._currEndDay = initEndDateTime.day; // handle DateTime range - this._minDateTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - this._maxDateTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + this._minDateTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + this._maxDateTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); // limit the range of year this._currStartYear = @@ -172,7 +174,7 @@ class _DatePickerWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -180,7 +182,7 @@ class _DatePickerWidgetState extends State { /// pressed confirm widget void _onPressedConfirm() { if (widget.onConfirm != null) { - widget.onConfirm(_startSelectedDateTime, _endSelectedDateTime, + widget.onConfirm!(_startSelectedDateTime, _endSelectedDateTime, _startSelectedIndex, _endSelectedIndex); } Navigator.pop(context); @@ -201,12 +203,12 @@ class _DatePickerWidgetState extends State { _isSecondScroll = false; } - List pickers = List(); + List pickers = []; pickers.add(Expanded( flex: 6, child: Container( - height: widget.themeData.pickerHeight, - color: widget.themeData.backgroundColor, + height: widget.themeData!.pickerHeight, + color: widget.themeData!.backgroundColor, child: BrnDateRangeSideWidget( key: firstGlobalKey, dateFormat: widget.dateFormat, @@ -230,8 +232,8 @@ class _DatePickerWidgetState extends State { pickers.add(Expanded( flex: 6, child: Container( - height: widget.themeData.pickerHeight, - color: widget.themeData.backgroundColor, + height: widget.themeData!.pickerHeight, + color: widget.themeData!.backgroundColor, child: BrnDateRangeSideWidget( key: secondGlobalKey, dateFormat: widget.dateFormat, @@ -262,22 +264,22 @@ class _DatePickerWidgetState extends State { return Expanded( flex: 1, child: Container( - height: widget.themeData.pickerHeight, + height: widget.themeData!.pickerHeight, decoration: BoxDecoration( border: Border(left: BorderSide.none, right: BorderSide.none), - color: widget.themeData.backgroundColor), + color: widget.themeData!.backgroundColor), child: BrnPicker.builder( - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, - itemExtent: widget.themeData.itemHeight, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, + itemExtent: widget.themeData!.itemHeight, childCount: 1, itemBuilder: (context, index) { return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( "至", - style: widget.themeData.itemTextStyle.generateTextStyle(), + style: widget.themeData!.itemTextStyle.generateTextStyle(), ), ); }, diff --git a/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_side_widget.dart b/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_side_widget.dart index 47421443..79112dde 100755 --- a/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_side_widget.dart +++ b/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_side_widget.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -12,46 +14,49 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class BrnTimeRangeSideWidget extends StatefulWidget { /// 可选最小时间 - final DateTime minDateTime; + final DateTime? minDateTime; /// 可选最大时间 - final DateTime maxDateTime; + final DateTime? maxDateTime; /// 初始开始选中时间 - final DateTime initialStartDateTime; + final DateTime? initialStartDateTime; /// 时间展示格式 - final String dateFormat; + final String? dateFormat; final DateTimePickerLocale locale; /// 时间选择变化时回调 - final DateRangeSideValueCallback onChange; + final DateRangeSideValueCallback? onChange; /// 分钟的展示间隔 - final int minuteDivider; + final int? minuteDivider; /// 当前默认选择的时间变化时对外部回调,外部监听该事件同步修改默认初始选中的时间 - final DateRangeSideValueCallback onInitSelectChange; + final DateRangeSideValueCallback? onInitSelectChange; /// 主题定制 - BrnPickerConfig themeData; + BrnPickerConfig? themeData; BrnTimeRangeSideWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.initialStartDateTime, - this.dateFormat: DATETIME_RANGE_PICKER_TIME_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, + this.dateFormat: datetimeRangePickerTimeFormat, + this.locale: datetimePickerLocaleDefault, this.minuteDivider = 1, this.onChange, this.onInitSelectChange, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) <= 0); this.themeData ??= BrnPickerConfig(); - this.themeData.initThemeConfigPersonal(); + this.themeData = BrnThemeConfigurator.instance + .getConfig(configId: this.themeData!.configId) + .pickerConfig + .merge(this.themeData); } @override @@ -66,38 +71,38 @@ class BrnTimeRangeSideWidget extends StatefulWidget { class _TimePickerWidgetState extends State { final int _defaultMinuteDivider = 1; - DateTime _minTime, _maxTime; - int _currStartHour, _currStartMinute; - int _minuteDivider; - List _hourRange, _minuteRange; - FixedExtentScrollController _startHourScrollCtrl, _startMinuteScrollCtrl; + late DateTime _minTime, _maxTime; + late int _currStartHour, _currStartMinute; + late int _minuteDivider; + late List _hourRange, _minuteRange; + late FixedExtentScrollController _startHourScrollCtrl, _startMinuteScrollCtrl; - Map _startScrollCtrlMap; - Map> _valueRangeMap; + late Map _startScrollCtrlMap; + late Map> _valueRangeMap; bool _isChangeTimeRange = false; bool _scrolledNotMinute = false; - DateRangeSideValueCallback _onInitSelectChange; + DateRangeSideValueCallback? _onInitSelectChange; _TimePickerWidgetState( - DateTime minTime, - DateTime maxTime, - DateTime initStartTime, - int minuteDivider, - DateRangeSideValueCallback onInitSelectChange) { + DateTime? minTime, + DateTime? maxTime, + DateTime? initStartTime, + int? minuteDivider, + DateRangeSideValueCallback? onInitSelectChange) { _onInitSelectChange = onInitSelectChange; _initData(minTime, maxTime, initStartTime, minuteDivider); } - void _initData(DateTime minTime, DateTime maxTime, DateTime initStartTime, - int minuteDivider) { + void _initData(DateTime? minTime, DateTime? maxTime, DateTime? initStartTime, + int? minuteDivider) { if (minTime == null) { - minTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); + minTime = DateTime.parse(datePickerMinDatetime); } if (maxTime == null) { - maxTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + maxTime = DateTime.parse(datePickerMaxDatetime); } this._minTime = minTime; this._maxTime = maxTime; @@ -113,20 +118,18 @@ class _TimePickerWidgetState extends State { this._minuteDivider = minuteDivider; } - // limit the range of hour + this._currStartHour = initStartTime.hour; this._hourRange = _calcHourRange(); + this._currStartHour = + min(max(_hourRange.first, _currStartHour), _hourRange.last); + + this._currStartMinute = initStartTime.minute; this._minuteRange = _calcMinuteRange(); + this._currStartMinute = + min(max(_minuteRange.first, _currStartMinute), _minuteRange.last); + _currStartMinute -= _currStartMinute % _minuteDivider; - if (_currStartHour == null || _currStartMinute == null) { - this._currStartHour = initStartTime.hour; - this._currStartHour = - min(max(_hourRange.first, _currStartHour), _hourRange.last); - this._currStartMinute = initStartTime.minute; - this._currStartMinute = - min(max(_minuteRange.first, _currStartMinute), _minuteRange.last); - _currStartMinute -= _currStartMinute % _minuteDivider; - } _onInitSelectedChange(); // create scroll controller _startHourScrollCtrl = FixedExtentScrollController( @@ -146,7 +149,7 @@ class _TimePickerWidgetState extends State { _initData(_minTime, _maxTime, widget.initialStartDateTime, _minuteDivider); return GestureDetector( child: Container( - color: widget.themeData.backgroundColor, + color: widget.themeData!.backgroundColor, child: _renderPickerView(context)), ); } @@ -162,7 +165,7 @@ class _TimePickerWidgetState extends State { DateTime now = DateTime.now(); DateTime startDateTime = DateTime( now.year, now.month, now.day, _currStartHour, _currStartMinute); - _onInitSelectChange(startDateTime, _calcStartSelectIndexList()); + _onInitSelectChange!(startDateTime, _calcStartSelectIndexList()); } } @@ -172,13 +175,13 @@ class _TimePickerWidgetState extends State { DateTime now = DateTime.now(); DateTime startDateTime = DateTime( now.year, now.month, now.day, _currStartHour, _currStartMinute); - widget.onChange(startDateTime, _calcStartSelectIndexList()); + widget.onChange!(startDateTime, _calcStartSelectIndexList()); } } /// find start scroll controller by specified format - FixedExtentScrollController _findScrollCtrl(String format) { - FixedExtentScrollController scrollCtrl; + FixedExtentScrollController? _findScrollCtrl(String format) { + FixedExtentScrollController? scrollCtrl; _startScrollCtrlMap.forEach((key, value) { if (format.contains(key)) { scrollCtrl = value; @@ -188,8 +191,8 @@ class _TimePickerWidgetState extends State { } /// find item value range by specified format - List _findPickerItemRange(String format) { - List valueRange; + List? _findPickerItemRange(String format) { + List? valueRange; _valueRangeMap.forEach((key, value) { if (format.contains(key)) { valueRange = value; @@ -200,11 +203,11 @@ class _TimePickerWidgetState extends State { /// render the picker widget of year、month and day Widget _renderDatePickerWidget() { - List pickers = List(); + List pickers = []; List formatArr = DateTimeFormatter.splitDateFormat(widget.dateFormat); formatArr.forEach((format) { - List valueRange = _findPickerItemRange(format); + List? valueRange = _findPickerItemRange(format); Widget pickerColumn = _renderDatePickerColumnComponent( scrollCtrl: _findScrollCtrl(format), @@ -225,10 +228,10 @@ class _TimePickerWidgetState extends State { } Widget _renderDatePickerColumnComponent({ - @required FixedExtentScrollController scrollCtrl, - @required List valueRange, - @required String format, - @required ValueChanged valueChanged, + required FixedExtentScrollController? scrollCtrl, + required List? valueRange, + required String format, + required ValueChanged valueChanged, }) { var globalKey; if (_scrolledNotMinute && format.contains("m")) { @@ -239,14 +242,14 @@ class _TimePickerWidgetState extends State { return Expanded( flex: 1, child: Container( - height: widget.themeData.pickerHeight, - color: widget.themeData.backgroundColor, + height: widget.themeData!.pickerHeight, + color: widget.themeData!.backgroundColor, child: BrnPicker.builder( key: globalKey, - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, scrollController: scrollCtrl, - itemExtent: widget.themeData.itemHeight, + itemExtent: widget.themeData!.itemHeight, onSelectedItemChanged: (int index) { if (!format.contains("m")) { _scrolledNotMinute = true; @@ -255,9 +258,9 @@ class _TimePickerWidgetState extends State { }, childCount: format.contains('m') ? _calculateMinuteChildCount(valueRange, _minuteDivider) - : valueRange.last - valueRange.first + 1, + : valueRange!.last - valueRange.first + 1, itemBuilder: (context, index) { - int value = valueRange.first + index; + int value = valueRange!.first + index; if (format.contains('m')) { value = valueRange.first + _minuteDivider * index; @@ -270,24 +273,24 @@ class _TimePickerWidgetState extends State { ); } - _calculateMinuteChildCount(List valueRange, int divider) { + _calculateMinuteChildCount(List? valueRange, int? divider) { if (divider == 0 || divider == 1) { debugPrint("Cant devide by 0"); - return (valueRange.last - valueRange.first + 1); + return (valueRange!.last - valueRange.first + 1); } - return ((valueRange.last - valueRange.first) ~/ divider) + 1; + return ((valueRange!.last - valueRange.first) ~/ divider!) + 1; } Widget _renderDatePickerItemComponent( int index, bool isMinuteColumn, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); + TextStyle textStyle = widget.themeData!.itemTextStyle.generateTextStyle(); if ((!isMinuteColumn && (index == _calcStartSelectIndexList()[0])) || ((isMinuteColumn && (index == _calcStartSelectIndexList()[1])))) { - textStyle = widget.themeData.itemTextSelectedStyle.generateTextStyle(); + textStyle = widget.themeData!.itemTextSelectedStyle.generateTextStyle(); } return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( DateTimeFormatter.formatDateTime(value, format, widget.locale), diff --git a/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_widget.dart b/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_widget.dart index 0b521810..241b48c9 100755 --- a/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_widget.dart +++ b/lib/src/components/picker/time_picker/date_range_picker/brn_time_range_widget.dart @@ -1,3 +1,5 @@ + + import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -14,32 +16,32 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class BrnTimeRangeWidget extends StatefulWidget { /// 可选最小时间 - final DateTime minDateTime; + final DateTime? minDateTime; /// 可选最大时间 - final DateTime maxDateTime; + final DateTime? maxDateTime; /// 初始开始选中时间 - final DateTime initialStartDateTime; + final DateTime? initialStartDateTime; /// 初始结束选中时间 - final DateTime initialEndDateTime; + final DateTime? initialEndDateTime; /// 是否限制 Picker 选择的时间范围(开始时间≤结束时间) final isLimitTimeRange; /// 时间格式 - final String dateFormat; + final String? dateFormat; final DateTimePickerLocale locale; /// cancel 回调 - final DateVoidCallback onCancel; + final DateVoidCallback? onCancel; /// 选中时间变化时的回调,返回选中的开始、结束时间 - final DateRangeValueCallback onChange; + final DateRangeValueCallback? onChange; /// 确定回调,返回选中的开始、结束时间 - final DateRangeValueCallback onConfirm; + final DateRangeValueCallback? onConfirm; /// Picker title 相关内容配置 final BrnPickerTitleConfig pickerTitleConfig; @@ -48,20 +50,20 @@ class BrnTimeRangeWidget extends StatefulWidget { final int minuteDivider; /// Picker 主题配置 - BrnPickerConfig themeData; + BrnPickerConfig? themeData; /// 内部变量,记录左右两侧是否触发了滚动 bool _isFirstScroll = false, _isSecondScroll = false; BrnTimeRangeWidget({ - Key key, + Key? key, this.minDateTime, this.maxDateTime, this.isLimitTimeRange = true, this.initialStartDateTime, this.initialEndDateTime, - this.dateFormat: DATETIME_RANGE_PICKER_TIME_FORMAT, - this.locale: DATETIME_PICKER_LOCALE_DEFAULT, + this.dateFormat: datetimeRangePickerTimeFormat, + this.locale: datetimePickerLocaleDefault, this.pickerTitleConfig: BrnPickerTitleConfig.Default, this.minuteDivider = 1, this.onCancel, @@ -69,12 +71,12 @@ class BrnTimeRangeWidget extends StatefulWidget { this.onConfirm, this.themeData, }) : super(key: key) { - DateTime minTime = minDateTime ?? DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = maxDateTime ?? DateTime.parse(DATE_PICKER_MAX_DATETIME); + DateTime minTime = minDateTime ?? DateTime.parse(datePickerMinDatetime); + DateTime maxTime = maxDateTime ?? DateTime.parse(datePickerMaxDatetime); assert(minTime.compareTo(maxTime) < 0); this.themeData ??= BrnPickerConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .pickerConfig .merge(this.themeData); } @@ -91,28 +93,28 @@ class BrnTimeRangeWidget extends StatefulWidget { class _TimePickerWidgetState extends State { final int _defaultMinuteDivider = 1; - int _minuteDivider; - DateTime _minTime, _maxTime; - int _currStartHour, _currStartMinute; - int _currEndHour, _currEndMinute; - List _hourRange, _minuteRange; - List _startSelectedIndex; - List _endSelectedIndex; - DateTime _startSelectedDateTime; - DateTime _endSelectedDateTime; - - _TimePickerWidgetState(DateTime minTime, DateTime maxTime, - DateTime initStartTime, DateTime initEndTime, int minuteDivider) { + late int _minuteDivider; + late DateTime _minTime, _maxTime; + late int _currStartHour, _currStartMinute; + late int _currEndHour, _currEndMinute; + late List _hourRange, _minuteRange; + late List _startSelectedIndex; + late List _endSelectedIndex; + late DateTime _startSelectedDateTime; + late DateTime _endSelectedDateTime; + + _TimePickerWidgetState(DateTime? minTime, DateTime? maxTime, + DateTime? initStartTime, DateTime? initEndTime, int minuteDivider) { _initData(minTime, maxTime, initStartTime, initEndTime, minuteDivider); } - void _initData(DateTime minTime, DateTime maxTime, DateTime initStartTime, - DateTime initEndTime, int minuteDivider) { + void _initData(DateTime? minTime, DateTime? maxTime, DateTime? initStartTime, + DateTime? initEndTime, int? minuteDivider) { if (minTime == null) { - minTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); + minTime = DateTime.parse(datePickerMinDatetime); } if (maxTime == null) { - maxTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + maxTime = DateTime.parse(datePickerMaxDatetime); } DateTime now = DateTime.now(); this._minTime = DateTime(now.year, now.month, now.day, minTime.hour, @@ -137,24 +139,20 @@ class _TimePickerWidgetState extends State { } this._currStartHour = initStartTime.hour; - this._currStartMinute = initStartTime.minute; - - this._currEndHour = initEndTime.hour; - this._currEndMinute = initEndTime.minute; - - // limit the range of hour this._hourRange = _calcHourRange(); - this._minuteRange = _calcMinuteRange(); - this._currStartHour = min(max(_hourRange.first, _currStartHour), _hourRange.last); - this._currEndHour = min(_currEndHour, _hourRange.last); - // limit the range of minute + this._currStartMinute = initStartTime.minute; + this._minuteRange = _calcMinuteRange(); this._currStartMinute = min(max(_minuteRange.first, _currStartMinute), _minuteRange.last); _currStartMinute -= _currStartMinute % _minuteDivider; + this._currEndHour = initEndTime.hour; + this._currEndHour = min(_currEndHour, _hourRange.last); + + this._currEndMinute = initEndTime.minute; this._currEndMinute = min(_currEndMinute, _minuteRange.last); _currEndMinute -= _currEndMinute % _minuteDivider; @@ -198,7 +196,7 @@ class _TimePickerWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -206,7 +204,7 @@ class _TimePickerWidgetState extends State { /// pressed confirm widget void _onPressedConfirm() { if (widget.onConfirm != null) { - widget.onConfirm(_startSelectedDateTime, _endSelectedDateTime, + widget.onConfirm!(_startSelectedDateTime, _endSelectedDateTime, _startSelectedIndex, _endSelectedIndex); } Navigator.pop(context); @@ -227,12 +225,12 @@ class _TimePickerWidgetState extends State { widget._isSecondScroll = false; } - List pickers = List(); + List pickers = []; pickers.add(Expanded( flex: 6, child: Container( - height: widget.themeData.pickerHeight, - color: widget.themeData.backgroundColor, + height: widget.themeData!.pickerHeight, + color: widget.themeData!.backgroundColor, child: BrnTimeRangeSideWidget( key: firstGlobalKey, dateFormat: widget.dateFormat, @@ -258,8 +256,8 @@ class _TimePickerWidgetState extends State { pickers.add(Expanded( flex: 6, child: Container( - height: widget.themeData.pickerHeight, - color: widget.themeData.backgroundColor, + height: widget.themeData!.pickerHeight, + color: widget.themeData!.backgroundColor, child: BrnTimeRangeSideWidget( key: secondGlobalKey, dateFormat: widget.dateFormat, @@ -334,22 +332,22 @@ class _TimePickerWidgetState extends State { return Expanded( flex: 1, child: Container( - height: widget.themeData.pickerHeight, + height: widget.themeData!.pickerHeight, decoration: BoxDecoration( border: Border(left: BorderSide.none, right: BorderSide.none), - color: widget.themeData.backgroundColor), + color: widget.themeData!.backgroundColor), child: BrnPicker.builder( - backgroundColor: widget.themeData.backgroundColor, - lineColor: widget.themeData.dividerColor, - itemExtent: widget.themeData.itemHeight, + backgroundColor: widget.themeData!.backgroundColor, + lineColor: widget.themeData!.dividerColor, + itemExtent: widget.themeData!.itemHeight, childCount: 1, itemBuilder: (context, index) { return Container( - height: widget.themeData.itemHeight, + height: widget.themeData!.itemHeight, alignment: Alignment.center, child: Text( "至", - style: widget.themeData.itemTextStyle ?? PICKER_ITEM_TEXT_STYLE, + style: widget.themeData!.itemTextStyle.generateTextStyle(), ), ); }, diff --git a/lib/src/components/popup/brn_measure_size.dart b/lib/src/components/popup/brn_measure_size.dart index 93bdc51c..d2e08eaf 100644 --- a/lib/src/components/popup/brn_measure_size.dart +++ b/lib/src/components/popup/brn_measure_size.dart @@ -5,7 +5,7 @@ typedef void OnWidgetSizeChange(Size size); /// 描述: 计算 Widget 宽高的工具类。 class MeasureSizeRenderObject extends RenderProxyBox { - Size oldSize; + Size? oldSize; final OnWidgetSizeChange onChange; MeasureSizeRenderObject(this.onChange); @@ -14,13 +14,18 @@ class MeasureSizeRenderObject extends RenderProxyBox { void performLayout() { super.performLayout(); - Size newSize = child.size; + Size newSize = Size.zero; + if (child != null) { + newSize = child!.size; + } if (oldSize == newSize) return; oldSize = newSize; - WidgetsBinding.instance.addPostFrameCallback((_) { - onChange(newSize); - }); + if (WidgetsBinding.instance != null) { + WidgetsBinding.instance!.addPostFrameCallback((_) { + onChange(newSize); + }); + } } } @@ -28,11 +33,10 @@ class MeasureSize extends SingleChildRenderObjectWidget { final OnWidgetSizeChange onChange; const MeasureSize({ - Key key, - @required this.onChange, - @required Widget child, + Key? key, + required this.onChange, + required Widget child, }) : super(key: key, child: child); - @override RenderObject createRenderObject(BuildContext context) { return MeasureSizeRenderObject(onChange); diff --git a/lib/src/components/popup/brn_overlay_window.dart b/lib/src/components/popup/brn_overlay_window.dart index 6469dbb9..6ba24fe1 100644 --- a/lib/src/components/popup/brn_overlay_window.dart +++ b/lib/src/components/popup/brn_overlay_window.dart @@ -4,7 +4,6 @@ import 'dart:ui'; import 'package:bruno/src/components/popup/brn_measure_size.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; /// popWindow位于targetView的方向 enum BrnOverlayPopDirection { none, top, bottom, left, right } @@ -14,7 +13,7 @@ class BrnOverlayWindow extends StatefulWidget { final BuildContext context; /// 锚点 Widget 的 key,用于 OverlayWindow 的定位 - final Key targetKey; + final GlobalKey targetKey; /// OverlayWindow 相对于 key 的展示位置, 默认 bottom final BrnOverlayPopDirection popDirection; @@ -23,10 +22,10 @@ class BrnOverlayWindow extends StatefulWidget { final Widget content; const BrnOverlayWindow({ - this.context, - this.targetKey, + required this.context, + required this.targetKey, this.popDirection = BrnOverlayPopDirection.bottom, - this.content, + this.content = const SizedBox.shrink(), }); @override @@ -39,27 +38,27 @@ class BrnOverlayWindow extends StatefulWidget { /// [targetKey] 锚点 Widget 的 key,用于 OverlayWindow 的定位 /// [popDirection] OverlayWindow 相对于 key 的展示位置, 默认 bottom /// [content] 要展示的内容 - /// [autoDismissOnTouchOutSide] 点击 OverlayWindow 外部是否自动消失 + /// [autoDismissOnTouchOutSide] 点击 OverlayWindow 外部是否自动消失,默认为 true /// [onDismiss] OverlayWindow 消失回调 - static BrnOverlayController showOverlayWindow( - BuildContext context, Key targetKey, - {Widget content, - BrnOverlayPopDirection popDirection, - bool autoDismissOnTouchOutSide, - Function onDismiss}) { + static BrnOverlayController? showOverlayWindow( + BuildContext context, GlobalKey? targetKey, + {Widget? content, + BrnOverlayPopDirection popDirection = BrnOverlayPopDirection.bottom, + bool autoDismissOnTouchOutSide = true, + Function? onDismiss}) { assert(content != null); assert(targetKey != null); assert(content != null); if (content == null || targetKey == null) return null; - BrnOverlayController overlayController; + BrnOverlayController? overlayController; OverlayEntry entry = OverlayEntry(builder: (context) { return GestureDetector( - behavior: (autoDismissOnTouchOutSide ?? true) + behavior: (autoDismissOnTouchOutSide) ? HitTestBehavior.opaque : HitTestBehavior.deferToChild, - onTap: (autoDismissOnTouchOutSide ?? true) + onTap: (autoDismissOnTouchOutSide) ? () { overlayController?.removeOverlay(); if (onDismiss != null) { @@ -82,13 +81,16 @@ class BrnOverlayWindow extends StatefulWidget { class _BrnOverlayWindowState extends State { /// targetView的位置 - Rect _showRect; + Rect? _showRect; /// 屏幕的尺寸 - Size _screenSize; + late Size _screenSize; /// overlay 在targetView 四周的偏移位置 - double _left, _right, _top, _bottom; + double _left = 0; + double _right = 0; + double _top = 0; + double _bottom = 0; /// targetView 的 Size Size _targetViewSize = Size.zero; @@ -97,11 +99,14 @@ class _BrnOverlayWindowState extends State { Widget build(BuildContext context) { this._showRect = _getWidgetGlobalRect(widget.targetKey); this._screenSize = window.physicalSize / window.devicePixelRatio; - _calculateOffset(); - return _buildContent(); + if (this._showRect == null) { + return const SizedBox.shrink(); + } + _calculateOffset(this._showRect!); + return _buildContent(this._showRect!); } - Widget _buildContent() { + Widget _buildContent(Rect showRect) { var contentPart = Material( color: Colors.transparent, child: MeasureSize( @@ -115,14 +120,14 @@ class _BrnOverlayWindowState extends State { Widget realContent; double marginTop = - _showRect.top + (_showRect.height - _targetViewSize.height) / 2; + showRect.top + (showRect.height - _targetViewSize.height) / 2; if (_screenSize.height - marginTop < _targetViewSize.height) { marginTop = max(0, _screenSize.height - _targetViewSize.height); } marginTop = max(0, marginTop); double marginLeft = - _showRect.left + (_showRect.width - _targetViewSize.width) / 2; + showRect.left + (showRect.width - _targetViewSize.width) / 2; if (_screenSize.width - marginLeft < _targetViewSize.width) { marginLeft = max(0, _screenSize.width - _targetViewSize.width); } @@ -200,36 +205,40 @@ class _BrnOverlayWindowState extends State { /// /// 获取targetView的位置 /// - Rect _getWidgetGlobalRect(GlobalKey key) { - if (key == null) { - return null; + Rect? _getWidgetGlobalRect(GlobalKey key) { + BuildContext? ctx = key.currentContext; + RenderObject? obj; + if (ctx != null) { + obj = ctx.findRenderObject(); + } + if (obj != null && obj is RenderBox) { + RenderBox renderBox = obj; + var offset = renderBox.localToGlobal(Offset.zero); + return Rect.fromLTWH( + offset.dx, offset.dy, renderBox.size.width, renderBox.size.height); } - RenderBox renderBox = key.currentContext.findRenderObject(); - var offset = renderBox.localToGlobal(Offset.zero); - return Rect.fromLTWH( - offset.dx, offset.dy, renderBox.size.width, renderBox.size.height); + return null; } /// /// 计算popUpWindow显示的位置 /// - void _calculateOffset() { - _right = _left = _top = _bottom = 0; + void _calculateOffset(Rect showRect) { if (widget.popDirection == BrnOverlayPopDirection.left) { - _left = _showRect.left; + _left = showRect.left; } else if (widget.popDirection == BrnOverlayPopDirection.right) { - _right = _showRect.right; + _right = showRect.right; } else if (widget.popDirection == BrnOverlayPopDirection.bottom) { - _bottom = _showRect.bottom; + _bottom = showRect.bottom; } else if (widget.popDirection == BrnOverlayPopDirection.top) { // 在targetView上方 - _top = _showRect.top; + _top = showRect.top; } } } class BrnOverlayController { - OverlayEntry _entry; + OverlayEntry? _entry; BuildContext context; bool _isOverlayShowing = false; @@ -239,8 +248,10 @@ class BrnOverlayController { BrnOverlayController._(this.context, this._entry); showOverlay() { - Overlay.of(context).insert(_entry); - _isOverlayShowing = true; + if (_entry != null) { + Overlay.of(context)?.insert(_entry!); + _isOverlayShowing = true; + } } void removeOverlay() { diff --git a/lib/src/components/popup/brn_popup_window.dart b/lib/src/components/popup/brn_popup_window.dart index 640fe796..738be500 100644 --- a/lib/src/components/popup/brn_popup_window.dart +++ b/lib/src/components/popup/brn_popup_window.dart @@ -6,7 +6,6 @@ import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_text_util.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; /// popup window 位于 targetView 的方向 enum BrnPopupDirection { @@ -19,99 +18,120 @@ enum BrnPopupDirection { /// 通用 Popup Window 提示,带三角号 class BrnPopupWindow extends StatefulWidget { - /// 依附的组件的Context + /// 依附的组件的 Context final BuildContext context; - /// 箭头的高度 + /// 箭头的高度,默认 6 final double arrowHeight; /// 要显示的文本 - final String text; + final String? text; - /// 依附的组件和BrnPopUpWindow组件共同持有的GlobalKey + /// 依附的组件和 BrnPopUpWindow 组件共同持有的 GlobalKey final GlobalKey popKey; /// 要显示文本的样式 - final TextStyle textStyle; + final TextStyle? textStyle; - /// popUpWindow的背景颜色 - final Color backgroundColor; + /// popUpWindow 的背景颜色,使用 [showPopWindow] 方法时,默认值为 Color(0xFF1A1A1A) + final Color? backgroundColor; - /// 边框颜色 - final Color borderColor; + /// 边框颜色,[showPopWindow] 方法时,默认值为 Colors.transparent + final Color? borderColor; - /// 是否有关闭图标 + /// 是否有关闭图标,默认为 false,不显示 final bool isShowCloseIcon; - /// 距离targetView偏移量 + /// 距离 targetView 偏移量,默认为 0 final double offset; - /// popUpWindow位于targetView的方向 + /// popUpWindow 位于 targetView 的方向,默认为 [BrnPopupDirection.bottom] final BrnPopupDirection popDirection; - /// 自定义widget - final Widget widget; + /// 自定义 widget + final Widget? widget; - /// 容器内边距 + /// 容器内边距,默认为 EdgeInsets.only(left: 18, top: 14, right: 18, bottom: 14) final EdgeInsets paddingInsets; - /// 容器圆角 + /// 容器圆角,默认为 4 final double borderRadius; - /// 是否能多行显示 默认false:单行显示 + /// 是否能多行显,默认 false,单行显示 final bool canWrap; - /// 默认距离TargetView边线的距离,默认:20 + /// 距离 targetView 边线的距离,默认 20 final double spaceMargin; - /// 箭头偏移量 - final double arrowOffset; + /// 箭头图标水平方向的绝对偏移量,为 null 时则自动计算 + final double? arrowOffset; - /// popUpWindow消失回调 - final VoidCallback onDismiss; + /// popUpWindow 消失回调,此回调会在 pop 之后执行 + final VoidCallback? onDismiss; - /// popWindow距离底部的距离小于此值的时候, - /// 自动将popWindow在targetView上面弹出 + /// popWindow 距离底部的距离小于此值的时候, + /// 自动将 popWindow 在 targetView 上面弹出 final double turnOverFromBottom; - const BrnPopupWindow(this.context, - {this.text, - this.popKey, - this.arrowHeight, + BrnPopupWindow(this.context, + {Key? key, + this.text, + required this.popKey, + this.arrowHeight = 6.0, this.textStyle, this.backgroundColor, - this.isShowCloseIcon, - this.offset, - this.popDirection, + this.isShowCloseIcon = false, + this.offset = 0, + this.popDirection = BrnPopupDirection.bottom, this.widget, - this.paddingInsets, - this.borderRadius, + this.paddingInsets = + const EdgeInsets.only(left: 18, top: 14, right: 18, bottom: 14), + this.borderRadius = 4, this.borderColor, this.canWrap = false, - this.spaceMargin, + this.spaceMargin = 20, this.arrowOffset, this.onDismiss, - this.turnOverFromBottom = 50.0}); + this.turnOverFromBottom = 50.0}) + : super(key: key); - // 显示popUpWindow - static void showPopWindow(context, String text, GlobalKey popKey, + /// 显示 popUpWindow + /// [text] 显示的文本内容 + /// [popKey] 依附的组件和 BrnPopUpWindow 组件共同持有的 GlobalKey + /// [popDirection] 箭头的方向 + /// [arrowHeight] 箭头的高度,默认 6 + /// [textStyle] 文本样式 + /// [backgroundColor] popUpWindow 的背景颜色,默认 Color(0xFF1A1A1A) + /// [hasCloseIcon] 是否显示关闭图标,默认为 false,不显示 + /// [offset] 距离 targetView 垂直方向的偏移量 + /// [widget] 自定义 pop 视图 + /// [paddingInsets] 容器内边距,默认为 EdgeInsets.only(left: 18, top: 14, right: 18, bottom: 14) + /// [borderRadius] 容器圆角,默认为 4 + /// [borderColor] 边框颜色,默认为 Colors.transparent + /// [borderWidth] 边框宽度,默认为 1 + /// [canWrap] 是否能多行显,默认 false,单行显示 + /// [spaceMargin] 距离 targetView 边线的距离,默认 20 + /// [arrowOffset] 箭头图标水平方向的绝对偏移量,为 null 时则自动计算 + /// [dismissCallback] popUpWindow 消失回调,此回调会在 pop 之后执行 + /// [turnOverFromBottom] popWindow 小于此值的时候,自动将 popWindow 在 targetView 上面弹出,默认 50 + static void showPopWindow(context, String? text, GlobalKey popKey, {BrnPopupDirection popDirection = BrnPopupDirection.bottom, double arrowHeight = 6.0, - TextStyle textStyle = + TextStyle? textStyle = const TextStyle(fontSize: 16, color: Color(0xFFFFFFFF)), - Color backgroundColor = const Color(0xFF1A1A1A), + Color? backgroundColor = const Color(0xFF1A1A1A), bool hasCloseIcon = false, double offset = 0, - Widget widget, + Widget? widget, EdgeInsets paddingInsets = const EdgeInsets.only(left: 18, top: 14, right: 18, bottom: 14), double borderRadius = 8, - Color borderColor = Colors.transparent, + Color? borderColor = Colors.transparent, double borderWidth = 1, bool canWrap = false, double spaceMargin = 20, - double arrowOffset, - VoidCallback dismissCallback, + double? arrowOffset, + VoidCallback? dismissCallback, double turnOverFromBottom = 50.0}) { Navigator.push( context, @@ -144,10 +164,10 @@ class BrnPopupWindow extends StatefulWidget { class _BrnPopupWindowState extends State { /// targetView的位置 - Rect _showRect; + Rect? _showRect; /// 屏幕的尺寸 - Size _screenSize; + late Size _screenSize; /// 箭头和左右侧边线间距 double _arrowSpacing = 18; @@ -156,65 +176,80 @@ class _BrnPopupWindowState extends State { bool _expandedRight = true; /// popUpWindow在中线两侧的具体位置 - double _left, _right, _top, _bottom; + double _left = 0; + double _right = 0; + double _top = 0; + double _bottom = 0; /// 箭头展示方向 - BrnPopupDirection _popDirection; + late BrnPopupDirection _popDirection; /// 去除透明度的边框色 - Color _borderColor; + late Color _borderColor; /// 去除透明度的背景颜色 - Color _backgroundColor; + late Color _backgroundColor; @override void initState() { super.initState(); this._showRect = _getWidgetGlobalRect(widget.popKey); this._screenSize = window.physicalSize / window.devicePixelRatio; - _borderColor = widget.borderColor.withAlpha(255); - _backgroundColor = widget.backgroundColor.withAlpha(255); + _borderColor = (widget.borderColor ?? Colors.transparent).withAlpha(255); + _backgroundColor = + (widget.backgroundColor ?? Colors.transparent).withAlpha(255); _popDirection = widget.popDirection; - _calculateOffset(); + if (this._showRect != null) { + _calculateOffset(this._showRect!); + } } // 获取targetView的位置 - Rect _getWidgetGlobalRect(GlobalKey key) { - if (key == null) { - return null; + Rect? _getWidgetGlobalRect(GlobalKey key) { + BuildContext? ctx = key.currentContext; + RenderObject? obj; + if (ctx != null) { + obj = ctx.findRenderObject(); } - RenderBox renderBox = key.currentContext.findRenderObject(); - var offset = renderBox.localToGlobal(Offset.zero); - return Rect.fromLTWH( - offset.dx, offset.dy, renderBox.size.width, renderBox.size.height); + if (obj != null && obj is RenderBox) { + RenderBox renderBox = obj; + var offset = renderBox.localToGlobal(Offset.zero); + return Rect.fromLTWH( + offset.dx, offset.dy, renderBox.size.width, renderBox.size.height); + } + return null; } // 计算popUpWindow显示的位置 - void _calculateOffset() { - if (_showRect.center.dx < _screenSize.width / 2) { + void _calculateOffset(Rect showRect) { + if (showRect.center.dx < _screenSize.width / 2) { // popUpWindow向右侧延伸 _expandedRight = true; - _left = _showRect.left + widget.spaceMargin; + _left = showRect.left; } else { // popUpWindow向左侧延伸 _expandedRight = false; - _right = _screenSize.width - _showRect.right + widget.spaceMargin; + _right = _screenSize.width - showRect.right + widget.spaceMargin; } if (_popDirection == BrnPopupDirection.bottom) { // 在targetView下方 - _top = _showRect.height + _showRect.top + widget.offset; + _top = showRect.height + showRect.top + widget.offset; if ((_screenSize.height - _top) < widget.turnOverFromBottom) { _popDirection = BrnPopupDirection.top; - _bottom = _screenSize.height - _showRect.top + widget.offset; + _bottom = _screenSize.height - showRect.top + widget.offset; } } else if (_popDirection == BrnPopupDirection.top) { // 在targetView上方 - _bottom = _screenSize.height - _showRect.top + widget.offset; + _bottom = _screenSize.height - showRect.top + widget.offset; } } @override Widget build(BuildContext context) { + if (this._showRect == null) { + Navigator.pop(context); + return Container(); + } return ExcludeSemantics( excluding: true, child: WillPopScope( @@ -223,7 +258,7 @@ class _BrnPopupWindowState extends State { onTap: () { Navigator.pop(context); if (widget.onDismiss != null) { - widget.onDismiss(); + widget.onDismiss!(); } }, child: Material( @@ -239,7 +274,7 @@ class _BrnPopupWindowState extends State { ), onWillPop: () { if (widget.onDismiss != null) { - widget.onDismiss(); + widget.onDismiss!(); } return Future.value(true); }), @@ -252,7 +287,7 @@ class _BrnPopupWindowState extends State { ? Positioned( left: widget.arrowOffset ?? _left + - (_showRect.width - _arrowSpacing) / 2 - + (_showRect!.width - _arrowSpacing) / 2 - widget.spaceMargin, top: _popDirection == BrnPopupDirection.bottom ? _top - widget.arrowHeight @@ -271,7 +306,7 @@ class _BrnPopupWindowState extends State { : Positioned( right: widget.arrowOffset ?? _right + - (_showRect.width - _arrowSpacing) / 2 - + (_showRect!.width - _arrowSpacing) / 2 - widget.spaceMargin, top: _popDirection == BrnPopupDirection.bottom ? _top - widget.arrowHeight @@ -303,7 +338,7 @@ class _BrnPopupWindowState extends State { decoration: BoxDecoration( color: _backgroundColor, border: Border.all(color: _borderColor, width: 0.5), - borderRadius: BorderRadius.circular(widget.borderRadius ?? 4)), + borderRadius: BorderRadius.circular(widget.borderRadius)), constraints: BoxConstraints( maxWidth: _expandedRight ? _screenSize.width - _left @@ -324,7 +359,7 @@ class _BrnPopupWindowState extends State { child: Padding( padding: EdgeInsets.only(left: 6), child: BrunoTools.getAssetImage( - BrnAsset.ICON_POPUP_CLOSE), + BrnAsset.iconPopupClose), )) : TextSpan(text: "") ])) @@ -334,7 +369,7 @@ class _BrnPopupWindowState extends State { Flexible( fit: FlexFit.loose, child: Text( - widget.text, + widget.text ?? '', maxLines: 1, overflow: TextOverflow.ellipsis, style: widget.textStyle, @@ -344,7 +379,7 @@ class _BrnPopupWindowState extends State { ? Padding( padding: EdgeInsets.only(left: 6), child: BrunoTools.getAssetImage( - BrnAsset.ICON_POPUP_CLOSE), + BrnAsset.iconPopupClose), ) : Text("") ], @@ -360,9 +395,9 @@ class _TrianglePainter extends CustomPainter { Color borderColor; _TrianglePainter({ - this.isDownArrow, - this.color, - this.borderColor, + required this.isDownArrow, + required this.color, + required this.borderColor, }); @override @@ -413,16 +448,16 @@ class BrnPopupRoute extends PopupRoute { final Duration _duration = Duration(milliseconds: 200); Widget child; - BrnPopupRoute({@required this.child}); + BrnPopupRoute({required this.child}); @override - Color get barrierColor => null; + Color? get barrierColor => null; @override bool get barrierDismissible => true; @override - String get barrierLabel => null; + String? get barrierLabel => null; @override Widget buildPage(BuildContext context, Animation animation, @@ -442,7 +477,7 @@ typedef BrnPopupListItemClick = Function(int index, String item); /// popup 用于构造自定义的 Item /// [index] Item 的索引 /// [item] Item 内容 -typedef BrnPopupListItemBuilder = Widget Function(int index, String item); +typedef BrnPopupListItemBuilder = Widget? Function(int index, String item); /// 基于 PopUpWindow 的 弹窗列表工具类 class BrnPopupListWindow { @@ -453,10 +488,10 @@ class BrnPopupListWindow { /// [itemBuilder] 自定义 item 构造方法 /// [onItemClick] item 点击回调 static void showButtonPanelPopList(context, GlobalKey popKey, - {List data, + {List? data, BrnPopupDirection popDirection = BrnPopupDirection.bottom, - BrnPopupListItemBuilder itemBuilder, - BrnPopupListItemClick onItemClick}) { + BrnPopupListItemBuilder? itemBuilder, + BrnPopupListItemClick? onItemClick}) { TextStyle textStyle = TextStyle( color: BrnThemeConfigurator.instance .getConfig() @@ -497,7 +532,7 @@ class BrnPopupListWindow { padding: EdgeInsets.only(top: 6, bottom: 6), child: Column( children: _getItems(context, minWidth, maxWidth, - itemBuilder, textStyle, data, onItemClick, null), + itemBuilder, textStyle, data!, onItemClick, null), ), ), ), @@ -517,18 +552,18 @@ class BrnPopupListWindow { /// [onItemClick] item 点击回调 /// [onDismiss] popUpWindow消失回调 static void showPopListWindow(context, GlobalKey popKey, - {List data, + {List? data, BrnPopupDirection popDirection = BrnPopupDirection.bottom, double offset = 0, - BrnPopupListItemClick onItemClick, - VoidCallback onDismiss}) { + BrnPopupListItemClick? onItemClick, + VoidCallback? onDismiss}) { double arrowHeight = 6.0; double borderRadius = 4; double spaceMargin = 0; double minWidth = 100; double maxWidth = 150; double maxHeight = 200; - double arrowOffset; + double? arrowOffset; Color borderColor = BrnThemeConfigurator.instance.getConfig().commonConfig.dividerColorBase; Color backgroundColor = Colors.white; @@ -565,7 +600,7 @@ class BrnPopupListWindow { padding: EdgeInsets.only(top: 6, bottom: 6), child: Column( children: _getItems(context, minWidth, maxWidth, null, - textStyle, data, onItemClick, onDismiss), + textStyle, data!, onItemClick, onDismiss), ), ), ), @@ -582,13 +617,12 @@ class BrnPopupListWindow { BuildContext context, double minWidth, double maxWidth, - BrnPopupListItemBuilder itemBuilder, + BrnPopupListItemBuilder? itemBuilder, TextStyle textStyle, List data, - BrnPopupListItemClick onItemClick, - VoidCallback onDismiss) { - double textMaxWidth = _getMaxWidth( - textStyle ?? TextStyle(fontSize: 16, color: Color(0xFFFFFFFF)), data); + BrnPopupListItemClick? onItemClick, + VoidCallback? onDismiss) { + double textMaxWidth = _getMaxWidth(textStyle, data); if (textMaxWidth + 52 < minWidth) { textMaxWidth = minWidth; } else if (textMaxWidth + 52 > maxWidth) { @@ -596,34 +630,32 @@ class BrnPopupListWindow { } else { textMaxWidth = textMaxWidth + 52; } - return data?.map((f) { - return GestureDetector( - onTap: () { - if (onItemClick != null) { - dynamic isIntercept = onItemClick(data.indexOf(f), f); - if ((isIntercept is bool) && isIntercept) return; - } - Navigator.pop(context); - if (onDismiss != null) { - onDismiss(); - } - }, - child: Container( - width: textMaxWidth, - alignment: Alignment.center, - color: Colors.transparent, - padding: - EdgeInsets.only(left: 26, right: 26, top: 6, bottom: 6), - child: _getTextWidget(itemBuilder, data, f, textStyle))); - })?.toList() ?? - List(); + return data.map((f) { + return GestureDetector( + onTap: () { + if (onItemClick != null) { + dynamic isIntercept = onItemClick(data.indexOf(f), f); + if ((isIntercept is bool) && isIntercept) return; + } + Navigator.pop(context); + if (onDismiss != null) { + onDismiss(); + } + }, + child: Container( + width: textMaxWidth, + alignment: Alignment.center, + color: Colors.transparent, + padding: EdgeInsets.only(left: 26, right: 26, top: 6, bottom: 6), + child: _getTextWidget(itemBuilder, data, f, textStyle))); + }).toList(); } /// 遍历数据,计算每个 Item 内容,返回所有 Item 可展示的最大宽度 static double _getMaxWidth(TextStyle textStyle, List data) { double maxWidth = 0; if (!BrunoTools.isEmpty(data)) { - Size maxWidthSize; + Size? maxWidthSize; for (String entity in data) { Size size = BrnTextUtil.textSize(entity, textStyle); if (maxWidthSize == null) { @@ -634,12 +666,14 @@ class BrnPopupListWindow { } } } - maxWidth = maxWidthSize.width; + if (maxWidthSize != null) { + maxWidth = maxWidthSize.width; + } } return maxWidth; } - static Widget _getTextWidget(BrnPopupListItemBuilder itemBuilder, + static Widget _getTextWidget(BrnPopupListItemBuilder? itemBuilder, List data, String text, TextStyle textStyle) { if (itemBuilder == null) { return _getDefaultText(text, textStyle); @@ -654,11 +688,7 @@ class BrnPopupListWindow { text, overflow: TextOverflow.ellipsis, maxLines: 1, - style: textStyle ?? - TextStyle( - fontSize: 16, - color: Color(0xFFFFFFFF), - ), + style: textStyle, ); } } diff --git a/lib/src/components/radio/brn_checkbox.dart b/lib/src/components/radio/brn_checkbox.dart index 73d3f7e5..80437ca6 100644 --- a/lib/src/components/radio/brn_checkbox.dart +++ b/lib/src/components/radio/brn_checkbox.dart @@ -21,10 +21,10 @@ class BrnCheckbox extends StatefulWidget { /// 选择按钮的padding /// 默认EdgeInsets.all(5) - final EdgeInsets iconPadding; + final EdgeInsets? iconPadding; /// 配合使用的控件,比如卡片或者text - final Widget child; + final Widget? child; /// 控件是否在选择按钮的右边, /// true时 控件在选择按钮右边 @@ -43,18 +43,18 @@ class BrnCheckbox extends StatefulWidget { /// 默认值HitTestBehavior.translucent控制widget.onRadioItemClick触发的点击范围 final HitTestBehavior behavior; - const BrnCheckbox( - {Key key, - @required this.radioIndex, - @required this.onValueChangedAtIndex, - this.disable = false, - this.isSelected = false, - this.iconPadding, - this.child, - this.childOnRight = true, - this.mainAxisAlignment = MainAxisAlignment.start, - this.mainAxisSize = MainAxisSize.min, - this.behavior = HitTestBehavior.translucent}); + const BrnCheckbox({ + Key? key, + required this.radioIndex, + required this.onValueChangedAtIndex, + this.disable = false, + this.isSelected = false, + this.iconPadding, + this.child, + this.childOnRight = true, + this.mainAxisAlignment = MainAxisAlignment.start, + this.mainAxisSize = MainAxisSize.min, + this.behavior = HitTestBehavior.translucent}); @override State createState() { @@ -63,7 +63,7 @@ class BrnCheckbox extends StatefulWidget { } class BrnCheckboxState extends State { - bool _isSelected; + late bool _isSelected; @override void initState() { @@ -82,12 +82,12 @@ class BrnCheckboxState extends State { mainAxisAlignment: widget.mainAxisAlignment, mainAxisSize: widget.mainAxisSize, selectedImage: BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_RADIO_MULTI_SELECTED), - unselectedImage: BrunoTools.getAssetImage(BrnAsset.ICON_RADIO_UNSELECTED), + BrnAsset.iconRadioMultiSelected), + unselectedImage: BrunoTools.getAssetImage(BrnAsset.iconRadioUnSelected), disSelectedImage: - BrunoTools.getAssetImage(BrnAsset.ICON_RADIO_DISABLE_SINGLE_SELECTED), + BrunoTools.getAssetImage(BrnAsset.iconRadioDisableSingleSelected), disUnselectedImage: - BrunoTools.getAssetImage(BrnAsset.ICON_RADIO_DISABLE_UNSELECTED), + BrunoTools.getAssetImage(BrnAsset.iconRadioDisableUnselected), child: widget.child, onRadioItemClick: () { setState(() { diff --git a/lib/src/components/radio/brn_radio_button.dart b/lib/src/components/radio/brn_radio_button.dart index 257bf65a..ef3bd3ec 100644 --- a/lib/src/components/radio/brn_radio_button.dart +++ b/lib/src/components/radio/brn_radio_button.dart @@ -21,10 +21,10 @@ class BrnRadioButton extends StatelessWidget { /// 选择按钮的padding /// 默认EdgeInsets.all(5) - final EdgeInsets iconPadding; + final EdgeInsets? iconPadding; /// 配合使用的控件,比如卡片或者text - final Widget child; + final Widget? child; /// 控件是否在选择按钮的右边, /// true时 控件在选择按钮右边 @@ -43,18 +43,19 @@ class BrnRadioButton extends StatelessWidget { /// 默认值HitTestBehavior.translucent控制widget.onRadioItemClick触发的点击范围 final HitTestBehavior behavior; - const BrnRadioButton( - {Key key, - @required this.radioIndex, - @required this.onValueChangedAtIndex, - this.disable = false, - this.isSelected = false, - this.iconPadding, - this.child, - this.childOnRight = true, - this.mainAxisAlignment = MainAxisAlignment.start, - this.mainAxisSize = MainAxisSize.min, - this.behavior = HitTestBehavior.translucent}); + const BrnRadioButton({ + Key? key, + required this.radioIndex, + required this.onValueChangedAtIndex, + this.disable = false, + this.isSelected = false, + this.iconPadding, + this.child, + this.childOnRight = true, + this.mainAxisAlignment = MainAxisAlignment.start, + this.mainAxisSize = MainAxisSize.min, + this.behavior = HitTestBehavior.translucent + }); @override Widget build(BuildContext context) { @@ -67,12 +68,12 @@ class BrnRadioButton extends StatelessWidget { mainAxisAlignment: mainAxisAlignment, mainAxisSize: mainAxisSize, selectedImage: BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_RADIO_SINGLE_SELECTED), - unselectedImage: BrunoTools.getAssetImage(BrnAsset.ICON_RADIO_UNSELECTED), + BrnAsset.iconRadioSingleSelected), + unselectedImage: BrunoTools.getAssetImage(BrnAsset.iconRadioUnSelected), disSelectedImage: - BrunoTools.getAssetImage(BrnAsset.ICON_RADIO_DISABLE_MULTI_SELECTED), + BrunoTools.getAssetImage(BrnAsset.iconRadioDisableMultiSelected), disUnselectedImage: - BrunoTools.getAssetImage(BrnAsset.ICON_RADIO_DISABLE_UNSELECTED), + BrunoTools.getAssetImage(BrnAsset.iconRadioDisableUnselected), child: child, onRadioItemClick: () { onValueChangedAtIndex(radioIndex, true); diff --git a/lib/src/components/radio/brn_radio_core.dart b/lib/src/components/radio/brn_radio_core.dart index 8f5c027a..2d0af1e0 100644 --- a/lib/src/components/radio/brn_radio_core.dart +++ b/lib/src/components/radio/brn_radio_core.dart @@ -1,6 +1,5 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/rendering.dart'; /// 描述: radio组件 /// 1. 支持单选/多选 @@ -21,10 +20,10 @@ class BrnRadioCore extends StatefulWidget { /// 选择按钮的padding /// 默认EdgeInsets.all(5) - final EdgeInsets iconPadding; + final EdgeInsets? iconPadding; /// 配合使用的控件,比如卡片或者text - final Widget child; + final Widget? child; /// 控件是否在选择按钮的右边, /// true时 控件在选择按钮右边 @@ -40,22 +39,22 @@ class BrnRadioCore extends StatefulWidget { /// 默认值MainAxisSize.min final MainAxisSize mainAxisSize; - final Image selectedImage; + final Image? selectedImage; - final Image unselectedImage; + final Image? unselectedImage; - final Image disSelectedImage; + final Image? disSelectedImage; - final Image disUnselectedImage; + final Image? disUnselectedImage; - final VoidCallback onRadioItemClick; + final VoidCallback? onRadioItemClick; /// 默认值HitTestBehavior.translucent控制widget.onRadioItemClick触发的点击范围 final HitTestBehavior behavior; const BrnRadioCore( - {Key key, - @required this.radioIndex, + {Key? key, + required this.radioIndex, this.disable = false, this.isSelected = false, this.iconPadding, @@ -76,8 +75,8 @@ class BrnRadioCore extends StatefulWidget { } class _BrnRadioCoreState extends State { - bool _isSelected; - bool _disable; + late bool _isSelected; + late bool _disable; @override void initState() { @@ -119,12 +118,12 @@ class _BrnRadioCoreState extends State { // 没设置左右widget的时候就不返回row radioWidget = icon; } else { - List list = List(); + List list = []; if (widget.childOnRight) { list.add(icon); - list.add(widget.child); + list.add(widget.child!); } else { - list.add(widget.child); + list.add(widget.child!); list.add(icon); } radioWidget = Row( @@ -139,7 +138,9 @@ class _BrnRadioCoreState extends State { behavior: widget.behavior, onTap: () { if (widget.disable == true) return; - widget.onRadioItemClick(); + if (widget.onRadioItemClick != null) { + widget.onRadioItemClick!(); + } // if (widget.onValueChangedAtIndex != null) { // if (widget.radioType == BrnRadioType.single) { // // 单选 diff --git a/lib/src/components/rating/brn_rating_star.dart b/lib/src/components/rating/brn_rating_star.dart index f8d1a49c..605121f4 100644 --- a/lib/src/components/rating/brn_rating_star.dart +++ b/lib/src/components/rating/brn_rating_star.dart @@ -40,13 +40,13 @@ class BrnRatingStar extends StatefulWidget { final bool canRatingZero; /// 单颗星星视图的自定义构造器 - final BrnRatingStarBuilder starBuilder; + final BrnRatingStarBuilder? starBuilder; /// 如果设置了,就支持编辑 - final ValueChanged onSelected; + final ValueChanged? onSelected; const BrnRatingStar({ - Key key, + Key? key, this.count = DEFAULT_COUNT, this.selectedCount = 0, this.space = DEFAULT_SPACE, @@ -60,7 +60,7 @@ class BrnRatingStar extends StatefulWidget { } class _BrnRatingStarState extends State { - double currSelected; + late double currSelected; @override void initState() { @@ -84,7 +84,7 @@ class _BrnRatingStarState extends State { } List _getContent() { - List list = List(); + List list = []; for (var i = 0; i < widget.count; i++) { RatingState state; if (i < currSelected.floor()) { @@ -95,7 +95,7 @@ class _BrnRatingStarState extends State { state = RatingState.unselect; } var rating = widget.starBuilder != null - ? widget.starBuilder(state) + ? widget.starBuilder!(state) : _buildRating(state); if (widget.onSelected != null) { @@ -108,7 +108,7 @@ class _BrnRatingStarState extends State { } else { currSelected = (i + 1).toDouble(); } - widget.onSelected(currSelected.toInt()); + widget.onSelected!(currSelected.toInt()); setState(() {}); }, behavior: HitTestBehavior.opaque, @@ -130,12 +130,12 @@ class _BrnRatingStarState extends State { Widget _buildRating(RatingState state) { switch (state) { case RatingState.select: - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STAR, 16, 16); + return BrunoTools.getAssetSizeImage(BrnAsset.iconStar, 16, 16); case RatingState.half: - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STAR_HALF, 16, 16); + return BrunoTools.getAssetSizeImage(BrnAsset.iconStarHalf, 16, 16); case RatingState.unselect: default: - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STAR, 16, 16, + return BrunoTools.getAssetSizeImage(BrnAsset.iconStar, 16, 16, color: Color(0xFFF0F0F0)); } } diff --git a/lib/src/components/scroll_anchor/brn_scroll_anchor_tab.dart b/lib/src/components/scroll_anchor/brn_scroll_anchor_tab.dart index 9f0945df..29b3fea2 100644 --- a/lib/src/components/scroll_anchor/brn_scroll_anchor_tab.dart +++ b/lib/src/components/scroll_anchor/brn_scroll_anchor_tab.dart @@ -1,3 +1,5 @@ + + import 'dart:async'; import 'dart:ui'; @@ -18,15 +20,15 @@ class BrnAnchorTab extends StatefulWidget { final BrnAnchorTabBarStyle tabBarStyle; final AnchorTabWidgetIndexedBuilder widgetIndexedBuilder; final AnchorTabIndexedBuilder tabIndexedBuilder; - final Widget tabDivider; + final Widget? tabDivider; //设置tab与widget的个数 final int itemCount; BrnAnchorTab( - {@required this.widgetIndexedBuilder, - @required this.tabIndexedBuilder, - @required this.itemCount, + {required this.widgetIndexedBuilder, + required this.tabIndexedBuilder, + required this.itemCount, this.tabDivider, this.tabBarStyle = const BrnAnchorTabBarStyle()}); @@ -38,31 +40,31 @@ class BrnAnchorTab extends StatefulWidget { class _BrnScrollAnchorTabWidgetState extends State with SingleTickerProviderStateMixin { //用于控制 滑动 - ScrollController scrollController; + late ScrollController _scrollController; //用于 滑动 和 tab 之间的通信 - StreamController streamController; + late StreamController _streamController; //用于控制tab - TabController tabController; + late TabController _tabController; //滑动组件的 key - GlobalKey key; + late GlobalKey _key; //当前选中的索引 - int currentIndex; + int currentIndex = 0; //滑动组件的元素、 - List bodyWidgetList; + late List _bodyWidgetList; //滑动组件的元素的key - List bodyKeyList; + late List _bodyKeyList; //每个元素在滑动组件中的位置 - List cardOffsetList; + late List _cardOffsetList; //tab - List tabList; + late List _tabList; //是否点击滑动 bool tab = false; @@ -72,29 +74,28 @@ class _BrnScrollAnchorTabWidgetState extends State @override void initState() { - streamController = StreamController(); - scrollController = ScrollController(); + _streamController = StreamController(); + _scrollController = ScrollController(); - key = GlobalKey(); - cardOffsetList = List.filled(widget.itemCount, -1.0); - bodyWidgetList = List(); - bodyKeyList = List(); - tabList = List(); + _key = GlobalKey(); + _cardOffsetList = List.filled(widget.itemCount, -1.0); + _bodyWidgetList = []; + _bodyKeyList = []; + _tabList = []; - currentIndex = 0; - tabController = TabController(length: widget.itemCount, vsync: this); + _tabController = TabController(length: widget.itemCount, vsync: this); fillKeyList(); fillList(); fillTab(); - WidgetsBinding.instance.addPostFrameCallback((da) { + WidgetsBinding.instance!.addPostFrameCallback((da) { fillOffset(); - scrollController.addListener(() { + _scrollController.addListener(() { updateOffset(); - currentIndex = createIndex(scrollController.offset); + currentIndex = createIndex(_scrollController.offset); //防止再次 发送消息 - if (!tab) streamController.add(currentIndex); + if (!tab) _streamController.add(currentIndex); }); }); @@ -106,11 +107,11 @@ class _BrnScrollAnchorTabWidgetState extends State return Column( mainAxisSize: MainAxisSize.min, children: [ - StreamBuilder( + StreamBuilder( initialData: currentIndex, - stream: streamController.stream, + stream: _streamController.stream, builder: (context, snap) { - tabController.index = currentIndex; + _tabController.index = currentIndex; return BrnTabBar( indicatorColor: widget.tabBarStyle.indicatorColor, indicatorWeight: widget.tabBarStyle.indicatorWeight, @@ -121,14 +122,14 @@ class _BrnScrollAnchorTabWidgetState extends State unselectedLabelColor: widget.tabBarStyle.unselectedLabelColor, unselectedLabelStyle: widget.tabBarStyle.unselectedLabelStyle, dragStartBehavior: widget.tabBarStyle.dragStartBehavior, - controller: tabController, - tabs: tabList, + controller: _tabController, + tabs: _tabList, onTap: (state, index) { state.refreshBadgeState(index); currentIndex = index; tab = true; - scrollController - .animateTo(cardOffsetList[index], + _scrollController + .animateTo(_cardOffsetList[index], duration: Duration(milliseconds: 100), curve: Curves.linear) .whenComplete(() { @@ -147,10 +148,10 @@ class _BrnScrollAnchorTabWidgetState extends State child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, - children: bodyWidgetList, + children: _bodyWidgetList, ), - key: key, - controller: scrollController, + key: _key, + controller: _scrollController, ), ) ], @@ -158,59 +159,55 @@ class _BrnScrollAnchorTabWidgetState extends State } void fillList() { - if (widget.widgetIndexedBuilder != null) { - for (int i = 0, n = widget.itemCount; i < n; i++) { - bodyWidgetList.add( - Container( - key: bodyKeyList[i], - child: widget.widgetIndexedBuilder(context, i)), - ); - } + for (int i = 0, n = widget.itemCount; i < n; i++) { + _bodyWidgetList.add( + Container( + key: _bodyKeyList[i], + child: widget.widgetIndexedBuilder(context, i)), + ); } } void fillKeyList() { for (int i = 0, n = widget.itemCount; i < n; i++) { - bodyKeyList.add(GlobalKey()); + _bodyKeyList.add(GlobalKey()); } } void fillOffset() { - Offset globalToLocal = (key.currentContext.findRenderObject() as RenderBox) + Offset globalToLocal = (_key.currentContext!.findRenderObject() as RenderBox) .localToGlobal(Offset.zero); listDy = globalToLocal.dy; for (int i = 0, n = widget.itemCount; i < n; i++) { - if (cardOffsetList[i] == -1.0) if (bodyKeyList[i].currentContext != + if (_cardOffsetList[i] == -1.0) if (_bodyKeyList[i].currentContext != null) { double cardOffset = - (bodyKeyList[i].currentContext.findRenderObject() as RenderBox) + (_bodyKeyList[i].currentContext!.findRenderObject() as RenderBox) .localToGlobal(Offset.zero) //相对于原点 控件的位置 .dy; //y点坐标 - cardOffsetList[i] = cardOffset + scrollController.offset - listDy; + _cardOffsetList[i] = cardOffset + _scrollController.offset - listDy; } } } void fillTab() { - if (widget.tabIndexedBuilder != null) { for (int i = 0, n = widget.itemCount; i < n; i++) { - tabList.add(widget.tabIndexedBuilder(context, i)); + _tabList.add(widget.tabIndexedBuilder(context, i)); } - } } void updateOffset() { for (int i = 0, n = widget.itemCount; i < n; i++) { - if (cardOffsetList[i] == -1.0) if (bodyKeyList[i].currentContext != + if (_cardOffsetList[i] == -1.0) if (_bodyKeyList[i].currentContext != null) { double cardOffset = - (bodyKeyList[i].currentContext.findRenderObject() as RenderBox) + (_bodyKeyList[i].currentContext!.findRenderObject() as RenderBox) .localToGlobal(Offset.zero) //相对于原点 控件的位置 .dy; //y点坐标 - cardOffsetList[i] = cardOffset + scrollController.offset - listDy; + _cardOffsetList[i] = cardOffset + _scrollController.offset - listDy; } } } @@ -219,7 +216,7 @@ class _BrnScrollAnchorTabWidgetState extends State int createIndex(double offset) { int index = 0; for (int i = 0, n = widget.itemCount; i < n; i++) { - if (offset >= cardOffsetList[i] && (offset <= cardOffsetList[i + 1])) { + if (offset >= _cardOffsetList[i] && (offset <= _cardOffsetList[i + 1])) { return i; } } @@ -229,28 +226,28 @@ class _BrnScrollAnchorTabWidgetState extends State @override void dispose() { super.dispose(); - tabController.dispose(); - streamController.close(); - scrollController.dispose(); + _tabController.dispose(); + _streamController.close(); + _scrollController.dispose(); } } class BrnAnchorTabBarStyle { - final Color indicatorColor; + final Color? indicatorColor; final double indicatorWeight; final EdgeInsetsGeometry indicatorPadding; - final Color labelColor; + final Color? labelColor; - final Color unselectedLabelColor; + final Color? unselectedLabelColor; - final TextStyle labelStyle; + final TextStyle? labelStyle; - final EdgeInsetsGeometry labelPadding; + final EdgeInsetsGeometry? labelPadding; - final TextStyle unselectedLabelStyle; + final TextStyle? unselectedLabelStyle; final DragStartBehavior dragStartBehavior; diff --git a/lib/src/components/selectcity/brn_az_common.dart b/lib/src/components/selectcity/brn_az_common.dart index 6dcb7bcf..82db6329 100644 --- a/lib/src/components/selectcity/brn_az_common.dart +++ b/lib/src/components/selectcity/brn_az_common.dart @@ -2,16 +2,16 @@ import 'package:flutter/material.dart'; /// ISuspension Bean. abstract class ISuspensionBean { - bool isShowSuspension; - String name; - String tag; //Suspension Tag + bool isShowSuspension = false; + String name = ""; + String tag = ""; //Suspension Tag } /// AzListView Header. class AzListViewHeader { AzListViewHeader({ - @required this.height, - @required this.builder, + required this.height, + required this.builder, this.tag = "↑", }); @@ -24,7 +24,7 @@ class AzListViewHeader { class SuspensionUtil { /// sort list by suspension tag. /// 根据[A-Z]排序。 - static void sortListBySuspensionTag(List list) { + static void sortListBySuspensionTag(List? list) { if (list == null || list.isEmpty) return; list.sort((a, b) { if (a.tag == "@" || b.tag == "#") { @@ -39,10 +39,10 @@ class SuspensionUtil { /// get index data list by suspension tag. /// 获取索引列表。 - static List getTagIndexList(List list) { - List indexData = List(); + static List getTagIndexList(List? list) { + List indexData = []; if (list != null && list.isNotEmpty) { - String tempTag; + String? tempTag; for (int i = 0, length = list.length; i < length; i++) { String tag = list[i].tag; if (tag.length > 2) tag = tag.substring(0, 2); @@ -56,11 +56,11 @@ class SuspensionUtil { } /// set show suspension status. - static void setShowSuspensionStatus(List list) { + static void setShowSuspensionStatus(List? list) { if (list == null || list.isEmpty) return; - String tempTag; + String? tempTag; for (int i = 0, length = list.length; i < length; i++) { - String tag = list[i].tag; + String? tag = list[i].tag; if (tempTag != tag) { tempTag = tag; list[i].isShowSuspension = true; diff --git a/lib/src/components/selectcity/brn_az_listview.dart b/lib/src/components/selectcity/brn_az_listview.dart index 0c39ed98..5243f172 100644 --- a/lib/src/components/selectcity/brn_az_listview.dart +++ b/lib/src/components/selectcity/brn_az_listview.dart @@ -18,7 +18,7 @@ typedef Widget IndexHintBuilder(BuildContext context, String hint); /// _Header. class _Header extends ISuspensionBean { - String tag; + String tag = ""; String getSuspensionTag() => tag; @@ -29,15 +29,15 @@ class _Header extends ISuspensionBean { /// AzListView. class AzListView extends StatefulWidget { AzListView( - {Key key, + {Key? key, this.data, this.topData, - this.itemBuilder, + required this.itemBuilder, this.controller, this.physics, this.shrinkWrap = true, this.padding = EdgeInsets.zero, - this.suspensionWidget, + required this.suspensionWidget, this.isUseRealIndex = true, this.itemHeight = 50, this.suspensionHeight = 40, @@ -46,20 +46,19 @@ class AzListView extends StatefulWidget { this.indexBarBuilder, this.indexHintBuilder, this.showIndexHint = true}) - : assert(itemBuilder != null), - super(key: key); + : super(key: key); ///with ISuspensionBean Data - final List data; + final List? data; ///with ISuspensionBean topData, Do not participate in [A-Z] sorting (such as hotList). - final List topData; + final List? topData; final ItemWidgetBuilder itemBuilder; - final ScrollController controller; + final ScrollController? controller; - final ScrollPhysics physics; + final ScrollPhysics? physics; final bool shrinkWrap; @@ -78,13 +77,13 @@ class AzListView extends StatefulWidget { final int suspensionHeight; ///on sus tag change callback. - final ValueChanged onSusTagChanged; + final ValueChanged? onSusTagChanged; - final AzListViewHeader header; + final AzListViewHeader? header; - final IndexBarBuilder indexBarBuilder; + final IndexBarBuilder? indexBarBuilder; - final IndexHintBuilder indexHintBuilder; + final IndexHintBuilder? indexHintBuilder; final bool showIndexHint; @@ -98,12 +97,12 @@ class _AzListViewState extends State { //右侧索引tag 与 距离offset的value,比如 a---0, b---item*个数,c---a+b Map _suspensionSectionMap = Map(); - List _cityList = List(); - List _indexTagList = List(); + List _cityList = []; + List _indexTagList = []; bool _isShowIndexBarHint = false; String _indexBarHint = ""; - ScrollController _scrollController; + late ScrollController _scrollController; @override void initState() { @@ -113,7 +112,7 @@ class _AzListViewState extends State { @override void dispose() { - _scrollController?.dispose(); + _scrollController.dispose(); super.dispose(); } @@ -121,7 +120,7 @@ class _AzListViewState extends State { setState(() { _indexBarHint = model.tag; _isShowIndexBarHint = model.isTouchDown; - int offset = _suspensionSectionMap[model.tag]; + int? offset = _suspensionSectionMap[model.tag]; if (offset != null) { _scrollController.jumpTo(offset .toDouble() @@ -132,10 +131,10 @@ class _AzListViewState extends State { void _init() { _cityList.clear(); - if (widget.topData != null && widget.topData.isNotEmpty) { - _cityList.addAll(widget.topData); + if (widget.topData != null && widget.topData!.isNotEmpty) { + _cityList.addAll(widget.topData!); } - List list = widget.data; + List? list = widget.data; if (list != null && list.isNotEmpty) { // SuspensionUtil.sortListBySuspensionTag(list); _cityList.addAll(list); @@ -144,7 +143,7 @@ class _AzListViewState extends State { SuspensionUtil.setShowSuspensionStatus(_cityList); if (widget.header != null) { - _cityList.insert(0, _Header()..tag = widget.header.tag); + _cityList.insert(0, _Header()..tag = widget.header!.tag); } _indexTagList.clear(); if (widget.isUseRealIndex) { @@ -169,8 +168,8 @@ class _AzListViewState extends State { itemBuilder: (BuildContext context, int index) { if (index == 0 && _cityList[index] is _Header) { return SizedBox( - height: widget.header.height.toDouble(), - child: widget.header.builder(context)); + height: widget.header!.height.toDouble(), + child: widget.header!.builder(context)); } return widget.itemBuilder(context, _cityList[index]); }), @@ -193,7 +192,7 @@ class _AzListViewState extends State { onTouch: _onIndexBarTouch, ); } else { - indexBar = widget.indexBarBuilder( + indexBar = widget.indexBarBuilder!( context, _indexTagList, _onIndexBarTouch, @@ -205,7 +204,7 @@ class _AzListViewState extends State { )); Widget indexHint; if (widget.indexHintBuilder != null) { - indexHint = widget.indexHintBuilder(context, '$_indexBarHint'); + indexHint = widget.indexHintBuilder!(context, '$_indexBarHint'); } else { indexHint = Card( color: Colors.black54, diff --git a/lib/src/components/selectcity/brn_base_azlistview_page.dart b/lib/src/components/selectcity/brn_base_azlistview_page.dart index 04a8a3c4..953bf7bc 100644 --- a/lib/src/components/selectcity/brn_base_azlistview_page.dart +++ b/lib/src/components/selectcity/brn_base_azlistview_page.dart @@ -25,10 +25,10 @@ abstract class BaseAZListViewPage extends StatefulWidget { Widget buildItemWidget(ISuspensionBean item); //悬浮的widget - Widget buildSuspensionWidget(String tag); + Widget buildSuspensionWidget(String? tag); List getTopData() { - return List(); + return []; } //item的高度 默认50 @@ -39,16 +39,19 @@ abstract class BaseAZListViewPage extends StatefulWidget { //每个modal 对应的 tag,默认是拼音来设置 String createTagByModal(ISuspensionBean bean) { - String pinyin = PinyinHelper.getPinyinE(bean.name); - return pinyin.substring(0, 1).toUpperCase(); + if (bean.name.isNotEmpty) { + String pinyin = PinyinHelper.getPinyinE(bean.name); + return pinyin.substring(0, 1).toUpperCase(); + } + return ""; } } class _BaseAZListViewPageState extends State { String suspensionTag = ""; - List _dataList = List(); - StreamController streamController; + List _dataList = []; + late StreamController streamController; @override void initState() { @@ -70,14 +73,15 @@ class _BaseAZListViewPageState extends State { if (snapShot.connectionState == ConnectionState.done) { if (snapShot.hasError) { return BrnAbnormalStateUtils.getEmptyWidgetByState( - context, AbnormalState.networkConnectError, (index) { + context, AbnormalState.networkConnectError, + action: (index) { setState(() {}); }); } else { return buildContentBody(snapShot.data); } } - return null; + return Container(); }, )); } @@ -96,7 +100,7 @@ class _BaseAZListViewPageState extends State { if (_dataList.isEmpty && top.isEmpty) { return BrnAbnormalStateUtils.getEmptyWidgetByState( - context, AbnormalState.noData, (index) {}); + context, AbnormalState.noData); } suspensionTag = top.isEmpty ? _dataList[0].tag : top[0].tag; @@ -107,7 +111,7 @@ class _BaseAZListViewPageState extends State { child: StreamBuilder( initialData: suspensionTag, stream: streamController.stream, - builder: (context, snapShot) { + builder: (context, AsyncSnapshot snapShot) { return AzListView( data: _dataList, topData: top, @@ -126,14 +130,14 @@ class _BaseAZListViewPageState extends State { ); } - Widget _buildSusWidget(String susTag) { + Widget _buildSusWidget(String? susTag) { return Container( height: widget.getSuspensionHeight(), child: widget.buildSuspensionWidget(susTag), ); } - void _handleList(List list) { + void _handleList(List? list) { if (list == null || list.isEmpty) return; for (int i = 0, length = list.length; i < length; i++) { String tag = widget.createTagByModal(list[i]); @@ -152,7 +156,7 @@ class _BaseAZListViewPageState extends State { } Widget _buildListItem(ISuspensionBean model) { - String susTag = model.tag; + String? susTag = model.tag; return Column( children: [ //当offstage为true,当前控件不会被绘制在屏幕上 diff --git a/lib/src/components/selectcity/brn_index_bar.dart b/lib/src/components/selectcity/brn_index_bar.dart index e8ffe23d..a802c71d 100644 --- a/lib/src/components/selectcity/brn_index_bar.dart +++ b/lib/src/components/selectcity/brn_index_bar.dart @@ -5,11 +5,9 @@ typedef void IndexBarTouchCallback(IndexBarDetails model); /// IndexModel. class IndexBarDetails { - String tag; //current touch tag. - int position; //current touch position. - bool isTouchDown; //is touch down. - - IndexBarDetails({this.tag, this.position, this.isTouchDown}); + String tag = ""; //current touch tag. + int position = -1; //current touch position. + bool isTouchDown = false; //is touch down. } ///Default Index data. @@ -46,9 +44,9 @@ const List INDEX_DATA_DEF = const [ /// IndexBar. class IndexBar extends StatefulWidget { IndexBar( - {Key key, + {Key? key, this.data = INDEX_DATA_DEF, - @required this.onTouch, + required this.onTouch, this.width = 30, this.itemHeight = 16, this.color = Colors.transparent, @@ -102,14 +100,12 @@ class _SuspensionListViewIndexBarState extends State { textStyle: widget.textStyle, touchDownTextStyle: widget.touchDownTextStyle, onTouch: (details) { - if (widget.onTouch != null) { - if (_isTouchDown != details.isTouchDown) { - setState(() { - _isTouchDown = details.isTouchDown; - }); - } - widget.onTouch(details); + if (_isTouchDown != details.isTouchDown) { + setState(() { + _isTouchDown = details.isTouchDown; + }); } + widget.onTouch(details); }, ), ); @@ -128,30 +124,29 @@ class _IndexBar extends StatefulWidget { final int itemHeight; /// IndexBar text style. - final TextStyle textStyle; + final TextStyle? textStyle; - final TextStyle touchDownTextStyle; + final TextStyle? touchDownTextStyle; /// Item touch callback. final IndexBarTouchCallback onTouch; _IndexBar( - {Key key, + {Key? key, this.data = INDEX_DATA_DEF, - @required this.onTouch, + required this.onTouch, this.width = 30, this.itemHeight = 16, this.textStyle, this.touchDownTextStyle}) - : assert(onTouch != null), - super(key: key); + : super(key: key); @override _IndexBarState createState() => _IndexBarState(); } class _IndexBarState extends State<_IndexBar> { - List _indexSectionList = List(); + List _indexSectionList = []; int _widgetTop = -1; int _lastIndex = 0; bool _widgetTopChange = false; @@ -174,27 +169,25 @@ class _IndexBarState extends State<_IndexBar> { _indexSectionList.clear(); _indexSectionList.add(0); int tempHeight = 0; - widget.data?.forEach((value) { + widget.data.forEach((value) { tempHeight = tempHeight + widget.itemHeight; _indexSectionList.add(tempHeight); }); } _triggerTouchEvent() { - if (widget.onTouch != null) { - widget.onTouch(_indexModel); - } + widget.onTouch(_indexModel); } @override Widget build(BuildContext context) { - TextStyle _style = widget.textStyle; + TextStyle? _style = widget.textStyle; if (_indexModel.isTouchDown == true) { _style = widget.touchDownTextStyle; } _init(); - List children = List(); + List children = []; widget.data.forEach((v) { children.add(SizedBox( width: widget.width.toDouble(), @@ -207,7 +200,7 @@ class _IndexBarState extends State<_IndexBar> { onVerticalDragDown: (DragDownDetails details) { if (_widgetTop == -1 || _widgetTopChange) { _widgetTopChange = false; - RenderBox box = context.findRenderObject(); + RenderBox box = context.findRenderObject() as RenderBox; Offset topLeftPosition = box.localToGlobal(Offset.zero); _widgetTop = topLeftPosition.dy.toInt(); } diff --git a/lib/src/components/selectcity/brn_select_city_model.dart b/lib/src/components/selectcity/brn_select_city_model.dart index a7af5d68..d8c28a6b 100644 --- a/lib/src/components/selectcity/brn_select_city_model.dart +++ b/lib/src/components/selectcity/brn_select_city_model.dart @@ -1,23 +1,21 @@ import 'package:bruno/src/components/selectcity/brn_az_common.dart'; class BrnSelectCityModel extends ISuspensionBean { - String name; - String tagIndex; - String namePinyin; - String tag; - String cityCode; + String name = ""; + String tagIndex = ""; + String? namePinyin; + String tag = ""; + String cityCode = ""; BrnSelectCityModel({ - this.name, - this.tagIndex, + required this.name, + this.tagIndex = "", this.namePinyin, - this.tag, - this.cityCode, + this.tag = "", + this.cityCode = "", }); - BrnSelectCityModel.fromJson(Map json) - : name = json['name'] == null ? "" : json['name'], - cityCode = json['cityCode'] == null ? "" : json['cityCode']; + BrnSelectCityModel.fromJson(Map json); Map toJson() => { 'name': name, diff --git a/lib/src/components/selectcity/brn_single_select_city_page.dart b/lib/src/components/selectcity/brn_single_select_city_page.dart index 789b9b60..b8b7c961 100644 --- a/lib/src/components/selectcity/brn_single_select_city_page.dart +++ b/lib/src/components/selectcity/brn_single_select_city_page.dart @@ -9,7 +9,7 @@ import 'package:bruno/src/components/sugsearch/brn_search_text.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/constants/brn_strings_constants.dart'; import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:bruno/src/utils/font/brn_font.dart'; +import 'package:bruno/src/constants/brn_fonts_constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:lpinyin/lpinyin.dart'; @@ -18,10 +18,10 @@ import 'package:lpinyin/lpinyin.dart'; /// 功能:多可以自定制导航栏文案,搜索文案信息,定位信息,右侧可快速滑动查看城市 class BrnSingleSelectCityPage extends StatefulWidget { /// 页面标题,默认空 - final String appBarTitle; + final String? appBarTitle; /// 热门推荐标题,默认空 - final String hotCityTitle; + final String? hotCityTitle; /// 是否展示searchBar,默认 true final bool showSearchBar; @@ -30,18 +30,18 @@ class BrnSingleSelectCityPage extends StatefulWidget { final String locationText; /// 城市列表 - final List cityList; + final List? cityList; /// 热门推荐城市列表 final List hotCityList; /// 单选项 点击的回调 - final ValueChanged onValueChanged; + final ValueChanged? onValueChanged; BrnSingleSelectCityPage({ this.appBarTitle = '', this.hotCityTitle = '', - this.hotCityList, + required this.hotCityList, this.cityList, this.showSearchBar = true, this.locationText = '', @@ -55,7 +55,7 @@ class BrnSingleSelectCityPage extends StatefulWidget { } class _BrnSingleSelectCityPageState extends State { - List _cityList = List(); + List _cityList = []; ///搜索框的高度 int _suspensionHeight = 40; @@ -73,7 +73,7 @@ class _BrnSingleSelectCityPageState extends State { String _searchText = ""; /// search的TextController - BrnSearchTextController _brnSearchTextController; + late BrnSearchTextController _brnSearchTextController; @override void initState() { @@ -83,7 +83,7 @@ class _BrnSingleSelectCityPageState extends State { } void _loadData() async { - if (widget.cityList == null || widget.cityList.isEmpty) { + if (widget.cityList == null || widget.cityList!.isEmpty) { //加载城市列表 rootBundle .loadString( @@ -98,13 +98,13 @@ class _BrnSingleSelectCityPageState extends State { setState(() {}); }); } else { - _cityList = widget.cityList; + _cityList = widget.cityList!; _handleList(_cityList); setState(() {}); } } - void _handleList(List list) { + void _handleList(List? list) { if (list == null || list.isEmpty) return; for (int i = 0, length = list.length; i < length; i++) { String pinyin = PinyinHelper.getPinyinE(list[i].name); @@ -151,10 +151,12 @@ class _BrnSingleSelectCityPageState extends State { runAlignment: WrapAlignment.start, spacing: 10.0, children: hotCityList.map((e) { - return OutlineButton( - padding: EdgeInsets.all(0), - borderSide: BorderSide(color: Color(0xFFF8F8F8), width: .5), - color: Color(0xFFF8F8F8), + return OutlinedButton( + style: OutlinedButton.styleFrom( + padding: EdgeInsets.all(0), + side: BorderSide(color: Color(0xFFF8F8F8), width: .5), + backgroundColor: Color(0xFFF8F8F8), + ), child: Container( alignment: Alignment.center, height: 36.0, @@ -166,7 +168,7 @@ class _BrnSingleSelectCityPageState extends State { textAlign: TextAlign.center, style: TextStyle( color: Color(0xFF222222), - fontSize: BrnFont.FONT_12, + fontSize: BrnFonts.f12, fontWeight: FontWeight.w400, ), ), @@ -174,7 +176,7 @@ class _BrnSingleSelectCityPageState extends State { onPressed: () { debugPrint("OnItemClick: $e"); if (widget.onValueChanged != null) { - widget.onValueChanged(e); + widget.onValueChanged!(e); } Navigator.pop(context, e); }, @@ -186,7 +188,7 @@ class _BrnSingleSelectCityPageState extends State { ); } - Widget _buildSusWidget(String susTag) { + Widget _buildSusWidget(String? susTag) { return Container( height: _suspensionHeight.toDouble(), padding: const EdgeInsets.only(left: 15.0), @@ -218,7 +220,7 @@ class _BrnSingleSelectCityPageState extends State { onTap: () { debugPrint("OnItemClick: $model"); if (widget.onValueChanged != null) { - widget.onValueChanged(model); + widget.onValueChanged!(model); } Navigator.pop(context, model); }, @@ -234,7 +236,7 @@ class _BrnSingleSelectCityPageState extends State { hintText: '请输入搜索信息', onTextChange: (text) { _searchText = text; - _showCityStack = (text.length == 0 || text == null) ? true : false; + _showCityStack = text.isEmpty; setState(() {}); }, onTextCommit: (text) { @@ -270,12 +272,13 @@ class _BrnSingleSelectCityPageState extends State { @override Widget build(BuildContext context) { return Scaffold( + resizeToAvoidBottomInset: false, appBar: BrnAppBar(title: widget.appBarTitle ?? '城市选择'), body: Container( decoration: BoxDecoration(color: Colors.white), child: Column( children: [ - widget.locationText.isEmpty || widget.locationText == null + widget.locationText.isEmpty ? Container() : _buildLocationBar(widget.locationText), widget.showSearchBar ? _buildSearchBar() : Container(), @@ -300,13 +303,16 @@ class _BrnSingleSelectCityPageState extends State { headerHeight = 0; } if (_suspensionTag.isEmpty || _suspensionTag == '') { - _suspensionTag = _cityList.first.tag; + if (_cityList.isNotEmpty) { + _suspensionTag = _cityList.first.tag; + } } return Expanded( flex: 1, child: AzListView( data: _cityList, - itemBuilder: (context, model) => _buildListItem(model), + itemBuilder: (context, model) => + _buildListItem(model as BrnSelectCityModel), suspensionWidget: _buildSusWidget(_suspensionTag), isUseRealIndex: true, itemHeight: _itemHeight, @@ -361,7 +367,7 @@ class _BrnSingleSelectCityPageState extends State { ///获取城市搜索结果 List _searchCityList(String searchText) { - List cList = List(); + List cList = []; for (int index = 0; index < _cityList.length; index++) { BrnSelectCityModel cInfo = _cityList[index]; if (cInfo.name.contains(searchText) || diff --git a/lib/src/components/selectcity/brn_suspension_view.dart b/lib/src/components/selectcity/brn_suspension_view.dart index 5282705d..34f0bcbc 100644 --- a/lib/src/components/selectcity/brn_suspension_view.dart +++ b/lib/src/components/selectcity/brn_suspension_view.dart @@ -25,27 +25,25 @@ class SuspensionView extends StatefulWidget { final int itemHeight; /// on sus tag change callback. - final ValueChanged onSusTagChanged; + final ValueChanged? onSusTagChanged; /// on sus section callback. - final OnSusSectionCallBack onSusSectionInited; + final OnSusSectionCallBack? onSusSectionInited; - final AzListViewHeader header; + final AzListViewHeader? header; SuspensionView({ - Key key, - @required this.data, - @required this.contentWidget, - @required this.suspensionWidget, - @required this.controller, + Key? key, + required this.data, + required this.contentWidget, + required this.suspensionWidget, + required this.controller, this.suspensionHeight = 40, this.itemHeight = 50, this.onSusTagChanged, this.onSusSectionInited, this.header, - }) : assert(contentWidget != null), - assert(controller != null), - super(key: key); + }) : super(key: key); @override _SuspensionWidgetState createState() => _SuspensionWidgetState(); @@ -53,25 +51,25 @@ class SuspensionView extends StatefulWidget { class _SuspensionWidgetState extends State { int _suspensionTop = 0; - int _lastIndex; - int _suSectionListLength; + int _lastIndex = -1; + late int _suSectionListLength; - List _suspensionSectionList = List(); + List _suspensionSectionList = []; Map _suspensionSectionMap = Map(); @override void initState() { super.initState(); if (widget.header != null) { - _suspensionTop = -widget.header.height; + _suspensionTop = -widget.header!.height; } - widget.controller?.addListener(_handleScrollerListenerTick); + widget.controller.addListener(_handleScrollerListenerTick); } @override void dispose() { super.dispose(); - widget.controller?.removeListener(_handleScrollerListenerTick); + widget.controller.removeListener(_handleScrollerListenerTick); } void _handleScrollerListenerTick() { @@ -80,17 +78,16 @@ class _SuspensionWidgetState extends State { if (_index != -1 && _lastIndex != _index) { _lastIndex = _index; if (widget.onSusTagChanged != null) { - widget.onSusTagChanged(_suspensionSectionMap.keys.toList()[_index]); + widget.onSusTagChanged!(_suspensionSectionMap.keys.toList()[_index]); } } } int _getIndex(int offset) { - if (widget.header != null && offset < widget.header.height) { - if (_suspensionTop != -widget.header.height && - widget.suspensionWidget != null) { + if (widget.header != null && offset < widget.header!.height) { + if (_suspensionTop != -widget.header!.height) { setState(() { - _suspensionTop = -widget.header.height; + _suspensionTop = -widget.header!.height; }); } return 0; @@ -102,7 +99,7 @@ class _SuspensionWidgetState extends State { } else { space = 0; } - if (_suspensionTop != space && widget.suspensionWidget != null) { + if (_suspensionTop != space) { setState(() { _suspensionTop = space; }); @@ -122,15 +119,15 @@ class _SuspensionWidgetState extends State { void _init() { _suspensionSectionMap.clear(); int offset = 0; - String tag; + String? tag; if (widget.header != null) { - _suspensionSectionMap[widget.header.tag] = 0; - offset = widget.header.height; + _suspensionSectionMap[widget.header!.tag] = 0; + offset = widget.header!.height; } - widget.data?.forEach((v) { + widget.data.forEach((v) { if (tag != v.tag) { tag = v.tag; - _suspensionSectionMap.putIfAbsent(tag, () => offset); + _suspensionSectionMap.putIfAbsent(tag!, () => offset); offset = offset + widget.suspensionHeight + widget.itemHeight; } else { offset = offset + widget.itemHeight; @@ -141,7 +138,7 @@ class _SuspensionWidgetState extends State { ..addAll(_suspensionSectionMap.values); _suSectionListLength = _suspensionSectionList.length; if (widget.onSusSectionInited != null) { - widget.onSusSectionInited(_suspensionSectionMap); + widget.onSusSectionInited!(_suspensionSectionMap); } } @@ -151,15 +148,15 @@ class _SuspensionWidgetState extends State { var children = [ widget.contentWidget, ]; - if (widget.suspensionWidget != null) { - children.add(Positioned( - ///-0.1修复部分手机丢失精度问题 - top: _suspensionTop.toDouble() - 0.1, - left: 0.0, - right: 0.0, - child: widget.suspensionWidget, - )); - } + + children.add(Positioned( + ///-0.1修复部分手机丢失精度问题 + top: _suspensionTop.toDouble() - 0.1, + left: 0.0, + right: 0.0, + child: widget.suspensionWidget, + )); + return Stack(children: children); } } diff --git a/lib/src/components/selection/bean/brn_filter_entity.dart b/lib/src/components/selection/bean/brn_filter_entity.dart index 2d02487b..4f65d98d 100644 --- a/lib/src/components/selection/bean/brn_filter_entity.dart +++ b/lib/src/components/selection/bean/brn_filter_entity.dart @@ -1,14 +1,13 @@ class ItemEntity { - String key; + String? key; String name; - String value; + String? value; - ItemEntity({this.key, this.name, this.value}); + ItemEntity({this.key, this.name = '', this.value}); - ItemEntity.fromJson(Map map) { - if (map == null) return; - key = map['key'] ?? ""; - name = map['title'] ?? ""; - value = map['value'] ?? ""; + ItemEntity.fromJson(Map map) : this.name = '' { + key = map['key'] ?? ''; + name = map['title'] ?? ''; + value = map['value'] ?? ''; } } diff --git a/lib/src/components/selection/bean/brn_selection_common_entity.dart b/lib/src/components/selection/bean/brn_selection_common_entity.dart index 93c84fb9..c4c04c94 100644 --- a/lib/src/components/selection/bean/brn_selection_common_entity.dart +++ b/lib/src/components/selection/bean/brn_selection_common_entity.dart @@ -5,72 +5,69 @@ import 'package:bruno/src/utils/brn_tools.dart'; enum BrnSelectionFilterType { /// 未设置 - None, + none, /// 不限类型 - UnLimit, + unLimit, /// 单选列表、单选项 type 为 radio - Radio, + radio, /// 多选列表、多选项 type 为 checkbox - Checkbox, + checkbox, /// 一般的值范围自定义区间 type 为 range - Range, + range, /// 日期选择,普通筛选时使用 CalendarView 展示选择时间,更多情况下使用 DatePicker 选择时间 - Date, + date, /// 自定义选择日期区间, type 为 dateRange - DateRange, + dateRange, /// 自定义通过 Calendar 选择日期区间,type 为 dateRangeCalendar - DateRangeCalendar, + dateRangeCalendar, /// 标签筛选 type 为 customerTag - CustomHandle, + customHandle, /// 更多列表、多选项 无 type - More, + more, /// 去二级页面 - Layer, + layer, /// 去自定义二级页面 - CustomLayer, + customLayer, } /// 筛选弹窗展示风格 enum BrnSelectionWindowType { /// 列表类型,使用列表 Item 展示 - List, + list, /// 值范围类型,使用 Tag + Range 的 Item 展示 - Range, + range, } class BrnSelectionEntity { /// 类型 是单选、复选还是有自定义输入 - String type; + String? type; /// 回传给服务器的 key - String key; + String? key; /// 回传给服务器的 value - String value; + String? value; /// 默认值 - String defaultValue; + String? defaultValue; /// 显示的文案 String title; /// 显示的文案 - String subTitle; - - /// 单位。例如居室、万,适配自定义区间填写的内容 - String unit; + String? subTitle; /// 扩展字段,目前只有min和max Map extMap; @@ -85,30 +82,30 @@ class BrnSelectionEntity { bool isSelected; /// 自定义输入 - Map customMap; + Map? customMap; /// 用于临时存储原有自定义字段数据,在筛选数据变化后未点击【确定】按钮时还原。 - Map originalCustomMap; + late Map originalCustomMap; /// 最大可选数量 int maxSelectedCount; /// 父级筛选项 - BrnSelectionEntity parent; + BrnSelectionEntity? parent; /// 筛选类型,具体参见 [BrnSelectionFilterType] - BrnSelectionFilterType filterType; + late BrnSelectionFilterType filterType; /// 筛选弹窗展示风格对应的首字母小写的字符串,例如 `range`、`list`,参见 [BrnSelectionWindowType] - String showType; + String? showType; /// 筛选弹窗展示风格,具体参见 [BrnSelectionWindowType] - BrnSelectionWindowType filterShowType; + BrnSelectionWindowType? filterShowType; /// 自定义标题 - String customTitle; + String? customTitle; - ///自定义筛选的 title + ///自定义筛选的 title 是否高亮 bool isCustomTitleHighLight; /// 临时字段用于判断是否要将筛选项 [name] 字段拼接展示 @@ -118,126 +115,127 @@ class BrnSelectionEntity { {this.key, this.value, this.defaultValue, - this.title, + this.title = '', this.subTitle, - this.children, + this.children = const [], this.isSelected = false, - this.unit, - this.extMap, + this.extMap = const {}, this.customMap, this.type, this.showType, - this.maxSelectedCount}) { - this.filterType = this.parserFilterTypeWithType(this.type); - this.filterShowType = this.parserShowType(this.showType); + this.isCustomTitleHighLight = false, + this.maxSelectedCount = BrnSelectionConstant.maxSelectCount}) { + this.filterType = parserFilterTypeWithType(this.type); + this.filterShowType = parserShowType(this.showType); this.originalCustomMap = Map(); - - /// 默认支持最大选中个数为 65535 - this.maxSelectedCount = - maxSelectedCount ?? BrnSelectionConstant.MAX_SELECT_COUNT; } /// 构造简单筛选数据 BrnSelectionEntity.simple({ this.key, this.value, - this.title, + this.title = '', this.type, - }) { - this.filterType = this.parserFilterTypeWithType(this.type); - this.filterShowType = this.parserShowType(this.showType); + }) : this.maxSelectedCount = BrnSelectionConstant.maxSelectCount, + this.isCustomTitleHighLight = false, + this.isSelected = false, + this.children = [], + this.extMap = {} { + this.filterType = parserFilterTypeWithType(this.type); + this.filterShowType = parserShowType(this.showType); this.originalCustomMap = Map(); this.isSelected = false; - - /// 默认支持最大选中个数为 65535 - this.maxSelectedCount = - maxSelectedCount ?? BrnSelectionConstant.MAX_SELECT_COUNT; - } - - BrnSelectionEntity.fromJson(Map map) { - if (map == null) return; - title = map['title'] ?? ""; - subTitle = map['subTitle'] ?? ""; - key = map['key'] ?? ""; - type = map['type'] ?? ""; - defaultValue = map['defaultValue'] ?? ""; - value = map['value'] ?? ""; - if (map['maxSelectedCount'] != null && - int.tryParse(map['maxSelectedCount']) != null) { - maxSelectedCount = int.tryParse(map['maxSelectedCount']); - } else { - maxSelectedCount = BrnSelectionConstant.MAX_SELECT_COUNT; - } - extMap = map['ext'] ?? {}; - children = List() - ..addAll((map['children'] as List ?? []) - .map((o) => BrnSelectionEntity.fromMap(o))); - filterType = parserFilterTypeWithType(map['type'] ?? ""); - isSelected = false; } - /// 建议使用上面构造函数[BrnSelectionEntity.fromJson] + /// 建议使用 [BrnSelectionEntity.fromJson] static BrnSelectionEntity fromMap(Map map) { - if (map == null) return null; BrnSelectionEntity entity = BrnSelectionEntity(); - entity.title = map['title'] ?? ""; - entity.subTitle = map['subTitle'] ?? ""; - entity.key = map['key'] ?? ""; - entity.type = map['type'] ?? ""; + entity.title = map['title'] ?? ''; + entity.subTitle = map['subTitle'] ?? ''; + entity.key = map['key'] ?? ''; + entity.type = map['type'] ?? ''; entity.defaultValue = map['defaultValue'] ?? ""; entity.value = map['value'] ?? ""; if (map['maxSelectedCount'] != null && int.tryParse(map['maxSelectedCount']) != null) { - entity.maxSelectedCount = int.tryParse(map['maxSelectedCount']); + entity.maxSelectedCount = int.tryParse(map['maxSelectedCount']) ?? BrnSelectionConstant.maxSelectCount; } else { - entity.maxSelectedCount = BrnSelectionConstant.MAX_SELECT_COUNT; + entity.maxSelectedCount = BrnSelectionConstant.maxSelectCount; } entity.extMap = map['ext'] ?? {}; - entity.children = List() - ..addAll((map['children'] as List ?? []) + if(map['children'] != null && map['children'] is List) { + entity.children = []..addAll((map['children'] as List) .map((o) => BrnSelectionEntity.fromMap(o))); + } entity.filterType = entity.parserFilterTypeWithType(map['type'] ?? ""); return entity; } + + BrnSelectionEntity.fromJson(Map? map) + : this.title = '', + this.maxSelectedCount = BrnSelectionConstant.maxSelectCount, + this.isCustomTitleHighLight = false, + this.isSelected = false, + this.children = [], + this.extMap = {} { + if (map == null) return; + title = map['title'] ?? ''; + subTitle = map['subTitle'] ?? ''; + key = map['key'] ?? ''; + type = map['type'] ?? ''; + defaultValue = map['defaultValue'] ?? ''; + value = map['value'] ?? ''; + if (map['maxSelectedCount'] != null && int.tryParse(map['maxSelectedCount']) != null) { + maxSelectedCount = + int.tryParse(map['maxSelectedCount']) ?? BrnSelectionConstant.maxSelectCount; + } + extMap = map['ext'] ?? {}; + children = [] + ..addAll((map['children'] ?? []).map((o) => BrnSelectionEntity.fromJson(o))); + filterType = parserFilterTypeWithType(map['type'] ?? ''); + isSelected = false; + } + void configRelationshipAndDefaultValue() { configRelationship(); configDefaultValue(); } void configRelationship() { - if (this.children != null && this.children.length > 0) { - for (BrnSelectionEntity entity in this.children) { + if (children.length > 0) { + for (BrnSelectionEntity entity in children) { entity.parent = this; } - for (BrnSelectionEntity entity in this.children) { + for (BrnSelectionEntity entity in children) { entity.configRelationship(); } } } void configDefaultValue() { - if (this.children != null && this.children.length > 0) { - for (BrnSelectionEntity entity in this.children) { - if (!BrunoTools.isEmpty(this.defaultValue)) { - List values = this.defaultValue.split(','); - entity.isSelected = values != null && values.contains(entity.value); + if (children.length > 0) { + for (BrnSelectionEntity entity in children) { + if (!BrunoTools.isEmpty(defaultValue)) { + List values = defaultValue!.split(','); + entity.isSelected = values.contains(entity.value); } } /// 当 default 不在普通 Item 类型中时,尝试填充 同级别 Range Item. if (children.where((_) => _.isSelected).toList().length == 0) { - BrnSelectionEntity rangeEntity = this.children.firstWhere((_) { - return (_.filterType == BrnSelectionFilterType.Range || - _.filterType == BrnSelectionFilterType.DateRange || - _.filterType == BrnSelectionFilterType.DateRangeCalendar); - }, orElse: () { - return null; - }); - if (rangeEntity != null && !BrunoTools.isEmpty(this.defaultValue)) { - List values = this.defaultValue.split(':'); - if (values != null && - values.length == 2 && + List rangeItems = this.children.where((_) { + return (_.filterType == BrnSelectionFilterType.range || + _.filterType == BrnSelectionFilterType.dateRange || + _.filterType == BrnSelectionFilterType.dateRangeCalendar); + }).toList(); + BrnSelectionEntity? rangeEntity; + if (rangeItems.isNotEmpty) { + rangeEntity = rangeItems[0]; + } + if (rangeEntity != null && !BrunoTools.isEmpty(defaultValue)) { + List values = defaultValue!.split(':'); + if (values.length == 2 && int.tryParse(values[0]) != null && int.tryParse(values[1]) != null) { rangeEntity.customMap = {}; @@ -253,60 +251,58 @@ class BrnSelectionEntity { if (hasCheckBoxBrother()) { isSelected = children.where((_) => _.isSelected).length > 0; } else { - isSelected = - isSelected || children.where((_) => _.isSelected).length > 0; + isSelected = isSelected || children.where((_) => _.isSelected).length > 0; } } } - BrnSelectionWindowType parserShowType(String showType) { + BrnSelectionWindowType parserShowType(String? showType) { if (showType == "list") { - return BrnSelectionWindowType.List; + return BrnSelectionWindowType.list; } else if (showType == "range") { - return BrnSelectionWindowType.Range; + return BrnSelectionWindowType.range; } - return BrnSelectionWindowType.List; + return BrnSelectionWindowType.list; } - BrnSelectionFilterType parserFilterTypeWithType(String type) { - if (type == null) return BrnSelectionFilterType.None; + BrnSelectionFilterType parserFilterTypeWithType(String? type) { if (type == 'unlimit') { - return BrnSelectionFilterType.UnLimit; + return BrnSelectionFilterType.unLimit; } else if (type == "radio") { - return BrnSelectionFilterType.Radio; + return BrnSelectionFilterType.radio; } else if (type == "checkbox") { - return BrnSelectionFilterType.Checkbox; + return BrnSelectionFilterType.checkbox; } else if (type == "range") { - return BrnSelectionFilterType.Range; + return BrnSelectionFilterType.range; } else if (type == "customHandle") { - return BrnSelectionFilterType.CustomHandle; + return BrnSelectionFilterType.customHandle; } else if (type == "more") { - return BrnSelectionFilterType.More; + return BrnSelectionFilterType.more; } else if (type == 'floatinglayer') { - return BrnSelectionFilterType.Layer; + return BrnSelectionFilterType.layer; } else if (type == 'customfloatinglayer') { - return BrnSelectionFilterType.CustomLayer; + return BrnSelectionFilterType.customLayer; } else if (type == 'date') { - return BrnSelectionFilterType.Date; + return BrnSelectionFilterType.date; } else if (type == 'daterange') { - return BrnSelectionFilterType.DateRange; + return BrnSelectionFilterType.dateRange; } else if (type == 'daterangecalendar') { - return BrnSelectionFilterType.DateRangeCalendar; + return BrnSelectionFilterType.dateRangeCalendar; } - return BrnSelectionFilterType.None; + return BrnSelectionFilterType.none; } void clearChildSelection() { - if (this.children != null && this.children.length > 0) { - for (BrnSelectionEntity entity in this.children) { + if (children.length > 0) { + for (BrnSelectionEntity entity in children) { entity.isSelected = false; - if (entity.filterType == BrnSelectionFilterType.Date) { + if (entity.filterType == BrnSelectionFilterType.date) { entity.value = null; } - if (entity.filterType == BrnSelectionFilterType.Range || - entity.filterType == BrnSelectionFilterType.DateRange || - entity.filterType == BrnSelectionFilterType.DateRangeCalendar) { - entity.customMap = null; + if (entity.filterType == BrnSelectionFilterType.range || + entity.filterType == BrnSelectionFilterType.dateRange || + entity.filterType == BrnSelectionFilterType.dateRangeCalendar) { + entity.customMap = Map(); } entity.clearChildSelection(); } @@ -314,18 +310,14 @@ class BrnSelectionEntity { } List selectedLastColumnList() { - List list = List(); - if (this.children != null && this.children.length > 0) { - List firstList = List(); + List list = []; + if (this.children.length > 0) { + List firstList = []; for (BrnSelectionEntity firstEntity in this.children) { - if (firstEntity != null && - firstEntity.children != null && - firstEntity.children.length > 0) { - List secondList = List(); + if (firstEntity.children.length > 0) { + List secondList = []; for (BrnSelectionEntity secondEntity in firstEntity.children) { - if (secondEntity != null && - secondEntity.children != null && - secondEntity.children.length > 0) { + if (secondEntity.children.length > 0) { List thirds = BrnSelectionUtil.currentSelectListForEntity(secondEntity); if (thirds.length > 0) { @@ -333,12 +325,12 @@ class BrnSelectionEntity { } else if (secondEntity.isSelected) { secondList.add(secondEntity); } - } else if (secondEntity != null && secondEntity.isSelected) { + } else if (secondEntity.isSelected) { secondList.add(secondEntity); } } list.addAll(secondList); - } else if (firstEntity != null && firstEntity.isSelected) { + } else if (firstEntity.isSelected) { firstList.add(firstEntity); } } @@ -350,43 +342,38 @@ class BrnSelectionEntity { List selectedListWithoutUnlimit() { List selected = selectedList(); return selected - ?.where((_) => !_.isUnLimit()) - ?.where((_) => - (_.filterType != BrnSelectionFilterType.Range) || - (_.filterType == BrnSelectionFilterType.Range && - !BrunoTools.isEmpty(_.customMap))) - ?.where((_) => - (_.filterType != BrnSelectionFilterType.DateRange) || - (_.filterType == BrnSelectionFilterType.DateRange && + .where((_) => !_.isUnLimit()) + .where((_) => + (_.filterType != BrnSelectionFilterType.range) || + (_.filterType == BrnSelectionFilterType.range && !BrunoTools.isEmpty(_.customMap))) + .where((_) => + (_.filterType != BrnSelectionFilterType.dateRange) || + (_.filterType == BrnSelectionFilterType.dateRange && !BrunoTools.isEmpty(_.customMap))) - ?.where((_) => - (_.filterType != BrnSelectionFilterType.DateRangeCalendar) || - (_.filterType == BrnSelectionFilterType.DateRangeCalendar && + .where((_) => + (_.filterType != BrnSelectionFilterType.dateRangeCalendar) || + (_.filterType == BrnSelectionFilterType.dateRangeCalendar && !BrunoTools.isEmpty(_.customMap))) - ?.toList() ?? - List(); + .toList(); } List selectedList() { - if (BrnSelectionFilterType.More == this.filterType) { + if (BrnSelectionFilterType.more == this.filterType) { return this.selectedLastColumnList(); } else { - List results = List(); - List firstColumn = - BrnSelectionUtil.currentSelectListForEntity(this); + List results = []; + List firstColumn = BrnSelectionUtil.currentSelectListForEntity(this); results.addAll(firstColumn); - if (firstColumn != null && firstColumn.length > 0) { + if (firstColumn.length > 0) { for (BrnSelectionEntity firstEntity in firstColumn) { - if (firstEntity != null) { - List secondColumn = - BrnSelectionUtil.currentSelectListForEntity(firstEntity); - results.addAll(secondColumn); - if (secondColumn != null && secondColumn.length > 0) { - for (BrnSelectionEntity secondEntity in secondColumn) { - List thirdColumn = - BrnSelectionUtil.currentSelectListForEntity(secondEntity); - results.addAll(thirdColumn); - } + List secondColumn = + BrnSelectionUtil.currentSelectListForEntity(firstEntity); + results.addAll(secondColumn); + if (secondColumn.length > 0) { + for (BrnSelectionEntity secondEntity in secondColumn) { + List thirdColumn = + BrnSelectionUtil.currentSelectListForEntity(secondEntity); + results.addAll(thirdColumn); } } } @@ -396,22 +383,19 @@ class BrnSelectionEntity { } List allSelectedList() { - List results = List(); - List firstColumn = - BrnSelectionUtil.currentSelectListForEntity(this); + List results = []; + List firstColumn = BrnSelectionUtil.currentSelectListForEntity(this); results.addAll(firstColumn); - if (firstColumn != null && firstColumn.length > 0) { + if (firstColumn.length > 0) { for (BrnSelectionEntity firstEntity in firstColumn) { - if (firstEntity != null) { - List secondColumn = - BrnSelectionUtil.currentSelectListForEntity(firstEntity); - results.addAll(secondColumn); - if (secondColumn != null && secondColumn.length > 0) { - for (BrnSelectionEntity secondEntity in secondColumn) { - List thirdColumn = - BrnSelectionUtil.currentSelectListForEntity(secondEntity); - results.addAll(thirdColumn); - } + List secondColumn = + BrnSelectionUtil.currentSelectListForEntity(firstEntity); + results.addAll(secondColumn); + if (secondColumn.length > 0) { + for (BrnSelectionEntity secondEntity in secondColumn) { + List thirdColumn = + BrnSelectionUtil.currentSelectListForEntity(secondEntity); + results.addAll(thirdColumn); } } } @@ -429,17 +413,18 @@ class BrnSelectionEntity { BrnSelectionEntity getRootEntity(BrnSelectionEntity rootEntity) { if (rootEntity.parent == null || - rootEntity.parent.maxSelectedCount == - BrnSelectionConstant.MAX_SELECT_COUNT) { + rootEntity.parent!.maxSelectedCount == BrnSelectionConstant.maxSelectCount) { return rootEntity; } else { - return getRootEntity(rootEntity.parent); + return getRootEntity(rootEntity.parent!); } } /// 返回最后一层级【选中状态】 Item 的 个数 int getSelectedChildCount(BrnSelectionEntity entity) { - if (BrunoTools.isEmpty(entity.children)) return entity.isSelected ? 1 : 0; + if (BrunoTools.isEmpty(entity.children)) { + return entity.isSelected ? 1 : 0; + } int count = 0; for (BrnSelectionEntity child in entity.children) { @@ -451,13 +436,11 @@ class BrnSelectionEntity { /// 判断当前的筛选 Item 是否为当前层次中第一个被选中的 Item。 /// 用于展开筛选弹窗时显示选中效果。 int getIndexInCurrentLevel() { - if (parent == null || - parent.children == null || - parent.children.length == 0) return -1; + if (parent == null || parent!.children.length == 0) return -1; - for (BrnSelectionEntity entity in parent.children) { + for (BrnSelectionEntity entity in parent!.children) { if (entity == this) { - return parent.children.indexOf(entity); + return parent!.children.indexOf(entity); } } return -1; @@ -465,12 +448,10 @@ class BrnSelectionEntity { /// 是否在筛选数据的最后一层。 如果最大层次为 3;某个筛选数据层次为 2,但其无子节点。此时认为不在最后一层。 bool isInLastLevel() { - if (parent == null || - parent.children == null || - parent.children.length == 0) return true; + if (parent == null || parent!.children.length == 0) return true; - for (BrnSelectionEntity entity in parent.children) { - if (entity.children != null && entity.children.length > 0) { + for (BrnSelectionEntity entity in parent!.children) { + if (entity.children.length > 0) { return false; } } @@ -479,36 +460,35 @@ class BrnSelectionEntity { /// 检查自己的兄弟结点是否存在 checkbox 类型。 bool hasCheckBoxBrother() { - int count = parent?.children - ?.where((f) => f.filterType == BrnSelectionFilterType.Checkbox) - ?.length; + int? count = + parent?.children.where((f) => f.filterType == BrnSelectionFilterType.checkbox).length; return count == null ? false : count > 0; } /// 在这里简单认为 value 为空【null 或 ''】时为 unlimit. bool isUnLimit() { - return filterType == BrnSelectionFilterType.UnLimit; + return filterType == BrnSelectionFilterType.unLimit; } void clearSelectedEntity() { - List tmp = List(); + List tmp = []; BrnSelectionEntity node = this; tmp.add(node); while (tmp.isNotEmpty) { node = tmp.removeLast(); node.isSelected = false; - node.children?.forEach((data) { + node.children.forEach((data) { tmp.add(data); }); } } List currentTagListForEntity() { - List list = List(); - this.children?.forEach((data) { - if (data.filterType != BrnSelectionFilterType.Range && - data.filterType != BrnSelectionFilterType.DateRange && - data.filterType != BrnSelectionFilterType.DateRangeCalendar) { + List list = []; + children.forEach((data) { + if (data.filterType != BrnSelectionFilterType.range && + data.filterType != BrnSelectionFilterType.dateRange && + data.filterType != BrnSelectionFilterType.dateRangeCalendar) { list.add(data); } }); @@ -535,18 +515,18 @@ class BrnSelectionEntity { /// 接口返回默认展示tag个数 int getDefaultShowCount() { int defaultCount = 3; - if (extMap != null && extMap.containsKey('defaultShowCount')) { + if (extMap.containsKey('defaultShowCount')) { defaultCount = extMap['defaultShowCount'] ?? 3; } return defaultCount; } List currentRangeListForEntity() { - List list = List(); - this.children.forEach((data) { - if (data.filterType == BrnSelectionFilterType.Range || - data.filterType == BrnSelectionFilterType.DateRange || - data.filterType == BrnSelectionFilterType.DateRangeCalendar) { + List list = []; + children.forEach((data) { + if (data.filterType == BrnSelectionFilterType.range || + data.filterType == BrnSelectionFilterType.dateRange || + data.filterType == BrnSelectionFilterType.dateRangeCalendar) { list.add(data); } }); @@ -554,36 +534,34 @@ class BrnSelectionEntity { } bool isValidRange() { - if (this.filterType == BrnSelectionFilterType.Range || - this.filterType == BrnSelectionFilterType.DateRange || - this.filterType == BrnSelectionFilterType.DateRangeCalendar) { - DateTime minTime = DateTime.parse(DATE_PICKER_MIN_DATETIME); - DateTime maxTime = DateTime.parse(DATE_PICKER_MAX_DATETIME); + if (this.filterType == BrnSelectionFilterType.range || + this.filterType == BrnSelectionFilterType.dateRange || + this.filterType == BrnSelectionFilterType.dateRangeCalendar) { + DateTime minTime = DateTime.parse(datePickerMinDatetime); + DateTime maxTime = DateTime.parse(datePickerMaxDatetime); int limitMin = int.tryParse(extMap['min']?.toString() ?? "") ?? - (this.filterType == BrnSelectionFilterType.DateRange || - this.filterType == BrnSelectionFilterType.DateRangeCalendar + (this.filterType == BrnSelectionFilterType.dateRange || + this.filterType == BrnSelectionFilterType.dateRangeCalendar ? minTime.millisecondsSinceEpoch : 0); // 日期最大值没设置 默认是2121年01月01日 08:00:00 int limitMax = int.tryParse(extMap['max']?.toString() ?? "") ?? - (this.filterType == BrnSelectionFilterType.DateRange || - this.filterType == BrnSelectionFilterType.DateRangeCalendar + (this.filterType == BrnSelectionFilterType.dateRange || + this.filterType == BrnSelectionFilterType.dateRangeCalendar ? maxTime.millisecondsSinceEpoch : 9999); - if (customMap != null && customMap.isNotEmpty) { - String min = customMap['min'] ?? ""; - String max = customMap['max'] ?? ""; + if (customMap != null && customMap!.isNotEmpty) { + String min = customMap!['min'] ?? ""; + String max = customMap!['max'] ?? ""; if (min.isEmpty && max.isEmpty) { return true; } - int inputMin = int.tryParse(customMap['min'] ?? ""); - int inputMax = int.tryParse(customMap['max'] ?? ""); + int? inputMin = int.tryParse(customMap!['min'] ?? ""); + int? inputMax = int.tryParse(customMap!['max'] ?? ""); if (inputMax != null && inputMin != null) { - if (inputMin >= limitMin && - inputMax <= limitMax && - inputMax >= inputMin) { + if (inputMin >= limitMin && inputMax <= limitMax && inputMax >= inputMin) { return true; } else { return false; @@ -601,7 +579,7 @@ class BrnSelectionEntity { } int getFirstSelectedChildIndex() { - return this.children.indexWhere((data) { + return children.indexWhere((data) { return data.isSelected; }); } @@ -617,7 +595,6 @@ class BrnSelectionEntity { title == other.title && children == other.children && isSelected == other.isSelected && - unit == other.unit && extMap == other.extMap && customMap == other.customMap && type == other.type && @@ -632,7 +609,6 @@ class BrnSelectionEntity { title.hashCode ^ children.hashCode ^ isSelected.hashCode ^ - unit.hashCode ^ extMap.hashCode ^ customMap.hashCode ^ type.hashCode ^ diff --git a/lib/src/components/selection/brn_flat_selection.dart b/lib/src/components/selection/brn_flat_selection.dart index 9e78535f..e581dde6 100644 --- a/lib/src/components/selection/brn_flat_selection.dart +++ b/lib/src/components/selection/brn_flat_selection.dart @@ -21,70 +21,65 @@ class BrnFlatSelection extends StatefulWidget { final List entityDataList; /// 点击确定回调 - final Function(Map) confirmCallback; + final Function(Map)? confirmCallback; /// 每行展示tag数量 默认真是3个 final int preLineTagSize; - /// 当[BrnSelectionEntity.filterType]为[BrnSelectionFilterType.Layer] or[BrnSelectionFilterType.CustomLayer]时 + /// 当[BrnSelectionEntity.filterType]为[BrnSelectionFilterType.layer] or[BrnSelectionFilterType.customLayer]时 /// 跳转到二级页面的自定义操作 - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; /// controller.dispose() 操作交由外部处理 - final BrnFlatSelectionController controller; + final BrnFlatSelectionController? controller; /// 是否需要配置子选项 final bool isNeedConfigChild; /// 主题配置 /// 如有对文本样式、圆角、间距等[BrnSelectionConfig]有特定要求可以配置该属性 - BrnSelectionConfig themeData; + BrnSelectionConfig? themeData; BrnFlatSelection( - {this.entityDataList, + {Key? key, + required this.entityDataList, this.confirmCallback, this.onCustomFloatingLayerClick, this.preLineTagSize = 3, this.isNeedConfigChild = true, this.controller, - this.themeData}) { + this.themeData}) + : super(key: key) { this.themeData ??= BrnSelectionConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: this.themeData!.configId) .selectionConfig - .merge(themeData); + .merge(this.themeData!); } @override _BrnFlatSelectionState createState() => _BrnFlatSelectionState(); } -class _BrnFlatSelectionState extends State - with SingleTickerProviderStateMixin { - List _originalSelectedItemsList; +class _BrnFlatSelectionState extends State with SingleTickerProviderStateMixin { + List _originalSelectedItemsList = []; - StreamController clearController; + StreamController clearController = StreamController.broadcast(); bool isValid = true; - BrnFlatSelectionController _controller; - var _lineWidth = 0.0; + double _lineWidth = 0.0; @override void initState() { super.initState(); - _controller = widget.controller; - if (widget.isNeedConfigChild ?? true) { - widget.entityDataList - ?.forEach((f) => f.configRelationshipAndDefaultValue()); + if (widget.isNeedConfigChild) { + widget.entityDataList.forEach((f) => f.configRelationshipAndDefaultValue()); } - _controller?.addListener(_handleFlatControllerTick); + widget.controller?.addListener(_handleFlatControllerTick); - _originalSelectedItemsList = List(); - _originalSelectedItemsList.clear(); - - List firstColumn = List(); - if (widget.entityDataList != null && widget.entityDataList.length > 0) { + List firstColumn = []; + if (widget.entityDataList.length > 0) { for (BrnSelectionEntity entity in widget.entityDataList) { if (entity.isSelected) { firstColumn.add(entity); @@ -92,18 +87,16 @@ class _BrnFlatSelectionState extends State } } _originalSelectedItemsList.addAll(firstColumn); - if (firstColumn != null && firstColumn.length > 0) { + if (firstColumn.length > 0) { for (BrnSelectionEntity firstEntity in firstColumn) { - if (firstEntity != null) { - List secondColumn = - BrnSelectionUtil.currentSelectListForEntity(firstEntity); - _originalSelectedItemsList.addAll(secondColumn); - if (secondColumn != null && secondColumn.length > 0) { - for (BrnSelectionEntity secondEntity in secondColumn) { - List thirdColumn = - BrnSelectionUtil.currentSelectListForEntity(secondEntity); - _originalSelectedItemsList.addAll(thirdColumn); - } + List secondColumn = + BrnSelectionUtil.currentSelectListForEntity(firstEntity); + _originalSelectedItemsList.addAll(secondColumn); + if (secondColumn.length > 0) { + for (BrnSelectionEntity secondEntity in secondColumn) { + List thirdColumn = + BrnSelectionUtil.currentSelectListForEntity(secondEntity); + _originalSelectedItemsList.addAll(thirdColumn); } } } @@ -112,29 +105,27 @@ class _BrnFlatSelectionState extends State for (BrnSelectionEntity entity in _originalSelectedItemsList) { entity.isSelected = true; if (entity.customMap != null) { - //ori 是存数据 customMap是用来展示ui的 - entity.originalCustomMap = Map.from(entity.customMap); + // originalCustomMap 是用来存临时状态数据, customMap 用来展示 ui + entity.originalCustomMap = Map.from(entity.customMap!); } } - - clearController = StreamController.broadcast(); } void _handleFlatControllerTick() { - if (_controller.isResetSelectedOptions) { + if (widget.controller?.isResetSelectedOptions ?? false) { if (mounted) { setState(() { _resetSelectedOptions(); }); } - _controller.isResetSelectedOptions = false; - } else if (_controller.isCancelSelectedOptions) { + widget.controller?.isResetSelectedOptions = false; + } else if (widget.controller?.isCancelSelectedOptions ?? false) { // 外部关闭调用无UI更新操作 _cancelSelectedOptions(); - _controller.isCancelSelectedOptions = false; - } else if (_controller.isConfirmSelectedOptions) { + widget.controller?.isCancelSelectedOptions = false; + } else if (widget.controller?.isConfirmSelectedOptions ?? false) { _confirmSelectedOptions(); - _controller.isConfirmSelectedOptions = false; + widget.controller?.isConfirmSelectedOptions = false; } } @@ -151,13 +142,13 @@ class _BrnFlatSelectionState extends State @override void dispose() { - _controller?.removeListener(_handleFlatControllerTick); + widget.controller?.removeListener(_handleFlatControllerTick); super.dispose(); } /// 取消 _cancelSelectedOptions() { - if (widget.entityDataList == null || widget.entityDataList.length <= 0) { + if (widget.entityDataList.length <= 0) { return; } for (BrnSelectionEntity entity in widget.entityDataList) { @@ -167,13 +158,11 @@ class _BrnFlatSelectionState extends State _originalSelectedItemsList.forEach((data) { data.isSelected = true; if (data.customMap != null) { - //ori 是存数据 customMap是用来展示ui的 + // originalCustomMap 是用来存临时状态数据, customMap 用来展示 ui data.customMap = Map(); - if (data.originalCustomMap != null) { - data.originalCustomMap.forEach((key, value) { - data.customMap[key.toString()] = value.toString() ?? ""; - }); - } + data.originalCustomMap.forEach((key, value) { + data.customMap![key.toString()] = value.toString(); + }); } }); } @@ -181,7 +170,7 @@ class _BrnFlatSelectionState extends State /// 重置 _resetSelectedOptions() { clearController.add(FlatClearEvent()); - if (widget.entityDataList != null && widget.entityDataList.length > 0) { + if (widget.entityDataList.length > 0) { for (BrnSelectionEntity entity in widget.entityDataList) { _clearUIData(entity); } @@ -203,9 +192,10 @@ class _BrnFlatSelectionState extends State data.isSelected = false; } }); - - widget.confirmCallback( - DefaultSelectionConverter().convertSelectedData(widget.entityDataList)); + if (widget.confirmCallback != null) { + widget + .confirmCallback!(DefaultSelectionConverter().convertSelectedData(widget.entityDataList)); + } } /// 标题+筛选条件的 列表 @@ -223,7 +213,7 @@ class _BrnFlatSelectionState extends State onCustomFloatingLayerClick: widget.onCustomFloatingLayerClick, preLineTagSize: widget.preLineTagSize, parentWidth: _lineWidth, - themeData: widget.themeData, + themeData: widget.themeData!, ); }, itemCount: widget.entityDataList.length, @@ -237,18 +227,16 @@ class _BrnFlatSelectionState extends State void _clearUIData(BrnSelectionEntity entity) { entity.isSelected = false; entity.customMap = Map(); - if (BrnSelectionFilterType.Range == entity.filterType) { - entity.title = null; + if (BrnSelectionFilterType.range == entity.filterType) { + entity.title = ''; } - if (entity.children != null) { - for (BrnSelectionEntity subEntity in entity.children) { - _clearUIData(subEntity); - } + for (BrnSelectionEntity subEntity in entity.children) { + _clearUIData(subEntity); } } void _clearSelectedEntity() { - List tmp = List(); + List tmp = []; BrnSelectionEntity node; tmp.addAll(widget.entityDataList); while (tmp.isNotEmpty) { @@ -258,7 +246,7 @@ class _BrnFlatSelectionState extends State BrnToast.show('您输入的区间有误', context); return; } - node.children?.forEach((data) { + node.children.forEach((data) { tmp.add(data); }); } diff --git a/lib/src/components/selection/brn_more_selection.dart b/lib/src/components/selection/brn_more_selection.dart index 7747b340..95d90c72 100644 --- a/lib/src/components/selection/brn_more_selection.dart +++ b/lib/src/components/selection/brn_more_selection.dart @@ -27,15 +27,17 @@ import 'package:flutter/material.dart'; /// 参考[BrnSelectionEntity]和[BrnSelectionView] class BrnMoreSelectionPage extends StatefulWidget { final BrnSelectionEntity entityData; - final Function(BrnSelectionEntity) confirmCallback; - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; + final Function(BrnSelectionEntity)? confirmCallback; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; final BrnSelectionConfig themeData; BrnMoreSelectionPage( - {this.entityData, + {Key? key, + required this.entityData, this.confirmCallback, this.onCustomFloatingLayerClick, - this.themeData}); + required this.themeData}) + : super(key: key); @override _BrnMoreSelectionPageState createState() => _BrnMoreSelectionPageState(); @@ -43,10 +45,10 @@ class BrnMoreSelectionPage extends StatefulWidget { class _BrnMoreSelectionPageState extends State with SingleTickerProviderStateMixin { - List _originalSelectedItemsList; - AnimationController _controller; - Animation animation; - StreamController clearController; + List _originalSelectedItemsList = []; + late AnimationController _controller; + late Animation _animation; + StreamController _clearController = StreamController.broadcast(); bool isValid = true; @override @@ -56,23 +58,17 @@ class _BrnMoreSelectionPageState extends State duration: const Duration(milliseconds: 300), vsync: this, ); - animation = - Tween(end: Offset.zero, begin: Offset(1.0, 0.0)).animate(_controller); + _animation = Tween(end: Offset.zero, begin: Offset(1.0, 0.0)).animate(_controller); _controller.forward(); - _originalSelectedItemsList = List(); - _originalSelectedItemsList.clear(); - _originalSelectedItemsList - .addAll(widget.entityData?.allSelectedList() ?? List()); + _originalSelectedItemsList.addAll(widget.entityData.allSelectedList()); for (BrnSelectionEntity entity in _originalSelectedItemsList) { entity.isSelected = true; if (entity.customMap != null) { - //ori 是存数据 customMap是用来展示ui的 - entity.originalCustomMap = Map.from(entity.customMap); + // originalCustomMap 是用来存临时状态数据, customMap 用来展示 ui + entity.originalCustomMap = Map.from(entity.customMap!); } } - - clearController = StreamController.broadcast(); } /// 页面结构:左侧的透明黑 + 右侧宽为300的内容区域 @@ -87,7 +83,7 @@ class _BrnMoreSelectionPageState extends State animation: _controller, builder: (context, child) { return SlideTransition( - position: animation, + position: _animation, child: child, ); }, @@ -105,7 +101,7 @@ class _BrnMoreSelectionPageState extends State animation: _controller, builder: (context, child) { return SlideTransition( - position: animation, + position: _animation, child: child, ); }, @@ -132,7 +128,8 @@ class _BrnMoreSelectionPageState extends State @override void dispose() { super.dispose(); - _controller?.dispose(); + _controller.dispose(); + _clearController.close(); } /// 左侧为透明黑,点击直接退出页面 @@ -145,13 +142,11 @@ class _BrnMoreSelectionPageState extends State _originalSelectedItemsList.forEach((data) { data.isSelected = true; if (data.customMap != null) { - //ori 是存数据 customMap是用来展示ui的 + // originalCustomMap 是用来存临时状态数据, customMap 用来展示 ui data.customMap = Map(); - if (data.originalCustomMap != null) { - data.originalCustomMap.forEach((key, value) { - data.customMap[key.toString()] = value.toString() ?? ""; - }); - } + data.originalCustomMap.forEach((key, value) { + data.customMap![key.toString()] = value.toString(); + }); } }); Navigator.maybePop(context); @@ -180,7 +175,7 @@ class _BrnMoreSelectionPageState extends State return ListView.builder( itemBuilder: (context, index) { return BrnMoreSelectionWidget( - clearController: clearController, + clearController: _clearController, selectionEntity: widget.entityData.children[index], onCustomFloatingLayerClick: widget.onCustomFloatingLayerClick, themeData: widget.themeData); @@ -196,7 +191,7 @@ class _BrnMoreSelectionPageState extends State themeData: widget.themeData, clearCallback: () { setState(() { - clearController.add(ClearEvent()); + _clearController.add(ClearEvent()); _clearUIData(widget.entityData); }); }, @@ -215,7 +210,7 @@ class _BrnMoreSelectionPageState extends State } }); if (widget.confirmCallback != null) { - widget.confirmCallback(data); + widget.confirmCallback!(data); } Navigator.of(context).pop(); }, @@ -226,13 +221,11 @@ class _BrnMoreSelectionPageState extends State void _clearUIData(BrnSelectionEntity entity) { entity.isSelected = false; entity.customMap = Map(); - if (BrnSelectionFilterType.Range == entity.filterType) { - entity.title = null; + if (BrnSelectionFilterType.range == entity.filterType) { + entity.title = ''; } - if (entity.children != null) { - for (BrnSelectionEntity subEntity in entity.children) { - _clearUIData(subEntity); - } + for (BrnSelectionEntity subEntity in entity.children) { + _clearUIData(subEntity); } } @@ -241,26 +234,24 @@ class _BrnMoreSelectionPageState extends State } void clearSelectedEntity() { - List tmp = List(); + List tmp = []; BrnSelectionEntity node = widget.entityData; tmp.add(node); while (tmp.isNotEmpty) { node = tmp.removeLast(); if (node.isSelected && - (node.filterType == BrnSelectionFilterType.Range || - node.filterType == BrnSelectionFilterType.DateRange || - node.filterType == BrnSelectionFilterType.DateRangeCalendar)) { + (node.filterType == BrnSelectionFilterType.range || + node.filterType == BrnSelectionFilterType.dateRange || + node.filterType == BrnSelectionFilterType.dateRangeCalendar)) { if (node.customMap != null && - ((node.customMap['min'] != null && - node.customMap['min'].length > 0) || - (node.customMap['max'] != null && - node.customMap['max'].length > 0))) { + (BrunoTools.isEmpty(node.customMap!['min']) || + BrunoTools.isEmpty(node.customMap!['max']))) { if (!node.isValidRange()) { isValid = false; - if (node?.filterType == BrnSelectionFilterType.Range) { + if (node.filterType == BrnSelectionFilterType.range) { BrnToast.show('您输入的区间有误', context); - } else if (node?.filterType == BrnSelectionFilterType.DateRange || - node?.filterType == BrnSelectionFilterType.DateRangeCalendar) { + } else if (node.filterType == BrnSelectionFilterType.dateRange || + node.filterType == BrnSelectionFilterType.dateRangeCalendar) { BrnToast.show('您选择的区间有误', context); } return; @@ -269,52 +260,27 @@ class _BrnMoreSelectionPageState extends State node.isSelected = false; } } - node.children?.forEach((data) { + node.children.forEach((data) { tmp.add(data); }); } } } -/// 用于侧边滑动开一个页面 -class SlideRightRoute extends PageRouteBuilder { - final Widget page; - - SlideRightRoute({this.page}) - : super( - opaque: false, - pageBuilder: ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - ) => - page, - transitionsBuilder: ( - BuildContext context, - Animation animation, - Animation secondaryAnimation, - Widget child, - ) => - SlideTransition( - position: Tween( - begin: const Offset(1, 0), - end: Offset.zero, - ).animate(animation), - child: child, - ), - ); -} - /// 底部的重置+确定 -// ignore: must_be_immutable class MoreBottomSelectionWidget extends StatelessWidget { - final VoidCallback clearCallback; - final Function(BrnSelectionEntity) conformCallback; final BrnSelectionEntity entity; - BrnSelectionConfig themeData; + final VoidCallback? clearCallback; + final Function(BrnSelectionEntity)? conformCallback; + final BrnSelectionConfig themeData; - MoreBottomSelectionWidget( - {this.clearCallback, this.conformCallback, this.entity, this.themeData}); + MoreBottomSelectionWidget({ + Key? key, + required this.entity, + this.clearCallback, + this.conformCallback, + required this.themeData, + }) : super(key: key); @override Widget build(BuildContext context) { @@ -324,7 +290,7 @@ class MoreBottomSelectionWidget extends StatelessWidget { GestureDetector( onTap: () { if (clearCallback != null) { - clearCallback(); + clearCallback!(); } }, child: Container( @@ -351,7 +317,7 @@ class MoreBottomSelectionWidget extends StatelessWidget { title: '确定', onTap: () { if (conformCallback != null) { - conformCallback(entity); + conformCallback!(entity); } }, )), diff --git a/lib/src/components/selection/brn_selection_list_entity.dart b/lib/src/components/selection/brn_selection_list_entity.dart index 89b80bbb..ce2c36dd 100644 --- a/lib/src/components/selection/brn_selection_list_entity.dart +++ b/lib/src/components/selection/brn_selection_list_entity.dart @@ -1,16 +1,14 @@ import 'package:bruno/src/components/selection/bean/brn_selection_common_entity.dart'; class BrnSelectionEntityListBean { - List list; + List? list; BrnSelectionEntityListBean(this.list); - static BrnSelectionEntityListBean fromMap(Map map) { - if (map == null) return null; + static BrnSelectionEntityListBean? fromJson(Map? map) { + if (map == null || map['list'] == null) return null; BrnSelectionEntityListBean bean = BrnSelectionEntityListBean(null); - bean.list = List() - ..addAll((map['list'] as List ?? []) - .map((o) => BrnSelectionEntity.fromMap(o))); + bean.list = (map['list'] as List).map((o) => BrnSelectionEntity.fromMap(o)).toList(); return bean; } } diff --git a/lib/src/components/selection/brn_selection_util.dart b/lib/src/components/selection/brn_selection_util.dart index 7fe2315a..69b488d8 100644 --- a/lib/src/components/selection/brn_selection_util.dart +++ b/lib/src/components/selection/brn_selection_util.dart @@ -9,17 +9,17 @@ class BrnSelectionUtil { /// 处理兄弟结点为未选中状态,将自己置为选中状态 static void processBrotherItemSelectStatus( BrnSelectionEntity selectionEntity) { - if (BrnSelectionFilterType.Checkbox == selectionEntity.filterType) { + if (BrnSelectionFilterType.checkbox == selectionEntity.filterType) { selectionEntity.isSelected = !selectionEntity.isSelected; - List allBrothers = selectionEntity.parent?.children; + List? allBrothers = selectionEntity.parent?.children; if (!BrunoTools.isEmpty(allBrothers)) { - for (BrnSelectionEntity entity in allBrothers) { + for (BrnSelectionEntity entity in allBrothers!) { if (entity != selectionEntity) { - if (entity.filterType == BrnSelectionFilterType.Radio) { + if (entity.filterType == BrnSelectionFilterType.radio) { entity.isSelected = false; } - if (entity.filterType == BrnSelectionFilterType.Date) { + if (entity.filterType == BrnSelectionFilterType.date) { entity.isSelected = false; entity.value = null; } @@ -27,13 +27,13 @@ class BrnSelectionUtil { } } } - if (BrnSelectionFilterType.Radio == selectionEntity.filterType) { - selectionEntity?.parent?.clearChildSelection(); + if (BrnSelectionFilterType.radio == selectionEntity.filterType) { + selectionEntity.parent?.clearChildSelection(); selectionEntity.isSelected = true; } - if (BrnSelectionFilterType.Date == selectionEntity.filterType) { - selectionEntity?.parent?.clearChildSelection(); + if (BrnSelectionFilterType.date == selectionEntity.filterType) { + selectionEntity.parent?.clearChildSelection(); /// 日期类型时在外部 Picker 点击确定时设置 选中状态 selectionEntity.isSelected = true; @@ -45,21 +45,17 @@ class BrnSelectionUtil { int level = 0; BrnSelectionEntity rootEntity = entity; while (rootEntity.parent != null) { - rootEntity = rootEntity.parent; + rootEntity = rootEntity.parent!; } - if (rootEntity != null && - rootEntity.children != null && - rootEntity.children.length > 0) { + if (rootEntity.children.length > 0) { level = level > 1 ? level : 1; for (BrnSelectionEntity firstLevelEntity in rootEntity.children) { - if (firstLevelEntity.children != null && - firstLevelEntity.children.length > 0) { + if (firstLevelEntity.children.length > 0) { level = level > 2 ? level : 2; for (BrnSelectionEntity secondLevelEntity in firstLevelEntity.children) { - if (secondLevelEntity.children != null && - secondLevelEntity.children.length > 0) { + if (secondLevelEntity.children.length > 0) { level = 3; break; } @@ -73,12 +69,10 @@ class BrnSelectionUtil { /// 返回状态为选中的子节点 static List currentSelectListForEntity( BrnSelectionEntity entity) { - List list = List(); - if (entity.children != null && entity.children.length > 0) { - for (BrnSelectionEntity entity in entity.children) { - if (entity.isSelected) { - list.add(entity); - } + List list = []; + for (BrnSelectionEntity entity in entity.children) { + if (entity.isSelected) { + list.add(entity); } } return list; @@ -87,10 +81,10 @@ class BrnSelectionUtil { /// 判断列表中是否有range类型 static bool hasRangeItem(List list) { for (BrnSelectionEntity entity in list) { - if (BrnSelectionFilterType.Range == entity.filterType || - BrnSelectionFilterType.DateRange == entity.filterType || - BrnSelectionFilterType.DateRangeCalendar == entity.filterType || - BrnSelectionWindowType.Range == entity.filterShowType) { + if (BrnSelectionFilterType.range == entity.filterType || + BrnSelectionFilterType.dateRange == entity.filterType || + BrnSelectionFilterType.dateRangeCalendar == entity.filterType || + BrnSelectionWindowType.range == entity.filterShowType) { return true; } } @@ -98,20 +92,19 @@ class BrnSelectionUtil { } /// 判断列表中是否有range类型 - static BrnSelectionEntity getFilledCustomInputItem( + static BrnSelectionEntity? getFilledCustomInputItem( List list) { - BrnSelectionEntity filledCustomInputItem; - if (list == null) return filledCustomInputItem; + BrnSelectionEntity? filledCustomInputItem; for (BrnSelectionEntity entity in list) { if (entity.isSelected && - (BrnSelectionFilterType.Range == entity.filterType || - BrnSelectionFilterType.DateRange == entity.filterType || - BrnSelectionFilterType.DateRangeCalendar == entity.filterType) && + (BrnSelectionFilterType.range == entity.filterType || + BrnSelectionFilterType.dateRange == entity.filterType || + BrnSelectionFilterType.dateRangeCalendar == entity.filterType) && entity.customMap != null) { filledCustomInputItem = entity; break; } - if (entity.children != null && entity.children.length > 0) { + if (entity.children.length > 0) { filledCustomInputItem = getFilledCustomInputItem(entity.children); } if (filledCustomInputItem != null) { @@ -122,7 +115,7 @@ class BrnSelectionUtil { } /// 确定当前 Item 在第几层级 - static int getCurrentListIndex(BrnSelectionEntity currentItem) { + static int getCurrentListIndex(BrnSelectionEntity? currentItem) { int listIndex = -1; if (currentItem != null) { listIndex = 0; @@ -140,22 +133,16 @@ class BrnSelectionUtil { /// !!! 在设置 isSelected = true之前进行 check。 /// 返回 true 符合条件,false 不符合条件 static bool checkMaxSelectionCount(BrnSelectionEntity entity) { - if (entity == null) return false; return entity.getLimitedRootSelectedChildCount() < entity.getLimitedRootMaxSelectedCount(); } //设置数据为未选中状态 static void resetSelectionDatas(BrnSelectionEntity entity) { - if (entity == null) { - return; - } - entity?.isSelected = false; - entity?.customMap = Map(); - if (entity.children != null) { - for (BrnSelectionEntity subEntity in entity.children) { - resetSelectionDatas(subEntity); - } + entity.isSelected = false; + entity.customMap = Map(); + for (BrnSelectionEntity subEntity in entity.children) { + resetSelectionDatas(subEntity); } } } diff --git a/lib/src/components/selection/brn_selection_view.dart b/lib/src/components/selection/brn_selection_view.dart index 3b61d541..6ee37f02 100644 --- a/lib/src/components/selection/brn_selection_view.dart +++ b/lib/src/components/selection/brn_selection_view.dart @@ -18,11 +18,8 @@ typedef BrnConfigTagCountPerRow(int index, BrnSelectionEntity entity); typedef BrnSetCustomSelectionMenuTitle = void Function( {String menuTitle, bool isMenuTitleHighLight}); -typedef BrnOnSelectionChanged = void Function( - int menuIndex, - Map selectedParams, - Map customParams, - BrnSetCustomSelectionMenuTitle setCustomMenuTitle); +typedef BrnOnSelectionChanged = void Function(int menuIndex, Map selectedParams, + Map customParams, BrnSetCustomSelectionMenuTitle setCustomMenuTitle); /// menu 点击拦截回调 /// [index] menu 的索引位置 @@ -36,26 +33,21 @@ typedef BrnOnSelectionPreShow = BrnSelectionWindowType Function( /// 点击【更多】筛选项时的回调, /// [index] 为点击的位置, /// [openMorePage] 为让用户触发的回调用于展开更多筛选页面 -typedef BrnOnMoreSelectionMenuClick = void Function( - int index, BrnOpenMorePage openMorePage); +typedef BrnOnMoreSelectionMenuClick = void Function(int index, BrnOpenMorePage openMorePage); /// 打开更多筛选页面, /// [updateData] 是否要更新更多筛选的数据, /// [moreSelections] 最新的更多筛选数据,是否更新取决于 [updateData] -typedef BrnOpenMorePage = void Function( - {bool updateData, List moreSelections}); +typedef BrnOpenMorePage = void Function({bool updateData, List moreSelections}); /// 自定义类型的 Menu 被点击时 让外部设置选中的 value 进来统一更新 UI,并将 function 传给外部设置筛选值。 -typedef BrnSetCustomSelectionParams = void Function( - Map customParams); +typedef BrnSetCustomSelectionParams = void Function(Map customParams); /// 自定义类型的 menu 被点击的回调, /// [index] 点击位置, /// [customMenuItem] 自定义筛选 menu 原始数据, /// [customSelectionParams] 开放给外部回调给函数,用于更新自定义筛选参数,触发[BrnOnSelectionChanged]。 -typedef BrnOnCustomSelectionMenuClick = Function( - int index, - BrnSelectionEntity customMenuItem, +typedef BrnOnCustomSelectionMenuClick = Function(int index, BrnSelectionEntity customMenuItem, BrnSetCustomSelectionParams customSelectionParams); /// 当更多筛选页面中,类型为 CustomLayer 被回调时,该函数用于回传参数进 BrnSelectionView 中, @@ -70,48 +62,45 @@ typedef BrnSetCustomFloatingLayerSelectionParams = void Function( typedef BrnOnCustomFloatingLayerClick = Function( int index, BrnSelectionEntity customFloatingLayerEntity, - BrnSetCustomFloatingLayerSelectionParams - setCustomFloatingLayerSelectionParams); + BrnSetCustomFloatingLayerSelectionParams setCustomFloatingLayerSelectionParams); -typedef OnDefaultParamsPrepared = void Function( - Map selectedParams); +typedef OnDefaultParamsPrepared = void Function(Map selectedParams); /// 默认筛选参数转换器,对传入的筛选数据做处理,返回 Map 参数对象。 -const BrnSelectionConverterDelegate _defaultConverter = - const DefaultSelectionConverter(); +const BrnSelectionConverterDelegate _defaultConverter = const DefaultSelectionConverter(); // ignore: must_be_immutable class BrnSelectionView extends StatefulWidget { final BrnSelectionConverterDelegate selectionConverterDelegate; - final BrnOnCustomSelectionMenuClick onCustomSelectionMenuClick; - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; - final BrnOnMoreSelectionMenuClick onMoreSelectionMenuClick; + final BrnOnCustomSelectionMenuClick? onCustomSelectionMenuClick; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; + final BrnOnMoreSelectionMenuClick? onMoreSelectionMenuClick; final BrnOnSelectionChanged onSelectionChanged; final List originalSelectionData; - final BrnOnMenuItemInterceptor onMenuClickInterceptor; - final BrnOnSelectionPreShow onSelectionPreShow; + final BrnOnMenuItemInterceptor? onMenuClickInterceptor; + final BrnOnSelectionPreShow? onSelectionPreShow; ///筛选所在列表的外部列表滚动需要收起筛选,此处为最外层列表,有点恶心,但是暂时只想到这个方法,有更好方式的一定要告诉我 - final ScrollController extraScrollController; + final ScrollController? extraScrollController; ///指定筛选固定的相对于屏幕的顶部距离,默认null不指定 - final double constantTop; + final double? constantTop; /// 处理完默认选中的参数后给外部回调 - final OnDefaultParamsPrepared onDefaultParamsPrepared; + final OnDefaultParamsPrepared? onDefaultParamsPrepared; /// 用于对 SelectionWindowType.Range 类型的列数做配置的回调。 - final BrnConfigTagCountPerRow configRowCount; + final BrnConfigTagCountPerRow? configRowCount; - BrnSelectionViewController selectionViewController; + BrnSelectionViewController? selectionViewController; - BrnSelectionConfig themeData; + BrnSelectionConfig? themeData; BrnSelectionView( - {Key key, - this.originalSelectionData, + {Key? key, + required this.originalSelectionData, this.selectionViewController, - @required this.onSelectionChanged, + required this.onSelectionChanged, this.configRowCount, this.selectionConverterDelegate = _defaultConverter, this.onMenuClickInterceptor, @@ -124,12 +113,11 @@ class BrnSelectionView extends StatefulWidget { this.extraScrollController, this.themeData}) : super(key: key) { - selectionViewController ??= BrnSelectionViewController(); this.themeData ??= BrnSelectionConfig(); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: this.themeData!.configId) .selectionConfig - .merge(themeData); + .merge(this.themeData!); } @override @@ -140,57 +128,49 @@ class BrnSelectionView extends StatefulWidget { } class BrnSelectionViewState extends State { - List _selectionData; Map _customParams = Map(); - BrnSelectionConverterDelegate _selectionConverterDelegate; - OnDefaultParamsPrepared _onDefaultParamsPrepared; - + BrnSelectionViewController? _selectionViewController; @override void initState() { super.initState(); - _selectionData = widget.originalSelectionData; - _selectionData?.forEach((f) => f.configRelationshipAndDefaultValue()); - - _selectionConverterDelegate = widget.selectionConverterDelegate; - _onDefaultParamsPrepared = widget.onDefaultParamsPrepared; + _selectionViewController = widget.selectionViewController ?? BrnSelectionViewController(); + widget.originalSelectionData.forEach((f) => f.configRelationshipAndDefaultValue()); - if (_onDefaultParamsPrepared != null) { - _onDefaultParamsPrepared( - _selectionConverterDelegate?.convertSelectedData(_selectionData)); + if (widget.onDefaultParamsPrepared != null) { + widget.onDefaultParamsPrepared!( + widget.selectionConverterDelegate.convertSelectedData(widget.originalSelectionData)); } } @override Widget build(BuildContext context) { - if (_selectionData != null && _selectionData.length > 0) { - _selectionData?.forEach((f) => f.configRelationship()); + if (widget.originalSelectionData.length > 0) { + widget.originalSelectionData.forEach((f) => f.configRelationship()); return BrnSelectionMenuWidget( context: context, - data: _selectionData, - themeData: widget.themeData, + data: widget.originalSelectionData, + themeData: widget.themeData!, extraScrollController: widget.extraScrollController, constantTop: widget.constantTop, configRowCount: widget.configRowCount, onMenuItemClick: (int menuIndex) { - if (widget.onMenuClickInterceptor != null && - widget.onMenuClickInterceptor(menuIndex)) { + if (widget.onMenuClickInterceptor != null && widget.onMenuClickInterceptor!(menuIndex)) { return true; } if (widget.onSelectionPreShow != null) { - _selectionData[menuIndex].filterShowType = - widget.onSelectionPreShow(menuIndex, _selectionData[menuIndex]); + widget.originalSelectionData[menuIndex].filterShowType = + widget.onSelectionPreShow!(menuIndex, widget.originalSelectionData[menuIndex]); } /// 自定义 Menu 的时候, /// 1、外部设置选中的 key-value 参数。 /// 2、触发更新 UI。 /// 3、触发 _onSelectionChanged 统一回调给外部 - if (_selectionData[menuIndex].filterType == - BrnSelectionFilterType.CustomHandle && + if (widget.originalSelectionData[menuIndex].filterType == + BrnSelectionFilterType.customHandle && widget.onCustomSelectionMenuClick != null) { - widget.onCustomSelectionMenuClick( - menuIndex, _selectionData[menuIndex], + widget.onCustomSelectionMenuClick!(menuIndex, widget.originalSelectionData[menuIndex], (Map customParams) { _customParams.clear(); if (customParams != null) { @@ -202,28 +182,24 @@ class BrnSelectionViewState extends State { } /// 自定义 Menu 的时候,让外部设置选中的 value 进来统一更新 UI。 然后触发 _onSelectionChanged 统一回调给外部 - if (_selectionData[menuIndex].filterType == - BrnSelectionFilterType.More && + if (widget.originalSelectionData[menuIndex].filterType == BrnSelectionFilterType.more && widget.onMoreSelectionMenuClick != null) { - widget.onMoreSelectionMenuClick(menuIndex, ( - {bool updateData = false, - List moreSelections}) { - if (updateData != null && updateData) { - List moreSelectionEntities = moreSelections; - _selectionData[menuIndex].children = moreSelectionEntities; - _selectionData[menuIndex].configRelationshipAndDefaultValue(); + widget.onMoreSelectionMenuClick!(menuIndex, ( + {bool updateData = false, List? moreSelections}) { + if (updateData) { + List moreSelectionEntities = moreSelections ?? []; + widget.originalSelectionData[menuIndex].children = moreSelectionEntities; + widget.originalSelectionData[menuIndex].configRelationshipAndDefaultValue(); } setState(() {}); - _openMore(_selectionData[menuIndex], - onCustomFloatingLayerClick: - widget.onCustomFloatingLayerClick); + _openMore(widget.originalSelectionData[menuIndex], + onCustomFloatingLayerClick: widget.onCustomFloatingLayerClick); }); } return false; }, - onConfirm: (BrnSelectionEntity results, int firstIndex, int secondIndex, - int thirdIndex) { - _onSelectionChanged(_selectionData.indexOf(results)); + onConfirm: (BrnSelectionEntity results, int firstIndex, int secondIndex, int thirdIndex) { + _onSelectionChanged(widget.originalSelectionData.indexOf(results)); }, ); } @@ -233,38 +209,37 @@ class BrnSelectionViewState extends State { void _onSelectionChanged(int menuIndex) { widget.onSelectionChanged( menuIndex, - widget.selectionConverterDelegate.convertSelectedData(_selectionData), - _customParams, ({String menuTitle, bool isMenuTitleHighLight}) { + widget.selectionConverterDelegate.convertSelectedData(widget.originalSelectionData), + _customParams, ({String? menuTitle, bool isMenuTitleHighLight = false}) { /// 说明没有 menu 被选中,不需要更新。 if (menuIndex >= 0) { - _selectionData[menuIndex].isCustomTitleHighLight = - isMenuTitleHighLight ?? false; - _selectionData[menuIndex].customTitle = menuTitle; + widget.originalSelectionData[menuIndex].isCustomTitleHighLight = isMenuTitleHighLight; + widget.originalSelectionData[menuIndex].customTitle = menuTitle; } /// 当设置了自定义的参数时: /// 1、执行关闭筛选页面动作(会将menu 中的箭头置为朝下的非激活状态); /// 2、刷新 Menu title; - widget.selectionViewController?.closeSelectionView(); - widget.selectionViewController?.refreshSelectionTitle(); + _selectionViewController?.closeSelectionView(); + _selectionViewController?.refreshSelectionTitle(); setState(() {}); }); setState(() {}); } void _openMore(BrnSelectionEntity entity, - {BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick}) { + {BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick}) { if (entity.children.length > 0) { Navigator.of(context).push(PageRouteBuilder( opaque: false, pageBuilder: (context, animation, second) { return BrnMoreSelectionPage( entityData: entity, - themeData: widget.themeData, + themeData: widget.themeData!, onCustomFloatingLayerClick: onCustomFloatingLayerClick, confirmCallback: (_) { EventBus.instance.fire(RefreshMenuTitleEvent()); - _onSelectionChanged(_selectionData.indexOf(entity)); + _onSelectionChanged(widget.originalSelectionData.indexOf(entity)); }, ); })); diff --git a/lib/src/components/selection/brn_simple_selection.dart b/lib/src/components/selection/brn_simple_selection.dart index 8931d4a7..bf21351c 100644 --- a/lib/src/components/selection/brn_simple_selection.dart +++ b/lib/src/components/selection/brn_simple_selection.dart @@ -4,10 +4,9 @@ import 'package:bruno/src/components/selection/brn_selection_view.dart'; import 'package:bruno/src/constants/brn_constants.dart'; import 'package:flutter/material.dart'; -typedef BrnSimpleSelectionOnSelectionChanged = void Function( - List selectedParams); +typedef BrnSimpleSelectionOnSelectionChanged = void Function(List selectedParams); -const String defaultMenuKey = "defaultMenuKey"; +const String _defaultMenuKey = "defaultMenuKey"; // ignore: must_be_immutable class BrnSimpleSelection extends StatefulWidget { @@ -18,7 +17,7 @@ class BrnSimpleSelection extends StatefulWidget { final String menuKey; /// 默认选中选项值 - final String defaultValue; + final String? defaultValue; /// 最大选中个数 默认 radio模式 65535 checkbox模式外部传入 final int maxSelectedCount; @@ -30,33 +29,33 @@ class BrnSimpleSelection extends StatefulWidget { final BrnSimpleSelectionOnSelectionChanged onSimpleSelectionChanged; /// 菜单点击事件 - final Function onMenuItemClick; + final Function? onMenuItemClick; /// 是否单选 默认 radio模式 is true , checkbox模式 is false final bool isRadio; /// 单选构造函数 BrnSimpleSelection.radio({ - Key key, - this.menuName, - this.menuKey = defaultMenuKey, + Key? key, + required this.menuName, + this.menuKey = _defaultMenuKey, this.defaultValue, - this.items, - @required this.onSimpleSelectionChanged, + required this.items, + required this.onSimpleSelectionChanged, this.onMenuItemClick, }) : this.isRadio = true, - this.maxSelectedCount = BrnSelectionConstant.MAX_SELECT_COUNT, + this.maxSelectedCount = BrnSelectionConstant.maxSelectCount, super(key: key); /// 多选构造函数 BrnSimpleSelection.checkbox({ - this.menuName, - this.menuKey, + Key? key, + required this.menuName, + this.menuKey = _defaultMenuKey, this.defaultValue, - this.maxSelectedCount, - this.items, - Key key, - @required this.onSimpleSelectionChanged, + this.maxSelectedCount = BrnSelectionConstant.maxSelectCount, + required this.items, + required this.onSimpleSelectionChanged, this.onMenuItemClick, }) : this.isRadio = false, super(key: key); @@ -68,7 +67,7 @@ class BrnSimpleSelection extends StatefulWidget { } class BrnSimpleSelectionState extends State { - List selectionEntityList; + late List selectionEntityList; @override void initState() { @@ -78,9 +77,9 @@ class BrnSimpleSelectionState extends State { /// 将筛选数据转换成通用筛选数据 List _convertFilterToBrnSelection() { - List list = List(); - if (widget.items != null && widget.items.isNotEmpty) { - List children = List(); + List list = []; + if (widget.items.isNotEmpty) { + List children = []; for (var filter in widget.items) { children.add(BrnSelectionEntity.simple( key: filter.key, @@ -104,32 +103,24 @@ class BrnSimpleSelectionState extends State { Widget build(BuildContext context) { return BrnSelectionView( originalSelectionData: selectionEntityList, - onSelectionChanged: - (menuIndex, selectedParams, customParams, setCustomTitleFunction) { - if (widget.onSimpleSelectionChanged != null && selectedParams != null) { - List selectedItems = List(); - String valueStr = selectedParams[widget.menuKey ?? defaultMenuKey]; - if (valueStr != null) { - List values = valueStr.split(','); - - ///遍历获取选中的items - for (String value in values) { - for (ItemEntity item in widget.items) { - if (item.value != null && - value != null && - item.value == value) { - selectedItems.add(item); - break; - } - } + onSelectionChanged: (menuIndex, selectedParams, customParams, setCustomTitleFunction) { + List results = []; + String valueStr = selectedParams[widget.menuKey] ?? ''; + List values = valueStr.split(','); + ///遍历获取选中的items + for (String value in values) { + for (ItemEntity item in widget.items) { + if (item.value != null && item.value == value) { + results.add(item); + break; } } - widget.onSimpleSelectionChanged(selectedItems); } + widget.onSimpleSelectionChanged(results); }, onMenuClickInterceptor: (index) { if (widget.onMenuItemClick != null) { - widget.onMenuItemClick(); + widget.onMenuItemClick!(); } return false; }, diff --git a/lib/src/components/selection/controller/brn_selection_view_controller.dart b/lib/src/components/selection/controller/brn_selection_view_controller.dart index 721d73fe..2dc25955 100644 --- a/lib/src/components/selection/controller/brn_selection_view_controller.dart +++ b/lib/src/components/selection/controller/brn_selection_view_controller.dart @@ -3,13 +3,17 @@ import "package:flutter/foundation.dart"; import 'package:flutter/material.dart'; class BrnSelectionListViewController extends ChangeNotifier { - double listViewTop; //下拉筛选列表顶部坐标 - double screenHeight; int menuIndex; + bool isShow; //是否显示下拉筛选列表 - bool isShow = false; //是否显示下拉筛选列表 + double? listViewTop; //下拉筛选列表顶部坐标 + double? screenHeight; + OverlayEntry? entry; //显示下拉筛选列表的图层 - OverlayEntry entry; //显示下拉筛选列表的图层 + BrnSelectionListViewController({ + this.menuIndex = -1, + this.isShow = false, + }); void show(int index) { isShow = true; @@ -19,6 +23,8 @@ class BrnSelectionListViewController extends ChangeNotifier { void hide() { isShow = false; + entry?.remove(); + entry = null; notifyListeners(); } } diff --git a/lib/src/components/selection/controller/brn_selection_view_date_picker_controller.dart b/lib/src/components/selection/controller/brn_selection_view_date_picker_controller.dart index e198900e..81376f9d 100644 --- a/lib/src/components/selection/controller/brn_selection_view_date_picker_controller.dart +++ b/lib/src/components/selection/controller/brn_selection_view_date_picker_controller.dart @@ -2,10 +2,13 @@ import "package:flutter/foundation.dart"; import 'package:flutter/material.dart'; class BrnSelectionDatePickerController extends ChangeNotifier { - bool isShow = false; //是否显示下拉筛选列表 - OverlayEntry entry; + bool isShow; //是否显示下拉筛选列表 + OverlayEntry? entry; - double screenHeight; //显示下拉筛选列表的图层 + BrnSelectionDatePickerController({ + this.isShow = false, + this.entry, +}); void show() { isShow = true; @@ -13,5 +16,7 @@ class BrnSelectionDatePickerController extends ChangeNotifier { void hide() { isShow = false; + entry?.remove(); + entry = null; } } diff --git a/lib/src/components/selection/converter/brn_selection_converter.dart b/lib/src/components/selection/converter/brn_selection_converter.dart index 76681e69..f9b3ce12 100644 --- a/lib/src/components/selection/converter/brn_selection_converter.dart +++ b/lib/src/components/selection/converter/brn_selection_converter.dart @@ -4,16 +4,14 @@ import 'package:bruno/src/utils/brn_tools.dart'; abstract class BrnSelectionConverterDelegate { /// 统一的数据结构 转换为 用户需要的数据结构,并通过 [BrnSelectionOnSelectionChanged] 回传给用户使用。 - Map convertSelectedData( - List selectedResults); + Map convertSelectedData(List selectedResults); } class DefaultSelectionConverter implements BrnSelectionConverterDelegate { const DefaultSelectionConverter(); @override - Map convertSelectedData( - List selectedResults) { + Map convertSelectedData(List selectedResults) { return getSelectionParams(selectedResults); } } @@ -22,50 +20,45 @@ class DefaultMoreSelectionConverter implements BrnSelectionConverterDelegate { const DefaultMoreSelectionConverter(); @override - Map convertSelectedData( - List selectedResults) { + Map convertSelectedData(List selectedResults) { return getSelectionParams(selectedResults); } } -class DefaultSelectionQuickFilterConverter - implements BrnSelectionConverterDelegate { +class DefaultSelectionQuickFilterConverter implements BrnSelectionConverterDelegate { const DefaultSelectionQuickFilterConverter(); @override - Map convertSelectedData( - List selectedResults) { + Map convertSelectedData(List selectedResults) { return getSelectionParams(selectedResults); } } /// 注意,此方法仅在初始化筛选项之前调用。如果再筛选之后使用会影响筛选View 的展示以及筛选结果。 -Map getSelectionParamsWithConfigChild( - List selectedResults) { +Map getSelectionParamsWithConfigChild(List? selectedResults) { Map params = Map(); if (selectedResults == null) return params; - selectedResults?.forEach((f) => f.configRelationshipAndDefaultValue()); + selectedResults.forEach((f) => f.configRelationshipAndDefaultValue()); return getSelectionParams(selectedResults); } -Map getSelectionParams( - List selectedResults) { +Map getSelectionParams(List? selectedResults) { Map params = Map(); if (selectedResults == null) return params; for (BrnSelectionEntity menuItemEntity in selectedResults) { - if (menuItemEntity.filterType == BrnSelectionFilterType.More) { + if (menuItemEntity.filterType == BrnSelectionFilterType.more) { params.addAll(getSelectionParams(menuItemEntity.children)); } else { /// 1、首先找出 自定义范围的筛选项参数。 - BrnSelectionEntity selectedCustomInputItem = + BrnSelectionEntity? selectedCustomInputItem = BrnSelectionUtil.getFilledCustomInputItem(menuItemEntity.children); if (selectedCustomInputItem != null && !BrunoTools.isEmpty(selectedCustomInputItem.customMap)) { - String key = selectedCustomInputItem.parent.key; + String? key = selectedCustomInputItem.parent?.key; if (!BrunoTools.isEmpty(key)) { - params[key] = selectedCustomInputItem.customMap["min"] + + params[key!] = (selectedCustomInputItem.customMap!["min"] ?? '') + ':' + - selectedCustomInputItem.customMap["max"]; + (selectedCustomInputItem.customMap!["max"] ?? ''); } } @@ -75,13 +68,13 @@ Map getSelectionParams( params.addAll(getCurrentSelectionEntityParams(menuItemEntity)); } else if (levelCount == 2) { params.addAll(getCurrentSelectionEntityParams(menuItemEntity)); - menuItemEntity.children?.forEach((firstLevelItem) => - params.addAll(getCurrentSelectionEntityParams(firstLevelItem))); + menuItemEntity.children.forEach( + (firstLevelItem) => params.addAll(getCurrentSelectionEntityParams(firstLevelItem))); } else if (levelCount == 3) { params.addAll(getCurrentSelectionEntityParams(menuItemEntity)); - menuItemEntity.children?.forEach((firstLevelItem) { + menuItemEntity.children.forEach((firstLevelItem) { params.addAll(getCurrentSelectionEntityParams(firstLevelItem)); - firstLevelItem.children?.forEach((secondLevelItem) { + firstLevelItem.children.forEach((secondLevelItem) { params.addAll(getCurrentSelectionEntityParams(secondLevelItem)); }); }); @@ -91,19 +84,17 @@ Map getSelectionParams( return params; } -Map getCurrentSelectionEntityParams( - BrnSelectionEntity selectionEntity) { +Map getCurrentSelectionEntityParams(BrnSelectionEntity selectionEntity) { Map params = Map(); - String parentKey = selectionEntity.key; - var selectedEntity = selectionEntity.children - ?.where((BrnSelectionEntity f) => f.isSelected) - ?.where((BrnSelectionEntity f) => !BrunoTools.isEmpty(f.value)) - ?.map((BrnSelectionEntity f) => f.value) - ?.toList(); - String selectedParams = - selectedEntity == null ? "" : selectedEntity.join(","); + String? parentKey = selectionEntity.key; + List selectedEntity = selectionEntity.children + .where((BrnSelectionEntity f) => f.isSelected) + .where((BrnSelectionEntity f) => !BrunoTools.isEmpty(f.value)) + .map((BrnSelectionEntity f) => f.value) + .toList(); + String selectedParams = selectedEntity.isEmpty ? '' : selectedEntity.join(','); if (!BrunoTools.isEmpty(selectedParams) && !BrunoTools.isEmpty(parentKey)) { - params[parentKey] = selectedParams; + params[parentKey!] = selectedParams; } return params; } diff --git a/lib/src/components/selection/widget/brn_flat_selection_item.dart b/lib/src/components/selection/widget/brn_flat_selection_item.dart index cf5d89d3..3f8ffc80 100644 --- a/lib/src/components/selection/widget/brn_flat_selection_item.dart +++ b/lib/src/components/selection/widget/brn_flat_selection_item.dart @@ -21,17 +21,16 @@ import 'package:flutter/cupertino.dart'; ///主要是分为两种:标签和跳到其他页面的layer ///标签类型包罗了:标题、有无更多的展开收起、自定义输入、标签项 ///页面类型保罗了:标题、选择框 -// ignore: must_be_immutable class BrnFlatMoreSelection extends StatefulWidget { /// 数据源 final BrnSelectionEntity selectionEntity; /// 清空已选项 一般跟重置功能搭配使用 - final StreamController clearController; + final StreamController? clearController; - /// 当[BrnSelectionEntity.filterType]为[BrnSelectionFilterType.Layer] or[BrnSelectionFilterType.CustomLayer]时 + /// 当[BrnSelectionEntity.filterType]为[BrnSelectionFilterType.layer] or[BrnSelectionFilterType.customLayer]时 /// 跳转到二级页面的自定义操作 - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; /// 每行tag数 默认3个 final int preLineTagSize; @@ -41,16 +40,17 @@ class BrnFlatMoreSelection extends StatefulWidget { final double parentWidth; /// 主题配置 - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; BrnFlatMoreSelection({ - this.selectionEntity, + Key? key, + required this.selectionEntity, this.clearController, this.onCustomFloatingLayerClick, this.preLineTagSize = 3, this.parentWidth = 0, - this.themeData, - }); + required this.themeData, + }): super(key: key); @override _BrnFlatMoreSelectionState createState() => _BrnFlatMoreSelectionState(); @@ -60,9 +60,8 @@ class _BrnFlatMoreSelectionState extends State { @override Widget build(BuildContext context) { //弹出浮层 - if (widget.selectionEntity.filterType == BrnSelectionFilterType.Layer || - widget.selectionEntity.filterType == - BrnSelectionFilterType.CustomLayer) { + if (widget.selectionEntity.filterType == BrnSelectionFilterType.layer || + widget.selectionEntity.filterType == BrnSelectionFilterType.customLayer) { return FilterLayerTypeWidget( selectionEntity: widget.selectionEntity, onCustomFloatingLayerClick: widget.onCustomFloatingLayerClick, @@ -85,31 +84,30 @@ class _BrnFlatMoreSelectionState extends State { class _FilterCommonTypeWidget extends StatefulWidget { //楼层 final BrnSelectionEntity selectionEntity; - final StreamController clearController; + final StreamController? clearController; final int preLineTagSize; final double parentWidth; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; _FilterCommonTypeWidget( - {this.selectionEntity, + {required this.selectionEntity, this.clearController, this.preLineTagSize = 3, this.parentWidth = 0, - this.themeData}); + required this.themeData}); @override - __FilterCommonTypeWidgetState createState() => - __FilterCommonTypeWidgetState(); + __FilterCommonTypeWidgetState createState() => __FilterCommonTypeWidgetState(); } class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { bool isExpanded = false; ///展开收起的通知 - ValueNotifier valueNotifier; + late ValueNotifier _valueNotifier; ///用于 range和 tag 之间通信 - StreamController streamController; + late StreamController _streamController; /// 标签宽度 double _tagWidth = 0; @@ -123,19 +121,17 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { @override void initState() { super.initState(); - streamController = StreamController.broadcast(); + _streamController = StreamController.broadcast(); //如果是输入事件 //如果是单选的情况,将选中的tag清空 //如果是多选则,不作处理 - streamController.stream.listen((event) { + _streamController.stream.listen((event) { if (event is InputEvent) { setState(() { if (!event.filter) { //将所有tag设置为未选中 - event.rangeEntity.parent - ?.currentTagListForEntity() - ?.forEach((data) { + event.rangeEntity.parent?.currentTagListForEntity().forEach((data) { data.clearSelectedEntity(); }); } @@ -144,10 +140,10 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { }); //展开收起的事件 - valueNotifier = ValueNotifier(isExpanded); - valueNotifier.addListener(() { + _valueNotifier = ValueNotifier(isExpanded); + _valueNotifier.addListener(() { setState(() { - isExpanded = valueNotifier.value; + isExpanded = _valueNotifier.value; }); }); } @@ -155,14 +151,11 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { @override Widget build(BuildContext context) { try { - _tagWidth = (widget.parentWidth - - _spacing * (widget.preLineTagSize - 1) - - _padding * 2) / + _tagWidth = (widget.parentWidth - _spacing * (widget.preLineTagSize - 1) - _padding * 2) / widget.preLineTagSize; //保留小数点后3位 - _tagWidth = double.parse(_tagWidth - .toStringAsFixed(4) - .substring(0, _tagWidth.toStringAsFixed(4).length - 1)); + _tagWidth = double.parse( + _tagWidth.toStringAsFixed(4).substring(0, _tagWidth.toStringAsFixed(4).length - 1)); _tagWidth = _tagWidth < 75 ? 75 : _tagWidth; } catch (e) { debugPrint('get tag width error'); @@ -180,10 +173,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { child: _buildTitleWidget(), ), Visibility( - visible: widget.selectionEntity - .currentShowTagByExpanded(isExpanded) - .length > - 0, + visible: widget.selectionEntity.currentShowTagByExpanded(isExpanded).length > 0, child: Container( padding: EdgeInsets.only(top: 12), child: _buildOptionWidgets(), @@ -197,7 +187,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { visible: widget.selectionEntity.currentTagListForEntity().length > widget.selectionEntity.getDefaultShowCount(), child: _MoreArrow( - valueNotifier: valueNotifier, + valueNotifier: _valueNotifier, themeData: widget.themeData, ), ), @@ -216,7 +206,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { children: [ Expanded( child: Text( - widget.selectionEntity.title ?? "", + widget.selectionEntity.title, style: widget.themeData.titleForMoreTextStyle.generateTextStyle(), ), ), @@ -232,7 +222,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { width: 0, ) : _MoreRangeWidget( - streamController: streamController, + streamController: _streamController, clearController: widget.clearController, rangeEntity: widget.selectionEntity.currentRangeListForEntity()[0], themeData: widget.themeData, @@ -249,12 +239,12 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { return GestureDetector( onTap: () { setState(() { - if (data.filterType == BrnSelectionFilterType.Radio) { - data.parent.clearSelectedEntity(); + if (data.filterType == BrnSelectionFilterType.radio) { + data.parent?.clearSelectedEntity(); data.isSelected = true; //用于发送 标签点击事件 - streamController.add(SelectEvent()); - } else if (data.filterType == BrnSelectionFilterType.Checkbox) { + _streamController.add(SelectEvent()); + } else if (data.filterType == BrnSelectionFilterType.checkbox) { if (!data.isSelected) { if (!BrnSelectionUtil.checkMaxSelectionCount(data)) { BrnToast.show('您选择的筛选条件数量已达上限', context); @@ -262,13 +252,13 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { } } - data.parent.children - ?.where((_) => _.filterType == BrnSelectionFilterType.Radio) - ?.forEach((f) => f.isSelected = false); + data.parent?.children + .where((_) => _.filterType == BrnSelectionFilterType.radio) + .forEach((f) => f.isSelected = false); data.isSelected = !data.isSelected; //用于发送 标签点击事件 - streamController.add(SelectEvent()); - } else if (data.filterType == BrnSelectionFilterType.Date) { + _streamController.add(SelectEvent()); + } else if (data.filterType == BrnSelectionFilterType.date) { _showDatePicker(data); } }); @@ -283,7 +273,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { /// 当默认显示tag数<= tag总数时,仅展示tag /// 当点击更多时全部展示 Widget _buildOptionWidgets() { - List widgets = List(); + List widgets = []; widgets.addAll(_buildSelectionTag()); if (isExpanded || (widget.selectionEntity.currentRangeListForEntity().isNotEmpty && @@ -299,20 +289,17 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { } Widget _buildSingleTag(BrnSelectionEntity data) { - bool isDate = data.filterType == BrnSelectionFilterType.Date; + bool isDate = data.filterType == BrnSelectionFilterType.date; String showName; if (isDate) { - if (data.value == null || data.value.isEmpty) { + if (data.value == null || data.value!.isEmpty) { showName = data.title; } else { - int time = int.tryParse(data.value ?? "") ?? - DateTime.now().millisecondsSinceEpoch; + int time = int.tryParse(data.value ?? "") ?? DateTime.now().millisecondsSinceEpoch; showName = DateTimeFormatter.formatDate( - DateTime.fromMillisecondsSinceEpoch(time), - 'yyyy/MMMM/dd', - DateTimePickerLocale.zh_cn); + DateTime.fromMillisecondsSinceEpoch(time), 'yyyy/MMMM/dd', DateTimePickerLocale.zh_cn); } } else { showName = data.title; @@ -344,8 +331,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { } void _showDatePicker(BrnSelectionEntity data) { - int time = - int.tryParse(data.value ?? "") ?? DateTime.now().millisecondsSinceEpoch; + int time = int.tryParse(data.value ?? "") ?? DateTime.now().millisecondsSinceEpoch; BrnDatePicker.showDatePicker(context, pickerMode: BrnDateTimePickerMode.date, pickerTitleConfig: BrnPickerTitleConfig.Default, @@ -353,7 +339,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { dateFormat: 'yyyy年,MMMM月,dd日', onConfirm: (dateTime, list) { if (mounted) { setState(() { - data.parent.clearSelectedEntity(); + data.parent?.clearSelectedEntity(); data.isSelected = true; data.value = dateTime.millisecondsSinceEpoch.toString(); }); @@ -363,13 +349,12 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { } /// 更多和箭头widget -// ignore: must_be_immutable class _MoreArrow extends StatefulWidget { ///用于通知 展开和收起 - final ValueNotifier valueNotifier; - BrnSelectionConfig themeData; + final ValueNotifier? valueNotifier; + final BrnSelectionConfig themeData; - _MoreArrow({this.valueNotifier, this.themeData}); + _MoreArrow({this.valueNotifier, required this.themeData}); @override __MoreArrowState createState() => __MoreArrowState(); @@ -381,7 +366,7 @@ class __MoreArrowState extends State<_MoreArrow> { @override Widget build(BuildContext context) { String asset = - isExpanded ? BrnAsset.ICON_UP_ARROW : BrnAsset.ICON_DOWN_ARROW; + isExpanded ? BrnAsset.iconUpArrow : BrnAsset.iconDownArrow; return GestureDetector( behavior: HitTestBehavior.opaque, @@ -389,7 +374,7 @@ class __MoreArrowState extends State<_MoreArrow> { setState(() { isExpanded = !isExpanded; if (widget.valueNotifier != null) { - widget.valueNotifier.value = isExpanded; + widget.valueNotifier!.value = isExpanded; } }); }, @@ -398,8 +383,7 @@ class __MoreArrowState extends State<_MoreArrow> { child: Row( mainAxisSize: MainAxisSize.min, children: [ - Text('更多', - style: widget.themeData.moreTextStyle.generateTextStyle()), + Text('更多', style: widget.themeData.moreTextStyle.generateTextStyle()), Container( height: 16, width: 16, @@ -419,59 +403,55 @@ class __MoreArrowState extends State<_MoreArrow> { // ignore: must_be_immutable class _MoreRangeWidget extends StatefulWidget { ///用于标签和自定义输入 通信 - final StreamController streamController; + final StreamController? streamController; ///用于自定义的筛选条件 最大值最小值 final BrnSelectionEntity rangeEntity; ///用于监听重置事件 - final StreamController clearController; + final StreamController? clearController; final double width; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; - _MoreRangeWidget( - {this.streamController, - this.rangeEntity, - this.clearController, - this.themeData, - this.width = 0, - Key key}) - : super(key: key); + _MoreRangeWidget({ + Key? key, + required this.rangeEntity, + this.streamController, + this.clearController, + this.width = 0, + required this.themeData, + }) : super(key: key); @override __MoreRangeWidgetState createState() => __MoreRangeWidgetState(); } class __MoreRangeWidgetState extends State<_MoreRangeWidget> { - //最小值 输入框监听 - TextEditingController minController; + /// 最小值 输入框监听 + TextEditingController minController = TextEditingController(); - //最大值 输入框监听 - TextEditingController maxController; + /// 最大值 输入框监听 + TextEditingController maxController = TextEditingController(); - //最小值 焦点监听 - FocusNode minFocusNode; + /// 最小值 焦点监听 + FocusNode minFocusNode = FocusNode(); - //最大值 焦点监听 - FocusNode maxFocusNode; + /// 最大值 焦点监听 + FocusNode maxFocusNode = FocusNode(); //默认的最大值 - int max; + int max = 9999; //默认的最小值 - int min; + int min = 0; @override void initState() { super.initState(); - minFocusNode = FocusNode(); - maxFocusNode = FocusNode(); - minController = TextEditingController(); - maxController = TextEditingController(); - widget?.clearController?.stream?.listen((event) { + widget.clearController?.stream.listen((event) { minController.clear(); maxController.clear(); }); @@ -480,30 +460,28 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { widget.rangeEntity.customMap = Map(); } - minController.text = (widget.rangeEntity.customMap['min'] != null) - ? widget.rangeEntity.customMap['min']?.toString() - : null; - maxController.text = (widget.rangeEntity.customMap['max'] != null) - ? widget.rangeEntity.customMap['max']?.toString() - : null; + minController.text = (widget.rangeEntity.customMap!['min'] != null) + ? widget.rangeEntity.customMap!['min']?.toString() ?? '' + : ''; + maxController.text = (widget.rangeEntity.customMap!['max'] != null) + ? widget.rangeEntity.customMap!['max']?.toString() ?? '' + : ''; - min = - int.tryParse(widget.rangeEntity?.extMap['min']?.toString() ?? "") ?? 0; - max = int.tryParse(widget.rangeEntity?.extMap['max']?.toString() ?? "") ?? - 9999; + min = int.tryParse(widget.rangeEntity.extMap['min']?.toString() ?? '') ?? 0; + max = int.tryParse(widget.rangeEntity.extMap['max']?.toString() ?? '') ?? 9999; ///处理的逻辑: /// 1:将输入框的 文本写入 customMap中 /// 2:如果最大值和最小值满足条件 则将range选中 minController.addListener(() { - String maxInput = maxController.text ?? ""; - String minInput = minController.text ?? ""; + String maxInput = maxController.text; + String minInput = minController.text; - widget.rangeEntity.customMap['min'] = minInput; + widget.rangeEntity.customMap!['min'] = minInput; if (minInput.isNotEmpty && maxInput.isNotEmpty) { - int inputMin = int.tryParse(minController.text ?? ""); - int inputMax = int.tryParse(maxController.text ?? ""); + int? inputMin = int.tryParse(minController.text); + int? inputMax = int.tryParse(maxController.text); if (inputMin != null && inputMin >= min && @@ -520,13 +498,13 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { }); maxController.addListener(() { - String maxInput = maxController.text ?? ""; - String minInput = minController.text ?? ""; - widget.rangeEntity.customMap['max'] = maxInput; + String maxInput = maxController.text; + String minInput = minController.text; + widget.rangeEntity.customMap!['max'] = maxInput; if (minInput.isNotEmpty && maxInput.isNotEmpty) { - int inputMin = int.tryParse(minController.text ?? "") ?? -1; - int inputMax = int.tryParse(maxController.text ?? "") ?? -1; + int inputMin = int.tryParse(minController.text) ?? -1; + int inputMax = int.tryParse(maxController.text) ?? -1; if (inputMin >= min && inputMax <= max && inputMin <= inputMax) { widget.rangeEntity.isSelected = true; } else { @@ -542,21 +520,19 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { /// 如果是多选 则不处理 minFocusNode.addListener(() { if (minFocusNode.hasFocus) { - widget.streamController - .add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); + widget.streamController?.add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); } }); maxFocusNode.addListener(() { if (maxFocusNode.hasFocus) { - widget.streamController - .add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); + widget.streamController?.add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); } }); ///用于监听tab的点击事件 ///如果父亲是单选 则将输入框清空并失去焦点,并且将自定义筛选设置为 未选中,以及更新用于显示的map - widget.streamController.stream.listen((event) { + widget.streamController?.stream.listen((event) { if (event is SelectEvent) { maxController.clear(); minController.clear(); @@ -574,8 +550,7 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.center, children: [ - _buildRangeField( - '最小值', minController, minFocusNode, widget.width, widget.themeData), + _buildRangeField('最小值', minController, minFocusNode, widget.width, widget.themeData), Padding( padding: EdgeInsets.only(left: 2), ), @@ -587,8 +562,7 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { Padding( padding: EdgeInsets.only(right: 2), ), - _buildRangeField( - '最大值', maxController, maxFocusNode, widget.width, widget.themeData), + _buildRangeField('最大值', maxController, maxFocusNode, widget.width, widget.themeData), ], ); } @@ -602,8 +576,7 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { ) { return Container( decoration: BoxDecoration( - color: Color(0xFFF9F9F9), - borderRadius: BorderRadius.all(Radius.circular(4.0))), + color: Color(0xFFF9F9F9), borderRadius: BorderRadius.all(Radius.circular(4.0))), height: 32, width: width, child: Center( @@ -624,15 +597,13 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { } /// 浮层类型的项 : 标题 + 点击跳转的layout -// ignore: must_be_immutable class FilterLayerTypeWidget extends StatefulWidget { //entity是 商圈 final BrnSelectionEntity selectionEntity; - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; - BrnSelectionConfig themeData; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; + final BrnSelectionConfig themeData; - FilterLayerTypeWidget( - {this.selectionEntity, this.onCustomFloatingLayerClick, this.themeData}); + FilterLayerTypeWidget({required this.selectionEntity, this.onCustomFloatingLayerClick, required this.themeData}); @override _FilterLayerTypeWidgetState createState() => _FilterLayerTypeWidgetState(); @@ -641,7 +612,7 @@ class FilterLayerTypeWidget extends StatefulWidget { class _FilterLayerTypeWidgetState extends State { @override Widget build(BuildContext context) { - widget.selectionEntity?.configDefaultValue(); + widget.selectionEntity.configDefaultValue(); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ @@ -656,8 +627,7 @@ class _FilterLayerTypeWidgetState extends State { padding: const EdgeInsets.only(left: 20, right: 20, top: 6), child: GestureDetector( onTap: () { - if (widget.selectionEntity.filterType == - BrnSelectionFilterType.Layer) { + if (widget.selectionEntity.filterType == BrnSelectionFilterType.layer) { Navigator.of(context) .push(PageRouteBuilder( opaque: false, @@ -670,22 +640,18 @@ class _FilterLayerTypeWidgetState extends State { .then((data) { updateContent(); }); - } else if (widget.selectionEntity.filterType == - BrnSelectionFilterType.CustomLayer) { + } else if (widget.selectionEntity.filterType == BrnSelectionFilterType.customLayer) { if (widget.onCustomFloatingLayerClick != null) { int entityIndex = -1; if (widget.selectionEntity.parent != null && - widget.selectionEntity.parent.children != null) { - entityIndex = widget.selectionEntity.parent.children - .indexOf(widget.selectionEntity); + widget.selectionEntity.parent!.children.isNotEmpty) { + entityIndex = + widget.selectionEntity.parent!.children.indexOf(widget.selectionEntity); } - widget.onCustomFloatingLayerClick( - entityIndex, widget.selectionEntity, + widget.onCustomFloatingLayerClick!(entityIndex, widget.selectionEntity, (List customFloatingLayerParams) { - widget.selectionEntity.children?.clear(); - widget.selectionEntity.children = []; - widget.selectionEntity.children - .addAll(customFloatingLayerParams); + widget.selectionEntity.children.clear(); + widget.selectionEntity.children.addAll(customFloatingLayerParams); widget.selectionEntity.configDefaultValue(); setState(() {}); }); @@ -699,13 +665,12 @@ class _FilterLayerTypeWidgetState extends State { child: Text(isEmptyCondition() ? '请选择' : getCondition(), style: isEmptyCondition() ? widget.themeData.hintTextStyle.generateTextStyle() - : widget.themeData.optionTextStyle - .generateTextStyle()), + : widget.themeData.optionTextStyle.generateTextStyle()), ), Container( height: 16, width: 16, - child: BrunoTools.getAssetImage(BrnAsset.ICON_RIGHT_ARROW), + child: BrunoTools.getAssetImage(BrnAsset.iconRightArrow), ) ], ), @@ -722,14 +687,13 @@ class _FilterLayerTypeWidgetState extends State { bool isEmptyCondition() { String condition = getCondition(); - return condition == null || condition.isEmpty; + return condition.isEmpty; } String getCondition() { String tmp = ""; //返回所有选中的 - List selectedList = - widget.selectionEntity.selectedList(); + List selectedList = widget.selectionEntity.selectedList(); //判断步骤: //第一步:取出来所有选中的: 房山 不限 小白楼 西城 不限 @@ -773,5 +737,5 @@ class InputEvent extends Event { BrnSelectionEntity rangeEntity; bool filter; - InputEvent({this.rangeEntity, this.filter}); + InputEvent({required this.rangeEntity, required this.filter}); } diff --git a/lib/src/components/selection/widget/brn_layer_more_selection_page.dart b/lib/src/components/selection/widget/brn_layer_more_selection_page.dart index 06ec0098..f345c1cb 100644 --- a/lib/src/components/selection/widget/brn_layer_more_selection_page.dart +++ b/lib/src/components/selection/widget/brn_layer_more_selection_page.dart @@ -6,7 +6,6 @@ import 'package:bruno/src/components/toast/brn_toast.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_selection_config.dart'; -import 'package:bruno/src/theme/img/brn_theme_default_utils.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -14,48 +13,47 @@ import 'package:flutter/services.dart'; /// 用于展示浮层的筛选项 如商圈 /// 左侧是:二级筛选项 右侧是三级筛选项 /// 默认将第一个元素选中 -// ignore: must_be_immutable class BrnLayerMoreSelectionPage extends StatefulWidget { - //entity是商圈 final BrnSelectionEntity entityData; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; - BrnLayerMoreSelectionPage({this.entityData, this.themeData}); + BrnLayerMoreSelectionPage({ + Key? key, + required this.entityData, + required this.themeData, + }): super(key: key); @override - _BrnLayerMoreSelectionPageState createState() => - _BrnLayerMoreSelectionPageState(); + _BrnLayerMoreSelectionPageState createState() => _BrnLayerMoreSelectionPageState(); } class _BrnLayerMoreSelectionPageState extends State with SingleTickerProviderStateMixin { - List firstList; + List _firstList = []; - List _originalSelectedItemsList; + late List _originalSelectedItemsList; ///当前选中的 一级筛选条件 - BrnSelectionEntity currentFirstEntity; + BrnSelectionEntity? _currentFirstEntity; ///当前选中的 一级筛选条件的索引 - int currentIndex; + int _currentIndex = 0; - AnimationController _controller; - Animation animation; + late AnimationController _controller; + late Animation _animation; @override void initState() { super.initState(); - + WidgetsBinding.instance?.addPostFrameCallback((_) { + SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark); + }); _controller = AnimationController( duration: const Duration(milliseconds: 300), vsync: this, ); - animation = - Tween(end: Offset.zero, begin: Offset(1.0, 0.0)).animate(_controller); + _animation = Tween(end: Offset.zero, begin: Offset(1.0, 0.0)).animate(_controller); _controller.forward(); - - currentIndex = 0; - firstList = List(); _originalSelectedItemsList = widget.entityData.selectedList(); _initData(); @@ -63,9 +61,6 @@ class _BrnLayerMoreSelectionPageState extends State @override Widget build(BuildContext context) { - WidgetsBinding.instance.addPostFrameCallback((_) { - SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark); - }); return Scaffold( backgroundColor: Colors.transparent, body: Row( @@ -75,7 +70,7 @@ class _BrnLayerMoreSelectionPageState extends State animation: _controller, builder: (context, child) { return SlideTransition( - position: animation, + position: _animation, child: child, ); }, @@ -89,7 +84,7 @@ class _BrnLayerMoreSelectionPageState extends State @override void dispose() { super.dispose(); - _controller?.dispose(); + _controller.dispose(); } ///左侧是黑色浮层 @@ -130,10 +125,7 @@ class _BrnLayerMoreSelectionPageState extends State leading: IconButton( icon: Icon( Icons.arrow_back, - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBase, + color: BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase, ), onPressed: () { //将选中的筛选项返回 @@ -148,10 +140,7 @@ class _BrnLayerMoreSelectionPageState extends State title: Text( '选择${widget.entityData.title}', style: TextStyle( - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBase, + color: BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBase, fontSize: 16, fontWeight: FontWeight.w600), ), @@ -189,7 +178,7 @@ class _BrnLayerMoreSelectionPageState extends State itemBuilder: (context, index) { return _buildRightItem(index); }, - itemCount: currentFirstEntity.children.length, + itemCount: _currentFirstEntity?.children.length ?? 0, ), ), ) @@ -209,45 +198,46 @@ class _BrnLayerMoreSelectionPageState extends State // 如果是选中的情况,则将已选中的兄弟节点清除 // 如果是未选的情况,则直接选中 - if (index == currentIndex) { + if (index == _currentIndex) { return; } - if (firstList[index].filterType == BrnSelectionFilterType.Radio) { + if (_firstList[index].filterType == BrnSelectionFilterType.radio) { setState(() { - currentIndex = index; - currentFirstEntity = firstList[index]; - if (currentFirstEntity.isSelected) { - currentFirstEntity.clearSelectedEntity(); - } else { - currentFirstEntity.parent.clearSelectedEntity(); - //设置不限 - setInitialSecondShowingItem(); + _currentIndex = index; + _currentFirstEntity = _firstList[index]; + if (_currentFirstEntity != null) { + if (_currentFirstEntity!.isSelected) { + _currentFirstEntity!.clearSelectedEntity(); + } else { + _currentFirstEntity!.parent?.clearSelectedEntity(); + //设置不限 + setInitialSecondShowingItem(_currentFirstEntity!); + } } }); } else { - firstList[index].parent?.children?.where((data) { - return data.filterType != BrnSelectionFilterType.Checkbox; - })?.forEach((data) { + _firstList[index].parent?.children.where((data) { + return data.filterType != BrnSelectionFilterType.checkbox; + }).forEach((data) { data.isSelected = false; data.clearChildSelection(); }); - if (!this.firstList[index].isSelected) { - if (!BrnSelectionUtil.checkMaxSelectionCount( - firstList[index])) { + if (!this._firstList[index].isSelected) { + if (!BrnSelectionUtil.checkMaxSelectionCount(_firstList[index])) { BrnToast.show('您选择的筛选条件数量已达上限', context); setState(() {}); return; } else { - currentIndex = index; - currentFirstEntity = firstList[index]; + _currentIndex = index; + _currentFirstEntity = _firstList[index]; //一级选中的情况,初始化二级 - setInitialSecondShowingItem(); + setInitialSecondShowingItem(_currentFirstEntity!); setState(() {}); } } else { - currentIndex = index; - currentFirstEntity = firstList[index]; + _currentIndex = index; + _currentFirstEntity = _firstList[index]; setState(() {}); } } @@ -255,7 +245,7 @@ class _BrnLayerMoreSelectionPageState extends State child: _buildLeftItem(index), ); }, - itemCount: firstList.length, + itemCount: _firstList.length, ); } @@ -300,20 +290,18 @@ class _BrnLayerMoreSelectionPageState extends State Widget _buildLeftItem(int index) { //如果房山 被选中了或者房山处于正在选择的状态 则加粗 - TextStyle textStyle = - widget.themeData.flayNormalTextStyle.generateTextStyle(); - if (index == currentIndex) { - textStyle = widget.themeData.flatSelectedTextStyle.generateTextStyle(); - } else if ((firstList[index].isSelected) && - firstList[index].selectedList().isNotEmpty) { - textStyle = widget.themeData.flatBoldTextStyle.generateTextStyle(); + TextStyle textStyle = widget.themeData.flayerNormalTextStyle.generateTextStyle(); + if (index == _currentIndex) { + textStyle = widget.themeData.flayerSelectedTextStyle.generateTextStyle(); + } else if ((_firstList[index].isSelected) && _firstList[index].selectedList().isNotEmpty) { + textStyle = widget.themeData.flayerBoldTextStyle.generateTextStyle(); } - List list = firstList[index].selectedList(); + List list = _firstList[index].selectedList(); //如果选中了不限 则展示 房山全部 //如果选中了某几个 // 如果可以跨区域 则显示数量 否则只加粗 - String name = firstList[index].title; + String name = _firstList[index].title; if (list.isNotEmpty) { if (list.every((data) { @@ -321,12 +309,11 @@ class _BrnLayerMoreSelectionPageState extends State })) { name += '(全部)'; } else { - bool containsCheck = firstList[index].hasCheckBoxBrother(); + bool containsCheck = _firstList[index].hasCheckBoxBrother(); bool containsCheckChildren = false; - if (firstList[index].children.isNotEmpty) { - containsCheckChildren = - firstList[index].children[0].hasCheckBoxBrother(); + if (_firstList[index].children.isNotEmpty) { + containsCheckChildren = _firstList[index].children[0].hasCheckBoxBrother(); } if (containsCheck && containsCheckChildren) { name += '(${list.length})'; @@ -336,7 +323,7 @@ class _BrnLayerMoreSelectionPageState extends State return Container( alignment: Alignment.centerLeft, height: 48, - color: index == currentIndex ? Colors.white : Color(0xff8F8F8), + color: index == _currentIndex ? Colors.white : Color(0xff8F8F8), child: Padding( padding: const EdgeInsets.only(left: 20), child: Text( @@ -348,41 +335,41 @@ class _BrnLayerMoreSelectionPageState extends State } Widget _buildRightItem(int index) { - bool isSingle = (currentFirstEntity.children[index].filterType == - BrnSelectionFilterType.Radio) || - (currentFirstEntity.children[index].filterType == - BrnSelectionFilterType.UnLimit); + bool isSingle = + (_currentFirstEntity?.children[index].filterType == BrnSelectionFilterType.radio) || + (_currentFirstEntity?.children[index].filterType == BrnSelectionFilterType.unLimit); return GestureDetector( onTap: () { setState(() { - if (isSingle) { - currentFirstEntity.clearSelectedEntity(); - currentFirstEntity.isSelected = true; - currentFirstEntity.children[index].isSelected = true; - //Navigator.pop(context, widget.entityData); - } else { - currentFirstEntity.children?.where((data) { - return data.filterType != BrnSelectionFilterType.Checkbox; - })?.forEach((data) { - data.isSelected = false; - }); - if (!currentFirstEntity.children[index].isSelected) { - if (!BrnSelectionUtil.checkMaxSelectionCount( - this.currentFirstEntity.children[index])) { - BrnToast.show('您选择的筛选条件数量已达上限', context); - return; + if (_currentFirstEntity != null) { + if (isSingle) { + _currentFirstEntity!.clearSelectedEntity(); + _currentFirstEntity!.isSelected = true; + _currentFirstEntity!.children[index].isSelected = true; + } else { + _currentFirstEntity!.children.where((data) { + return data.filterType != BrnSelectionFilterType.checkbox; + }).forEach((data) { + data.isSelected = false; + }); + if (!_currentFirstEntity!.children[index].isSelected) { + if (!BrnSelectionUtil.checkMaxSelectionCount( + this._currentFirstEntity!.children[index])) { + BrnToast.show('您选择的筛选条件数量已达上限', context); + return; + } } + this._currentFirstEntity!.children[index].isSelected = + !this._currentFirstEntity!.children[index].isSelected; } - this.currentFirstEntity.children[index].isSelected = - !this.currentFirstEntity.children[index].isSelected; - } - //如果二级没有任何选中的,那么一级为不选中 - if (currentFirstEntity.selectedList().isEmpty) { - currentFirstEntity.isSelected = false; - } else { - currentFirstEntity.isSelected = true; + //如果二级没有任何选中的,那么一级为不选中 + if (_currentFirstEntity!.selectedList().isEmpty) { + _currentFirstEntity!.isSelected = false; + } else { + _currentFirstEntity!.isSelected = true; + } } }); }, @@ -393,8 +380,8 @@ class _BrnLayerMoreSelectionPageState extends State child: Padding( padding: const EdgeInsets.only(left: 20, right: 20), child: isSingle - ? _buildRightSingleItem(currentFirstEntity.children[index]) - : _buildRightMultiItem(currentFirstEntity.children[index]), + ? _buildRightSingleItem(_currentFirstEntity?.children[index]) + : _buildRightMultiItem(_currentFirstEntity?.children[index]), ), ), ); @@ -402,61 +389,71 @@ class _BrnLayerMoreSelectionPageState extends State void _initData() { //填充一级筛选数据 - firstList = widget.entityData.children ?? List(); + _firstList = widget.entityData.children; //找到一级需要显示 的索引 - for (int i = 0; i < firstList.length; i++) { - if (firstList[i].selectedList().isNotEmpty) { - firstList[i].isSelected = true; + for (int i = 0; i < _firstList.length; i++) { + if (_firstList[i].selectedList().isNotEmpty) { + _firstList[i].isSelected = true; } } - currentIndex = firstList.indexWhere((data) { + _currentIndex = _firstList.indexWhere((data) { return data.isSelected; }); - if (currentIndex >= firstList.length || currentIndex == -1) { - currentIndex = 0; + if (_currentIndex >= _firstList.length || _currentIndex == -1) { + _currentIndex = 0; } //当前选中的一级筛选条件 - currentFirstEntity = firstList[currentIndex]; - currentFirstEntity.isSelected = true; + _currentFirstEntity = _firstList[_currentIndex]; + _currentFirstEntity?.isSelected = true; //找到第二级需要默认选中的索引 - setInitialSecondShowingItem(); + if (_currentFirstEntity != null) { + setInitialSecondShowingItem(_currentFirstEntity!); + } } - Widget _buildRightMultiItem(BrnSelectionEntity tmp) { - return Row( - children: [ - Expanded( - child: Text( - tmp.title.toString(), - style: tmp.isSelected - ? widget.themeData.flatSelectedTextStyle.generateTextStyle() - : widget.themeData.flayNormalTextStyle.generateTextStyle(), + Widget _buildRightMultiItem(BrnSelectionEntity? entity) { + if (entity == null) { + return SizedBox.shrink(); + } else { + return Row( + children: [ + Expanded( + child: Text( + entity.title, + style: entity.isSelected + ? widget.themeData.flayerSelectedTextStyle.generateTextStyle() + : widget.themeData.flayerNormalTextStyle.generateTextStyle(), + ), ), - ), - Container( - height: 16, - width: 16, - child: tmp.isSelected - ? BrnThemeImg.instance.CHECKED_STATUS + Container( + height: 16, + width: 16, + child: entity.isSelected + ? BrunoTools.getAssetImageWithBandColor(BrnAsset.selectCheckedStatus) : BrunoTools.getAssetImage(BrnAsset.iconUnSelect), - ) - ], - ); + ) + ], + ); + } } - Widget _buildRightSingleItem(BrnSelectionEntity tmp) { - return Text(tmp.title.toString(), - textAlign: TextAlign.left, - style: tmp.isSelected - ? widget.themeData.flatSelectedTextStyle.generateTextStyle() - : widget.themeData.flayNormalTextStyle.generateTextStyle()); + Widget _buildRightSingleItem(BrnSelectionEntity? entity) { + if (entity == null) { + return SizedBox.shrink(); + } else { + return Text(entity.title, + textAlign: TextAlign.left, + style: entity.isSelected + ? widget.themeData.flayerSelectedTextStyle.generateTextStyle() + : widget.themeData.flayerNormalTextStyle.generateTextStyle()); + } } //初始化二级的选中(小白楼) //规则:如果二级没有选中的,那么 选中二级的不限 - void setInitialSecondShowingItem() { + void setInitialSecondShowingItem(BrnSelectionEntity currentFirstEntity) { //设置初始化的二级筛选条件 -1没有 int secondIndex = currentFirstEntity.getFirstSelectedChildIndex(); @@ -464,7 +461,7 @@ class _BrnLayerMoreSelectionPageState extends State if (secondIndex == -1 && currentFirstEntity.children.isNotEmpty) { for (int i = 0, n = currentFirstEntity.children.length; i < n; i++) { if (currentFirstEntity.children[i].isUnLimit() && - currentFirstEntity.filterType == BrnSelectionFilterType.Checkbox) { + currentFirstEntity.filterType == BrnSelectionFilterType.checkbox) { currentFirstEntity.children[i].isSelected = true; break; } diff --git a/lib/src/components/selection/widget/brn_selection_animate_widget.dart b/lib/src/components/selection/widget/brn_selection_animate_widget.dart index 1683a157..88516ae1 100644 --- a/lib/src/components/selection/widget/brn_selection_animate_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_animate_widget.dart @@ -8,38 +8,33 @@ class BrnSelectionAnimationWidget extends StatefulWidget { final Widget view; final int animationMilliseconds; - const BrnSelectionAnimationWidget( - {Key key, - @required this.controller, - @required this.view, - this.animationMilliseconds = 100}) - : super(key: key); + const BrnSelectionAnimationWidget({ + Key? key, + required this.controller, + required this.view, + this.animationMilliseconds = 100, + }) : super(key: key); @override - _BrnSelectionAnimationWidgetState createState() => - _BrnSelectionAnimationWidgetState(); + _BrnSelectionAnimationWidgetState createState() => _BrnSelectionAnimationWidgetState(); } -class _BrnSelectionAnimationWidgetState - extends State +class _BrnSelectionAnimationWidgetState extends State with SingleTickerProviderStateMixin { bool _isControllerDisposed = false; - Animation _animation; - AnimationController _controller; + late AnimationController _animationController; @override void initState() { super.initState(); - widget.controller.addListener(_onController); - _controller = AnimationController( - duration: Duration(milliseconds: widget.animationMilliseconds), - vsync: this); + _animationController = AnimationController( + duration: Duration(milliseconds: widget.animationMilliseconds), vsync: this); } dispose() { - widget.controller?.removeListener(_onController); - _controller.dispose(); + widget.controller.removeListener(_onController); + _animationController.dispose(); _isControllerDisposed = true; super.dispose(); } @@ -50,30 +45,28 @@ class _BrnSelectionAnimationWidgetState @override Widget build(BuildContext context) { - _controller.duration = Duration(milliseconds: widget.animationMilliseconds); + _animationController.duration = Duration(milliseconds: widget.animationMilliseconds); return _buildListViewWidget(); } _showListViewWidget() { - if (widget.view == null) { - return; - } - - _animation = Tween( + Animation animation = Tween( begin: 0.0, - end: widget.controller.screenHeight - widget.controller.listViewTop) - .animate(_controller) + end: MediaQuery.of(context).size.height - (widget.controller.listViewTop ?? 0)) + .animate(_animationController) ..addListener(() { //这行如果不写,没有动画效果 setState(() {}); }); - if (_isControllerDisposed) return; + if (_isControllerDisposed) { + return; + } - if (_animation.status == AnimationStatus.completed) { - _controller.reverse(); + if (animation.status == AnimationStatus.completed) { + _animationController.reverse(); } else { - _controller.forward(); + _animationController.forward(); } } @@ -85,8 +78,7 @@ class _BrnSelectionAnimationWidgetState color: Color(0xB3000000), child: Container( width: MediaQuery.of(context).size.width, - height: MediaQuery.of(context).size.height - - widget.controller.listViewTop, + height: MediaQuery.of(context).size.height - (widget.controller.listViewTop ?? 0), child: Padding( padding: EdgeInsets.all(0), child: widget.view, diff --git a/lib/src/components/selection/widget/brn_selection_common_item_widget.dart b/lib/src/components/selection/widget/brn_selection_common_item_widget.dart index c4156d71..1feaa7d6 100644 --- a/lib/src/components/selection/widget/brn_selection_common_item_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_common_item_widget.dart @@ -8,43 +8,40 @@ import 'package:flutter/material.dart'; typedef void ItemSelectFunction(BrnSelectionEntity entity); -// ignore: must_be_immutable class BrnSelectionCommonItemWidget extends StatelessWidget { final BrnSelectionEntity item; - final Color backgroundColor; - final Color selectedBackgroundColor; + final Color? backgroundColor; + final Color? selectedBackgroundColor; final bool isCurrentFocused; final bool isFirstLevel; - final bool isMoreSelectionListType; - final ItemSelectFunction itemSelectFunction; + final ItemSelectFunction? itemSelectFunction; - BrnSelectionConfig themeData; + final BrnSelectionConfig? themeData; BrnSelectionCommonItemWidget({ - @required this.item, + Key? key, + required this.item, this.backgroundColor, this.isFirstLevel = false, this.isMoreSelectionListType = false, this.itemSelectFunction, this.selectedBackgroundColor, - this.isCurrentFocused, + this.isCurrentFocused = false, this.themeData, - }); + }): super(key: key); @override Widget build(BuildContext context) { var checkbox; - if (!item.isUnLimit() && - (item.children == null || item.children.length == 0)) { + if (!item.isUnLimit() && (item.children.length == 0)) { if (item.isInLastLevel() && item.hasCheckBoxBrother()) { checkbox = Container( padding: EdgeInsets.only(left: 6), width: 21, child: (item.isSelected) - ? BrunoTools.getAssetImageWithBandColor( - BrnAsset.iconMultiSelected) + ? BrunoTools.getAssetImageWithBandColor(BrnAsset.iconMultiSelected) : BrunoTools.getAssetImage(BrnAsset.iconUnSelect), ); } else { @@ -57,7 +54,7 @@ class BrnSelectionCommonItemWidget extends StatelessWidget { return GestureDetector( onTap: () { if (itemSelectFunction != null) { - itemSelectFunction(item); + itemSelectFunction!(item); } }, child: Container( @@ -88,14 +85,13 @@ class BrnSelectionCommonItemWidget extends StatelessWidget { Visibility( visible: !BrunoTools.isEmpty(item.subTitle), child: Padding( - padding: - EdgeInsets.only(right: item.isInLastLevel() ? 21 : 0), + padding: EdgeInsets.only(right: item.isInLastLevel() ? 21 : 0), child: BrnCSS2Text.toTextView(item.subTitle ?? '', defaultStyle: TextStyle( fontSize: 12, fontWeight: FontWeight.normal, decoration: TextDecoration.none, - color: themeData.commonConfig.colorTextSecondary), + color: themeData?.commonConfig.colorTextSecondary), maxLines: 1, textOverflow: TextOverflow.ellipsis), ), @@ -107,7 +103,7 @@ class BrnSelectionCommonItemWidget extends StatelessWidget { ); } - Color getItemBGColor() { + Color? getItemBGColor() { if (isCurrentFocused) { return this.selectedBackgroundColor; } else { @@ -135,28 +131,25 @@ class BrnSelectionCommonItemWidget extends StatelessWidget { } } - TextStyle getItemTextStyle() { + TextStyle? getItemTextStyle() { if (isHighLight(item)) { - return themeData.itemSelectedTextStyle.generateTextStyle(); + return themeData?.itemSelectedTextStyle.generateTextStyle(); } else if (isBold(item)) { - return themeData.itemBoldTextStyle.generateTextStyle(); + return themeData?.itemBoldTextStyle.generateTextStyle(); } - return themeData.itemNormalTextStyle.generateTextStyle(); + return themeData?.itemNormalTextStyle.generateTextStyle(); } String getSelectedItemCount(BrnSelectionEntity item) { String itemCount = ""; - if ((BrnSelectionUtil.getTotalLevel(item) < 3 || !isFirstLevel) && - item.children != null) { - int count = - item.children.where((f) => f.isSelected && !f.isUnLimit()).length; + if ((BrnSelectionUtil.getTotalLevel(item) < 3 || !isFirstLevel) && item.children.isNotEmpty) { + int count = item.children.where((f) => f.isSelected && !f.isUnLimit()).length; if (count > 1) { return '($count)'; } else if (count == 1 && item.hasCheckBoxBrother()) { return '($count)'; } else { - var unLimited = - item.children.where((f) => f.isSelected && f.isUnLimit()).toList(); + var unLimited = item.children.where((f) => f.isSelected && f.isUnLimit()).toList(); if (unLimited.length > 0) { return '(全部)'; } diff --git a/lib/src/components/selection/widget/brn_selection_date_range_item_widget.dart b/lib/src/components/selection/widget/brn_selection_date_range_item_widget.dart index 5684019f..e00fea96 100644 --- a/lib/src/components/selection/widget/brn_selection_date_range_item_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_date_range_item_widget.dart @@ -13,21 +13,15 @@ import 'package:flutter/services.dart'; typedef void OnRangeChangedFunction(String minInput, String maxInput); typedef void OnTappedFunction(); +const String _defaultDateFormat = 'yyyy年MM月dd日'; + // ignore: must_be_immutable class BrnSelectionDateRangeItemWidget extends StatefulWidget { final BrnSelectionEntity item; - /// 选中色 - final Color confirmColor; - - /// 背景色 - final Color backgroundColor; - /// 输入框显示文字大小 final double showTextSize; - final bool isShouldClearText; - /// 是否需要标题 final bool isNeedTitle; @@ -37,51 +31,43 @@ class BrnSelectionDateRangeItemWidget extends StatefulWidget { final TextEditingController minTextEditingController; final TextEditingController maxTextEditingController; - final OnTappedFunction onTapped; + final OnTappedFunction? onTapped; BrnSelectionConfig themeData; BrnSelectionDateRangeItemWidget( - {this.item, - @required this.minTextEditingController, - @required this.maxTextEditingController, - this.confirmColor, - this.backgroundColor = Colors.white, - this.isShouldClearText = false, + {Key? key, + required this.item, + required this.minTextEditingController, + required this.maxTextEditingController, this.isNeedTitle = true, this.showTextSize = 16, - this.dateFormat, + this.dateFormat = _defaultDateFormat, this.onTapped, - this.themeData}); + required this.themeData}) + : super(key: key); - _BrnSelectionDateRangeItemWidgetState createState() => - _BrnSelectionDateRangeItemWidgetState(); + _BrnSelectionDateRangeItemWidgetState createState() => _BrnSelectionDateRangeItemWidgetState(); } -class _BrnSelectionDateRangeItemWidgetState - extends State { - BrnSelectionDatePickerController _datePickerController = - BrnSelectionDatePickerController(); +class _BrnSelectionDateRangeItemWidgetState extends State { + BrnSelectionDatePickerController _datePickerController = BrnSelectionDatePickerController(); @override void initState() { var minDateTime; - if (widget.item.customMap != null && widget.item.customMap['min'] != null) { - minDateTime = DateTimeFormatter.convertIntValueToDateTime( - widget.item?.customMap['min']); + if (widget.item.customMap != null && widget.item.customMap!['min'] != null) { + minDateTime = DateTimeFormatter.convertIntValueToDateTime(widget.item.customMap!['min']); } var maxDateTime; - if (widget.item.customMap != null && widget.item.customMap['max'] != null) { - maxDateTime = DateTimeFormatter.convertIntValueToDateTime( - widget.item?.customMap['max']); + if (widget.item.customMap != null && widget.item.customMap!['max'] != null) { + maxDateTime = DateTimeFormatter.convertIntValueToDateTime(widget.item.customMap!['max']); } widget.minTextEditingController.text = minDateTime != null - ? DateTimeFormatter.formatDate(minDateTime, - widget.dateFormat ?? 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn) + ? DateTimeFormatter.formatDate(minDateTime, widget.dateFormat, DateTimePickerLocale.zh_cn) : ''; widget.maxTextEditingController.text = maxDateTime != null - ? DateTimeFormatter.formatDate(maxDateTime, - widget.dateFormat ?? 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn) + ? DateTimeFormatter.formatDate(maxDateTime, widget.dateFormat, DateTimePickerLocale.zh_cn) : ''; super.initState(); } @@ -89,7 +75,6 @@ class _BrnSelectionDateRangeItemWidgetState @override Widget build(BuildContext context) { return Container( - // color: widget.backgroundColor, child: Padding( padding: EdgeInsets.only(left: 20, right: 20, bottom: 20), child: Column( @@ -99,10 +84,9 @@ class _BrnSelectionDateRangeItemWidgetState margin: EdgeInsets.only(bottom: 5), alignment: Alignment.centerLeft, child: Text( - widget.item.title != null ? widget.item.title : '自定义区间', + widget.item.title.isEmpty ? '自定义区间' : widget.item.title, textAlign: TextAlign.left, - style: widget.themeData.rangeTitleTextStyle - ?.generateTextStyle(), + style: widget.themeData.rangeTitleTextStyle.generateTextStyle(), ), ) : Container(), @@ -112,7 +96,7 @@ class _BrnSelectionDateRangeItemWidgetState Container( child: Text( "至", - style: widget.themeData.inputTextStyle?.generateTextStyle(), + style: widget.themeData.inputTextStyle.generateTextStyle(), ), ), getDateRangeTextField(true), @@ -130,22 +114,22 @@ class _BrnSelectionDateRangeItemWidgetState enableInteractiveSelection: false, readOnly: true, onTap: () { - widget.onTapped(); + if (widget.onTapped != null) { + widget.onTapped!(); + } onTextTapped(isMax); }, - style: widget.themeData.inputTextStyle?.generateTextStyle(), + style: widget.themeData.inputTextStyle.generateTextStyle(), inputFormatters: [FilteringTextInputFormatter.digitsOnly], keyboardType: TextInputType.numberWithOptions(), onChanged: (input) { widget.item.isSelected = true; }, - controller: isMax - ? widget.maxTextEditingController - : widget.minTextEditingController, + controller: isMax ? widget.maxTextEditingController : widget.minTextEditingController, cursorColor: widget.themeData.commonConfig.brandPrimary, textAlign: TextAlign.center, decoration: InputDecoration( - hintStyle: widget.themeData.hintTextStyle?.generateTextStyle(), + hintStyle: widget.themeData.hintTextStyle.generateTextStyle(), hintText: (!isMax ? '开始日期' : '结束日期'), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( @@ -164,27 +148,24 @@ class _BrnSelectionDateRangeItemWidgetState } void onTextTapped(bool isMax) { - if (_datePickerController?.isShow ?? false) return; + if (_datePickerController.isShow) return; String format = 'yyyy年,MM月,dd日'; - DateTime minDate = DateTimeFormatter.convertIntValueToDateTime( - (widget.item?.extMap ?? Map())['min']); - DateTime maxDate = DateTimeFormatter.convertIntValueToDateTime( - (widget.item?.extMap ?? Map())['max']); + DateTime? minDate = + DateTimeFormatter.convertIntValueToDateTime((widget.item.extMap )['min']); + DateTime? maxDate = + DateTimeFormatter.convertIntValueToDateTime((widget.item.extMap)['max']); - DateTime minSelectedDateTime = BrunoTools.isEmpty(widget.item?.customMap) + DateTime? minSelectedDateTime = BrunoTools.isEmpty(widget.item.customMap) ? null - : DateTimeFormatter.convertIntValueToDateTime( - widget.item?.customMap['min']); - DateTime maxSelectedDateTime = BrunoTools.isEmpty(widget.item?.customMap) + : DateTimeFormatter.convertIntValueToDateTime(widget.item.customMap!['min']); + DateTime? maxSelectedDateTime = BrunoTools.isEmpty(widget.item.customMap) ? null - : DateTimeFormatter.convertIntValueToDateTime( - widget.item?.customMap['max']); + : DateTimeFormatter.convertIntValueToDateTime(widget.item.customMap!['max']); - DateTime _minDateTime; - DateTime _maxDateTime; - if (widget.item?.customMap == null || - (widget.item?.customMap['min'] == null && - widget.item?.customMap['max'] == null)) { + DateTime? _minDateTime; + DateTime? _maxDateTime; + if (widget.item.customMap == null || + (widget.item.customMap!['min'] == null && widget.item.customMap!['max'] == null)) { // 如果开始时间和结束时间均未选择 _minDateTime = minDate; _maxDateTime = maxDate; @@ -208,45 +189,38 @@ class _BrnSelectionDateRangeItemWidgetState }, onConfirm: (DateTime selectedDate, List selectedIndex) { widget.item.isSelected = true; - String selectedDateStr = DateTimeFormatter.formatDate(selectedDate, - widget.dateFormat ?? 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn); + String selectedDateStr = DateTimeFormatter.formatDate( + selectedDate, widget.dateFormat, DateTimePickerLocale.zh_cn); if (isMax) { widget.maxTextEditingController.text = selectedDateStr; } else { widget.minTextEditingController.text = selectedDateStr; } if (widget.item.customMap == null) { - widget.item.customMap = {}; + widget.item.customMap = Map(); } - widget.item.customMap[isMax ? 'max' : 'min'] = + widget.item.customMap![isMax ? 'max' : 'min'] = selectedDate.millisecondsSinceEpoch.toString(); closeSelectionPopupWindow(); - if (!isMax && - BrunoTools.isEmpty(widget.maxTextEditingController.text)) { + if (!isMax && BrunoTools.isEmpty(widget.maxTextEditingController.text)) { onTextTapped(true); } setState(() {}); }, ); - _datePickerController.screenHeight = MediaQuery.of(context).size.height; - _createDatePickerEntry(context, content); - Overlay.of(context).insert(_datePickerController.entry); + OverlayEntry entry = _createDatePickerEntry(context, content); + Overlay.of(context)?.insert(entry); + _datePickerController.entry = entry; _datePickerController.show(); } - void _createDatePickerEntry(BuildContext context, Widget content) { - OverlayEntry entry = OverlayEntry(builder: (context) { + OverlayEntry _createDatePickerEntry(BuildContext context, Widget content) { + return OverlayEntry(builder: (context) { return GestureDetector( onTap: () { closeSelectionPopupWindow(); }, -// onVerticalDragStart: (_) { -// closeSelectionPopupWindow(); -// }, -// onHorizontalDragStart: (_) { -// closeSelectionPopupWindow(); -// }, child: Container( color: Color(0xB3000000), height: MediaQuery.of(context).size.height, @@ -256,26 +230,18 @@ class _BrnSelectionDateRangeItemWidgetState ), ); }); - - _datePickerController.entry = entry; } void closeSelectionPopupWindow() { - if (_datePickerController?.isShow ?? false) { - _datePickerController?.isShow = false; - _datePickerController?.hide(); - _datePickerController?.entry?.remove(); - _datePickerController?.entry = null; + if (_datePickerController.isShow) { + _datePickerController.hide(); } } @override void dispose() { // TODO: implement dispose - _datePickerController?.isShow = false; - _datePickerController?.hide(); - _datePickerController?.entry?.remove(); - _datePickerController?.entry = null; + _datePickerController.hide(); super.dispose(); } } diff --git a/lib/src/components/selection/widget/brn_selection_datepicker_animate_widget.dart b/lib/src/components/selection/widget/brn_selection_datepicker_animate_widget.dart index a6c4b866..cb5d211f 100644 --- a/lib/src/components/selection/widget/brn_selection_datepicker_animate_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_datepicker_animate_widget.dart @@ -9,9 +9,9 @@ class BrnSelectionDatePickerAnimationWidget extends StatefulWidget { final int animationMilliseconds; const BrnSelectionDatePickerAnimationWidget( - {Key key, - @required this.controller, - @required this.view, + {Key? key, + required this.controller, + required this.view, this.animationMilliseconds = 100}) : super(key: key); @@ -24,8 +24,8 @@ class _BrnSelectionDatePickerAnimationWidgetState extends State with SingleTickerProviderStateMixin { bool _isControllerDisposed = false; - Animation _animation; - AnimationController _controller; + Animation? _animation; + late AnimationController _controller; @override void initState() { @@ -38,7 +38,7 @@ class _BrnSelectionDatePickerAnimationWidgetState } dispose() { - widget.controller?.removeListener(_onController); + widget.controller.removeListener(_onController); _controller.dispose(); _isControllerDisposed = true; super.dispose(); @@ -55,20 +55,16 @@ class _BrnSelectionDatePickerAnimationWidgetState } _showListViewWidget() { - if (widget.view == null) { - return; - } - - _animation = Tween(begin: widget.controller.screenHeight, end: 300.0) + _animation = Tween(begin: MediaQuery.of(context).size.height, end: 300.0) .animate(_controller) - ..addListener(() { - //这行如果不写,没有动画效果 - setState(() {}); - }); + ..addListener(() { + //这行如果不写,没有动画效果 + setState(() {}); + }); if (_isControllerDisposed) return; - if (_animation.status == AnimationStatus.completed) { + if (_animation!.status == AnimationStatus.completed) { _controller.reverse(); } else { _controller.forward(); diff --git a/lib/src/components/selection/widget/brn_selection_list_widget.dart b/lib/src/components/selection/widget/brn_selection_list_widget.dart index 72016083..2a716df4 100644 --- a/lib/src/components/selection/widget/brn_selection_list_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_list_widget.dart @@ -10,8 +10,7 @@ import 'package:bruno/src/theme/configs/brn_selection_config.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; -typedef void SingleListItemSelect( - int listIndex, int index, BrnSelectionEntity entity); +typedef void SingleListItemSelect(int listIndex, int index, BrnSelectionEntity entity); typedef void ListBgClickFunction(); @@ -20,19 +19,19 @@ class BrnListSelectionGroupWidget extends StatefulWidget { final BrnSelectionEntity entity; final double maxContentHeight; final bool showSelectedCount; - final ListBgClickFunction bgClickFunction; - final BrnOnRangeSelectionConfirm onSelectionConfirm; + final ListBgClickFunction? bgClickFunction; + final BrnOnRangeSelectionConfirm? onSelectionConfirm; BrnSelectionConfig themeData; - BrnListSelectionGroupWidget( - {Key key, - @required this.entity, - this.maxContentHeight = DESIGN_SELECTION_HEIGHT, - this.showSelectedCount = false, - this.bgClickFunction, - this.onSelectionConfirm, - this.themeData}) - : super(key: key); + BrnListSelectionGroupWidget({ + Key? key, + required this.entity, + this.maxContentHeight = DESIGN_SELECTION_HEIGHT, + this.showSelectedCount = false, + this.bgClickFunction, + this.onSelectionConfirm, + required this.themeData, + }) : super(key: key); @override _BrnSelectionGroupViewState createState() => _BrnSelectionGroupViewState(); @@ -41,13 +40,13 @@ class BrnListSelectionGroupWidget extends StatefulWidget { class _BrnSelectionGroupViewState extends State { final int maxShowCount = 6; - List _firstList = List(); - List _secondList = List(); - List _thirdList = List(); - List _originalSelectedItemsList = List(); - int _firstIndex; - int _secondIndex; - int _thirdIndex; + List _firstList = []; + List _secondList = []; + List _thirdList = []; + List _originalSelectedItemsList = []; + int _firstIndex = -1; + int _secondIndex = -1; + int _thirdIndex = -1; int totalLevel = 0; @@ -62,7 +61,7 @@ class _BrnSelectionGroupViewState extends State { @override void dispose() { if (!_isConfirmClick) { - _resetSelectionDatas(widget.entity); + _resetSelectionData(widget.entity); _restoreOriginalData(); } super.dispose(); @@ -89,22 +88,19 @@ class _BrnSelectionGroupViewState extends State { //pragma mark -- config widgets List _configWidgets() { - List widgetList = List(); + List widgetList = []; widgetList.add(_listWidget()); // TODO 判断是否添加 Bottom - if (_firstList != null) { - if (totalLevel == 1 && - widget.entity.filterType == BrnSelectionFilterType.Radio) { - } else { - widgetList.add(_bottomWidget()); - } + if (totalLevel == 1 && widget.entity.filterType == BrnSelectionFilterType.radio) { + } else { + widgetList.add(_bottomWidget()); } return widgetList; } Widget _listWidget() { - List widgets = List(); + List widgets = []; if (!BrunoTools.isEmpty(_firstList) && BrunoTools.isEmpty(_secondList) && @@ -114,16 +110,14 @@ class _BrnSelectionGroupViewState extends State { widgets.add(BrnSelectionSingleListWidget( items: _firstList, themeData: widget.themeData, - backgroundColor: getBgByListIndex(1), - selectedBackgroundColor: getSelectBgByListIndex(1), + backgroundColor: _getBgByListIndex(1), + selectedBackgroundColor: _getSelectBgByListIndex(1), maxHeight: widget.maxContentHeight, - flex: getFlexByListIndex(1), + flex: _getFlexByListIndex(1), focusedIndex: _firstIndex, - singleListItemSelect: - (int listIndex, int index, BrnSelectionEntity entity) { + singleListItemSelect: (int listIndex, int index, BrnSelectionEntity entity) { _setFirstIndex(index); - if (totalLevel == 1 && - widget.entity.filterType == BrnSelectionFilterType.Radio) { + if (totalLevel == 1 && widget.entity.filterType == BrnSelectionFilterType.radio) { _confirmButtonClickEvent(); } })); @@ -134,24 +128,22 @@ class _BrnSelectionGroupViewState extends State { widgets.add(BrnSelectionSingleListWidget( items: _firstList, themeData: widget.themeData, - backgroundColor: getBgByListIndex(1), - selectedBackgroundColor: getSelectBgByListIndex(1), - flex: getFlexByListIndex(1), + backgroundColor: _getBgByListIndex(1), + selectedBackgroundColor: _getSelectBgByListIndex(1), + flex: _getFlexByListIndex(1), focusedIndex: _firstIndex, - singleListItemSelect: - (int listIndex, int index, BrnSelectionEntity entity) { + singleListItemSelect: (int listIndex, int index, BrnSelectionEntity entity) { _setFirstIndex(index); })); widgets.add(BrnSelectionSingleListWidget( items: _secondList, themeData: widget.themeData, - backgroundColor: getBgByListIndex(2), - selectedBackgroundColor: getSelectBgByListIndex(2), - flex: getFlexByListIndex(2), + backgroundColor: _getBgByListIndex(2), + selectedBackgroundColor: _getSelectBgByListIndex(2), + flex: _getFlexByListIndex(2), focusedIndex: _secondIndex, - singleListItemSelect: - (int listIndex, int index, BrnSelectionEntity entity) { + singleListItemSelect: (int listIndex, int index, BrnSelectionEntity entity) { _setSecondIndex(index); })); } else if (!BrunoTools.isEmpty(_firstList) && @@ -161,35 +153,32 @@ class _BrnSelectionGroupViewState extends State { widgets.add(BrnSelectionSingleListWidget( items: _firstList, themeData: widget.themeData, - backgroundColor: getBgByListIndex(1), - selectedBackgroundColor: getSelectBgByListIndex(1), - flex: getFlexByListIndex(1), + backgroundColor: _getBgByListIndex(1), + selectedBackgroundColor: _getSelectBgByListIndex(1), + flex: _getFlexByListIndex(1), focusedIndex: _firstIndex, - singleListItemSelect: - (int listIndex, int index, BrnSelectionEntity entity) { + singleListItemSelect: (int listIndex, int index, BrnSelectionEntity entity) { _setFirstIndex(index); })); widgets.add(BrnSelectionSingleListWidget( items: _secondList, themeData: widget.themeData, - backgroundColor: getBgByListIndex(2), - selectedBackgroundColor: getSelectBgByListIndex(2), - flex: getFlexByListIndex(2), + backgroundColor: _getBgByListIndex(2), + selectedBackgroundColor: _getSelectBgByListIndex(2), + flex: _getFlexByListIndex(2), focusedIndex: _secondIndex, - singleListItemSelect: - (int listIndex, int index, BrnSelectionEntity entity) { + singleListItemSelect: (int listIndex, int index, BrnSelectionEntity entity) { _setSecondIndex(index); })); widgets.add(BrnSelectionSingleListWidget( items: _thirdList, themeData: widget.themeData, - backgroundColor: getBgByListIndex(3), - selectedBackgroundColor: getSelectBgByListIndex(3), - flex: getFlexByListIndex(3), + backgroundColor: _getBgByListIndex(3), + selectedBackgroundColor: _getSelectBgByListIndex(3), + flex: _getFlexByListIndex(3), focusedIndex: _thirdIndex, - singleListItemSelect: - (int listIndex, int index, BrnSelectionEntity entity) { + singleListItemSelect: (int listIndex, int index, BrnSelectionEntity entity) { if (entity.isSelected) { _thirdIndex = index; } else { @@ -213,7 +202,7 @@ class _BrnSelectionGroupViewState extends State { ), ), // 目前列表最大高度为 240,每个 Item 高度为 40。顾最大展示个数是 6,大于 6 则显示阴影。 - getMostListCount(widgets.length) > maxShowCount + _getListMaxCount(widgets.length) > maxShowCount ? IgnorePointer( child: Container( height: 40, @@ -258,13 +247,11 @@ class _BrnSelectionGroupViewState extends State { Container( height: 24, width: 24, - child: BrunoTools.getAssetImage( - BrnAsset.iconSelectionReset), + child: BrunoTools.getAssetImage(BrnAsset.iconSelectionReset), ), Text( "重置", - style: - widget.themeData.resetTextStyle.generateTextStyle(), + style: widget.themeData.resetTextStyle.generateTextStyle(), ) ], ), @@ -295,13 +282,12 @@ class _BrnSelectionGroupViewState extends State { _processFilterDataOnConfirm(); if (widget.onSelectionConfirm != null) { //更多和无tips等外部调用的多选需要传递此值selectedLastColumnArray - widget.onSelectionConfirm( - widget.entity, _firstIndex, _secondIndex, _thirdIndex); + widget.onSelectionConfirm!(widget.entity, _firstIndex, _secondIndex, _thirdIndex); } } void _clearAllSelectedItems() { - _resetSelectionDatas(widget.entity); + _resetSelectionData(widget.entity); setState(() { _configDefaultInitSelectIndex(); _refreshDataSource(); @@ -310,15 +296,14 @@ class _BrnSelectionGroupViewState extends State { //pragma mark -- private methods - // 初始化数据 - + /// 初始化数据 void _initData() { // 生成筛选节点树 _originalSelectedItemsList = widget.entity.selectedList(); for (BrnSelectionEntity entity in _originalSelectedItemsList) { entity.isSelected = true; if (entity.customMap != null) { - entity.originalCustomMap = Map.from(entity.customMap); + entity.originalCustomMap = Map.from(entity.customMap!); } } @@ -343,59 +328,55 @@ class _BrnSelectionGroupViewState extends State { if (_secondIndex >= 0 && _secondList.length > _secondIndex) { _thirdList = _secondList[_secondIndex].children; } else { - _thirdList = null; + _thirdList = []; } } else { - _secondList = null; - _thirdList = null; + _secondList = []; + _thirdList = []; } } void _configDefaultSelectedData() { _firstList = widget.entity.children; //是否已选择的item里面有第一列的 - if (_firstList == null) { + if (_firstList.isEmpty) { _secondIndex = -1; - _secondList = null; + _secondList = []; _thirdIndex = -1; - _thirdList = null; + _thirdList = []; return; } - _firstIndex = getInitialSelectIndex(_firstList); + _firstIndex = _getInitialSelectIndex(_firstList); if (_firstIndex >= 0 && _firstIndex < _firstList.length) { _secondList = _firstList[_firstIndex].children; - if (_secondList != null) { - _secondIndex = getInitialSelectIndex(_secondList); - } + _secondIndex = _getInitialSelectIndex(_secondList); } - if (_secondList == null) { + if (_secondList.isEmpty) { _thirdIndex = -1; - _thirdList = null; + _thirdList = []; return; } if (_secondIndex >= 0 && _secondIndex < _secondList.length) { _thirdList = _secondList[_secondIndex].children; - if (_thirdList != null) { - _thirdIndex = getInitialSelectIndex(_thirdList); + if (_thirdList.isNotEmpty) { + _thirdIndex = _getInitialSelectIndex(_thirdList); } } } ///还原数据选中状态 - void _resetSelectionDatas(BrnSelectionEntity entity) { + void _resetSelectionData(BrnSelectionEntity entity) { entity.isSelected = false; - entity.customMap = null; - if (BrnSelectionFilterType.Range == entity.filterType) { - entity.title = null; + entity.customMap = Map(); + if (BrnSelectionFilterType.range == entity.filterType) { + entity.title = ''; } - if (entity.children != null) { - for (BrnSelectionEntity subEntity in entity.children) { - _resetSelectionDatas(subEntity); - } + for (BrnSelectionEntity subEntity in entity.children) { + _resetSelectionData(subEntity); } } @@ -403,26 +384,18 @@ class _BrnSelectionGroupViewState extends State { void _restoreOriginalData() { for (BrnSelectionEntity commonEntity in _originalSelectedItemsList) { commonEntity.isSelected = true; - if (commonEntity.originalCustomMap != null) { - commonEntity.customMap = Map.from(commonEntity.originalCustomMap); - } + commonEntity.customMap = Map.from(commonEntity.originalCustomMap); } } - - //pragma mark -- getter and setter - + void _setFirstIndex(int firstIndex) { _firstIndex = firstIndex; _secondIndex = -1; if (widget.entity.children.length > _firstIndex) { - List seconds = - widget.entity.children[_firstIndex].children; - if (seconds != null) { - _secondIndex = getInitialSelectIndex(seconds); - - if (_secondIndex >= 0) { - _setSecondIndex(_secondIndex); - } + List seconds = widget.entity.children[_firstIndex].children; + _secondIndex = _getInitialSelectIndex(seconds); + if (_secondIndex >= 0) { + _setSecondIndex(_secondIndex); } } setState(() { @@ -433,12 +406,11 @@ class _BrnSelectionGroupViewState extends State { void _setSecondIndex(int secondIndex) { _secondIndex = secondIndex; _thirdIndex = -1; - List seconds = - widget.entity.children[_firstIndex].children; + List seconds = widget.entity.children[_firstIndex].children; if (seconds.length > _secondIndex) { List thirds = seconds[_secondIndex].children; - if (thirds != null) { - _thirdIndex = getInitialSelectIndex(thirds); + if (thirds.isNotEmpty) { + _thirdIndex = _getInitialSelectIndex(thirds); } } setState(() { @@ -446,9 +418,9 @@ class _BrnSelectionGroupViewState extends State { }); } - int getInitialSelectIndex(List levelList) { + int _getInitialSelectIndex(List levelList) { int index = -1; - if (levelList == null || levelList.length == 0) { + if (levelList.length == 0) { return index; } @@ -464,7 +436,7 @@ class _BrnSelectionGroupViewState extends State { for (BrnSelectionEntity entity in levelList) { if (entity.isUnLimit() && BrnSelectionUtil.getTotalLevel(entity) > 1 && - !entity.parent.hasCheckBoxBrother()) { + !(entity.parent?.hasCheckBoxBrother() ?? false)) { index = levelList.indexOf(entity); break; } @@ -476,7 +448,7 @@ class _BrnSelectionGroupViewState extends State { /// 默认占比为 1, /// 其中一列、两列情况下,占比都是 1 /// 当为三列数据时,占比随着 listIndex 增加而增大。为 3:3:4 比例水平占据屏幕 - int getFlexByListIndex(int listIndex) { + int _getFlexByListIndex(int listIndex) { int flex = 1; if (totalLevel == 1 || totalLevel == 2) { flex = 1; @@ -484,7 +456,7 @@ class _BrnSelectionGroupViewState extends State { if (listIndex == 1) { flex = 3; } else if (listIndex == 2) { - if (_thirdList == null) { + if (_thirdList.isEmpty) { flex = 7; } else { flex = 3; @@ -496,7 +468,7 @@ class _BrnSelectionGroupViewState extends State { return flex; } - Color getSelectBgByListIndex(int listIndex) { + Color _getSelectBgByListIndex(int listIndex) { Color deepSelectBgColor = widget.themeData.deepSelectBgColor; Color middleSelectBgColor = widget.themeData.middleSelectBgColor; Color lightSelectBgColor = widget.themeData.lightSelectBgColor; @@ -520,7 +492,7 @@ class _BrnSelectionGroupViewState extends State { return lightSelectBgColor; } - Color getBgByListIndex(int listIndex) { + Color _getBgByListIndex(int listIndex) { Color deepNormalBgColor = widget.themeData.deepNormalBgColor; Color middleNormalBgColor = widget.themeData.middleNormalBgColor; Color lightNormalBgColor = widget.themeData.lightNormalBgColor; @@ -549,7 +521,7 @@ class _BrnSelectionGroupViewState extends State { _resetSelectStatus(); if (widget.bgClickFunction != null) { //执行回调 - widget.bgClickFunction(); + widget.bgClickFunction!(); } } @@ -558,44 +530,37 @@ class _BrnSelectionGroupViewState extends State { //数据还原 for (BrnSelectionEntity commonEntity in _originalSelectedItemsList) { commonEntity.isSelected = true; - if (commonEntity.originalCustomMap != null) { - commonEntity.customMap = Map.from(commonEntity.originalCustomMap); - } + commonEntity.customMap = Map.from(commonEntity.originalCustomMap); } } /// 提交前对筛选数据做进一步处理, /// !!! 只有子筛选项存在被选中的 Item 才可以被设置为 true。 void _processFilterDataOnConfirm() { - if (widget.entity?.children != null) { - _processSelectedStatus(widget.entity); - } + _processSelectedStatus(widget.entity); } _processSelectedStatus(BrnSelectionEntity entity) { - if (entity != null && - entity.children != null && - entity.children.length > 0) { + if (entity.children.length > 0) { entity.children.forEach((f) => _processSelectedStatus(f)); if (entity.hasCheckBoxBrother()) { - entity.isSelected = - entity.children.where((_) => _.isSelected).length > 0; + entity.isSelected = entity.children.where((_) => _.isSelected).length > 0; } } } - int getMostListCount(int length) { + int _getListMaxCount(int length) { int mostCount = 0; if (length == 1) { - mostCount = _firstList?.length ?? 0; + mostCount = _firstList.length; } else if (length == 2) { - int firstCount = _firstList?.length ?? 0; - int secondCount = _secondList?.length ?? 0; + int firstCount = _firstList.length; + int secondCount = _secondList.length; mostCount = max(firstCount, secondCount); } else if (length == 3) { - int firstCount = _firstList?.length ?? 0; - int secondCount = _secondList?.length ?? 0; - int thirdCount = _secondList?.length ?? 0; + int firstCount = _firstList.length; + int secondCount = _secondList.length; + int thirdCount = _secondList.length; mostCount = max(firstCount, max(secondCount, thirdCount)); } return mostCount; diff --git a/lib/src/components/selection/widget/brn_selection_menu_item_widget.dart b/lib/src/components/selection/widget/brn_selection_menu_item_widget.dart index c9703753..cf74bb03 100644 --- a/lib/src/components/selection/widget/brn_selection_menu_item_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_menu_item_widget.dart @@ -9,19 +9,19 @@ typedef void ItemClickFunction(); class BrnSelectionMenuItemWidget extends StatelessWidget { final String title; final bool isHighLight; - final int index; final bool active; - final ItemClickFunction itemClickFunction; + final ItemClickFunction? itemClickFunction; BrnSelectionConfig themeData; BrnSelectionMenuItemWidget( - {@required this.title, + {Key? key, + required this.title, this.isHighLight = false, - this.index, this.active = false, this.itemClickFunction, - this.themeData}); + required this.themeData}) + : super(key: key); @override Widget build(BuildContext context) { @@ -45,8 +45,8 @@ class BrnSelectionMenuItemWidget extends StatelessWidget { maxLines: 1, softWrap: true, style: isHighLight - ? themeData.menuSelectedTextStyle?.generateTextStyle() - : themeData.menuNormalTextStyle?.generateTextStyle(), + ? themeData.menuSelectedTextStyle.generateTextStyle() + : themeData.menuNormalTextStyle.generateTextStyle(), ), )), Padding( @@ -54,16 +54,16 @@ class BrnSelectionMenuItemWidget extends StatelessWidget { child: isHighLight ? (active ? BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_ARROWUP_SELECT, + BrnAsset.iconArrowUpSelect, configId: themeData.configId) : BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_ARROWDOWN_SELECT)) + BrnAsset.iconArrowDownSelect)) : (active ? BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_ARROWUP_SELECT, + BrnAsset.iconArrowUpSelect, configId: themeData.configId) : BrunoTools.getAssetImage( - BrnAsset.ICON_ARROWDOWN_UNSELECT))) + BrnAsset.iconArrowDownUnSelect))) ], ), ), @@ -74,7 +74,7 @@ class BrnSelectionMenuItemWidget extends StatelessWidget { void _menuItemTapped() { if (this.itemClickFunction != null) { - this.itemClickFunction(); + this.itemClickFunction!(); } } } diff --git a/lib/src/components/selection/widget/brn_selection_menu_widget.dart b/lib/src/components/selection/widget/brn_selection_menu_widget.dart index fb3b6b66..b7a9d332 100644 --- a/lib/src/components/selection/widget/brn_selection_menu_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_menu_widget.dart @@ -2,46 +2,44 @@ import 'dart:async'; import 'package:bruno/src/components/picker/time_picker/brn_date_time_formatter.dart'; import 'package:bruno/src/components/selection/bean/brn_selection_common_entity.dart'; +import 'package:bruno/src/components/selection/brn_selection_util.dart'; import 'package:bruno/src/components/selection/brn_selection_view.dart'; import 'package:bruno/src/components/selection/controller/brn_selection_view_controller.dart'; -import 'package:bruno/src/components/selection/brn_selection_util.dart'; import 'package:bruno/src/components/selection/widget/brn_selection_animate_widget.dart'; import 'package:bruno/src/components/selection/widget/brn_selection_list_widget.dart'; import 'package:bruno/src/components/selection/widget/brn_selection_menu_item_widget.dart'; import 'package:bruno/src/components/selection/widget/brn_selection_range_widget.dart'; import 'package:bruno/src/theme/configs/brn_selection_config.dart'; -import 'package:bruno/src/utils/brn_tools.dart'; import 'package:bruno/src/utils/brn_event_bus.dart'; +import 'package:bruno/src/utils/brn_tools.dart'; import 'package:bruno/src/utils/i18n/brn_date_picker_i18n.dart'; import 'package:flutter/material.dart'; typedef bool BrnOnMenuItemClick(int index); -typedef void BrnOnRangeSelectionConfirm(BrnSelectionEntity results, - int firstIndex, int secondIndex, int thirdIndex); +typedef void BrnOnRangeSelectionConfirm( + BrnSelectionEntity results, int firstIndex, int secondIndex, int thirdIndex); class BrnSelectionMenuWidget extends StatefulWidget { final List data; final BuildContext context; final double height; - final double width; - final BrnOnRangeSelectionConfirm onConfirm; - final BrnOnMenuItemClick onMenuItemClick; - final BrnConfigTagCountPerRow configRowCount; + final double? width; + final BrnOnRangeSelectionConfirm? onConfirm; + final BrnOnMenuItemClick? onMenuItemClick; + final BrnConfigTagCountPerRow? configRowCount; ///筛选所在列表的外部列表滚动需要收起筛选,此处为最外层列表,有点恶心,但是暂时只想到这个方法,有更好方式的一定要告诉我 - final ScrollController extraScrollController; + final ScrollController? extraScrollController; ///指定筛选固定的相对于屏幕的顶部距离,默认null不指定 - final double constantTop; - - BrnSelectionViewController selectionViewController; + final double? constantTop; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; BrnSelectionMenuWidget( - {@required this.data, - @required this.context, + { Key? key,required this.context, + required this.data, this.height = 50.0, this.width, this.onMenuItemClick, @@ -49,8 +47,7 @@ class BrnSelectionMenuWidget extends StatefulWidget { this.configRowCount, this.extraScrollController, this.constantTop, - this.selectionViewController, - this.themeData}); + required this.themeData}): super(key: key); @override _BrnSelectionMenuWidgetState createState() => _BrnSelectionMenuWidgetState(); @@ -58,55 +55,46 @@ class BrnSelectionMenuWidget extends StatefulWidget { class _BrnSelectionMenuWidgetState extends State { bool _needRefreshTitle = true; - List result; - List titles = List(); - List menuItemActiveState = List(); - List menuItemHighlightState = List(); - BrnSelectionListViewController listViewController = - BrnSelectionListViewController(); - ScrollController _scrollController; + List result = []; + List titles = []; + List menuItemActiveState = []; + List menuItemHighlightState = []; + BrnSelectionListViewController listViewController = BrnSelectionListViewController(); + ScrollController? _scrollController; - StreamSubscription _refreshTitleSubscription; + late StreamSubscription _refreshTitleSubscription; - StreamSubscription _closeSelectionPopupWindowSubscription; + late StreamSubscription _closeSelectionPopupWindowSubscription; @override void initState() { super.initState(); - _refreshTitleSubscription = EventBus.instance - .on() - .listen((RefreshMenuTitleEvent event) { + _refreshTitleSubscription = + EventBus.instance.on().listen((RefreshMenuTitleEvent event) { _needRefreshTitle = true; setState(() {}); }); - _closeSelectionPopupWindowSubscription = EventBus.instance - .on() - .listen((CloseSelectionViewEvent event) { + _closeSelectionPopupWindowSubscription = + EventBus.instance.on().listen((CloseSelectionViewEvent event) { _closeSelectionPopupWindow(); }); if (widget.extraScrollController != null) { - _scrollController = widget.extraScrollController; - _scrollController.addListener(_closeSelectionPopupWindow); + _scrollController = widget.extraScrollController!; + _scrollController!.addListener(_closeSelectionPopupWindow); } - result = List(); - if (widget.data != null) { - for (BrnSelectionEntity parentEntity in widget.data) { - titles.add(parentEntity.title); - menuItemActiveState.add(false); - menuItemHighlightState.add(false); - } + for (BrnSelectionEntity parentEntity in widget.data) { + titles.add(parentEntity.title); + menuItemActiveState.add(false); + menuItemHighlightState.add(false); } } void _closeSelectionPopupWindow() { - if (listViewController?.isShow ?? false) { - listViewController.isShow = false; + if (listViewController.isShow) { listViewController.hide(); - listViewController.entry?.remove(); - listViewController.entry = null; setState(() { for (int i = 0; i < menuItemActiveState.length; i++) { if (i != listViewController.menuIndex) { @@ -124,50 +112,39 @@ class _BrnSelectionMenuWidgetState extends State { dispose() { _scrollController?.removeListener(_closeSelectionPopupWindow); - _refreshTitleSubscription?.cancel(); - _closeSelectionPopupWindowSubscription?.cancel(); - listViewController?.isShow = false; - listViewController?.hide(); - listViewController?.entry?.remove(); - listViewController?.entry = null; + _refreshTitleSubscription.cancel(); + _closeSelectionPopupWindowSubscription.cancel(); + listViewController.hide(); super.dispose(); } /// 根据【Filter组】 创建 widget。 - void _createEntry(BrnSelectionEntity entity) { - var content = isRange(entity) - ? _createRangeView(entity) - : _createSelectionListView(entity); - OverlayEntry entry = OverlayEntry(builder: (context) { + OverlayEntry _createEntry(BrnSelectionEntity entity) { + var content = _isRange(entity) ? _createRangeView(entity) : _createSelectionListView(entity); + return OverlayEntry(builder: (context) { return GestureDetector( onTap: () { _closeSelectionPopupWindow(); }, child: Container( padding: EdgeInsets.only( - top: listViewController.listViewTop, + top: listViewController.listViewTop ?? 0, ), child: Stack( children: [ - BrnSelectionAnimationWidget( - controller: listViewController, view: content) + BrnSelectionAnimationWidget(controller: listViewController, view: content) ], ), ), ); }); - - listViewController.screenHeight = MediaQuery.of(widget.context).size.height; - listViewController.entry = entry; } @override Widget build(BuildContext context) { return Container( height: widget.height, - width: (widget.width != null) - ? widget.width - : MediaQuery.of(context).size.width, + width: (widget.width != null) ? widget.width : MediaQuery.of(context).size.width, color: Colors.white, child: Column( mainAxisAlignment: MainAxisAlignment.start, @@ -192,13 +169,13 @@ class _BrnSelectionMenuWidgetState extends State { } List _configMenuItems() { - List itemViewList = List(); + List itemViewList = []; itemViewList.add(Padding( padding: EdgeInsets.only(left: 14), )); for (int index = 0; index < titles.length; index++) { if (_needRefreshTitle) { - refreshSelectionMenuTitle(index, widget.data[index]); + _refreshSelectionMenuTitle(index, widget.data[index]); if (index == titles.length - 1) { _needRefreshTitle = false; } @@ -210,49 +187,44 @@ class _BrnSelectionMenuWidgetState extends State { title: titles[index], themeData: widget.themeData, active: menuItemActiveState[index], - isHighLight: - menuItemActiveState[index] || menuItemHighlightState[index], + isHighLight: menuItemActiveState[index] || menuItemHighlightState[index], itemClickFunction: () { if (widget.onMenuItemClick != null) { /// 拦截 menuItem 点击。 - if (widget.onMenuItemClick(index)) { + if (widget.onMenuItemClick!(index)) { return; } } - final RenderBox dropDownItemRenderBox = context.findRenderObject(); - - var position = - dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: null); - var size = dropDownItemRenderBox.size; + RenderBox? dropDownItemRenderBox; + if (context.findRenderObject() != null && context.findRenderObject() is RenderBox) { + dropDownItemRenderBox = context.findRenderObject() as RenderBox; + } + Offset? position = dropDownItemRenderBox?.localToGlobal(Offset.zero, ancestor: null); + Size? size = dropDownItemRenderBox?.size; listViewController.listViewTop = - size.height + (widget.constantTop ?? position.dy); - if (listViewController.isShow && - listViewController.menuIndex != index) { + (size?.height ?? 0) + (widget.constantTop ?? position?.dy ?? 0); + if (listViewController.isShow && listViewController.menuIndex != index) { listViewController.hide(); - listViewController.entry?.remove(); - listViewController.entry = null; } if (listViewController.isShow) { listViewController.hide(); - listViewController.entry?.remove(); - listViewController.entry = null; } else { /// 点击不是 More、自定义类型,则直接展开。 - if (widget.data[index].filterType != BrnSelectionFilterType.More && - widget.data[index].filterType != - BrnSelectionFilterType.CustomHandle) { + if (widget.data[index].filterType != BrnSelectionFilterType.more && + widget.data[index].filterType != BrnSelectionFilterType.customHandle) { /// 创建 筛选组件的的入口 - _createEntry(widget.data[index]); - Overlay.of(widget.context).insert(listViewController.entry); + OverlayEntry entry = _createEntry(widget.data[index]); + Overlay.of(widget.context)?.insert(entry); + + listViewController.entry = entry; listViewController.show(index); - } else if (widget.data[index].filterType == - BrnSelectionFilterType.CustomHandle) { + } else if (widget.data[index].filterType == BrnSelectionFilterType.customHandle) { /// 记录自定义筛选 menu 的点击状态,当点击自定义的 menu 时,menu 文案默认高亮。 listViewController.show(index); - refreshSelectionMenuTitle(index, widget.data[index]); + _refreshSelectionMenuTitle(index, widget.data[index]); } else { - refreshSelectionMenuTitle(index, widget.data[index]); + _refreshSelectionMenuTitle(index, widget.data[index]); } } @@ -283,36 +255,31 @@ class _BrnSelectionMenuWidgetState extends State { /// 1、子筛选项包含自定义范围的时候,使用 Tag 模式展示。 /// 2、被指定为 Tag 模式展示。 /// 3、只有一列筛选数据,且为多选时,使用 Tag 模式展示 - bool isRange(BrnSelectionEntity entity) { - if (entity.children != null) { - if (BrnSelectionUtil.hasRangeItem(entity.children) || - entity.filterShowType == BrnSelectionWindowType.Range) { - return true; - } - var totalLevel = BrnSelectionUtil.getTotalLevel(entity); - if (totalLevel == 1 && - entity.filterType == BrnSelectionFilterType.Checkbox) { - return true; - } + bool _isRange(BrnSelectionEntity entity) { + if (BrnSelectionUtil.hasRangeItem(entity.children) || + entity.filterShowType == BrnSelectionWindowType.range) { + return true; + } + var totalLevel = BrnSelectionUtil.getTotalLevel(entity); + if (totalLevel == 1 && entity.filterType == BrnSelectionFilterType.checkbox) { + return true; } return false; } Widget _createRangeView(BrnSelectionEntity entity) { - int rowCount; + int? rowCount; if (widget.configRowCount != null) { - rowCount = widget.configRowCount(widget.data.indexOf(entity), entity) ?? - rowCount; + rowCount = widget.configRowCount!(widget.data.indexOf(entity), entity) ?? rowCount; } return BrnRangeSelectionGroupWidget( entity: entity, - marginTop: listViewController.listViewTop, - maxContentHeight: DESIGN_SELECTION_HEIGHT / - DESIGN_SCREEN_HEIGHT * - MediaQuery.of(context).size.height, + marginTop: listViewController.listViewTop ?? 0, + maxContentHeight: + DESIGN_SELECTION_HEIGHT / DESIGN_SCREEN_HEIGHT * MediaQuery.of(context).size.height, // UI 给出的内容高度比例 248:812 themeData: widget.themeData, - rowount: rowCount, + rowCount: rowCount, bgClickFunction: () { setState(() { menuItemActiveState[listViewController.menuIndex] = false; @@ -320,14 +287,12 @@ class _BrnSelectionMenuWidgetState extends State { menuItemHighlightState[listViewController.menuIndex] = true; } listViewController.hide(); - listViewController.entry?.remove(); - listViewController.entry = null; }); }, - onSelectionConfirm: (BrnSelectionEntity result, int firstIndex, - int secondIndex, int thirdIndex) { + onSelectionConfirm: + (BrnSelectionEntity result, int firstIndex, int secondIndex, int thirdIndex) { setState(() { - onConfirmSelect(entity, result, firstIndex, secondIndex, thirdIndex); + _onConfirmSelect(entity, result, firstIndex, secondIndex, thirdIndex); }); }, ); @@ -337,9 +302,8 @@ class _BrnSelectionMenuWidgetState extends State { /// 顶层筛选 Tab return BrnListSelectionGroupWidget( entity: entity, - maxContentHeight: DESIGN_SELECTION_HEIGHT / - DESIGN_SCREEN_HEIGHT * - MediaQuery.of(context).size.height, + maxContentHeight: + DESIGN_SELECTION_HEIGHT / DESIGN_SCREEN_HEIGHT * MediaQuery.of(context).size.height, themeData: widget.themeData, // UI 给出的内容高度比例 248:812 bgClickFunction: () { @@ -349,139 +313,119 @@ class _BrnSelectionMenuWidgetState extends State { menuItemHighlightState[listViewController.menuIndex] = true; } listViewController.hide(); - listViewController.entry?.remove(); - listViewController.entry = null; }); }, - onSelectionConfirm: (BrnSelectionEntity result, int firstIndex, - int secondIndex, int thirdIndex) { + onSelectionConfirm: + (BrnSelectionEntity result, int firstIndex, int secondIndex, int thirdIndex) { setState(() { - onConfirmSelect(entity, result, firstIndex, secondIndex, thirdIndex); + _onConfirmSelect(entity, result, firstIndex, secondIndex, thirdIndex); }); }, ); } - void onConfirmSelect(BrnSelectionEntity entity, BrnSelectionEntity result, - int firstIndex, int secondIndex, int thirdIndex) { + void _onConfirmSelect(BrnSelectionEntity entity, BrnSelectionEntity result, int firstIndex, + int secondIndex, int thirdIndex) { if (listViewController.menuIndex < titles.length) { if (widget.onConfirm != null) { - widget.onConfirm(result, firstIndex, secondIndex, thirdIndex); + widget.onConfirm!(result, firstIndex, secondIndex, thirdIndex); } menuItemActiveState[listViewController.menuIndex] = false; - refreshSelectionMenuTitle(listViewController.menuIndex, entity); + _refreshSelectionMenuTitle(listViewController.menuIndex, entity); listViewController.hide(); - listViewController.entry?.remove(); - listViewController.entry = null; } } /// 筛选 Title 展示规则 - String getSelectedResultTitle(BrnSelectionEntity entity) { + String? _getSelectedResultTitle(BrnSelectionEntity entity) { /// 更多筛选不改变 title.故返回 null - if (entity.filterType == BrnSelectionFilterType.More) { + if (entity.filterType == BrnSelectionFilterType.more) { return null; } if (BrunoTools.isEmpty(entity.customTitle)) { - return getTitle(entity); + return _getTitle(entity); } else { return entity.customTitle; } } - String getTitle(BrnSelectionEntity entity) { - String title; - if (entity != null) { - List firstColumn = - BrnSelectionUtil.currentSelectListForEntity(entity); - List secondColumn = List(); - List thirdColumn = List(); - if (firstColumn != null && firstColumn.length > 0) { - for (BrnSelectionEntity firstEntity in firstColumn) { - if (firstEntity != null) { - secondColumn.addAll( - BrnSelectionUtil.currentSelectListForEntity(firstEntity)); - if (secondColumn != null && secondColumn.length > 0) { - for (BrnSelectionEntity secondEntity in secondColumn) { - thirdColumn.addAll( - BrnSelectionUtil.currentSelectListForEntity(secondEntity)); - } - } + String? _getTitle(BrnSelectionEntity entity) { + String? title; + List firstColumn = BrnSelectionUtil.currentSelectListForEntity(entity); + List secondColumn = []; + List thirdColumn = []; + if (firstColumn.length > 0) { + for (BrnSelectionEntity firstEntity in firstColumn) { + secondColumn.addAll(BrnSelectionUtil.currentSelectListForEntity(firstEntity)); + if (secondColumn.length > 0) { + for (BrnSelectionEntity secondEntity in secondColumn) { + thirdColumn.addAll(BrnSelectionUtil.currentSelectListForEntity(secondEntity)); } } } + } - if (firstColumn.length == 0 || firstColumn.length > 1) { + if (firstColumn.length == 0 || firstColumn.length > 1) { + title = entity.title; + } else { + /// 第一列选中了一个,为【不限】类型,使用上一级别的名字展示。 + if (firstColumn[0].isUnLimit()) { title = entity.title; + } else if (firstColumn[0].filterType == BrnSelectionFilterType.range || + firstColumn[0].filterType == BrnSelectionFilterType.date || + firstColumn[0].filterType == BrnSelectionFilterType.dateRange || + firstColumn[0].filterType == BrnSelectionFilterType.dateRangeCalendar) { + title = _getDateAndRangeTitle(firstColumn, entity); } else { - /// 第一列选中了一个,为【不限】类型,使用上一级别的名字展示。 - if (firstColumn[0].isUnLimit()) { - title = entity.title; - } else if (firstColumn[0].filterType == BrnSelectionFilterType.Range || - firstColumn[0].filterType == BrnSelectionFilterType.Date || - firstColumn[0].filterType == BrnSelectionFilterType.DateRange || - firstColumn[0].filterType == - BrnSelectionFilterType.DateRangeCalendar) { - title = getDateAndRangeTitle(firstColumn, entity); + if (secondColumn.length == 0 || secondColumn.length > 1) { + title = firstColumn[0].title; } else { - if (secondColumn.length == 0 || secondColumn.length > 1) { + /// 第二列选中了一个,为【不限】类型,使用上一级别的名字展示。 + if (secondColumn[0].isUnLimit()) { title = firstColumn[0].title; + } else if (secondColumn[0].filterType == BrnSelectionFilterType.range || + secondColumn[0].filterType == BrnSelectionFilterType.date || + secondColumn[0].filterType == BrnSelectionFilterType.dateRange || + secondColumn[0].filterType == BrnSelectionFilterType.dateRangeCalendar) { + title = _getDateAndRangeTitle(secondColumn, firstColumn[0]); } else { - /// 第二列选中了一个,为【不限】类型,使用上一级别的名字展示。 - if (secondColumn[0].isUnLimit()) { - title = firstColumn[0].title; - } else if (secondColumn[0].filterType == - BrnSelectionFilterType.Range || - secondColumn[0].filterType == BrnSelectionFilterType.Date || - secondColumn[0].filterType == - BrnSelectionFilterType.DateRange || - secondColumn[0].filterType == - BrnSelectionFilterType.DateRangeCalendar) { - title = getDateAndRangeTitle(secondColumn, firstColumn[0]); + if (thirdColumn.length == 0 || thirdColumn.length > 1) { + title = secondColumn[0].title; } else { - if (thirdColumn.length == 0 || thirdColumn.length > 1) { + /// 第三列选中了一个,为【不限】类型,使用上一级别的名字展示。 + if (thirdColumn[0].isUnLimit()) { title = secondColumn[0].title; + } else if (thirdColumn[0].filterType == BrnSelectionFilterType.range || + thirdColumn[0].filterType == BrnSelectionFilterType.date || + thirdColumn[0].filterType == BrnSelectionFilterType.dateRange || + thirdColumn[0].filterType == BrnSelectionFilterType.dateRangeCalendar) { + title = _getDateAndRangeTitle(thirdColumn, secondColumn[0]); } else { - /// 第三列选中了一个,为【不限】类型,使用上一级别的名字展示。 - if (thirdColumn[0].isUnLimit()) { - title = secondColumn[0].title; - } else if (thirdColumn[0].filterType == - BrnSelectionFilterType.Range || - thirdColumn[0].filterType == BrnSelectionFilterType.Date || - thirdColumn[0].filterType == - BrnSelectionFilterType.DateRange || - thirdColumn[0].filterType == - BrnSelectionFilterType.DateRangeCalendar) { - title = getDateAndRangeTitle(thirdColumn, secondColumn[0]); - } else { - title = thirdColumn[0].title; - } + title = thirdColumn[0].title; } } } } } - String joinTitle = - getJoinTitle(entity, firstColumn, secondColumn, thirdColumn); - title = BrunoTools.isEmpty(joinTitle) ? title : joinTitle; } + String joinTitle = _getJoinTitle(entity, firstColumn, secondColumn, thirdColumn); + title = BrunoTools.isEmpty(joinTitle) ? title : joinTitle; return title; } - String getDateAndRangeTitle( - List list, BrnSelectionEntity entity) { - String title = ""; + String? _getDateAndRangeTitle(List list, BrnSelectionEntity entity) { + String? title = ''; if (!BrunoTools.isEmpty(list[0].customMap)) { - if (list[0].filterType == BrnSelectionFilterType.Range) { + if (list[0].filterType == BrnSelectionFilterType.range) { title = - '${list[0].customMap['min']}-${list[0].customMap['max']}(${list[0].extMap['unit']?.toString()})'; - } else if (list[0].filterType == BrnSelectionFilterType.DateRange || - list[0].filterType == BrnSelectionFilterType.DateRangeCalendar) { - title = getDateRangeTitle(list); + '${list[0].customMap!['min']}-${list[0].customMap!['max']}(${list[0].extMap['unit']?.toString()})'; + } else if (list[0].filterType == BrnSelectionFilterType.dateRange || + list[0].filterType == BrnSelectionFilterType.dateRangeCalendar) { + title = _getDateRangeTitle(list); } } else { - if (list[0].filterType == BrnSelectionFilterType.Date) { - title = getDateTimeTitle(list); + if (list[0].filterType == BrnSelectionFilterType.date) { + title = _getDateTimeTitle(list); } else { title = entity.title; } @@ -489,62 +433,60 @@ class _BrnSelectionMenuWidgetState extends State { return title; } - String getDateRangeTitle(List list) { - String minDateTime = ""; - String maxDateTime = ""; + String _getDateRangeTitle(List list) { + String minDateTime = ''; + String maxDateTime = ''; + if (list[0].customMap != null && - list[0].customMap['min'] != null && - int.tryParse(list[0].customMap['min']) != null) { - minDateTime = DateTimeFormatter.formatDate( - DateTimeFormatter.convertIntValueToDateTime(list[0].customMap['min']), - 'yyyy年MM月dd日', - DateTimePickerLocale.zh_cn); + list[0].customMap!['min'] != null && + int.tryParse(list[0].customMap!['min'] ?? '') != null) { + DateTime? minDate = DateTimeFormatter.convertIntValueToDateTime(list[0].customMap!['min']); + if (minDate != null) { + minDateTime = + DateTimeFormatter.formatDate(minDate, 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn); + } } if (list[0].customMap != null && - list[0].customMap['max'] != null && - int.tryParse(list[0].customMap['max']) != null) { - maxDateTime = DateTimeFormatter.formatDate( - DateTimeFormatter.convertIntValueToDateTime(list[0].customMap['max']), - 'yyyy年MM月dd日', - DateTimePickerLocale.zh_cn); + list[0].customMap!['max'] != null && + int.tryParse(list[0].customMap!['max'] ?? '') != null) { + DateTime? maxDate = DateTimeFormatter.convertIntValueToDateTime(list[0].customMap!['max']); + if (maxDate != null) { + maxDateTime = + DateTimeFormatter.formatDate(maxDate, 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn); + } } return '$minDateTime-$maxDateTime'; } - String getDateTimeTitle(List list) { - String title = ""; - int msDateTime = int.tryParse(list[0].value ?? ""); + String? _getDateTimeTitle(List list) { + String? title = ""; + int? msDateTime = int.tryParse(list[0].value ?? ''); title = msDateTime != null - ? DateTimeFormatter.formatDate( - DateTime.fromMillisecondsSinceEpoch(msDateTime), - 'yyyy年MM月dd日', - DateTimePickerLocale.zh_cn) + ? DateTimeFormatter.formatDate(DateTime.fromMillisecondsSinceEpoch(msDateTime), + 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn) : list[0].title; return title; } - String getJoinTitle( - BrnSelectionEntity entity, - List firstColumn, - List secondColumn, - List thirdColumn) { + String _getJoinTitle(BrnSelectionEntity entity, List firstColumn, + List secondColumn, List thirdColumn) { String title = ""; if (entity.canJoinTitle) { if (firstColumn.length == 1) { - title = firstColumn[0].title ?? ""; + title = firstColumn[0].title; } if (secondColumn.length == 1) { - title += secondColumn[0].title ?? ""; + title += secondColumn[0].title; } if (thirdColumn.length == 1) { - title += thirdColumn[0].title ?? ""; + title += thirdColumn[0].title; } } return title; } - void refreshSelectionMenuTitle(int index, BrnSelectionEntity entity) { - if (entity.filterType == BrnSelectionFilterType.More) { + void _refreshSelectionMenuTitle(int index, BrnSelectionEntity entity) { + if (entity.filterType == BrnSelectionFilterType.more) { if (entity.allSelectedList().length > 0) { menuItemHighlightState[index] = true; } else { @@ -552,7 +494,7 @@ class _BrnSelectionMenuWidgetState extends State { } return; } - String title = getSelectedResultTitle(entity); + String? title = _getSelectedResultTitle(entity); if (title != null) { titles[index] = title; } diff --git a/lib/src/components/selection/widget/brn_selection_more_item_widget.dart b/lib/src/components/selection/widget/brn_selection_more_item_widget.dart index 465ecb34..528b7d36 100644 --- a/lib/src/components/selection/widget/brn_selection_more_item_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_more_item_widget.dart @@ -8,8 +8,8 @@ import 'package:bruno/src/components/picker/time_picker/date_picker/brn_date_pic import 'package:bruno/src/components/selection/bean/brn_selection_common_entity.dart'; import 'package:bruno/src/components/selection/brn_more_selection.dart'; import 'package:bruno/src/components/selection/brn_selection_util.dart'; -import 'package:bruno/src/components/selection/widget/brn_layer_more_selection_page.dart'; import 'package:bruno/src/components/selection/brn_selection_view.dart'; +import 'package:bruno/src/components/selection/widget/brn_layer_more_selection_page.dart'; import 'package:bruno/src/components/selection/widget/brn_selection_date_range_item_widget.dart'; import 'package:bruno/src/components/toast/brn_toast.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; @@ -28,15 +28,17 @@ import 'package:flutter/services.dart'; class BrnMoreSelectionWidget extends StatefulWidget { //entity 是商圈、钥匙等 final BrnSelectionEntity selectionEntity; - final StreamController clearController; - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; + final StreamController? clearController; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; BrnSelectionConfig themeData; BrnMoreSelectionWidget( - {this.selectionEntity, + {Key? key, + required this.selectionEntity, this.clearController, this.onCustomFloatingLayerClick, - this.themeData}); + required this.themeData}) + : super(key: key); @override _BrnMoreSelectionWidgetState createState() => _BrnMoreSelectionWidgetState(); @@ -46,9 +48,8 @@ class _BrnMoreSelectionWidgetState extends State { @override Widget build(BuildContext context) { //弹出浮层 - if (widget.selectionEntity.filterType == BrnSelectionFilterType.Layer || - widget.selectionEntity.filterType == - BrnSelectionFilterType.CustomLayer) { + if (widget.selectionEntity.filterType == BrnSelectionFilterType.layer || + widget.selectionEntity.filterType == BrnSelectionFilterType.customLayer) { return FilterLayerTypeWidget( selectionEntity: widget.selectionEntity, onCustomFloatingLayerClick: widget.onCustomFloatingLayerClick, @@ -65,29 +66,31 @@ class _BrnMoreSelectionWidgetState extends State { } /// 展示标签的布局:标题+更多+标签+自定义 -// ignore: must_be_immutable class _FilterCommonTypeWidget extends StatefulWidget { //楼层 final BrnSelectionEntity selectionEntity; - final StreamController clearController; - BrnSelectionConfig themeData; + final StreamController? clearController; + final BrnSelectionConfig themeData; - _FilterCommonTypeWidget( - {this.selectionEntity, this.clearController, this.themeData}); + _FilterCommonTypeWidget({ + Key? key, + required this.selectionEntity, + this.clearController, + required this.themeData, + }) : super(key: key); @override - __FilterCommonTypeWidgetState createState() => - __FilterCommonTypeWidgetState(); + __FilterCommonTypeWidgetState createState() => __FilterCommonTypeWidgetState(); } class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { bool isExpanded = false; ///展开收起的通知 - ValueNotifier valueNotifier; + late ValueNotifier valueNotifier; ///用于 range和 tag 之间通信 - StreamController streamController; + late StreamController streamController; @override void initState() { @@ -102,9 +105,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { setState(() { if (!event.filter) { //将所有tag设置为未选中 - event.rangeEntity.parent - ?.currentTagListForEntity() - ?.forEach((data) { + event.rangeEntity.parent?.currentTagListForEntity().forEach((data) { data.clearSelectedEntity(); }); } @@ -131,18 +132,14 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( - padding: - EdgeInsets.only(top: 20, right: _isVisibleMore() ? 40 : 0), + padding: EdgeInsets.only(top: 20, right: _isVisibleMore() ? 40 : 0), child: _buildTitleWidget(), ), //自定义输入框 _buildRangeWidget(), //标签的筛选条件 Visibility( - visible: widget.selectionEntity - .currentShowTagByExpanded(isExpanded) - .length > - 0, + visible: widget.selectionEntity.currentShowTagByExpanded(isExpanded).length > 0, child: Padding( padding: EdgeInsets.only(top: 12), child: _buildSelectionTag(), @@ -179,7 +176,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { children: [ Expanded( child: Text( - widget.selectionEntity.title ?? "", + widget.selectionEntity.title, style: widget.themeData.titleForMoreTextStyle.generateTextStyle(), ), ), @@ -220,12 +217,12 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { return GestureDetector( onTap: () { setState(() { - if (data.filterType == BrnSelectionFilterType.Radio) { - data.parent.clearSelectedEntity(); + if (data.filterType == BrnSelectionFilterType.radio) { + data.parent?.clearSelectedEntity(); data.isSelected = true; //用于发送 标签点击事件 streamController.add(SelectEvent()); - } else if (data.filterType == BrnSelectionFilterType.Checkbox) { + } else if (data.filterType == BrnSelectionFilterType.checkbox) { if (!data.isSelected) { if (!BrnSelectionUtil.checkMaxSelectionCount(data)) { BrnToast.show('您选择的筛选条件数量已达上限', context); @@ -233,13 +230,13 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { } } - data.parent.children - ?.where((_) => _.filterType == BrnSelectionFilterType.Radio) - ?.forEach((f) => f.isSelected = false); + data.parent?.children + .where((_) => _.filterType == BrnSelectionFilterType.radio) + .forEach((f) => f.isSelected = false); data.isSelected = !data.isSelected; //用于发送 标签点击事件 streamController.add(SelectEvent()); - } else if (data.filterType == BrnSelectionFilterType.Date) { + } else if (data.filterType == BrnSelectionFilterType.date) { _showDatePicker(data); } }); @@ -250,29 +247,26 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { ); } - Widget _buildSingleTag(BrnSelectionEntity data) { - bool isDate = data.filterType == BrnSelectionFilterType.Date; + Widget _buildSingleTag(BrnSelectionEntity entity) { + bool isDate = entity.filterType == BrnSelectionFilterType.date; - String showName; + String? showName; if (isDate) { - if (data.value == null || data.value.isEmpty) { - showName = data.title; + if (BrunoTools.isEmpty(entity.value)) { + showName = entity.title; } else { - int time = int.tryParse(data.value ?? "") ?? - DateTime.now().millisecondsSinceEpoch; + int time = int.tryParse(entity.value ?? "") ?? DateTime.now().millisecondsSinceEpoch; showName = DateTimeFormatter.formatDate( - DateTime.fromMillisecondsSinceEpoch(time), - 'yyyy/MMMM/dd', - DateTimePickerLocale.zh_cn); + DateTime.fromMillisecondsSinceEpoch(time), 'yyyy/MMMM/dd', DateTimePickerLocale.zh_cn); } } else { - showName = data.title; + showName = entity.title; } return Container( alignment: Alignment.center, decoration: BoxDecoration( - color: data.isSelected + color: entity.isSelected ? widget.themeData.tagSelectedBackgroundColor : widget.themeData.tagNormalBackgroundColor, borderRadius: BorderRadius.circular(widget.themeData.tagRadius)), @@ -281,22 +275,21 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { showName, maxLines: 2, textAlign: TextAlign.center, - style: data.isSelected ? _selectedTextStyle() : _tagTextStyle(), + style: entity.isSelected ? _selectedTextStyle() : _tagTextStyle(), ), ); } TextStyle _tagTextStyle() { - return widget.themeData.tagNormalTextStyle?.generateTextStyle(); + return widget.themeData.tagNormalTextStyle.generateTextStyle(); } TextStyle _selectedTextStyle() { - return widget.themeData.tagSelectedTextStyle?.generateTextStyle(); + return widget.themeData.tagSelectedTextStyle.generateTextStyle(); } void _showDatePicker(BrnSelectionEntity data) { - int time = - int.tryParse(data.value ?? "") ?? DateTime.now().millisecondsSinceEpoch; + int time = int.tryParse(data.value ?? "") ?? DateTime.now().millisecondsSinceEpoch; BrnDatePicker.showDatePicker(context, pickerMode: BrnDateTimePickerMode.date, pickerTitleConfig: BrnPickerTitleConfig.Default, @@ -304,7 +297,7 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { dateFormat: 'yyyy年,MMMM月,dd日', onConfirm: (dateTime, list) { if (mounted) { setState(() { - data.parent.clearSelectedEntity(); + data.parent?.clearSelectedEntity(); data.isSelected = true; data.value = dateTime.millisecondsSinceEpoch.toString(); }); @@ -314,14 +307,17 @@ class __FilterCommonTypeWidgetState extends State<_FilterCommonTypeWidget> { } /// 更多和箭头widget -// ignore: must_be_immutable class _MoreArrow extends StatefulWidget { ///用于通知 展开和收起 - final ValueNotifier valueNotifier; + final ValueNotifier? valueNotifier; - BrnSelectionConfig themeData; + final BrnSelectionConfig? themeData; - _MoreArrow({this.valueNotifier, this.themeData}); + _MoreArrow({ + Key? key, + this.valueNotifier, + this.themeData, + }) : super(key: key); @override __MoreArrowState createState() => __MoreArrowState(); @@ -332,8 +328,7 @@ class __MoreArrowState extends State<_MoreArrow> { @override Widget build(BuildContext context) { - String asset = - isExpanded ? BrnAsset.ICON_UP_ARROW : BrnAsset.ICON_DOWN_ARROW; + String asset = isExpanded ? BrnAsset.iconUpArrow : BrnAsset.iconDownArrow; return GestureDetector( behavior: HitTestBehavior.opaque, @@ -341,7 +336,7 @@ class __MoreArrowState extends State<_MoreArrow> { setState(() { isExpanded = !isExpanded; if (widget.valueNotifier != null) { - widget.valueNotifier.value = isExpanded; + widget.valueNotifier!.value = isExpanded; } }); }, @@ -352,7 +347,7 @@ class __MoreArrowState extends State<_MoreArrow> { children: [ Text( '更多', - style: widget.themeData.moreTextStyle.generateTextStyle(), + style: widget.themeData?.moreTextStyle.generateTextStyle(), ), Container( height: 16, @@ -370,26 +365,25 @@ class __MoreArrowState extends State<_MoreArrow> { } /// 自定义筛选条件 -// ignore: must_be_immutable class _MoreRangeWidget extends StatefulWidget { ///用于标签和自定义输入 通信 - final StreamController streamController; + final StreamController? streamController; ///用于自定义的筛选条件 最大值最小值 final BrnSelectionEntity rangeEntity; ///用于监听重置事件 - final StreamController clearController; + final StreamController? clearController; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; - _MoreRangeWidget( - {this.streamController, - this.rangeEntity, - this.clearController, - this.themeData, - Key key}) - : super(key: key); + _MoreRangeWidget({ + Key? key, + required this.rangeEntity, + this.streamController, + this.clearController, + required this.themeData, + }) : super(key: key); @override __MoreRangeWidgetState createState() => __MoreRangeWidgetState(); @@ -397,32 +391,28 @@ class _MoreRangeWidget extends StatefulWidget { class __MoreRangeWidgetState extends State<_MoreRangeWidget> { //最小值 输入框监听 - TextEditingController minController; + TextEditingController minController = TextEditingController(); //最大值 输入框监听 - TextEditingController maxController; + TextEditingController maxController = TextEditingController(); //最小值 焦点监听 - FocusNode minFocusNode; + FocusNode minFocusNode = FocusNode(); //最大值 焦点监听 - FocusNode maxFocusNode; + FocusNode maxFocusNode = FocusNode(); //默认的最大值 - int max; + late int max; //默认的最小值 - int min; + late int min; @override void initState() { super.initState(); - minFocusNode = FocusNode(); - maxFocusNode = FocusNode(); - minController = TextEditingController(); - maxController = TextEditingController(); - widget?.clearController?.stream?.listen((event) { + widget.clearController?.stream.listen((event) { minController.clear(); maxController.clear(); }); @@ -431,46 +421,40 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { widget.rangeEntity.customMap = Map(); } - minController.text = (widget.rangeEntity.customMap['min'] != null) - ? widget.rangeEntity.customMap['min']?.toString() - : null; - maxController.text = (widget.rangeEntity.customMap['max'] != null) - ? widget.rangeEntity.customMap['max']?.toString() - : null; + minController.text = widget.rangeEntity.customMap!['min']?.toString() ?? ''; + maxController.text = widget.rangeEntity.customMap!['max']?.toString() ?? ''; - min = - int.tryParse(widget.rangeEntity?.extMap['min']?.toString() ?? "") ?? 0; - max = int.tryParse(widget.rangeEntity?.extMap['max']?.toString() ?? "") ?? - 9999; + min = int.tryParse(widget.rangeEntity.extMap['min']?.toString() ?? "") ?? 0; + max = int.tryParse(widget.rangeEntity.extMap['max']?.toString() ?? "") ?? 9999; ///处理的逻辑: /// 1:将输入框的 文本写入 customMap中 /// 2:如果最大值和最小值满足条件 则将range选中 minController.addListener(() { - if (widget.rangeEntity.filterType != BrnSelectionFilterType.Range) { + if (widget.rangeEntity.filterType != BrnSelectionFilterType.range) { return; } - String minInput = minController.text ?? ""; + String minInput = minController.text; if (widget.rangeEntity.customMap == null) { widget.rangeEntity.customMap = {}; } - widget.rangeEntity.customMap['min'] = minInput; + widget.rangeEntity.customMap!['min'] = minInput; widget.rangeEntity.isSelected = true; }); maxController.addListener(() { - if (widget.rangeEntity.filterType != BrnSelectionFilterType.Range) { + if (widget.rangeEntity.filterType != BrnSelectionFilterType.range) { return; } - String maxInput = maxController.text ?? ""; + String maxInput = maxController.text; if (widget.rangeEntity.customMap == null) { widget.rangeEntity.customMap = {}; } - widget.rangeEntity.customMap['max'] = maxInput; + widget.rangeEntity.customMap!['max'] = maxInput; widget.rangeEntity.isSelected = true; }); @@ -480,21 +464,19 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { /// 如果是多选 则不处理 minFocusNode.addListener(() { if (minFocusNode.hasFocus) { - widget.streamController - .add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); + widget.streamController?.add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); } }); maxFocusNode.addListener(() { if (maxFocusNode.hasFocus) { - widget.streamController - .add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); + widget.streamController?.add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); } }); ///用于监听tab的点击事件 ///如果父亲是单选 则将输入框清空并失去焦点,并且将自定义筛选设置为 未选中,以及更新用于显示的map - widget.streamController.stream.listen((event) { + widget.streamController?.stream.listen((event) { if (event is SelectEvent) { maxController.clear(); minController.clear(); @@ -508,27 +490,25 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { @override Widget build(BuildContext context) { - if (widget.rangeEntity.filterType == BrnSelectionFilterType.DateRange) { + if (widget.rangeEntity.filterType == BrnSelectionFilterType.dateRange) { return BrnSelectionDateRangeItemWidget( item: widget.rangeEntity, isNeedTitle: false, showTextSize: 14, - dateFormat: DATETIME_PICKER_DATE_FORMAT, + dateFormat: datetimePickerDateFormat, minTextEditingController: minController, maxTextEditingController: maxController, themeData: widget.themeData, onTapped: () { //点击选择框通知标签清空 - widget.streamController.add( - InputEvent(filter: false, rangeEntity: widget.rangeEntity)); + widget.streamController?.add(InputEvent(filter: false, rangeEntity: widget.rangeEntity)); }); } else { return Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( - child: _buildRangeField( - '最小值', minController, minFocusNode, widget.themeData), + child: _buildRangeField('最小值', minController, minFocusNode, widget.themeData), ), Container( // height: 38, @@ -540,8 +520,7 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { ), ), Expanded( - child: _buildRangeField( - '最大值', maxController, maxFocusNode, widget.themeData), + child: _buildRangeField('最大值', maxController, maxFocusNode, widget.themeData), ), ], ); @@ -560,27 +539,20 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { focusNode: focusNode, textAlign: TextAlign.center, controller: textEditingController, - cursorColor: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary, + cursorColor: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, inputFormatters: [FilteringTextInputFormatter.digitsOnly], style: widget.themeData.inputTextStyle.generateTextStyle(), decoration: InputDecoration( hintText: hint, hintStyle: widget.themeData.hintTextStyle.generateTextStyle(), enabledBorder: UnderlineInputBorder( - borderRadius: - BorderRadius.circular(widget.themeData.tagRadius), - borderSide: BorderSide( - width: 1, - color: widget.themeData.commonConfig.borderColorBase)), + borderRadius: BorderRadius.circular(widget.themeData.tagRadius), + borderSide: + BorderSide(width: 1, color: widget.themeData.commonConfig.borderColorBase)), focusedBorder: UnderlineInputBorder( - borderRadius: - BorderRadius.circular(widget.themeData.tagRadius), - borderSide: BorderSide( - width: 1, - color: widget.themeData.commonConfig.borderColorBase))), + borderRadius: BorderRadius.circular(widget.themeData.tagRadius), + borderSide: + BorderSide(width: 1, color: widget.themeData.commonConfig.borderColorBase))), ), ), ); @@ -588,15 +560,18 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { } /// 浮层类型的项 : 标题 + 点击跳转的layout -// ignore: must_be_immutable class FilterLayerTypeWidget extends StatefulWidget { //entity是 商圈 final BrnSelectionEntity selectionEntity; - final BrnOnCustomFloatingLayerClick onCustomFloatingLayerClick; - BrnSelectionConfig themeData; + final BrnOnCustomFloatingLayerClick? onCustomFloatingLayerClick; + final BrnSelectionConfig themeData; - FilterLayerTypeWidget( - {this.selectionEntity, this.onCustomFloatingLayerClick, this.themeData}); + FilterLayerTypeWidget({ + Key? key, + required this.selectionEntity, + this.onCustomFloatingLayerClick, + required this.themeData, + }) : super(key: key); @override _FilterLayerTypeWidgetState createState() => _FilterLayerTypeWidgetState(); @@ -619,8 +594,7 @@ class _FilterLayerTypeWidgetState extends State { padding: const EdgeInsets.only(left: 20, right: 20, top: 6), child: GestureDetector( onTap: () { - if (widget.selectionEntity.filterType == - BrnSelectionFilterType.Layer) { + if (widget.selectionEntity.filterType == BrnSelectionFilterType.layer) { Navigator.of(context) .push(PageRouteBuilder( opaque: false, @@ -631,24 +605,20 @@ class _FilterLayerTypeWidgetState extends State { ); })) .then((data) { - updateContent(); + setState(() {}); }); - } else if (widget.selectionEntity.filterType == - BrnSelectionFilterType.CustomLayer) { + } else if (widget.selectionEntity.filterType == BrnSelectionFilterType.customLayer) { if (widget.onCustomFloatingLayerClick != null) { int entityIndex = -1; - if (widget.selectionEntity.parent != null && - widget.selectionEntity.parent.children != null) { - entityIndex = widget.selectionEntity.parent.children - .indexOf(widget.selectionEntity); + if (widget.selectionEntity.parent != null) { + entityIndex = + widget.selectionEntity.parent!.children.indexOf(widget.selectionEntity); } - widget.onCustomFloatingLayerClick( - entityIndex, widget.selectionEntity, + widget.onCustomFloatingLayerClick!(entityIndex, widget.selectionEntity, (List customFloatingLayerParams) { - widget.selectionEntity.children?.clear(); + widget.selectionEntity.children.clear(); widget.selectionEntity.children = []; - widget.selectionEntity.children - .addAll(customFloatingLayerParams); + widget.selectionEntity.children.addAll(customFloatingLayerParams); widget.selectionEntity.configDefaultValue(); setState(() {}); }); @@ -659,16 +629,15 @@ class _FilterLayerTypeWidgetState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( - child: Text(isEmptyCondition() ? '请选择' : getCondition(), - style: isEmptyCondition() + child: Text(_isEmptyCondition() ? '请选择' : _getCondition(), + style: _isEmptyCondition() ? widget.themeData.hintTextStyle.generateTextStyle() - : widget.themeData.optionTextStyle - .generateTextStyle()), + : widget.themeData.optionTextStyle.generateTextStyle()), ), Container( height: 16, width: 16, - child: BrunoTools.getAssetImage(BrnAsset.ICON_RIGHT_ARROW), + child: BrunoTools.getAssetImage(BrnAsset.iconRightArrow), ) ], ), @@ -679,20 +648,14 @@ class _FilterLayerTypeWidgetState extends State { ); } - void updateContent() { - setState(() {}); - } - - bool isEmptyCondition() { - String condition = getCondition(); - return condition == null || condition.isEmpty; + bool _isEmptyCondition() { + return _getCondition().isEmpty; } - String getCondition() { + String _getCondition() { String tmp = ""; //返回所有选中的 - List selectedList = - widget.selectionEntity.selectedList(); + List selectedList = widget.selectionEntity.selectedList(); //判断步骤: //第一步:取出来所有选中的: 房山 不限 小白楼 西城 不限 @@ -715,9 +678,11 @@ class _FilterLayerTypeWidgetState extends State { }).toList(); for (int i = 0; i < result.length; i++) { - tmp += result[i].title; - if (i != result.length - 1) { - tmp += '、'; + if (result[i].title.isNotEmpty) { + tmp += result[i].title; + if (i != result.length - 1) { + tmp += '、'; + } } } return tmp; @@ -733,8 +698,8 @@ class SelectEvent extends Event {} /// 输入框的事件:携带 自定义的筛选条件 和 过滤标识位 /// 由于点击标签之后,会清空筛选条件,清空的时候,textField的监听也会执行一遍,因此需要过滤 class InputEvent extends Event { - BrnSelectionEntity rangeEntity; - bool filter; + final BrnSelectionEntity rangeEntity; + final bool filter; - InputEvent({this.rangeEntity, this.filter}); + InputEvent({required this.rangeEntity, this.filter = false}); } diff --git a/lib/src/components/selection/widget/brn_selection_range_input_item_widget.dart b/lib/src/components/selection/widget/brn_selection_range_input_item_widget.dart index 4af722b5..baecf63f 100644 --- a/lib/src/components/selection/widget/brn_selection_range_input_item_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_range_input_item_widget.dart @@ -10,86 +10,83 @@ typedef void OnFocusChangedFunction(bool focus); /// 清空自定义范围输入框焦点的事件类 class ClearSelectionFocusEvent {} -// ignore: must_be_immutable class BrnSelectionRangeItemWidget extends StatefulWidget { final BrnSelectionEntity item; - final OnRangeChangedFunction onRangeChanged; - final OnFocusChangedFunction onFocusChanged; + final OnRangeChangedFunction? onRangeChanged; + final OnFocusChangedFunction? onFocusChanged; final bool isShouldClearText; final TextEditingController minTextEditingController; final TextEditingController maxTextEditingController; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; - BrnSelectionRangeItemWidget( - {this.item, - @required this.minTextEditingController, - @required this.maxTextEditingController, - this.isShouldClearText = false, - this.themeData, - this.onRangeChanged, - this.onFocusChanged}); + BrnSelectionRangeItemWidget({ + Key? key, + required this.item, + required this.minTextEditingController, + required this.maxTextEditingController, + this.isShouldClearText = false, + this.onRangeChanged, + this.onFocusChanged, + required this.themeData, + }): super(key: key); - _BrnSelectionRangeItemWidgetState createState() => - _BrnSelectionRangeItemWidgetState(); + _BrnSelectionRangeItemWidgetState createState() => _BrnSelectionRangeItemWidgetState(); } -class _BrnSelectionRangeItemWidgetState - extends State { +class _BrnSelectionRangeItemWidgetState extends State { FocusNode _minFocusNode = FocusNode(); FocusNode _maxFocusNode = FocusNode(); @override void initState() { widget.minTextEditingController.text = - (widget.item.customMap != null && widget.item.customMap['min'] != null) - ? widget.item.customMap['min']?.toString() - : null; + (widget.item.customMap != null && widget.item.customMap!['min'] != null) + ? widget.item.customMap!['min']?.toString() ?? '' + : ''; widget.maxTextEditingController.text = - (widget.item.customMap != null && widget.item.customMap['max'] != null) - ? widget.item.customMap['max']?.toString() - : null; + (widget.item.customMap != null && widget.item.customMap!['max'] != null) + ? widget.item.customMap!['max']?.toString() ?? '' + : ''; //输入框焦点 _minFocusNode.addListener(() { if (widget.onFocusChanged != null) { - widget.onFocusChanged(_minFocusNode.hasFocus || _maxFocusNode.hasFocus); + widget.onFocusChanged!(_minFocusNode.hasFocus || _maxFocusNode.hasFocus); } }); _maxFocusNode.addListener(() { if (widget.onFocusChanged != null) { - widget.onFocusChanged(_minFocusNode.hasFocus || _maxFocusNode.hasFocus); + widget.onFocusChanged!(_minFocusNode.hasFocus || _maxFocusNode.hasFocus); } }); widget.minTextEditingController.addListener(() { - String minInput = widget.minTextEditingController.text ?? ""; + String minInput = widget.minTextEditingController.text; if (widget.item.customMap == null) { widget.item.customMap = {}; } - widget.item.customMap['min'] = minInput; + widget.item.customMap!['min'] = minInput; widget.item.isSelected = true; }); widget.maxTextEditingController.addListener(() { - String maxInput = widget.maxTextEditingController.text ?? ""; + String maxInput = widget.maxTextEditingController.text; if (widget.item.customMap == null) { widget.item.customMap = {}; } - widget.item.customMap['max'] = maxInput; + widget.item.customMap!['max'] = maxInput; widget.item.isSelected = true; }); - EventBus.instance - .on() - .listen((ClearSelectionFocusEvent event) { - _minFocusNode?.unfocus(); - _maxFocusNode?.unfocus(); + EventBus.instance.on().listen((ClearSelectionFocusEvent event) { + _minFocusNode.unfocus(); + _maxFocusNode.unfocus(); }); super.initState(); @@ -106,13 +103,12 @@ class _BrnSelectionRangeItemWidgetState margin: EdgeInsets.only(bottom: 5), alignment: Alignment.centerLeft, child: Text( - (widget.item.title != null ? widget.item.title : '自定义区间') + + (widget.item.title.isNotEmpty ? widget.item.title : '自定义区间') + "(" + - widget.item.extMap['unit']?.toString() + + (widget.item.extMap['unit']?.toString() ?? '') + ")", textAlign: TextAlign.left, - style: - widget.themeData.rangeTitleTextStyle?.generateTextStyle(), + style: widget.themeData.rangeTitleTextStyle.generateTextStyle(), ), ), Row( @@ -121,7 +117,7 @@ class _BrnSelectionRangeItemWidgetState Container( child: Text( "至", - style: widget.themeData.inputTextStyle?.generateTextStyle(), + style: widget.themeData.inputTextStyle.generateTextStyle(), ), ), getRangeTextField(true), @@ -136,20 +132,18 @@ class _BrnSelectionRangeItemWidgetState Widget getRangeTextField(bool isMax) { return Expanded( child: TextFormField( - style: widget.themeData.inputTextStyle?.generateTextStyle(), + style: widget.themeData.inputTextStyle.generateTextStyle(), inputFormatters: [FilteringTextInputFormatter.digitsOnly], keyboardType: TextInputType.numberWithOptions(), onChanged: (input) { widget.item.isSelected = true; }, focusNode: isMax ? _maxFocusNode : _minFocusNode, - controller: isMax - ? widget.maxTextEditingController - : widget.minTextEditingController, + controller: isMax ? widget.maxTextEditingController : widget.minTextEditingController, cursorColor: widget.themeData.commonConfig.brandPrimary, textAlign: TextAlign.center, decoration: InputDecoration( - hintStyle: widget.themeData.hintTextStyle?.generateTextStyle(), + hintStyle: widget.themeData.hintTextStyle.generateTextStyle(), hintText: (isMax ? '最大值' : '最小值'), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( diff --git a/lib/src/components/selection/widget/brn_selection_range_tag_widget.dart b/lib/src/components/selection/widget/brn_selection_range_tag_widget.dart index 8e734255..52ee7fd3 100644 --- a/lib/src/components/selection/widget/brn_selection_range_tag_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_range_tag_widget.dart @@ -1,5 +1,3 @@ -import 'dart:ui'; - import 'package:bruno/src/components/picker/time_picker/brn_date_time_formatter.dart'; import 'package:bruno/src/components/selection/bean/brn_selection_common_entity.dart'; import 'package:bruno/src/components/selection/brn_selection_util.dart'; @@ -12,46 +10,42 @@ import 'package:flutter/material.dart'; /// /// /// /// /// /// /// /// /// / /// 描述: 多选 tag 组件 /// /// /// /// /// /// /// /// /// / -// ignore: must_be_immutable class BrnSelectionRangeTagWidget extends StatefulWidget { //tag 显示的文本 @required final List tagFilterList; //初始选中的 Index 列表 - final List initSelectStatus; + final List? initSelectStatus; //选择tag的回调 - final void Function(int, bool) onSelect; + final void Function(int, bool)? onSelect; final double spacing; final double verticalSpacing; final int tagWidth; final double tagHeight; - final int initFocusedindex; + final int initFocusedIndex; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; BrnSelectionRangeTagWidget( - {Key key, - @required this.tagFilterList, + {Key? key, + required this.tagFilterList, this.initSelectStatus, this.onSelect, this.spacing = 12, this.verticalSpacing = 10, this.tagWidth = 75, this.tagHeight = 34, - this.themeData, - this.initFocusedindex = -1}) - : assert(tagFilterList != null), - super(key: key); + required this.themeData, + this.initFocusedIndex = -1}) + : super(key: key); @override - _BrnSelectionRangeTagWidgetState createState() => - _BrnSelectionRangeTagWidgetState(); + _BrnSelectionRangeTagWidgetState createState() => _BrnSelectionRangeTagWidgetState(); } -class _BrnSelectionRangeTagWidgetState - extends State { +class _BrnSelectionRangeTagWidgetState extends State { @override Widget build(BuildContext context) { return Wrap( @@ -62,16 +56,14 @@ class _BrnSelectionRangeTagWidgetState } List _tagWidgetList(context) { - List list = List(); - for (int nameIndex = 0; - nameIndex < widget.tagFilterList.length; - nameIndex++) { + List list = []; + for (int nameIndex = 0; nameIndex < widget.tagFilterList.length; nameIndex++) { Widget tagWidget = _tagWidgetAtIndex(nameIndex); GestureDetector gdt = GestureDetector( child: tagWidget, onTap: () { var selectedEntity = widget.tagFilterList[nameIndex]; - if (BrnSelectionFilterType.Checkbox == selectedEntity.filterType && + if (BrnSelectionFilterType.checkbox == selectedEntity.filterType && !selectedEntity.isSelected) { if (!BrnSelectionUtil.checkMaxSelectionCount(selectedEntity)) { BrnToast.show("您选择的筛选条件数量已达上限", context); @@ -80,7 +72,7 @@ class _BrnSelectionRangeTagWidgetState } BrnSelectionUtil.processBrotherItemSelectStatus(selectedEntity); if (null != widget.onSelect) { - widget.onSelect(nameIndex, selectedEntity.isSelected); + widget.onSelect!(nameIndex, selectedEntity.isSelected); } setState(() {}); }); @@ -90,45 +82,42 @@ class _BrnSelectionRangeTagWidgetState } Widget _tagWidgetAtIndex(int nameIndex) { - bool selected = widget.tagFilterList[nameIndex].isSelected || - nameIndex == widget.initFocusedindex; + bool selected = + widget.tagFilterList[nameIndex].isSelected || nameIndex == widget.initFocusedIndex; String text = widget.tagFilterList[nameIndex].title; - if (widget.tagFilterList[nameIndex].filterType == - BrnSelectionFilterType.Date && + if (widget.tagFilterList[nameIndex].filterType == BrnSelectionFilterType.date && !BrunoTools.isEmpty(widget.tagFilterList[nameIndex].value)) { - if (int.tryParse(widget.tagFilterList[nameIndex].value) != null) { - text = DateTimeFormatter.formatDate( - DateTimeFormatter.convertIntValueToDateTime( - widget.tagFilterList[nameIndex].value), - 'yyyy年MM月dd日', - DateTimePickerLocale.zh_cn); + if (int.tryParse(widget.tagFilterList[nameIndex].value ?? '') != null) { + DateTime? dateTime = + DateTimeFormatter.convertIntValueToDateTime(widget.tagFilterList[nameIndex].value); + if (dateTime != null) { + text = DateTimeFormatter.formatDate(dateTime, 'yyyy年MM月dd日', DateTimePickerLocale.zh_cn); + } + } else { + text = widget.tagFilterList[nameIndex].value ?? ''; } - text = widget.tagFilterList[nameIndex].value; } - Text tx = Text( - text, - style: selected ? _selectedTextStyle() : _tagTextStyle(), - ); - Container cntn = Container( + Text tx = Text(text, style: selected ? _selectedTextStyle() : _tagTextStyle()); + Container tagItem = Container( alignment: Alignment.center, decoration: BoxDecoration( color: selected ? widget.themeData.tagSelectedBackgroundColor : widget.themeData.tagNormalBackgroundColor, borderRadius: BorderRadius.circular(widget.themeData.tagRadius)), - width: widget.tagWidth?.toDouble(), + width: widget.tagWidth.toDouble(), height: widget.tagHeight, child: tx, ); - return cntn; + return tagItem; } TextStyle _tagTextStyle() { - return widget.themeData.tagNormalTextStyle?.generateTextStyle(); + return widget.themeData.tagNormalTextStyle.generateTextStyle(); } TextStyle _selectedTextStyle() { - return widget.themeData.tagSelectedTextStyle?.generateTextStyle(); + return widget.themeData.tagSelectedTextStyle.generateTextStyle(); } } diff --git a/lib/src/components/selection/widget/brn_selection_range_widget.dart b/lib/src/components/selection/widget/brn_selection_range_widget.dart index 20e3baf6..a4ef0536 100644 --- a/lib/src/components/selection/widget/brn_selection_range_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_range_widget.dart @@ -22,51 +22,46 @@ import 'package:flutter/widgets.dart'; typedef void BrnOnRangeSelectionBgClick(); -// ignore: must_be_immutable class BrnRangeSelectionGroupWidget extends StatefulWidget { - static final double screenWidth = - window.physicalSize.width / window.devicePixelRatio; + static final double screenWidth = window.physicalSize.width / window.devicePixelRatio; final BrnSelectionEntity entity; final double maxContentHeight; final bool showSelectedCount; - final BrnOnRangeSelectionBgClick bgClickFunction; - final BrnOnRangeSelectionConfirm onSelectionConfirm; + final BrnOnRangeSelectionBgClick? bgClickFunction; + final BrnOnRangeSelectionConfirm? onSelectionConfirm; - final int rowount; + final int? rowCount; final double marginTop; - BrnSelectionConfig themeData; + final BrnSelectionConfig themeData; BrnRangeSelectionGroupWidget( - {Key key, - @required this.entity, + {Key? key, + required this.entity, this.maxContentHeight = DESIGN_SELECTION_HEIGHT, - this.rowount, + this.rowCount, this.showSelectedCount = false, this.bgClickFunction, this.onSelectionConfirm, this.marginTop = 0, - this.themeData}); + required this.themeData}): super(key: key); @override - _BrnRangeSelectionGroupWidgetState createState() => - _BrnRangeSelectionGroupWidgetState(); + _BrnRangeSelectionGroupWidgetState createState() => _BrnRangeSelectionGroupWidgetState(); } -class _BrnRangeSelectionGroupWidgetState - extends State +class _BrnRangeSelectionGroupWidgetState extends State with SingleTickerProviderStateMixin { - List _originalSelectedItemsList = List(); - List _firstList = List(); - List _secondList = List(); - int _firstIndex; - int _secondIndex; + List _originalSelectedItemsList = []; + List _firstList = []; + List _secondList = []; + int _firstIndex = -1; + int _secondIndex = -1; int totalLevel = 0; - TabController _tabController; - List tabs; + late TabController _tabController; TextEditingController _minTextEditingController = TextEditingController(); TextEditingController _maxTextEditingController = TextEditingController(); @@ -82,21 +77,17 @@ class _BrnRangeSelectionGroupWidgetState } _tabController.addListener(() { _clearAllSelectedItems(); - clearNotTagItem(totalLevel == 1 - ? _firstList - : _firstList[_tabController.index].children); + _clearNotTagItem(totalLevel == 1 ? _firstList : _firstList[_tabController.index].children); }); super.initState(); } @override void dispose() { - _tabController?.dispose(); + _tabController.dispose(); if (!_isConfirmClick) { _resetSelectionDatas(widget.entity); - clearNotTagItem(totalLevel == 1 - ? _firstList - : _firstList[_tabController.index].children); + _clearNotTagItem(totalLevel == 1 ? _firstList : _firstList[_tabController.index].children); _resetCustomMapData(); } super.dispose(); @@ -124,50 +115,45 @@ class _BrnRangeSelectionGroupWidgetState //pragma mark -- config widgets List _configWidgets() { - List widgetList = List(); + List widgetList = []; widgetList.add(_listWidget()); return widgetList; } Widget _listWidget() { - Widget rangeWidget; + Widget? rangeWidget; - if (_firstList != null && _secondList == null) { + if (_firstList.isNotEmpty && _secondList.isEmpty) { /// 1、仅有一级的情况 /// 1.2 一级多选 || 存在自定义范围的情况 - rangeWidget = _createNewTagAndRangeWidget(_firstList, null, Colors.white); - } else if (_firstList != null && _secondList != null) { + rangeWidget = _createNewTagAndRangeWidget(_firstList, Colors.white); + } else if (_firstList.isNotEmpty && _secondList.isNotEmpty) { /// 2、有二级的情况 - rangeWidget = - _createNewTagAndRangeWidget(_firstList, _secondList, Colors.white); + rangeWidget = _createNewTagAndRangeWidget(_firstList, Colors.white); } return Container( color: Colors.white, width: MediaQuery.of(context).size.width, - constraints: hasCalendarItem(widget.entity) + constraints: _hasCalendarItem(widget.entity) ? BoxConstraints( maxHeight: MediaQuery.of(context).size.height - MediaQuery.of(context).padding.bottom - widget.marginTop) - : BoxConstraints( - maxHeight: widget.maxContentHeight + DESIGN_BOTTOM_HEIGHT), + : BoxConstraints(maxHeight: widget.maxContentHeight + DESIGN_BOTTOM_HEIGHT), child: rangeWidget, ); } - Widget _createNewTagAndRangeWidget(List firstList, - List secondList, Color white) { - if (firstList != null && - BrnSelectionUtil.getTotalLevel(widget.entity) == 1) { + Widget _createNewTagAndRangeWidget(List firstList, Color white) { + if (firstList.isNotEmpty && BrnSelectionUtil.getTotalLevel(widget.entity) == 1) { return Column( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: SingleChildScrollView( child: Column( - mainAxisSize: MainAxisSize.min, - children: getOneTabContent(widget.entity)), + mainAxisSize: MainAxisSize.min, children: _getOneTabContent(widget.entity)), ), ), BrnLine( @@ -176,8 +162,7 @@ class _BrnRangeSelectionGroupWidgetState _bottomWidget() ], ); - } else if (firstList != null && - BrnSelectionUtil.getTotalLevel(widget.entity) == 2) { + } else if (firstList.isNotEmpty && BrnSelectionUtil.getTotalLevel(widget.entity) == 2) { var tabBar = BrnTabBar( tabHeight: 50, controller: _tabController, @@ -186,7 +171,7 @@ class _BrnRangeSelectionGroupWidgetState var tabContent = SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, - children: getOneTabContent(firstList[_tabController.index]))); + children: _getOneTabContent(firstList[_tabController.index]))); return Column( mainAxisSize: MainAxisSize.min, @@ -206,42 +191,34 @@ class _BrnRangeSelectionGroupWidgetState } } - List getOneTabContent(BrnSelectionEntity filterItem) { + List _getOneTabContent(BrnSelectionEntity filterItem) { List subFilterList = filterItem.children; /// TODO 还要添加 Date DateRange 类型的判断。 List tagFilterList = subFilterList .where((f) => - f.filterType != BrnSelectionFilterType.Range && - f.filterType != BrnSelectionFilterType.Date && - f.filterType != BrnSelectionFilterType.DateRange && - f.filterType != BrnSelectionFilterType.DateRangeCalendar) + f.filterType != BrnSelectionFilterType.range && + f.filterType != BrnSelectionFilterType.date && + f.filterType != BrnSelectionFilterType.dateRange && + f.filterType != BrnSelectionFilterType.dateRangeCalendar) .toList(); - Size maxWidthSize; + Size maxWidthSize = Size.zero; for (BrnSelectionEntity entity in subFilterList) { - Size size = BrnTextUtil.textSize(entity.title, - widget.themeData.tagNormalTextStyle.generateTextStyle()); - if (maxWidthSize == null) { + Size size = BrnTextUtil.textSize( + entity.title, widget.themeData.tagNormalTextStyle.generateTextStyle()); + if (maxWidthSize.width < size.width) { maxWidthSize = size; - } else { - if (maxWidthSize.width < size.width) { - maxWidthSize = size; - } } } int tagWidth; ///如果指定展示列,则按照指定列展示,否则动态计算宽度。最大不超过四列。 - if (widget.rowount == null) { - int oneCountTagWidth = - (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (1 - 1)) ~/ 1; - int twoCountTagWidth = - (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (2 - 1)) ~/ 2; - int threeCountTagWidth = - (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (3 - 1)) ~/ 3; - int fourCountTagWidth = - (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (4 - 1)) ~/ 4; + if (widget.rowCount == null) { + int oneCountTagWidth = (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (1 - 1)) ~/ 1; + int twoCountTagWidth = (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (2 - 1)) ~/ 2; + int threeCountTagWidth = (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (3 - 1)) ~/ 3; + int fourCountTagWidth = (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (4 - 1)) ~/ 4; if (maxWidthSize.width > twoCountTagWidth) { tagWidth = oneCountTagWidth; } else if (threeCountTagWidth < maxWidthSize.width && @@ -254,28 +231,25 @@ class _BrnRangeSelectionGroupWidgetState tagWidth = fourCountTagWidth; } } else { - tagWidth = (BrnRangeSelectionGroupWidget.screenWidth - - 40 - - 12 * (widget.rowount - 1)) ~/ - widget.rowount; + tagWidth = (BrnRangeSelectionGroupWidget.screenWidth - 40 - 12 * (widget.rowCount! - 1)) ~/ + widget.rowCount!; } - var tagContainer = (tagFilterList?.length ?? 0) > 0 + var tagContainer = (tagFilterList.length) > 0 ? Container( alignment: Alignment.centerLeft, padding: EdgeInsets.only(left: 20, right: 20, top: 20, bottom: 20), child: BrnSelectionRangeTagWidget( tagWidth: tagWidth, tagFilterList: tagFilterList, - initFocusedindex: getInitFocusedIndex(subFilterList), + initFocusedIndex: _getInitFocusedIndex(subFilterList), themeData: widget.themeData, onSelect: (index, isSelected) { setState(() { _setFirstIndex(_tabController.index); _setSecondIndex(index); - clearNotTagItem(totalLevel == 1 - ? _firstList - : _firstList[_tabController.index].children); + _clearNotTagItem( + totalLevel == 1 ? _firstList : _firstList[_tabController.index].children); _clearEditRangeText(); }); }), @@ -284,7 +258,7 @@ class _BrnRangeSelectionGroupWidgetState var content; for (BrnSelectionEntity item in subFilterList) { - if (item.filterType == BrnSelectionFilterType.Range) { + if (item.filterType == BrnSelectionFilterType.range) { content = BrnSelectionRangeItemWidget( item: item, minTextEditingController: _minTextEditingController, @@ -294,12 +268,12 @@ class _BrnRangeSelectionGroupWidgetState item.isSelected = focus; if (focus) { setState(() { - clearTagSelectStatus(subFilterList); + _clearTagSelectStatus(subFilterList); }); } }); break; - } else if (item.filterType == BrnSelectionFilterType.DateRange) { + } else if (item.filterType == BrnSelectionFilterType.dateRange) { content = BrnSelectionDateRangeItemWidget( item: item, minTextEditingController: _minTextEditingController, @@ -307,52 +281,46 @@ class _BrnRangeSelectionGroupWidgetState themeData: widget.themeData, onTapped: () { setState(() { - clearTagSelectStatus(subFilterList); + _clearTagSelectStatus(subFilterList); }); }); break; - } else if (item.filterType == BrnSelectionFilterType.Date) { - DateTime initialStartDate = - DateTimeFormatter.convertIntValueToDateTime(item.value); - DateTime initialEndDate = - DateTimeFormatter.convertIntValueToDateTime(item.value); - content = BrnCalendarView( + } else if (item.filterType == BrnSelectionFilterType.date) { + DateTime? initialStartDate = DateTimeFormatter.convertIntValueToDateTime(item.value); + DateTime? initialEndDate = DateTimeFormatter.convertIntValueToDateTime(item.value); + content = BrnCalendarView.single( key: GlobalKey(), - selectMode: SelectMode.SINGLE, initStartSelectedDate: initialStartDate, initEndSelectedDate: initialEndDate, initDisplayDate: initialEndDate, - startEndDateChange: (DateTime startDate, DateTime endDate) { - item.value = startDate.millisecondsSinceEpoch.toString(); + dateChange: (DateTime date) { + item.value = date.millisecondsSinceEpoch.toString(); item.isSelected = true; setState(() { - clearTagSelectStatus(subFilterList); + _clearTagSelectStatus(subFilterList); }); }, ); - } else if (item.filterType == BrnSelectionFilterType.DateRangeCalendar) { - DateTime initialStartDate = item.customMap == null + } else if (item.filterType == BrnSelectionFilterType.dateRangeCalendar) { + DateTime? initialStartDate = item.customMap == null ? null - : DateTimeFormatter.convertIntValueToDateTime( - item.customMap['min']); - DateTime initialEndDate = item.customMap == null + : DateTimeFormatter.convertIntValueToDateTime(item.customMap!['min']); + DateTime? initialEndDate = item.customMap == null ? null - : DateTimeFormatter.convertIntValueToDateTime( - item.customMap['max']); - content = BrnCalendarView( + : DateTimeFormatter.convertIntValueToDateTime(item.customMap!['max']); + content = BrnCalendarView.range( key: GlobalKey(), - selectMode: SelectMode.RANGE, initStartSelectedDate: initialStartDate, initEndSelectedDate: initialEndDate, - startEndDateChange: (DateTime startDate, DateTime endDate) { + rangeDateChange: (DateTimeRange range) { item.customMap = {}; item.customMap = { - 'min': startDate?.millisecondsSinceEpoch?.toString(), - 'max': endDate?.millisecondsSinceEpoch?.toString() + 'min': range.start.millisecondsSinceEpoch.toString(), + 'max': range.end.millisecondsSinceEpoch.toString() }; item.isSelected = true; setState(() { - clearTagSelectStatus(subFilterList); + _clearTagSelectStatus(subFilterList); }); }, ); @@ -379,8 +347,7 @@ class _BrnRangeSelectionGroupWidgetState Container( height: 24, width: 24, - child: - BrunoTools.getAssetImage(BrnAsset.iconSelectionReset), + child: BrunoTools.getAssetImage(BrnAsset.iconSelectionReset), ), Text( '重置', @@ -414,8 +381,7 @@ class _BrnRangeSelectionGroupWidgetState if (totalLevel == 2) { List subFilterList = widget.entity.children[_tabController.index].children; - List selectItems = - subFilterList.where((f) => f.isSelected).toList(); + List selectItems = subFilterList.where((f) => f.isSelected).toList(); if (selectItems.length > 0) { _firstList[_tabController.index].isSelected = true; } else { @@ -424,23 +390,18 @@ class _BrnRangeSelectionGroupWidgetState } // 处理Range类型的校验 - BrnSelectionEntity rangeEntity = getSelectRangeItem(totalLevel == 1 - ? _firstList - : _firstList[_tabController.index].children); + BrnSelectionEntity? rangeEntity = _getSelectRangeItem( + totalLevel == 1 ? _firstList : _firstList[_tabController.index].children); if (rangeEntity != null) { if (rangeEntity.customMap != null && - ((rangeEntity.customMap['min'] != null && - rangeEntity.customMap['min'].length > 0) || - (rangeEntity.customMap['max'] != null && - rangeEntity.customMap['max'].length > 0))) { + (!BrunoTools.isEmpty(rangeEntity.customMap!['min']) || + !BrunoTools.isEmpty(rangeEntity.customMap!['max']))) { if (!rangeEntity.isValidRange()) { FocusScope.of(context).requestFocus(FocusNode()); - if (rangeEntity?.filterType == BrnSelectionFilterType.Range) { + if (rangeEntity.filterType == BrnSelectionFilterType.range) { BrnToast.show('您输入的区间有误', context); - } else if (rangeEntity?.filterType == - BrnSelectionFilterType.DateRange || - rangeEntity?.filterType == - BrnSelectionFilterType.DateRangeCalendar) { + } else if (rangeEntity.filterType == BrnSelectionFilterType.dateRange || + rangeEntity.filterType == BrnSelectionFilterType.dateRangeCalendar) { BrnToast.show('您选择的区间有误', context); } return; @@ -451,15 +412,13 @@ class _BrnRangeSelectionGroupWidgetState } if (widget.onSelectionConfirm != null) { - widget.onSelectionConfirm(widget.entity, _firstIndex, _secondIndex, -1); + widget.onSelectionConfirm!(widget.entity, _firstIndex, _secondIndex, -1); } } void _clearAllSelectedItems() { _resetSelectionDatas(widget.entity); - clearNotTagItem(totalLevel == 1 - ? _firstList - : _firstList[_tabController.index].children); + _clearNotTagItem(totalLevel == 1 ? _firstList : _firstList[_tabController.index].children); _clearEditRangeText(); setState(() { _configDefaultInitSelectIndex(); @@ -474,7 +433,7 @@ class _BrnRangeSelectionGroupWidgetState for (BrnSelectionEntity entity in _originalSelectedItemsList) { entity.isSelected = true; if (entity.customMap != null) { - entity.originalCustomMap = Map.from(entity.customMap); + entity.originalCustomMap = Map.from(entity.customMap!); } } // 初始化每列的选中 index 为 -1,未选中。 @@ -494,9 +453,8 @@ class _BrnRangeSelectionGroupWidgetState _firstIndex = firstIndex; _secondIndex = -1; if (widget.entity.children.length > _firstIndex) { - List seconds = - widget.entity.children[_firstIndex].children; - if (seconds != null) { + List seconds = widget.entity.children[_firstIndex].children; + if (seconds.isNotEmpty) { for (BrnSelectionEntity entity in seconds) { if (entity.isSelected) { _setSecondIndex(seconds.indexOf(entity)); @@ -523,16 +481,16 @@ class _BrnRangeSelectionGroupWidgetState if (_firstIndex >= 0 && _firstList.length > _firstIndex) { _secondList = _firstList[_firstIndex].children; } else { - _secondList = null; + _secondList = []; } } void _configDefaultSelectedData() { _firstList = widget.entity.children; //是否已选择的item里面有第一列的 - if (_firstList == null) { + if (_firstList.isEmpty) { _secondIndex = -1; - _secondList = null; + _secondList = []; return; } for (BrnSelectionEntity entity in _firstList) { @@ -544,7 +502,7 @@ class _BrnRangeSelectionGroupWidgetState if (_firstIndex >= 0 && _firstIndex < _firstList.length) { _secondList = _firstList[_firstIndex].children; - if (_secondList != null) { + if (_secondList.isNotEmpty) { for (BrnSelectionEntity entity in _secondList) { if (entity.isSelected) { _secondIndex = _secondList.indexOf(entity); @@ -558,24 +516,22 @@ class _BrnRangeSelectionGroupWidgetState //设置数据为未选中状态 void _resetSelectionDatas(BrnSelectionEntity entity) { entity.isSelected = false; - entity.customMap = null; - if (entity.children != null) { - for (BrnSelectionEntity subEntity in entity.children) { - _resetSelectionDatas(subEntity); - } + entity.customMap = Map(); + for (BrnSelectionEntity subEntity in entity.children) { + _resetSelectionDatas(subEntity); } } - void clearNotTagItem(List subFilterList) { + void _clearNotTagItem(List subFilterList) { subFilterList - ?.where((f) => - f.filterType == BrnSelectionFilterType.Range || - f.filterType == BrnSelectionFilterType.Date || - f.filterType == BrnSelectionFilterType.DateRange || - f.filterType == BrnSelectionFilterType.DateRangeCalendar) - ?.forEach((f) { + .where((f) => + f.filterType == BrnSelectionFilterType.range || + f.filterType == BrnSelectionFilterType.date || + f.filterType == BrnSelectionFilterType.dateRange || + f.filterType == BrnSelectionFilterType.dateRangeCalendar) + .forEach((f) { f.isSelected = false; - f.customMap = null; + f.customMap = Map(); f.value = null; }); } @@ -586,27 +542,27 @@ class _BrnRangeSelectionGroupWidgetState EventBus.instance.fire(ClearSelectionFocusEvent()); } - void clearTagSelectStatus(List subFilterList) { + void _clearTagSelectStatus(List subFilterList) { subFilterList - .where((f) => f.filterType != BrnSelectionFilterType.Range) - .where((f) => f.filterType != BrnSelectionFilterType.Date) - .where((f) => f.filterType != BrnSelectionFilterType.DateRange) - .where((f) => f.filterType != BrnSelectionFilterType.DateRangeCalendar) + .where((f) => f.filterType != BrnSelectionFilterType.range) + .where((f) => f.filterType != BrnSelectionFilterType.date) + .where((f) => f.filterType != BrnSelectionFilterType.dateRange) + .where((f) => f.filterType != BrnSelectionFilterType.dateRangeCalendar) .forEach((f) { f.isSelected = false; - f.customMap = null; + f.customMap = Map(); }); } /// 获取针对 Range 类型进行value 检查。 DateRange、DateRangeCalendar 类型不需要检查,因为在选择时间的时候已经做了时间范围限制。 - BrnSelectionEntity getSelectRangeItem(List filterList) { + BrnSelectionEntity? _getSelectRangeItem(List filterList) { List ranges = filterList - ?.where((f) => - (f.filterType == BrnSelectionFilterType.Range || - f.filterType == BrnSelectionFilterType.DateRange || - f.filterType == BrnSelectionFilterType.DateRangeCalendar) && + .where((f) => + (f.filterType == BrnSelectionFilterType.range || + f.filterType == BrnSelectionFilterType.dateRange || + f.filterType == BrnSelectionFilterType.dateRangeCalendar) && f.isSelected) - ?.toList(); + .toList(); if (ranges.length > 0) { return ranges[0]; @@ -617,7 +573,7 @@ class _BrnRangeSelectionGroupWidgetState void _backgroundTap() { _resetSelectStatus(); if (widget.bgClickFunction != null) { - widget.bgClickFunction(); + widget.bgClickFunction!(); } } @@ -630,31 +586,29 @@ class _BrnRangeSelectionGroupWidgetState void _resetCustomMapData() { for (BrnSelectionEntity commonEntity in _originalSelectedItemsList) { commonEntity.isSelected = true; - if (commonEntity.originalCustomMap != null) { - commonEntity.customMap = Map.from(commonEntity.originalCustomMap); - } + commonEntity.customMap = Map.from(commonEntity.originalCustomMap); } } /// 如果自定义输入和默认选中都没有,则尝试默认高亮【不限】这种类型的 Tag。 - int getInitFocusedIndex(List subFilterList) { + int _getInitFocusedIndex(List subFilterList) { bool isCustomInputSelected = false; for (BrnSelectionEntity entity in subFilterList) { - if (BrnSelectionFilterType.Range == entity.filterType || - BrnSelectionFilterType.DateRange == entity.filterType || - BrnSelectionFilterType.DateRangeCalendar == entity.filterType) { + if (BrnSelectionFilterType.range == entity.filterType || + BrnSelectionFilterType.dateRange == entity.filterType || + BrnSelectionFilterType.dateRangeCalendar == entity.filterType) { isCustomInputSelected = entity.isSelected; break; } } var selectedItem = subFilterList - ?.where((f) => - f.filterType != BrnSelectionFilterType.Range && - f.filterType != BrnSelectionFilterType.DateRange && - f.filterType != BrnSelectionFilterType.DateRangeCalendar && + .where((f) => + f.filterType != BrnSelectionFilterType.range && + f.filterType != BrnSelectionFilterType.dateRange && + f.filterType != BrnSelectionFilterType.dateRangeCalendar && f.isSelected) - ?.toList(); + .toList(); if (!isCustomInputSelected && BrunoTools.isEmpty(selectedItem)) { for (BrnSelectionEntity item in subFilterList) { if (item.isUnLimit()) { @@ -666,32 +620,27 @@ class _BrnRangeSelectionGroupWidgetState return -1; } - bool hasCalendarItem(BrnSelectionEntity entity) { + bool _hasCalendarItem(BrnSelectionEntity entity) { bool hasCalendarItem = false; - if (entity != null && entity.children != null) { - /// 查找第一层级 - hasCalendarItem = entity.children - .where((_) => - _.filterType == BrnSelectionFilterType.Date || - _.filterType == BrnSelectionFilterType.DateRangeCalendar) - .toList() - .length > - 0; - - /// 查找第二层级 - if (!hasCalendarItem) { - for (BrnSelectionEntity subItem in entity.children) { - int count = subItem.children - ?.where((_) => - _.filterType == BrnSelectionFilterType.Date || - _.filterType == BrnSelectionFilterType.DateRangeCalendar) - ?.toList() - ?.length ?? - 0; - if (count > 0) { - hasCalendarItem = true; - break; - } + hasCalendarItem = entity.children + .where((_) => + _.filterType == BrnSelectionFilterType.date || + _.filterType == BrnSelectionFilterType.dateRangeCalendar) + .toList() + .length > 0; + + /// 查找第二层级 + if (!hasCalendarItem) { + for (BrnSelectionEntity subItem in entity.children) { + int count = subItem.children + .where((_) => + _.filterType == BrnSelectionFilterType.date || + _.filterType == BrnSelectionFilterType.dateRangeCalendar) + .toList() + .length; + if (count > 0) { + hasCalendarItem = true; + break; } } } diff --git a/lib/src/components/selection/widget/brn_selection_single_list_widget.dart b/lib/src/components/selection/widget/brn_selection_single_list_widget.dart index 2e084623..e578d08a 100644 --- a/lib/src/components/selection/widget/brn_selection_single_list_widget.dart +++ b/lib/src/components/selection/widget/brn_selection_single_list_widget.dart @@ -8,67 +8,55 @@ import 'package:flutter/material.dart'; // ignore: must_be_immutable class BrnSelectionSingleListWidget extends StatefulWidget { - List _selectedItems; - int focusedIndex = -1; + late List _selectedItems; + late int currentListIndex; + List items; - Color backgroundColor; - Color selectedBackgroundColor; int flex; - SingleListItemSelect singleListItemSelect; - int currentListIndex; + int focusedIndex; double maxHeight; + + Color? backgroundColor; + Color? selectedBackgroundColor; + SingleListItemSelect? singleListItemSelect; + BrnSelectionConfig themeData; BrnSelectionSingleListWidget({ - @required this.items, + Key? key, + required this.items, + required this.flex, + this.focusedIndex = -1, this.maxHeight = 0, this.backgroundColor, this.selectedBackgroundColor, - this.flex, - this.focusedIndex, this.singleListItemSelect, - this.themeData, - }) { - if (items == null) { - items = List(); - } else { - /// 自定义 Item 不在 list 样式中显示 - items = items - .where((_) => - _.filterType != BrnSelectionFilterType.Range && - _.filterType != BrnSelectionFilterType.Date && - _.filterType != BrnSelectionFilterType.DateRange && - _.filterType != BrnSelectionFilterType.DateRangeCalendar) - .toList(); - } + required this.themeData, + }) : super(key: key) { + items = items + .where((_) => + _.filterType != BrnSelectionFilterType.range && + _.filterType != BrnSelectionFilterType.date && + _.filterType != BrnSelectionFilterType.dateRange && + _.filterType != BrnSelectionFilterType.dateRangeCalendar) + .toList(); /// 当前 Items 所在的层级 - currentListIndex = BrnSelectionUtil.getCurrentListIndex( - items.length > 0 ? items[0] : null); - - _selectedItems = items?.where((f) => f.isSelected)?.toList(); - if (_selectedItems == null) { - _selectedItems = List(); - } + currentListIndex = BrnSelectionUtil.getCurrentListIndex(items.length > 0 ? items[0] : null); + _selectedItems = items.where((f) => f.isSelected).toList(); } @override - _BrnSelectionSingleListWidgetState createState() => - _BrnSelectionSingleListWidgetState(); - - List getSelectedItems() { - return _selectedItems; - } + _BrnSelectionSingleListWidgetState createState() => _BrnSelectionSingleListWidgetState(); } -class _BrnSelectionSingleListWidgetState - extends State { +class _BrnSelectionSingleListWidgetState extends State { @override Widget build(BuildContext context) { return Expanded( flex: widget.flex, child: Container( - constraints: (widget.maxHeight == null || widget.maxHeight == 0) + constraints: (widget.maxHeight == 0) ? BoxConstraints.expand() : BoxConstraints(maxHeight: widget.maxHeight), color: widget.backgroundColor, @@ -93,21 +81,14 @@ class _BrnSelectionSingleListWidgetState isMoreSelectionListType: false, isFirstLevel: (1 == widget.currentListIndex) ? true : false, itemSelectFunction: (BrnSelectionEntity entity) { - if ((entity.filterType == BrnSelectionFilterType.Checkbox && - !entity.isSelected) || - entity.filterType != BrnSelectionFilterType.Checkbox) { + if ((entity.filterType == BrnSelectionFilterType.checkbox && !entity.isSelected) || + entity.filterType != BrnSelectionFilterType.checkbox) { if (entity.hasCheckBoxBrother()) { if (entity.isUnLimit() && - entity.parent.children - .where((f) => f.isSelected) - .length > - 0 || - entity.parent.children - .where((f) => f.isSelected && f.isUnLimit()) - .length > - 0) { - ///点击的是不限类型,且不限类型同级别已经有选中的 Item 则不用检查数量。 - /// 不限类型已经选中,选择非不限类型时,什么也不做, + (entity.parent?.children.where((f) => f.isSelected).length ?? 0) > 0) { + /// 点击的是不限类型,且不限类型同级别已经有选中的 item,不检查数量限制。 + } else if((entity.parent?.children.where((f) => f.isSelected && f.isUnLimit()).length ?? 0) > 0){ + /// 同级别中,存在不限类型已经选中情况,选择非不限类型 item,不检查数量限制 } else if (entity.isInLastLevel() && !BrnSelectionUtil.checkMaxSelectionCount(entity)) { BrnToast.show("您选择的筛选条件数量已达上限", context); @@ -121,8 +102,9 @@ class _BrnSelectionSingleListWidgetState } } _processFilterData(entity); - widget.singleListItemSelect( - widget.currentListIndex, index, entity); + if(widget.singleListItemSelect != null) { + widget.singleListItemSelect!(widget.currentListIndex, index, entity); + } }, ); }, @@ -147,7 +129,7 @@ class _BrnSelectionSingleListWidgetState int totalLevel = BrnSelectionUtil.getTotalLevel(selectedEntity); if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent?.clearChildSelection(); } /// 设置选中数据。 @@ -162,11 +144,9 @@ class _BrnSelectionSingleListWidgetState /// Warning !!! /// (两列、三列时)第一列节点是否被选中取决于它的子节点是否被选中, /// 只有当它子节点被选中时才会认为第一列的节点相应被选中。 - if (widget.items != null && widget.items.length > 0) { - widget.items[0].parent?.isSelected = widget.items[0].parent.children - .where((BrnSelectionEntity f) => f.isSelected) - .length > - 0; + if (widget.items.length > 0) { + widget.items[0].parent?.isSelected = + (widget.items[0].parent?.children.where((BrnSelectionEntity f) => f.isSelected).length ?? 0)> 0; } for (BrnSelectionEntity item in widget.items) { @@ -183,22 +163,22 @@ class _BrnSelectionSingleListWidgetState } void configOneLevelList(BrnSelectionEntity selectedEntity) { - if (BrnSelectionFilterType.Radio == selectedEntity.filterType) { + if (BrnSelectionFilterType.radio == selectedEntity.filterType) { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent?.clearChildSelection(); selectedEntity.isSelected = true; - } else if (BrnSelectionFilterType.Checkbox == selectedEntity.filterType) { + } else if (BrnSelectionFilterType.checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent?.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 - var brotherItems; + List brotherItems; if (selectedEntity.parent == null) { brotherItems = widget.items; } else { - brotherItems = selectedEntity.parent.children; + brotherItems = selectedEntity.parent?.children ?? []; } for (BrnSelectionEntity entity in brotherItems) { if (entity.isUnLimit()) { @@ -210,34 +190,29 @@ class _BrnSelectionSingleListWidgetState } } - void configMultiLevelList( - BrnSelectionEntity selectedEntity, int currentListIndex) { + void configMultiLevelList(BrnSelectionEntity selectedEntity, int currentListIndex) { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 - if (BrnSelectionFilterType.Radio == selectedEntity.filterType) { - selectedEntity.parent?.children - ?.where((f) => f != selectedEntity) - ?.forEach((f) { + if (BrnSelectionFilterType.radio == selectedEntity.filterType) { + selectedEntity.parent?.children.where((f) => f != selectedEntity).forEach((f) { f.clearChildSelection(); f.isSelected = false; }); selectedEntity.isSelected = true; - } else if (BrnSelectionFilterType.Checkbox == selectedEntity.filterType) { + } else if (BrnSelectionFilterType.checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent?.children - ?.where((f) => f != selectedEntity) - ?.forEach((f) { + selectedEntity.parent?.children.where((f) => f != selectedEntity).forEach((f) { f.clearChildSelection(); f.isSelected = false; }); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 - var brotherItems; + List brotherItems; if (selectedEntity.parent == null) { brotherItems = widget.items; } else { - brotherItems = selectedEntity.parent.children; + brotherItems = selectedEntity.parent?.children ?? []; } for (BrnSelectionEntity entity in brotherItems) { if (entity.isUnLimit()) { diff --git a/lib/src/components/step/brn_horizontal_steps.dart b/lib/src/components/step/brn_horizontal_steps.dart index 996f6b3f..07c4749c 100644 --- a/lib/src/components/step/brn_horizontal_steps.dart +++ b/lib/src/components/step/brn_horizontal_steps.dart @@ -1,138 +1,103 @@ +import 'package:bruno/src/components/line/brn_line.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/material.dart'; +const double _kItemSidePadding = 5; /// 描述: 横向步骤条,是一种常见的导航形式,它具有导航通用的属性:告知用户”我在哪/我能去哪“, /// 步骤数目就相当于告知用户--能去哪或者说流程将要经历什么。 /// 通用组件步骤条分为三个状态:完成态/进行态/等待态,三种状态在样式上均加以区分 /// 注意事项:横向步骤条内的步骤总数最多只支持5个 -class BrnHorizontalStepsManager { - int maxCount = 0; - BrnStepsController controller = BrnStepsController(); - - /// - /// 构建步骤条widget - /// steps: 步骤条中元素的列表 - /// currentIndex: 指示当前进行态的步骤 - /// isCompleted: 整个流程是否完成 - /// doingIcon: 自定义正在进行状态的icon - /// completedIcon: 自定义已完成状态的icon - /// - Widget buildSteps( - {List steps, - int currentIndex, - bool isCompleted, - Widget doingIcon, - Widget completedIcon}) { - if (steps != null) { - maxCount = steps.length; - } - if (currentIndex != null) { - controller.currentIndex = currentIndex; - } - if (isCompleted != null) { - controller.isCompleted = isCompleted; - } - return Container( - child: BrnHorizontalSteps( - steps: steps, - controller: controller, - doingIcon: doingIcon, - completedIcon: completedIcon), - ); - } - - /// - /// 设置步骤条当前活跃的index - /// - void setCurrentIndex(int index) { - controller.setCurrentIndex(index); - } - - /// - /// 设置整个流程是否完成 - /// - void setIsCompleted(bool isCompleted) { - controller.setIsCompleted(isCompleted); - } - - /// - /// 向前一步 - /// - void forwardStep() { - if (controller.currentIndex < maxCount) { - controller.setCurrentIndex(controller.currentIndex + 1); - } - } - - /// - /// 向后一步 - /// - void backStep() { - int backIndex = - controller.currentIndex <= 0 ? 0 : controller.currentIndex - 1; - controller.setCurrentIndex(backIndex); - } -} - -// ignore: must_be_immutable class BrnHorizontalSteps extends StatefulWidget { /// The steps of the stepper whose titles, subtitles, icons always get shown. /// - /// The length of [steps] must not change. + /// 步骤条中元素的列表 final List steps; - BrnStepsController controller; + /// 控制类 + final BrnStepsController? controller; + + /// 自定义正在进行状态的icon + final Widget? doingIcon; - final Widget doingIcon; - final Widget completedIcon; + /// 自定义已完成状态的icon + final Widget? completedIcon; - BrnHorizontalSteps( - {this.steps, this.controller, this.doingIcon, this.completedIcon}) - : assert(steps.length < 6); + const BrnHorizontalSteps({ + Key? key, + required this.steps, + this.controller, + this.doingIcon, + this.completedIcon, + }) : assert(steps.length < 6), + super(key: key); @override - State createState() { - return BrnHorizontalStepsState(); - } + State createState() => BrnHorizontalStepsState(); } class BrnHorizontalStepsState extends State { - @override - void initState() { - super.initState(); - widget.controller?.addListener(_handleStepStateListenerTick); + Color get _primary { + return BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary; + } + + int get _currentIndex { + return widget.controller?.currentIndex ?? 0; + } + + Color _getStepContentTextColor(int index) { + return index > _currentIndex ? const Color(0xFFCCCCCC) : const Color(0xFF222222); } void _handleStepStateListenerTick() { setState(() {}); } + void _initController() { + widget.controller?._setMaxCount(widget.steps.length); + widget.controller?.addListener(_handleStepStateListenerTick); + } + + @override + void initState() { + super.initState(); + _initController(); + } + @override void dispose() { - super.dispose(); widget.controller?.removeListener(_handleStepStateListenerTick); + super.dispose(); } @override - Widget build(BuildContext context) { - return _buildHorizontalSteps(); + void didUpdateWidget(covariant BrnHorizontalSteps oldWidget) { + super.didUpdateWidget(oldWidget); + final bool isControllerDiff = + oldWidget.controller != null && widget.controller != oldWidget.controller; + final bool isCountDiff = widget.steps.length != oldWidget.steps.length; + if (isControllerDiff || isCountDiff) { + oldWidget.controller?.removeListener(_handleStepStateListenerTick); + _initController(); + } } - Widget _buildHorizontalSteps() { - Widget content; //单独一个widget组件,用于返回需要生成的内容widget + @override + Widget build(BuildContext context) { + /// 单独一个widget组件,用于返回需要生成的内容widget + Widget content; final List childrenList = []; - for (int i = 0; i < widget.steps.length; i += 1) { - childrenList.add(_applyStepItem(widget.steps[i], i)); - if (i < widget.steps.length - 1) { - childrenList.add(_applyLineItem(i)); - } + final List steps = widget.steps; + final int length = steps.length; + final int lastIndex = length - 1; + for (int i = 0; i < length; i += 1) { + childrenList.add(_applyStepItem(steps[i], i)); } content = Container( height: 78, - padding: EdgeInsets.fromLTRB(28, 0, 28, 0), child: Row( + mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: childrenList, ), @@ -140,15 +105,40 @@ class BrnHorizontalStepsState extends State { return content; } + Widget _applyStepItem(BrunoStep step, int index) { + return Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + _applyStepAndLine(step, index), + _applyStepContent(step, index), + ], + ), + ); + } + + Widget _applyStepAndLine(BrunoStep step, int index) { + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + index == 0 ? Expanded(child: SizedBox.shrink()) : _applyLineItem(index, true), + _applyStepIcon(step, index), + index == widget.steps.length - 1 + ? Expanded(child: SizedBox.shrink()) + : _applyLineItem(index, false), + ], + ); + } + Widget _applyStepIcon(BrunoStep step, int index) { Widget icon; - if (widget.controller.isCompleted) { + if (widget.controller?.isCompleted == true) { return _getCompletedIcon(step); } if (step.state != null) { switch (step.state) { case BrunoStepState.indexed: - icon = getIndexIcon(index); + icon = _getIndexIcon(index); break; case BrunoStepState.complete: icon = _getCompletedIcon(step); @@ -161,117 +151,111 @@ class BrnHorizontalStepsState extends State { break; } } else { - int currentIndex = widget.controller.currentIndex; - if (index < currentIndex) { + if (index < _currentIndex) { // 当前index小于指定的活跃index icon = _getCompletedIcon(step); - } else if (index == currentIndex) { + } else if (index == _currentIndex) { icon = _getDoingIcon(step); - } else if (index > currentIndex) { - icon = getIndexIcon(index); + } else { + icon = _getIndexIcon(index); } } return icon; } - Widget _applyStepItem(BrunoStep step, int index) { - return Container( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - _applyStepIcon(step, index), - _applyStepContent(step, index), - ], - ), - ); - } - - Widget _applyLineItem(int index) { + Widget _applyLineItem(int index, bool isLeft) { return Expanded( child: Container( - margin: EdgeInsets.fromLTRB(0, 0, 0, 28), - color: index >= widget.controller.currentIndex - ? Color(0xFFE7E7E7) - : BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary, - height: 1, + alignment: Alignment.center, + child: BrnLine( + height: 1, + leftInset: isLeft ? 0 : _kItemSidePadding, + rightInset: isLeft ? _kItemSidePadding : 0, + color: _getLineColor(index, isLeft), + ), ), ); } - Widget getIndexIcon(int index) { + Color _getLineColor(int index, bool isLeft) { + if (index < _currentIndex) { + return _primary; + } else if (_currentIndex == index && isLeft) { + return _primary; + } + return const Color(0xFFE7E7E7); + } + + Widget _getIndexIcon(int index) { Widget icon; switch (index) { case 1: - icon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_2, 20, 20); + icon = BrunoTools.getAssetSizeImage(BrnAsset.iconStep2, 20, 20); break; case 2: - icon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_3, 20, 20); + icon = BrunoTools.getAssetSizeImage(BrnAsset.iconStep3, 20, 20); break; case 3: - icon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_4, 20, 20); + icon = BrunoTools.getAssetSizeImage(BrnAsset.iconStep4, 20, 20); break; case 4: - icon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_5, 20, 20); + icon = BrunoTools.getAssetSizeImage(BrnAsset.iconStep5, 20, 20); break; default: - icon = BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_DOING, 20, 20); + icon = BrunoTools.getAssetSizeImage(BrnAsset.iconStepDoing, 20, 20); break; } return icon; } - _applyStepContent(BrunoStep step, int index) { - if (step.stepContent != null) { - return step.stepContent; + Widget _applyStepContent(BrunoStep step, int index) { + Widget? stepContent = step.stepContent; + if (stepContent != null) { + return stepContent; } return Container( - margin: EdgeInsets.only(top: 6), - child: Text( - step.stepContentText, - style: TextStyle( - fontSize: 14, - color: index > widget.controller.currentIndex - ? Color(0xFFCCCCCC) - : Color(0xFF222222), - ), - )); + margin: const EdgeInsets.only(top: 6, left: _kItemSidePadding, right: _kItemSidePadding), + child: Text( + step.stepContentText ?? '', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 14, + color: _getStepContentTextColor(index), + ), + ), + ); } Widget _getCompletedIcon(BrunoStep step) { - if (step.completedIcon != null) { - // 如果Step中自定义completedIcon不为空,则使用自定义的icon - return step.completedIcon; + Widget? completedIcon = step.completedIcon; + if (completedIcon != null) { + /// 如果Step中自定义completedIcon不为空,则使用自定义的icon + return completedIcon; } - if (widget.completedIcon != null) { - // 如果自定义completedIcon不为空,则使用自定义的icon - return widget.completedIcon; + completedIcon = widget.completedIcon; + if (completedIcon != null) { + /// 如果自定义completedIcon不为空,则使用自定义的icon + return completedIcon; } - // 使用组件默认的icon - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_COMPLETED, 20, 20, - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary); + + /// 使用组件默认的icon + return BrunoTools.getAssetSizeImage(BrnAsset.iconStepCompleted, 20, 20, color: _primary); } Widget _getDoingIcon(BrunoStep step) { - if (step.doingIcon != null) { - // 如果Step中自定义doingIcon不为空,则使用自定义的icon - return step.doingIcon; + Widget? doingIcon = step.doingIcon; + if (doingIcon != null) { + /// 如果Step中自定义doingIcon不为空,则使用自定义的icon + return doingIcon; } - if (widget.doingIcon != null) { - // 如果自定义doingIcon不为空,则使用自定义的icon - return widget.doingIcon; + doingIcon = widget.doingIcon; + if (doingIcon != null) { + /// 如果自定义doingIcon不为空,则使用自定义的icon + return doingIcon; } // 使用组件默认的icon - return BrunoTools.getAssetSizeImage(BrnAsset.ICON_STEP_DOING, 20, 20, - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary); + return BrunoTools.getAssetSizeImage(BrnAsset.iconStepDoing, 20, 20, color: _primary); } } @@ -286,49 +270,75 @@ enum BrunoStepState { complete } -@immutable class BrunoStep { /// Creates a step for a [Stepper]. /// - /// The [stepContent], [doingIcon] arguments must not be null. + /// The [stepContent], [doingIcon] arguments can be null. const BrunoStep({ this.stepContent, - this.stepContentText, this.doingIcon, + this.stepContentText, this.completedIcon, this.state, }); /// The String title of the step that typically describes it. - final String stepContentText; + final String? stepContentText; /// The title of the step that typically describes it. - final Widget stepContent; + final Widget? stepContent; /// The doingIcon of the step - final Widget doingIcon; + final Widget? doingIcon; /// The completedIcon of the step - final Widget completedIcon; + final Widget? completedIcon; /// The state of the step which determines the styling of its components /// and whether steps are interactive. - final BrunoStepState state; + final BrunoStepState? state; } class BrnStepsController with ChangeNotifier { - int currentIndex = 0; - bool isCompleted = false; + /// 指示当前进行态的步骤 + int currentIndex; - BrnStepsController({this.currentIndex, this.isCompleted}); + /// 整个流程是否完成 + bool isCompleted; - void setCurrentIndex(int index) { - currentIndex = index; - notifyListeners(); + /// 最大个数(最多只支持5个) + int _maxCount = 0; + + BrnStepsController({this.currentIndex = 0, this.isCompleted = false}); + + /// 只有在当前包内调用,不开放给外部调用 + void _setMaxCount(int _maxCount) { + this._maxCount = _maxCount; } - void setIsCompleted(bool isCompleted) { - this.isCompleted = isCompleted; + /// 设置当前步骤条的 index,从 0 开始。 + void setCurrentIndex(int currentIndex) { + if (this.currentIndex == currentIndex || currentIndex > _maxCount) return; + isCompleted = currentIndex == _maxCount; + this.currentIndex = currentIndex; notifyListeners(); } + + /// 整个链路完成 + void setCompleted() { + setCurrentIndex(_maxCount); + } + + /// 向前一步 + void forwardStep() { + if (currentIndex < _maxCount) { + setCurrentIndex(currentIndex + 1); + } + } + + /// 向后一步 + void backStep() { + final int backIndex = currentIndex <= 0 ? 0 : currentIndex - 1; + setCurrentIndex(backIndex); + } } diff --git a/lib/src/components/step/brn_step_line.dart b/lib/src/components/step/brn_step_line.dart index 1d4081a4..9567d8da 100644 --- a/lib/src/components/step/brn_step_line.dart +++ b/lib/src/components/step/brn_step_line.dart @@ -5,10 +5,10 @@ import 'package:flutter/material.dart'; ///[timeAxisSize]时间轴的大小必须要的。 /// ///线条顶部小圆点的大小 -final double _roundSize = 12; +const double _roundSize = 12; /// 线条和小圆点之间的间距 -final int _roundSpace = 4; +const double _roundSpace = 4; /// 在[contentWidget]的左侧自动添加 竖向步骤条的组件 /// @@ -85,7 +85,7 @@ class BrnStepLine extends StatefulWidget { ///整体是否是灰色,true 则使用normalColor,否则使用highlightColor final bool isGrey; - ///边框线的颜色:必须是Color 或者 List,如果未null,则会根据isGrey来使用normalColor或highlightColor + ///边框线的颜色:必须是Color 或者 List,如果为null,则会根据isGrey来使用normalColor或highlightColor final dynamic lineColor; /// 边框包裹的widget @@ -110,17 +110,17 @@ class BrnStepLine extends StatefulWidget { final double contentLeftPadding; /// 普通状态(isGrey=true)的颜色,默认值: Color(0xffeeeeee) - final Color normalColor; + final Color? normalColor; /// 高亮状态(isGrey=false)的颜色,默认值,主题色 - final Color highlightColor; + final Color? highlightColor; /// 自定义icon的widget - final Widget iconWidget; + final Widget? iconWidget; const BrnStepLine({ - Key key, - @required this.contentWidget, + Key? key, + required this.contentWidget, this.isGrey = false, this.lineColor, this.lineWidth = 2, @@ -129,10 +129,10 @@ class BrnStepLine extends StatefulWidget { this.dashLength = 4, this.dashSpace = 4, this.contentLeftPadding = 12, - this.normalColor = const Color(0xffeeeeee), + this.normalColor, this.highlightColor, this.iconWidget, - }); + }) : super(key: key); @override State createState() { @@ -147,12 +147,13 @@ class _BrnStepLineState extends State { children: [ CustomPaint( painter: _BrnStepLinePainter( - paintWidth: widget.lineWidth, - iconTopPadding: widget.iconTopPadding, - lineColor: _buildLineColor(), - isDash: widget.isDashLine, - dashLength: widget.dashLength, - dashSpace: widget.dashSpace), + paintWidth: widget.lineWidth, + iconTopPadding: widget.iconTopPadding, + lineColor: _buildLineColor(), + isDash: widget.isDashLine, + dashLength: widget.dashLength, + dashSpace: widget.dashSpace, + ), child: Container( padding: EdgeInsets.only(left: widget.contentLeftPadding), child: Container( @@ -169,7 +170,7 @@ class _BrnStepLineState extends State { } List _buildLineColor() { - List lineColor = List(); + List lineColor = []; if (widget.lineColor != null) { if (widget.lineColor is Color) { @@ -191,19 +192,18 @@ class _BrnStepLineState extends State { } } else { if (widget.isGrey) { - return List()..add(widget.normalColor ?? Color(0xffeeeeee)); + return [widget.normalColor ?? const Color(0xffeeeeee)]; } - return List() - ..add(widget.highlightColor ?? - BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary); + return [ + widget.highlightColor ?? + BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary + ]; } } Widget _buildGreyCircle() { - return _buildColorCircleWidget(widget.normalColor ?? Color(0xffeeeeee)); + return _buildColorCircleWidget( + widget.normalColor ?? const Color(0xffeeeeee)); } Widget _buildHighLightCircle() { @@ -235,38 +235,39 @@ class _BrnStepLineState extends State { class _BrnStepLinePainter extends CustomPainter { final List lineColor; - //边框的宽度 + /// 边框的宽度 final double paintWidth; - //icon距离顶部的padding + /// icon距离顶部的padding final double iconTopPadding; - //是否绘制虚线 + /// 是否绘制虚线 final bool isDash; - //虚线的间隔 + /// 虚线的间隔 final double dashSpace; - //虚线的长度 + /// 虚线的长度 final double dashLength; _BrnStepLinePainter( - {this.lineColor, - this.paintWidth = 1, - this.iconTopPadding, - this.isDash, - this.dashSpace, - this.dashLength}); + {required this.lineColor, + this.paintWidth = 1, + required this.iconTopPadding, + required this.isDash, + required this.dashSpace, + required this.dashLength}); - Paint _paint = Paint() - ..strokeCap = StrokeCap.round //画笔笔触类型 - ..isAntiAlias = true; //是否启动抗锯齿; //画笔的宽度 + final Paint _paint = Paint() + ..strokeCap = StrokeCap.round // 画笔笔触类型 + ..isAntiAlias = true; // 是否启动抗锯齿; @override void paint(Canvas canvas, Size size) { _paint.style = PaintingStyle.stroke; // 画线模式 - _paint.strokeWidth = this.paintWidth; - // 总长度 16是icon的长度 4是线条不通栏 + _paint.strokeWidth = paintWidth; + + /// 总长度 16是icon的长度 4是线条不通栏 double height = size.height - 16 - 4; if (height <= 0) { return; @@ -288,7 +289,7 @@ class _BrnStepLinePainter extends CustomPainter { int count = (height / (dashLength + dashSpace)).ceil(); for (int i = 0, n = count; i < n; i++) { - Path path = new Path(); + Path path = Path(); path.moveTo(_roundSize / 2, temp); if (temp + dashLength < size.height - _roundSpace) { temp += dashLength; @@ -312,7 +313,8 @@ class _BrnStepLinePainter extends CustomPainter { void _drawFillLine(double height, Canvas canvas) { double selection = height / lineColor.length; - //起始的位置 12是icon的长度 4是线条不通栏 化线的起点:icon的长度+自定义的icon的偏移量 + + /// 起始的位置 12是icon的长度 4是线条不通栏 化线的起点:icon的长度+自定义的icon的偏移量 double temp = 12 + 4 + iconTopPadding; for (int i = 0, n = lineColor.length; i < n; ++i) { _paint.color = lineColor[i]; diff --git a/lib/src/components/sugsearch/brn_search_text.dart b/lib/src/components/sugsearch/brn_search_text.dart index ec7531eb..ebd7befb 100644 --- a/lib/src/components/sugsearch/brn_search_text.dart +++ b/lib/src/components/sugsearch/brn_search_text.dart @@ -1,5 +1,4 @@ import 'package:bruno/src/constants/brn_asset_constants.dart'; -import 'package:bruno/src/constants/brn_strings_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/foundation.dart'; @@ -17,16 +16,16 @@ typedef BrnOnTextClear = bool Function(); /// 基本IOS风格搜索框, 提供输入回调 class BrnSearchText extends StatefulWidget { /// 提示语 - final String hintText; + final String? hintText; /// 提示语样式 - final TextStyle hintStyle; + final TextStyle? hintStyle; /// 输入框样式 - final TextStyle textStyle; + final TextStyle? textStyle; /// 用于设置搜索框前端的 Icon - final Widget prefixIcon; + final Widget? prefixIcon; /// 包裹搜索框的容器背景色 final Color outSideColor; @@ -38,7 +37,7 @@ class BrnSearchText extends StatefulWidget { final int maxLines; /// 最大输入长度 - final int maxLength; + final int? maxLength; /// 输入框最大高度,默认 60 final double maxHeight; @@ -47,44 +46,44 @@ class BrnSearchText extends StatefulWidget { final EdgeInsets innerPadding; ///普通状态的 border - final BoxBorder normalBorder; + final BoxBorder? normalBorder; /// 激活状态的 Border, 默认和 border 一致 - final BoxBorder activeBorder; + final BoxBorder? activeBorder; /// 输入框圆角 final BorderRadius borderRadius; /// 右侧操作 widget - final Widget action; + final Widget? action; /// 是否自动获取焦点 final bool autoFocus; /// 用于控制键盘动作 - final TextInputAction textInputAction; - final TextEditingController controller; - final FocusNode focusNode; + final TextInputAction? textInputAction; + final TextEditingController? controller; + final FocusNode? focusNode; /// 文本变化的回调 - final BrnOnSearchTextChange onTextChange; + final BrnOnSearchTextChange? onTextChange; /// 提交文本时的回调 - final BrnOnCommit onTextCommit; + final BrnOnCommit? onTextCommit; /// 右侧 action 区域点击的回调 - final VoidCallback onActionTap; + final VoidCallback? onActionTap; /// 清除按钮的回调 如果用户设置了该属性 /// 如果返回值为true,表明用户想要拦截,则不会走默认的清除行为 /// 如果返回值为false,表明用户不想要拦截,在执行了用户的行为之后,还会走默认的行为 - final BrnOnTextClear onTextClear; + final BrnOnTextClear? onTextClear; /// 用于控制清除 Icon 和右侧 Action 的显示与隐藏。等其他复杂的操作。 - final BrnSearchTextController searchController; + final BrnSearchTextController? searchController; const BrnSearchText({ - Key key, + Key? key, this.searchController, this.controller, this.maxLines = 1, @@ -118,12 +117,12 @@ class BrnSearchText extends StatefulWidget { } class _SearchTextState extends State { - FocusNode focusNode; - TextEditingController textEditingController; - BoxBorder border; - BrnSearchTextController searchTextController; + FocusNode? focusNode; + TextEditingController? textEditingController; + BoxBorder? border; + BrnSearchTextController? searchTextController; - BrnSearchTextController tmpController; + BrnSearchTextController? tmpController; @override void initState() { @@ -133,7 +132,7 @@ class _SearchTextState extends State { tmpController = BrnSearchTextController(); } searchTextController = widget.searchController ?? tmpController; - searchTextController.addListener(() { + searchTextController!.addListener(() { if (mounted) { setState(() {}); } @@ -146,7 +145,7 @@ class _SearchTextState extends State { color: widget.innerColor, ); - focusNode.addListener(_handleFocusNodeChangeListenerTick); + focusNode!.addListener(_handleFocusNodeChangeListenerTick); } @override @@ -154,12 +153,12 @@ class _SearchTextState extends State { // TODO: implement dispose super.dispose(); tmpController?.dispose(); - focusNode.removeListener(_handleFocusNodeChangeListenerTick); + focusNode!.removeListener(_handleFocusNodeChangeListenerTick); } /// 焦点状态回到,用于刷新当前 UI void _handleFocusNodeChangeListenerTick() { - if (focusNode.hasFocus) { + if (focusNode!.hasFocus) { border = widget.activeBorder ?? border; } else { border = widget.normalBorder ?? border; @@ -194,13 +193,8 @@ class _SearchTextState extends State { Padding( padding: const EdgeInsets.only(left: 14), child: Center( - child: Container( - child: Image.asset( - 'assets/${BrnAsset.ICON_SEARCH}', - package: BrnStrings.flutterPackageName, - height: 16, - width: 16, - )), + child: BrunoTools.getAssetSizeImage( + BrnAsset.iconSearch, 16, 16), ), ), Expanded( @@ -254,39 +248,38 @@ class _SearchTextState extends State { // 在改变属性,当正在编辑的文本发生更改时调用。 onChanged: (content) { if (widget.onTextChange != null) { - widget.onTextChange(content); + widget.onTextChange!(content); } setState(() {}); }, onSubmitted: (content) { if (widget.onTextCommit != null) { - widget.onTextCommit(content); + widget.onTextCommit!(content); } }), ), Visibility( - visible: searchTextController.isClearShow, + visible: searchTextController!.isClearShow, child: GestureDetector( onTap: () { if (widget.onTextClear != null) { - bool isIntercept = widget.onTextClear() ?? false; + bool isIntercept = widget.onTextClear!(); if (isIntercept) return; } - textEditingController.clear(); + textEditingController!.clear(); if (this.widget.onTextChange != null) { - this - .widget - .onTextChange(textEditingController.value.text); + this.widget.onTextChange!( + textEditingController!.value.text); } setState(() {}); }, child: Visibility( - visible: textEditingController.text.isNotEmpty, + visible: textEditingController!.text.isNotEmpty, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 12.0), child: BrunoTools.getAssetImage( - BrnAsset.ICON_DELETE_TEXT, + BrnAsset.iconDeleteText, ), ), ), @@ -297,12 +290,12 @@ class _SearchTextState extends State { ), ), Visibility( - visible: searchTextController.isActionShow, + visible: searchTextController!.isActionShow, child: widget.action ?? GestureDetector( onTap: () { if (widget.onActionTap != null) { - widget.onActionTap(); + widget.onActionTap!(); } }, child: Container( diff --git a/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_item.dart b/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_item.dart index 5a527bf1..0e8422a9 100644 --- a/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_item.dart +++ b/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_item.dart @@ -1,3 +1,5 @@ + + import 'dart:ui' show Color; import 'package:flutter/material.dart'; @@ -7,15 +9,14 @@ import 'package:flutter/material.dart'; /// 特别注意:Tab的右上角小红点可能不符合UI规范,可以使用BrnBadge小红点组件 class BrnBottomTabBarItem { const BrnBottomTabBarItem({ - @required this.icon, + required this.icon, this.title, - Widget activeIcon, + Widget? activeIcon, this.backgroundColor, this.badge, this.badgeNo, this.maxBadgeNo = 99, - }) : activeIcon = activeIcon ?? icon, - assert(icon != null); + }) : activeIcon = activeIcon ?? icon; /// 未选中时的icon final Widget icon; @@ -24,16 +25,16 @@ class BrnBottomTabBarItem { final Widget activeIcon; /// Tab标题名 - final Widget title; + final Widget? title; /// 背景色 - final Color backgroundColor; + final Color? backgroundColor; /// 未读信息 - final Widget badge; + final Widget? badge; /// 未读信息个数 - final String badgeNo; + final String? badgeNo; /// 未读消息最大个数 final int maxBadgeNo; diff --git a/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_main.dart b/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_main.dart index 9ec1c5d3..40cb9016 100644 --- a/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_main.dart +++ b/lib/src/components/tabbar/bottom/brn_bottom_tab_bar_main.dart @@ -1,3 +1,5 @@ + + import 'dart:collection' show Queue; import 'dart:math' as math; @@ -10,9 +12,9 @@ const double _kActiveFontSize = 10.0; const double _kInactiveFontSize = 9.0; const double _kTopMargin = 6.0; const double _kBottomMargin = 0.0; -const double _kmiddleInterval = 4.0; +const double _kMiddleInterval = 4.0; -/// Tabbar显示状态 +/// tabBar显示状态 enum BrnBottomTabBarDisplayType { /// 固定显示状态 fixed, @@ -26,8 +28,8 @@ enum BrnBottomTabBarDisplayType { /// 特别注意:默认关闭点击动画,为固定显示状态 class BrnBottomTabBar extends StatefulWidget { BrnBottomTabBar({ - Key key, - @required this.items, + Key? key, + required this.items, this.onTap, this.currentIndex = 0, BrnBottomTabBarDisplayType type = BrnBottomTabBarDisplayType.fixed, @@ -36,25 +38,22 @@ class BrnBottomTabBar extends StatefulWidget { this.isAnimation = false, this.badgeColor, this.isInkResponse = false, - }) : assert(items != null), - assert(items.length >= 1), + }) : assert(items.length >= 1), assert( items.every((BrnBottomTabBarItem item) => item.title != null) == true, 'Every item must have a non-null title', ), assert(0 <= currentIndex && currentIndex < items.length), - assert(iconSize != null), - type = type ?? - (items.length <= 3 + type = items.length <= 3 ? BrnBottomTabBarDisplayType.fixed - : BrnBottomTabBarDisplayType.shifting), + : BrnBottomTabBarDisplayType.shifting, super(key: key); /// 动画是否可见,默认:true final bool isAnimation; /// 未读弹窗背景颜色,默认:fixedColor - final Color badgeColor; + final Color? badgeColor; /// InkResponse:是否可访问, 默认:true final bool isInkResponse; @@ -63,7 +62,7 @@ class BrnBottomTabBar extends StatefulWidget { final List items; /// Tab点击之后的回调函数 - final ValueChanged onTap; + final ValueChanged? onTap; /// 当前活动项的索引值 final int currentIndex; @@ -72,7 +71,7 @@ class BrnBottomTabBar extends StatefulWidget { final BrnBottomTabBarDisplayType type; /// 底部Tab所选中时的颜色 - final Color fixedColor; + final Color? fixedColor; /// Tab中图标的大小 final double iconSize; @@ -96,29 +95,29 @@ class _BottomNavigationTile extends StatelessWidget { this.isAnimation = true, this.isInkResponse = true, this.badgeColor, - }) : assert(selected != null); + }) ; final BrnBottomTabBarDisplayType type; final BrnBottomTabBarItem item; final Animation animation; final double iconSize; - final VoidCallback onTap; - final ColorTween colorTween; - final double flex; + final VoidCallback? onTap; + final ColorTween? colorTween; + final double? flex; final bool selected; - final String indexLabel; + final String? indexLabel; final bool isAnimation; final bool isInkResponse; - final Color badgeColor; + final Color? badgeColor; /// 构建icon Widget _buildIcon() { - double tweenStart; - Color iconColor; + double? tweenStart; + Color? iconColor; switch (type) { case BrnBottomTabBarDisplayType.fixed: tweenStart = 8.0; - iconColor = colorTween.evaluate(animation); + iconColor = colorTween?.evaluate(animation); break; case BrnBottomTabBarDisplayType.shifting: tweenStart = 16.0; @@ -148,7 +147,7 @@ class _BottomNavigationTile extends StatelessWidget { ); } - /// 构建固定Lable + /// 构建固定Label /// 修改icon与text间距在这里修改 Widget _buildFixedLabel() { double scale = isAnimation @@ -162,11 +161,11 @@ class _BottomNavigationTile extends StatelessWidget { heightFactor: 1.0, child: Container( margin: const EdgeInsets.only( - bottom: _kBottomMargin, top: _kmiddleInterval), + bottom: _kBottomMargin, top: _kMiddleInterval), child: DefaultTextStyle.merge( style: TextStyle( fontSize: _kActiveFontSize, - color: colorTween.evaluate(animation), + color: colorTween?.evaluate(animation), ), /// 使用矩阵变化控制字体大小 @@ -184,7 +183,7 @@ class _BottomNavigationTile extends StatelessWidget { ); } - /// 构建可变Lable + /// 构建可变Label Widget _buildShiftingLabel() { return Align( alignment: Alignment.bottomCenter, @@ -206,7 +205,7 @@ class _BottomNavigationTile extends StatelessWidget { fontSize: _kActiveFontSize, color: Colors.blue, ), - child: item.title, + child: item.title!, ), ), ), @@ -214,8 +213,8 @@ class _BottomNavigationTile extends StatelessWidget { } /// 构建未读消息弹窗 - Widget _buildBadge() { - if (item.badge == null && (item.badgeNo == null || item.badgeNo.isEmpty)) { + Widget? _buildBadge() { + if (item.badge == null && (item.badgeNo == null || item.badgeNo!.isEmpty)) { return Container(); } if (item.badge != null) { @@ -231,15 +230,27 @@ class _BottomNavigationTile extends StatelessWidget { borderRadius: BorderRadius.all(Radius.circular(10))), child: Text( /// 设置未读数 > item.maxBadgeNo 则报加+ 默认 99 - '${int.parse(item.badgeNo) > item.maxBadgeNo ? '${item.maxBadgeNo}+' : item.badgeNo}', + _getUnReadText(), style: TextStyle(fontSize: 10, color: Colors.white), ), ); } + String _getUnReadText(){ + int _badgeNo = 0; + try { + if (item.badgeNo != null) { + _badgeNo = int.parse(item.badgeNo!); + } + } catch (e) { + debugPrint('badgeNo has FormatException'); + } + return '${_badgeNo > item.maxBadgeNo ? '${item.maxBadgeNo}+' : _badgeNo}'; + } + /// 构建底字体缩放动画 /// label: 传入的文字组件 - Widget _buildInkWidget(Widget label) { + Widget _buildInkWidget(Widget? label) { if (isInkResponse) { return InkResponse( onTap: onTap, @@ -249,7 +260,7 @@ class _BottomNavigationTile extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ _buildIcon(), - label, + label!, ], ), ); @@ -262,7 +273,7 @@ class _BottomNavigationTile extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ _buildIcon(), - label, + label!, ], )); } @@ -273,15 +284,15 @@ class _BottomNavigationTile extends StatelessWidget { /// 需要将flex分配中的更改划分为更小的块 /// 制作流畅的动画。我们通过将flex值相乘来实现这一点 /// (这是一个整数)乘以一个大数。 - int size; - Widget label; + late int size; + Widget? label; switch (type) { case BrnBottomTabBarDisplayType.fixed: size = 1; label = _buildFixedLabel(); break; case BrnBottomTabBarDisplayType.shifting: - size = (flex * 1000.0).round(); + size = (flex! * 1000.0).round(); label = _buildShiftingLabel(); break; } @@ -294,7 +305,7 @@ class _BottomNavigationTile extends StatelessWidget { selected: selected, child: Stack( children: [ - Positioned(right: 4, top: 4, child: _buildBadge()), + Positioned(right: 4, top: 4, child: _buildBadge()!), _buildInkWidget(label), Semantics( label: indexLabel, @@ -310,13 +321,13 @@ class _BottomNavigationTile extends StatelessWidget { class _BottomTabBarState extends State with TickerProviderStateMixin { List _controllers = []; - List _animations; + late List _animations; /// 当前正在执行图标变色逻辑的队列 final Queue<_Circle> _circles = Queue<_Circle>(); /// 执行完动画之后的背景颜色 - Color _backgroundColor; + Color? _backgroundColor; static final Animatable _flexTween = Tween(begin: 1.0, end: 1.5); @@ -373,7 +384,7 @@ class _BottomTabBarState extends State _Circle( state: this, index: index, - color: widget.items[index].backgroundColor, + color: widget.items[index].backgroundColor!, vsync: this, )..controller.addStatusListener( (AnimationStatus status) { @@ -427,13 +438,12 @@ class _BottomTabBarState extends State List _createTiles() { final MaterialLocalizations localizations = MaterialLocalizations.of(context); - assert(localizations != null); final List children = []; switch (widget.type) { case BrnBottomTabBarDisplayType.fixed: final ThemeData themeData = Theme.of(context); final TextTheme textTheme = themeData.textTheme; - Color themeColor; + Color? themeColor; switch (themeData.brightness) { case Brightness.light: themeColor = themeData.primaryColor; @@ -443,7 +453,7 @@ class _BottomTabBarState extends State break; } final ColorTween colorTween = ColorTween( - begin: textTheme.caption.color, + begin: textTheme.caption!.color, end: widget.fixedColor ?? themeColor, ); for (int i = 0; i < widget.items.length; i += 1) { @@ -454,7 +464,7 @@ class _BottomTabBarState extends State _animations[i], widget.iconSize, onTap: () { - if (widget.onTap != null) widget.onTap(i); + if (widget.onTap != null) widget.onTap!(i); }, colorTween: colorTween, selected: i == widget.currentIndex, @@ -478,7 +488,7 @@ class _BottomTabBarState extends State _animations[i], widget.iconSize, onTap: () { - if (widget.onTap != null) widget.onTap(i); + if (widget.onTap != null) widget.onTap!(i); }, flex: _evaluateFlex(_animations[i]), selected: i == widget.currentIndex, @@ -518,7 +528,7 @@ class _BottomTabBarState extends State /// 下标题距底部距离 final double additionalBottomPadding = math.max(MediaQuery.of(context).padding.bottom - _kBottomMargin, 0.0); - Color backgroundColor; + Color? backgroundColor; switch (widget.type) { case BrnBottomTabBarDisplayType.fixed: break; @@ -577,13 +587,11 @@ class _BottomTabBarState extends State /// 功能:实现点击飞溅动画 class _Circle { _Circle({ - @required this.state, - @required this.index, - @required this.color, - @required TickerProvider vsync, - }) : assert(state != null), - assert(index != null), - assert(color != null) { + required this.state, + required this.index, + required this.color, + required TickerProvider vsync, + }) { controller = AnimationController( duration: kThemeAnimationDuration, vsync: vsync, @@ -598,8 +606,8 @@ class _Circle { final _BottomTabBarState state; final int index; final Color color; - AnimationController controller; - CurvedAnimation animation; + late AnimationController controller; + late CurvedAnimation animation; double get horizontalLeadingOffset { double weightSum(Iterable> animations) { @@ -629,10 +637,9 @@ class _Circle { /// 绘制动画色彩飞溅的圆圈 class _RadialPainter extends CustomPainter { _RadialPainter({ - @required this.circles, - @required this.textDirection, - }) : assert(circles != null), - assert(textDirection != null); + required this.circles, + required this.textDirection, + }); final List<_Circle> circles; final TextDirection textDirection; @@ -661,7 +668,7 @@ class _RadialPainter extends CustomPainter { final Paint paint = Paint()..color = circle.color; final Rect rect = Rect.fromLTWH(0.0, 0.0, size.width, size.height); canvas.clipRect(rect); - double leftFraction; + late double leftFraction; switch (textDirection) { case TextDirection.rtl: leftFraction = 1.0 - circle.horizontalLeadingOffset; diff --git a/lib/src/components/tabbar/indicator/brn_custom_width_indicator.dart b/lib/src/components/tabbar/indicator/brn_custom_width_indicator.dart index e2c80176..a3d36225 100644 --- a/lib/src/components/tabbar/indicator/brn_custom_width_indicator.dart +++ b/lib/src/components/tabbar/indicator/brn_custom_width_indicator.dart @@ -1,3 +1,5 @@ + + import 'package:flutter/material.dart'; class CustomWidthUnderlineTabIndicator extends Decoration { @@ -25,35 +27,35 @@ class CustomWidthUnderlineTabIndicator extends Decoration { final double width; @override - Decoration lerpFrom(Decoration a, double t) { + Decoration? lerpFrom(Decoration? a, double t) { if (a is CustomWidthUnderlineTabIndicator) { return CustomWidthUnderlineTabIndicator( borderSide: BorderSide.lerp(a.borderSide, borderSide, t), - insets: EdgeInsetsGeometry.lerp(a.insets, insets, t), + insets: EdgeInsetsGeometry.lerp(a.insets, insets, t)!, ); } return super.lerpFrom(a, t); } @override - Decoration lerpTo(Decoration b, double t) { + Decoration? lerpTo(Decoration? b, double t) { if (b is CustomWidthUnderlineTabIndicator) { return CustomWidthUnderlineTabIndicator( borderSide: BorderSide.lerp(borderSide, b.borderSide, t), - insets: EdgeInsetsGeometry.lerp(insets, b.insets, t), + insets: EdgeInsetsGeometry.lerp(insets, b.insets, t)!, ); } return super.lerpTo(b, t); } @override - _UnderlinePainter createBoxPainter([VoidCallback onChanged]) { + _UnderlinePainter createBoxPainter([VoidCallback? onChanged]) { return _UnderlinePainter(this, width, onChanged); } } class _UnderlinePainter extends BoxPainter { - _UnderlinePainter(this.decoration, this.width, VoidCallback onChanged) + _UnderlinePainter(this.decoration, this.width, VoidCallback? onChanged) : assert(decoration != null), super(onChanged); @@ -70,7 +72,7 @@ class _UnderlinePainter extends BoxPainter { assert(textDirection != null); final Rect indicator = insets.resolve(textDirection).deflateRect(rect); //希望的宽度 - double wantWidth = width ?? 24; + double wantWidth = width; //取中间坐标 double cw = (indicator.left + indicator.right) / 2; return Rect.fromLTWH(cw - wantWidth / 2, @@ -81,8 +83,8 @@ class _UnderlinePainter extends BoxPainter { void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { assert(configuration != null); assert(configuration.size != null); - final Rect rect = offset & configuration.size; - final TextDirection textDirection = configuration.textDirection; + final Rect rect = offset & configuration.size!; + final TextDirection textDirection = configuration.textDirection!; final Rect indicator = _indicatorRectFor(rect, textDirection).deflate(borderSide.width / 2.0); final Paint paint = borderSide.toPaint()..strokeCap = StrokeCap.round; diff --git a/lib/src/components/tabbar/indicator/brn_fixed_underline_decoration.dart b/lib/src/components/tabbar/indicator/brn_fixed_underline_decoration.dart index 5ed7dc14..f0a27e8a 100644 --- a/lib/src/components/tabbar/indicator/brn_fixed_underline_decoration.dart +++ b/lib/src/components/tabbar/indicator/brn_fixed_underline_decoration.dart @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + + import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; @@ -46,35 +48,35 @@ class BrnFixedUnderlineIndicator extends Decoration { final Color color; @override - Decoration lerpFrom(Decoration a, double t) { + Decoration? lerpFrom(Decoration? a, double t) { if (a is BrnFixedUnderlineIndicator) { return BrnFixedUnderlineIndicator( borderSide: BorderSide.lerp(a.borderSide, borderSide, t), - insets: EdgeInsetsGeometry.lerp(a.insets, insets, t), + insets: EdgeInsetsGeometry.lerp(a.insets, insets, t)!, ); } return super.lerpFrom(a, t); } @override - Decoration lerpTo(Decoration b, double t) { + Decoration? lerpTo(Decoration? b, double t) { if (b is BrnFixedUnderlineIndicator) { return BrnFixedUnderlineIndicator( borderSide: BorderSide.lerp(borderSide, b.borderSide, t), - insets: EdgeInsetsGeometry.lerp(insets, b.insets, t), + insets: EdgeInsetsGeometry.lerp(insets, b.insets, t)!, ); } return super.lerpTo(b, t); } @override - _FixedUnderlinePainter createBoxPainter([VoidCallback onChanged]) { + _FixedUnderlinePainter createBoxPainter([VoidCallback? onChanged]) { return _FixedUnderlinePainter(this, onChanged); } } class _FixedUnderlinePainter extends BoxPainter { - _FixedUnderlinePainter(this.decoration, VoidCallback onChanged) + _FixedUnderlinePainter(this.decoration, VoidCallback? onChanged) : assert(decoration != null), super(onChanged); @@ -100,8 +102,8 @@ class _FixedUnderlinePainter extends BoxPainter { void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { assert(configuration != null); assert(configuration.size != null); - final Rect rect = offset & configuration.size; - final TextDirection textDirection = configuration.textDirection; + final Rect rect = offset & configuration.size!; + final TextDirection textDirection = configuration.textDirection!; final Rect indicator = _indicatorRectFor(rect, textDirection).deflate(borderSide.width / 2.0); final Paint paint = borderSide.toPaint()..strokeCap = StrokeCap.square; diff --git a/lib/src/components/tabbar/indicator/brn_triangle_decoration.dart b/lib/src/components/tabbar/indicator/brn_triangle_decoration.dart index 3b500068..60bccfb6 100644 --- a/lib/src/components/tabbar/indicator/brn_triangle_decoration.dart +++ b/lib/src/components/tabbar/indicator/brn_triangle_decoration.dart @@ -2,19 +2,21 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. + + import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; /// 三角形指示器 参考ShapeDecoration class BrnTriangleIndicator extends Decoration { - final Color color; // 指示器颜色 + final Color? color; // 指示器颜色 final double lineWidth; final double triWidth; // 三角形底边长 final double triHeight; // 三角形高 - final Gradient gradient; - final DecorationImage image; - final List shadows; - final ShapeBorder shape; + final Gradient? gradient; + final DecorationImage? image; + final List? shadows; + final ShapeBorder? shape; const BrnTriangleIndicator({ this.color = Colors.white, @@ -28,23 +30,23 @@ class BrnTriangleIndicator extends Decoration { }); factory BrnTriangleIndicator.fromBoxDecoration(BoxDecoration source) { - ShapeBorder shape; + ShapeBorder? shape; assert(source.shape != null); switch (source.shape) { case BoxShape.circle: if (source.border != null) { - assert(source.border.isUniform); - shape = CircleBorder(side: source.border.top); + assert(source.border!.isUniform); + shape = CircleBorder(side: source.border!.top); } else { shape = const CircleBorder(); } break; case BoxShape.rectangle: if (source.borderRadius != null) { - assert(source.border == null || source.border.isUniform); + assert(source.border == null || source.border!.isUniform); shape = RoundedRectangleBorder( side: source.border?.top ?? BorderSide.none, - borderRadius: source.borderRadius, + borderRadius: source.borderRadius!, ); } else { shape = source.border ?? const Border(); @@ -65,35 +67,35 @@ class BrnTriangleIndicator extends Decoration { /// /// This value may be misleading. See the discussion at [ShapeBorder.dimensions]. @override - EdgeInsets get padding => shape.dimensions; + EdgeInsets get padding => shape!.dimensions as EdgeInsets; @override bool get isComplex => shadows != null; @override - BrnTriangleIndicator lerpFrom(Decoration a, double t) { + BrnTriangleIndicator? lerpFrom(Decoration? a, double t) { if (a is BoxDecoration) { return BrnTriangleIndicator.lerp( BrnTriangleIndicator.fromBoxDecoration(a), this, t); } else if (a == null || a is BrnTriangleIndicator) { - return BrnTriangleIndicator.lerp(a, this, t); + return BrnTriangleIndicator.lerp(a as BrnTriangleIndicator?, this, t); } - return super.lerpFrom(a, t); + return super.lerpFrom(a, t) as BrnTriangleIndicator?; } @override - BrnTriangleIndicator lerpTo(Decoration b, double t) { + BrnTriangleIndicator? lerpTo(Decoration? b, double t) { if (b is BoxDecoration) { return BrnTriangleIndicator.lerp( this, BrnTriangleIndicator.fromBoxDecoration(b), t); } else if (b == null || b is BrnTriangleIndicator) { - return BrnTriangleIndicator.lerp(this, b, t); + return BrnTriangleIndicator.lerp(this, b as BrnTriangleIndicator?, t); } - return super.lerpTo(b, t); + return super.lerpTo(b, t) as BrnTriangleIndicator?; } - static BrnTriangleIndicator lerp( - BrnTriangleIndicator a, BrnTriangleIndicator b, double t) { + static BrnTriangleIndicator? lerp( + BrnTriangleIndicator? a, BrnTriangleIndicator? b, double t) { assert(t != null); if (a == null && b == null) return null; if (a != null && b != null) { @@ -103,7 +105,7 @@ class BrnTriangleIndicator extends Decoration { return BrnTriangleIndicator( color: Color.lerp(a?.color, b?.color, t), gradient: Gradient.lerp(a?.gradient, b?.gradient, t), - image: t < 0.5 ? a.image : b.image, + image: t < 0.5 ? a?.image : b?.image, shadows: BoxShadow.lerpList(a?.shadows, b?.shadows, t), shape: ShapeBorder.lerp(a?.shape, b?.shape, t), ); @@ -154,14 +156,14 @@ class BrnTriangleIndicator extends Decoration { } @override - bool hitTest(Size size, Offset position, {TextDirection textDirection}) { - return shape + bool hitTest(Size size, Offset position, {TextDirection? textDirection}) { + return shape! .getOuterPath(Offset.zero & size, textDirection: textDirection) .contains(position); } @override - _TriangleDecorationPainter createBoxPainter([VoidCallback onChanged]) { + _TriangleDecorationPainter createBoxPainter([VoidCallback? onChanged]) { assert(onChanged != null || image == null); Path path = Path(); Paint paint = Paint()..isAntiAlias = true; @@ -172,7 +174,7 @@ class BrnTriangleIndicator extends Decoration { /// An object that paints a [BrnTriangleIndicator] into a canvas. class _TriangleDecorationPainter extends BoxPainter { _TriangleDecorationPainter( - this._decoration, this._path, this._paint, VoidCallback onChanged) + this._decoration, this._path, this._paint, VoidCallback? onChanged) : assert(_decoration != null), super(onChanged); @@ -195,7 +197,7 @@ class _TriangleDecorationPainter extends BoxPainter { _path.lineTo(_vertexX + width / 2, _vertexY + height / 2); _path.close(); - _paint..color = _decoration.color; + _paint..color = _decoration.color!; _paint..strokeWidth = _decoration.lineWidth; canvas.drawPath(_path, _paint); @@ -211,7 +213,7 @@ class _TriangleDecorationPainter extends BoxPainter { void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) { assert(configuration != null); assert(configuration.size != null); - final Rect rect = offset & configuration.size; + final Rect rect = offset & configuration.size!; _paintTriangle(canvas, offset, rect, configuration); } diff --git a/lib/src/components/tabbar/normal/brn_sub_switch_title.dart b/lib/src/components/tabbar/normal/brn_sub_switch_title.dart index 0eb3b1a9..47d43f5c 100644 --- a/lib/src/components/tabbar/normal/brn_sub_switch_title.dart +++ b/lib/src/components/tabbar/normal/brn_sub_switch_title.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; @@ -12,18 +14,18 @@ class BrnSubSwitchTitle extends StatefulWidget { final int defaultSelectIndex; /// 选中回调 - final void Function(int index) onSelect; + final void Function(int index)? onSelect; /// 二级标题的padding /// 默认 EdgeInsets.only(right: 20) - final EdgeInsets padding; + final EdgeInsets? padding; /// tab切换控制器,默认不需要传递 - final TabController controller; + final TabController? controller; const BrnSubSwitchTitle({ - Key key, - @required this.nameList, + Key? key, + required this.nameList, this.defaultSelectIndex = 0, this.onSelect, this.padding, @@ -36,9 +38,9 @@ class BrnSubSwitchTitle extends StatefulWidget { class _BrnSubSwitchTitleState extends State with TickerProviderStateMixin { - List widgetList; + List? widgetList; - TabController _controller; + TabController? _controller; int _defaultSelectIndex = 0; @@ -49,7 +51,7 @@ class _BrnSubSwitchTitleState extends State _controller = widget.controller ?? TabController( initialIndex: _defaultSelectIndex, - length: widget.nameList?.length ?? 0, + length: widget.nameList.length, vsync: this, ); } @@ -59,7 +61,7 @@ class _BrnSubSwitchTitleState extends State super.didUpdateWidget(oldWidget); _defaultSelectIndex = widget.defaultSelectIndex; if (_controller != null) { - _controller.index = _defaultSelectIndex; + _controller!.index = _defaultSelectIndex; } } @@ -69,7 +71,7 @@ class _BrnSubSwitchTitleState extends State } Widget _toggleButtonsWidget(context) { - if (widget.nameList == null || widget.nameList.isEmpty) { + if (widget.nameList.isEmpty) { return Container( height: 0, width: 0, @@ -115,7 +117,7 @@ class _BrnSubSwitchTitleState extends State ), onTap: (index) { if (null != widget.onSelect) { - widget.onSelect(index); + widget.onSelect!(index); } }, ); diff --git a/lib/src/components/tabbar/normal/brn_switch_title.dart b/lib/src/components/tabbar/normal/brn_switch_title.dart index 4b955a82..2ddcdba4 100644 --- a/lib/src/components/tabbar/normal/brn_switch_title.dart +++ b/lib/src/components/tabbar/normal/brn_switch_title.dart @@ -1,3 +1,5 @@ + + import 'package:bruno/src/components/line/brn_line.dart'; import 'package:bruno/src/components/tabbar/indicator/brn_custom_width_indicator.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; @@ -15,7 +17,7 @@ class BrnSwitchTitle extends StatefulWidget { /// 选中时的回调 /// index 选中的title的索引 - final void Function(int index) onSelect; + final void Function(int index)? onSelect; /// 标题的 padding,默认 `EdgeInsets.fromLTRB(0, 14, 20, 14)` final EdgeInsets padding; @@ -28,17 +30,17 @@ class BrnSwitchTitle extends StatefulWidget { /// 控制tab切换,默认不需要传递 /// 只在需要外部控制tab切换时传递 - final TabController controller; + final TabController? controller; /// 选中时的标题样式,默认 `TextStyle(fontWeight: FontWeight.w600,fontSize: 18)` - final TextStyle selectedTextStyle; + final TextStyle? selectedTextStyle; /// 未选中时的标题样式,默认 `TextStyle(fontWeight: FontWeight.w600,fontSize: 18)` - final TextStyle unselectedTextStyle; + final TextStyle? unselectedTextStyle; const BrnSwitchTitle( - {Key key, - @required this.nameList, + {Key? key, + required this.nameList, this.defaultSelectIndex = 0, this.onSelect, this.indicatorWeight = 2.0, @@ -57,7 +59,7 @@ class _BrnSwitchTitleState extends State with TickerProviderStateMixin { static final Color _color = Color(0XFF243238); - TabController _controller; + TabController? _controller; int _defaultSelectIndex = 0; @@ -66,7 +68,7 @@ class _BrnSwitchTitleState extends State super.didUpdateWidget(oldWidget); _defaultSelectIndex = widget.defaultSelectIndex; if (_controller != null) { - _controller.index = _defaultSelectIndex; + _controller!.index = _defaultSelectIndex; } } @@ -84,7 +86,7 @@ class _BrnSwitchTitleState extends State @override Widget build(BuildContext context) { - if (widget.nameList != null && widget.nameList.length > 1) { + if (widget.nameList.length > 1) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, @@ -110,7 +112,7 @@ class _BrnSwitchTitleState extends State Text tx = Text(name); /// 有下划线的时候,需要将下划线的高度3减去 - double tempBottomPadding = widget.padding?.bottom ?? 0; + double tempBottomPadding = widget.padding.bottom; double bottomPadding = widget.nameList.length == 1 ? tempBottomPadding : tempBottomPadding - 3; @@ -120,20 +122,20 @@ class _BrnSwitchTitleState extends State return Container( padding: EdgeInsets.fromLTRB( - widget.padding?.left ?? 0, - widget.padding?.top ?? 0, - widget.padding?.right ?? 0, + widget.padding.left, + widget.padding.top, + widget.padding.right, bottomPadding), child: tx, ); }).toList(); Decoration _indicator = CustomWidthUnderlineTabIndicator( - width: widget.indicatorWidth ?? 24.0, + width: widget.indicatorWidth, insets: EdgeInsets.only( - left: widget.padding?.left ?? 0, right: widget.padding?.right ?? 0), + left: widget.padding.left, right: widget.padding.right), borderSide: BorderSide( - width: widget.indicatorWeight ?? 2.0, + width: widget.indicatorWeight, color: BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, ), @@ -173,7 +175,7 @@ class _BrnSwitchTitleState extends State indicatorWeight: 0, onTap: (index) { if (null != widget.onSelect && widget.nameList.length > 1) { - widget.onSelect(index); + widget.onSelect!(index); } }, ), diff --git a/lib/src/components/tabbar/normal/brn_tab_bar.dart b/lib/src/components/tabbar/normal/brn_tab_bar.dart index 825605ce..121eb38a 100644 --- a/lib/src/components/tabbar/normal/brn_tab_bar.dart +++ b/lib/src/components/tabbar/normal/brn_tab_bar.dart @@ -15,12 +15,12 @@ import 'package:flutter/rendering.dart'; /// [state]:当前组件的State对象,[BrnTabBarState] /// [index]:当前组件的角标 typedef BrnTabBarOnTap = Function(BrnTabBarState state, int index); - +const double _tagDefaultSize = 75.0; /// 带小红点的Tabbar // ignore: must_be_immutable class BrnTabBar extends StatefulWidget { /// BrnTabBarBadge填充的数据,长度匹配控制器的TabController.length - final List tabs; + final List? tabs; /// [BrnTabBar] 的tab模式 /// 默认:[BrnTabBarBadgeMode.average](按照屏幕平均分配模式) @@ -30,51 +30,51 @@ class BrnTabBar extends StatefulWidget { final bool isScroll; /// Tabbar的整体高度 - final double tabHeight; + final double? tabHeight; /// TabBar的padding final EdgeInsetsGeometry padding; /// 控制Tab的切换 - final TabController controller; + final TabController? controller; /// TabBar背景颜色 final Color backgroundcolor; /// 指示器的颜色 - final Color indicatorColor; + final Color? indicatorColor; /// 指示器的高度 - final double indicatorWeight; + final double? indicatorWeight; /// 指示器的宽度 - final double indicatorWidth; + final double? indicatorWidth; final EdgeInsetsGeometry indicatorPadding; /// 选中Tab文本的颜色 - final Color labelColor; + final Color? labelColor; /// 选中Tab文本的样式 - final TextStyle labelStyle; + final TextStyle? labelStyle; /// Tab文本的Padding final EdgeInsetsGeometry labelPadding; /// 未选中Tab文本的颜色 - final Color unselectedLabelColor; + final Color? unselectedLabelColor; /// 未中Tab文本的样式 - final TextStyle unselectedLabelStyle; + final TextStyle? unselectedLabelStyle; /// 处理拖拽开始行为方式,默认DragStartBehavior.start final DragStartBehavior dragStartBehavior; /// Tab的选中点击事件 - final BrnTabBarOnTap onTap; + final BrnTabBarOnTap? onTap; /// 添加的Tab的宽度(指定tabWidth就不会均分屏幕宽度) - final double tabWidth; + final double? tabWidth; /// 是否显示分隔线 final bool hasDivider; @@ -86,27 +86,27 @@ class BrnTabBar extends StatefulWidget { final bool showMore; /// 展开更多弹框标题 - final String moreWindowText; + final String? moreWindowText; /// 更多弹框弹出的时候 - final VoidCallback onMorePop; + final VoidCallback? onMorePop; /// 更多弹框关闭控制器 - final BrnCloseWindowController closeController; + final BrnCloseWindowController? closeController; /// tag间距 - final double tagSpacing; + final double? tagSpacing; /// 每行tag数 - final int preLineTagCount; + final int? preLineTagCount; /// tag高度 - final double tagHeight; + final double? tagHeight; - BrnTabBarConfig themeData; + BrnTabBarConfig? themeData; BrnTabBar({ - @required this.tabs, + required this.tabs, this.mode = BrnTabBarBadgeMode.average, this.isScroll = false, this.tabHeight, @@ -137,18 +137,19 @@ class BrnTabBar extends StatefulWidget { this.tagHeight, }) : assert(tabs == null || tabs is List) { this.themeData ??= BrnTabBarConfig(); - this.themeData = this.themeData.merge(BrnTabBarConfig( - tabHeight: tabHeight, - indicatorHeight: indicatorWeight, - indicatorWidth: indicatorWidth, - labelStyle: BrnTextStyle.withStyle(labelStyle), - unselectedLabelStyle: BrnTextStyle.withStyle(unselectedLabelStyle), - tagSpacing: tagSpacing, - preLineTagCount: preLineTagCount, - tagHeight: tagHeight, - )); + this.themeData = this.themeData!.merge(BrnTabBarConfig( + backgroundColor: backgroundcolor, + tabHeight: tabHeight, + indicatorHeight: indicatorWeight, + indicatorWidth: indicatorWidth, + labelStyle: BrnTextStyle.withStyle(labelStyle), + unselectedLabelStyle: BrnTextStyle.withStyle(unselectedLabelStyle), + tagSpacing: tagSpacing, + preLineTagCount: preLineTagCount, + tagHeight: tagHeight, + )); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .tabBarConfig .merge(this.themeData); } @@ -157,7 +158,7 @@ class BrnTabBar extends StatefulWidget { BrnTabBarState createState() => BrnTabBarState(closeController); } -/// BrnTabBarBadge的ta分配模式 +/// BrnTabBarBadge的tab分配模式 enum BrnTabBarBadgeMode { /// 原始的默认TabBar的分配模式 origin, @@ -168,33 +169,33 @@ enum BrnTabBarBadgeMode { class BrnTabBarState extends State { /// 小红点容器的样式 - BadgeShape _badgeShape; + late BadgeShape _badgeShape; /// 小红点文案 - String _badgeText; + late String _badgeText; /// 小红点容器内边距 - EdgeInsets _badgePadding; + late EdgeInsets _badgePadding; /// 小红点上偏移量 - double _paddingTop; + double _paddingTop = 0; /// 小红点右偏移量 - double _paddingRight; + double _paddingRight = 0; /// 小红点圆角 - BorderRadiusGeometry _borderRadius; + late BorderRadiusGeometry _borderRadius; /// 展开更多的按钮宽度 final double _moreSpacing = 50; /// BrnTabBarBadge展开更多数据处理控制器 - BrnTabbarController _brnTabbarController; + late BrnTabbarController _brnTabbarController; /// BrnTabBarBadge展开更多关闭处理控制器 - BrnCloseWindowController _closeWindowController; + BrnCloseWindowController? _closeWindowController; - BrnTabBarState(BrnCloseWindowController closeController) { + BrnTabBarState(BrnCloseWindowController? closeController) { this._closeWindowController = closeController; } @@ -203,11 +204,11 @@ class BrnTabBarState extends State { super.initState(); _brnTabbarController = BrnTabbarController(); // 监听更多弹框tab选中变化的时候 - _brnTabbarController?.addListener(() { + _brnTabbarController.addListener(() { _closeWindowController?.syncWindowState(_brnTabbarController.isShow); // 更新TabBar选中位置 if (widget.controller != null) { - widget.controller.animateTo(_brnTabbarController.selectIndex); + widget.controller!.animateTo(_brnTabbarController.selectIndex); } // 刷新选中TabBar小红点 refreshBadgeState(_brnTabbarController.selectIndex); @@ -215,10 +216,10 @@ class BrnTabBarState extends State { setState(() {}); }); - _closeWindowController?.getCloseController()?.stream?.listen((event) { - _brnTabbarController?.hide(); - _brnTabbarController?.entry?.remove(); - _brnTabbarController?.entry = null; + _closeWindowController?.getCloseController().stream.listen((event) { + _brnTabbarController.hide(); + _brnTabbarController.entry?.remove(); + _brnTabbarController.entry = null; }); widget.controller?.addListener(_handleTabIndexChangeTick); @@ -231,10 +232,10 @@ class BrnTabBarState extends State { } void _handleTabIndexChangeTick() { - if (widget.controller.index.toDouble() == - widget.controller.animation.value) { - _brnTabbarController?.selectIndex = widget.controller?.index ?? 0; - _brnTabbarController?.isShow = false; + if (widget.controller?.index.toDouble() == + widget.controller?.animation?.value) { + _brnTabbarController.selectIndex = widget.controller?.index ?? 0; + _brnTabbarController.isShow = false; } } @@ -242,18 +243,18 @@ class BrnTabBarState extends State { Widget build(BuildContext context) { return Container( padding: widget.padding, - constraints: BoxConstraints(minHeight: widget.themeData.tabHeight), - color: widget.themeData.backgroundColor, + constraints: BoxConstraints(minHeight: widget.themeData!.tabHeight), + color: widget.themeData!.backgroundColor, child: widget.showMore ? Row( - children: [ - Container( - width: MediaQuery.of(context).size.width - _moreSpacing, - child: _buildTabBar(), - ), - showMoreWidget(context) - ], - ) + children: [ + Container( + width: MediaQuery.of(context).size.width - _moreSpacing, + child: _buildTabBar(), + ), + showMoreWidget(context) + ], + ) : _buildTabBar(), ); } @@ -263,34 +264,34 @@ class BrnTabBarState extends State { return TabBar( tabs: fillWidgetByDataList(), controller: widget.controller, - isScrollable: widget.tabs.length > 4 || + isScrollable: widget.tabs!.length > 4 || widget.tabWidth != null || widget.isScroll, - labelColor: widget.labelColor ?? widget.themeData.labelStyle.color, + labelColor: widget.labelColor ?? widget.themeData!.labelStyle.color, labelStyle: widget.labelStyle ?? - widget.themeData.labelStyle.generateTextStyle(), + widget.themeData!.labelStyle.generateTextStyle(), labelPadding: widget.labelPadding, unselectedLabelColor: widget.unselectedLabelColor ?? - widget.themeData.unselectedLabelStyle.color, + widget.themeData!.unselectedLabelStyle.color, unselectedLabelStyle: widget.unselectedLabelStyle ?? - widget.themeData.unselectedLabelStyle.generateTextStyle(), + widget.themeData!.unselectedLabelStyle.generateTextStyle(), dragStartBehavior: widget.dragStartBehavior, onTap: (index) { if (widget.onTap != null) { - widget.onTap(this, index); - _brnTabbarController?.setSelectIndex(index); - _brnTabbarController?.isShow = false; - _brnTabbarController?.entry?.remove(); - _brnTabbarController?.entry = null; + widget.onTap!(this, index); + _brnTabbarController.setSelectIndex(index); + _brnTabbarController.isShow = false; + _brnTabbarController.entry?.remove(); + _brnTabbarController.entry = null; } }, indicator: CustomWidthUnderlineTabIndicator( insets: widget.indicatorPadding, borderSide: BorderSide( - width: widget.themeData.indicatorHeight, - color: widget.indicatorColor ?? widget.themeData.labelStyle.color, + width: widget.themeData!.indicatorHeight, + color: widget.indicatorColor ?? widget.themeData!.labelStyle.color!, ), - width: widget.themeData.indicatorWidth, + width: widget.themeData!.indicatorWidth, )); } @@ -301,11 +302,11 @@ class BrnTabBarState extends State { child: GestureDetector( onTap: () { if (!_brnTabbarController.isShow && - widget.controller.index.toDouble() == - widget.controller.animation.value) { - _brnTabbarController?.show(); + widget.controller!.index.toDouble() == + widget.controller!.animation!.value) { + _brnTabbarController.show(); if (widget.onMorePop != null) { - widget.onMorePop(); + widget.onMorePop!(); } showMoreWindow(context); setState(() {}); @@ -316,7 +317,7 @@ class BrnTabBarState extends State { }, child: Container( width: _moreSpacing, - height: widget.themeData.tabHeight, + height: widget.themeData!.tabHeight, decoration: BoxDecoration( color: Colors.white, boxShadow: [ @@ -327,9 +328,9 @@ class BrnTabBarState extends State { ], ), child: !_brnTabbarController.isShow - ? BrunoTools.getAssetImage(BrnAsset.ICON_TRIANGLE_DOWN) + ? BrunoTools.getAssetImage(BrnAsset.iconTriangleDown) : BrunoTools.getAssetImageWithBandColor( - BrnAsset.ICON_TRIANGLE_UP)), + BrnAsset.iconTriangleUp)), ), ); } @@ -337,7 +338,7 @@ class BrnTabBarState extends State { // 更新选中tab的小红点状态 void refreshBadgeState(int index) { setState(() { - BadgeTab badgeTab = widget.tabs[index]; + BadgeTab badgeTab = widget.tabs![index]; if (badgeTab != null && badgeTab.isAutoDismiss) { badgeTab.badgeNum = null; badgeTab.badgeText = null; @@ -347,10 +348,10 @@ class BrnTabBarState extends State { } List fillWidgetByDataList() { - List widgets = List(); - List tabList = widget.tabs; + List widgets = []; + List? tabList = widget.tabs; if (tabList != null && tabList.isNotEmpty) { - double minWidth; + double? minWidth; if (widget.tabWidth != null) { minWidth = widget.tabWidth; } else { @@ -397,11 +398,11 @@ class BrnTabBarState extends State { )), Badge( showBadge: (badgeTab.badgeNum != null - ? badgeTab.badgeNum > 0 - : false) || + ? badgeTab.badgeNum! > 0 + : false) || badgeTab.showRedBadge || (badgeTab.badgeText != null - ? badgeTab.badgeText.isNotEmpty + ? badgeTab.badgeText!.isNotEmpty : false), badgeContent: Text( _badgeText, @@ -415,8 +416,8 @@ class BrnTabBarState extends State { alignment: Alignment.topLeft, padding: _badgePadding, position: - BadgePosition.topEnd(top: _paddingTop, end: _paddingRight), - child: Text(badgeTab.text, + BadgePosition.topEnd(top: _paddingTop, end: _paddingRight), + child: Text(badgeTab.text!, maxLines: 1, softWrap: true, overflow: TextOverflow.ellipsis), @@ -438,7 +439,7 @@ class BrnTabBarState extends State { // 定制的等分tab样式 Widget _wrapAverageWidget( - BadgeTab badgeTab, double minWidth, bool lastElement) { + BadgeTab badgeTab, double? minWidth, bool lastElement) { caculateBadgeParams(badgeTab); return Container( width: minWidth, @@ -448,47 +449,47 @@ class BrnTabBarState extends State { children: [ Expanded( child: Container( - alignment: Alignment.center, - height: 47, - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Visibility( - visible: widget.hasIndex && badgeTab.topText != null, - child: Text( - badgeTab.topText ?? "", - maxLines: 1, - overflow: TextOverflow.ellipsis, - )), - Badge( - showBadge: (badgeTab.badgeNum != null - ? badgeTab.badgeNum > 0 + alignment: Alignment.center, + height: 47, + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Visibility( + visible: widget.hasIndex && badgeTab.topText != null, + child: Text( + badgeTab.topText ?? "", + maxLines: 1, + overflow: TextOverflow.ellipsis, + )), + Badge( + showBadge: (badgeTab.badgeNum != null + ? badgeTab.badgeNum! > 0 : false) || - badgeTab.showRedBadge || - (badgeTab.badgeText != null - ? badgeTab.badgeText.isNotEmpty - : false), - badgeContent: Text( - _badgeText, - style: TextStyle( - color: Color(0xFFFFFFFF), fontSize: 10, height: 1), - ), - shape: _badgeShape, - elevation: 0, - toAnimate: false, - borderRadius: _borderRadius, - alignment: Alignment.topLeft, - padding: _badgePadding, - position: BadgePosition.topEnd( - top: _paddingTop, end: _paddingRight), - child: Text(badgeTab.text, - maxLines: 1, - softWrap: true, - overflow: TextOverflow.ellipsis), - ) - ], - ), - )), + badgeTab.showRedBadge || + (badgeTab.badgeText != null + ? badgeTab.badgeText!.isNotEmpty + : false), + badgeContent: Text( + _badgeText, + style: TextStyle( + color: Color(0xFFFFFFFF), fontSize: 10, height: 1), + ), + shape: _badgeShape, + elevation: 0, + toAnimate: false, + borderRadius: _borderRadius, + alignment: Alignment.topLeft, + padding: _badgePadding, + position: BadgePosition.topEnd( + top: _paddingTop, end: _paddingRight), + child: Text(badgeTab.text!, + maxLines: 1, + softWrap: true, + overflow: TextOverflow.ellipsis), + ) + ], + ), + )), Visibility( visible: widget.hasDivider && !lastElement, child: Container( @@ -505,14 +506,14 @@ class BrnTabBarState extends State { // 计算小红点尺寸相关参数 void caculateBadgeParams(BadgeTab badgeTab) { if (badgeTab.badgeNum != null) { - if (badgeTab.badgeNum < 10) { + if (badgeTab.badgeNum! < 10) { _badgePadding = EdgeInsets.all(5); _badgeShape = BadgeShape.circle; _badgeText = badgeTab.badgeNum?.toString() ?? ""; _paddingTop = -8; _paddingRight = -18; _borderRadius = BorderRadius.all(Radius.circular(8.5)); - } else if (badgeTab.badgeNum > 99) { + } else if (badgeTab.badgeNum! > 99) { _badgePadding = EdgeInsets.fromLTRB(4, 3, 4, 2); _badgeShape = BadgeShape.square; _badgeText = "99+"; @@ -528,7 +529,7 @@ class BrnTabBarState extends State { _borderRadius = BorderRadius.all(Radius.circular(8.5)); } } else { - if (badgeTab.badgeText != null && badgeTab.badgeText.isNotEmpty) { + if (badgeTab.badgeText != null && badgeTab.badgeText!.isNotEmpty) { _badgePadding = EdgeInsets.fromLTRB(5, 3, 5, 2); _badgeShape = BadgeShape.square; _badgeText = badgeTab.badgeText?.toString() ?? ""; @@ -551,9 +552,10 @@ class BrnTabBarState extends State { // 展开更多 void showMoreWindow(BuildContext context) { - final RenderBox dropDownItemRenderBox = context.findRenderObject(); + final RenderBox dropDownItemRenderBox = + context.findRenderObject() as RenderBox; var position = - dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: null); + dropDownItemRenderBox.localToGlobal(Offset.zero, ancestor: null); var size = dropDownItemRenderBox.size; _brnTabbarController.top = size.height + position.dy; @@ -570,7 +572,7 @@ class BrnTabBarState extends State { }, child: Container( padding: EdgeInsets.only( - top: _brnTabbarController.top, + top: _brnTabbarController.top!, ), child: Stack( children: [ @@ -582,17 +584,17 @@ class BrnTabBarState extends State { child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height - - _brnTabbarController.top, + _brnTabbarController.top!, child: Padding( padding: EdgeInsets.all(0), child: _TabBarOverlayWidget( tabs: widget.tabs, moreWindowText: widget.moreWindowText, brnTabbarController: _brnTabbarController, - themeData: widget.themeData, - spacing: widget.themeData.tagSpacing, - preLineTagCount: widget.themeData.preLineTagCount, - tagHeight: widget.themeData.tagHeight, + themeData: widget.themeData!, + spacing: widget.themeData!.tagSpacing, + preLineTagCount: widget.themeData!.preLineTagCount, + tagHeight: widget.themeData!.tagHeight, ), ), ), @@ -608,17 +610,17 @@ class BrnTabBarState extends State { resetEntry(); } _brnTabbarController.entry = overlayEntry; - Overlay.of(context).insert(_brnTabbarController.entry); + Overlay.of(context)!.insert(_brnTabbarController.entry!); } void resetEntry() { - _brnTabbarController.entry.remove(); + _brnTabbarController.entry?.remove(); _brnTabbarController.entry = null; } void hideMoreWindow() { - if (_brnTabbarController?.isShow ?? false) { - _brnTabbarController?.hide(); + if (_brnTabbarController.isShow) { + _brnTabbarController.hide(); resetEntry(); } } @@ -627,11 +629,12 @@ class BrnTabBarState extends State { // 更多弹框样式 // ignore: must_be_immutable class _TabBarOverlayWidget extends StatefulWidget { - List tabs; - String moreWindowText; + List? tabs; - BrnTabbarController brnTabbarController; + String? moreWindowText; + + BrnTabbarController? brnTabbarController; BrnTabBarConfig themeData; @@ -642,15 +645,15 @@ class _TabBarOverlayWidget extends StatefulWidget { int preLineTagCount; /// tag高度 - double tagHeight; + double? tagHeight; _TabBarOverlayWidget( {this.tabs, this.moreWindowText, this.brnTabbarController, - this.themeData, - this.spacing, - this.preLineTagCount, + required this.themeData, + this.spacing: 12.0, + this.preLineTagCount: 4, this.tagHeight}); @override @@ -659,7 +662,7 @@ class _TabBarOverlayWidget extends StatefulWidget { class _TabBarOverlayWidgetState extends State<_TabBarOverlayWidget> { /// tag宽度 - double _tagWidth; + double _tagWidth = _tagDefaultSize; double _padding = 20; @@ -696,7 +699,7 @@ class _TabBarOverlayWidgetState extends State<_TabBarOverlayWidget> { children: [ Visibility( visible: widget.moreWindowText != null && - widget.moreWindowText.isNotEmpty, + widget.moreWindowText!.isNotEmpty, child: Padding( padding: EdgeInsets.only(bottom: 16), child: Text( @@ -723,13 +726,10 @@ class _TabBarOverlayWidgetState extends State<_TabBarOverlayWidget> { Widget _createMoreItems() { // 计算tag的宽度 - _tagWidth = (_parentWidth - - widget.spacing * (widget.preLineTagCount - 1) - - _padding * 2) / - widget.preLineTagCount; - - List widgets = List(); - List tabList = widget.tabs; + _tagWidth = (_parentWidth - widget.spacing * (widget.preLineTagCount - 1) - _padding * 2) / widget.preLineTagCount; + _tagWidth = _tagWidth <= _tagDefaultSize ? _tagDefaultSize : _tagWidth; + List widgets = []; + List? tabList = widget.tabs; if (tabList != null && tabList.isNotEmpty) { for (int i = 0; i < tabList.length; i++) { BadgeTab badgeTab = tabList[i]; @@ -746,14 +746,14 @@ class _TabBarOverlayWidgetState extends State<_TabBarOverlayWidget> { Widget _createMoreItemWidget(BadgeTab badgeTab, int index) { return GestureDetector( onTap: () { - if (widget.brnTabbarController.selectIndex == index) { + if (widget.brnTabbarController!.selectIndex == index) { widget.brnTabbarController?.setSelectIndex(index); widget.brnTabbarController?.isShow = false; widget.brnTabbarController?.entry?.remove(); widget.brnTabbarController?.entry = null; setState(() {}); } else { - widget.brnTabbarController.setSelectIndex(index); + widget.brnTabbarController!.setSelectIndex(index); widget.brnTabbarController?.isShow = false; widget.brnTabbarController?.entry?.remove(); widget.brnTabbarController?.entry = null; @@ -763,21 +763,21 @@ class _TabBarOverlayWidgetState extends State<_TabBarOverlayWidget> { child: Container( alignment: Alignment.center, decoration: BoxDecoration( - color: widget.brnTabbarController.selectIndex == index + color: widget.brnTabbarController!.selectIndex == index ? widget.themeData.tagSelectedBgColor : widget.themeData.tagNormalBgColor, borderRadius: BorderRadius.circular(widget.themeData.tagRadius)), height: widget.tagHeight, width: _tagWidth, child: Text( - badgeTab.text, + badgeTab.text ?? '', textAlign: TextAlign.center, maxLines: 1, softWrap: true, overflow: TextOverflow.ellipsis, - style: widget.brnTabbarController.selectIndex == index - ? widget.themeData.tagSelectedTextStyle?.generateTextStyle() - : widget.themeData.tagNormalTextStyle?.generateTextStyle(), + style: widget.brnTabbarController!.selectIndex == index + ? widget.themeData.tagSelectedTextStyle.generateTextStyle() + : widget.themeData.tagNormalTextStyle.generateTextStyle(), ), ), ); @@ -787,26 +787,26 @@ class _TabBarOverlayWidgetState extends State<_TabBarOverlayWidget> { class BadgeTab { BadgeTab( {this.key, - this.text, - this.badgeNum, - this.topText, - this.badgeText, - this.showRedBadge = false, - this.isAutoDismiss = true}); + this.text, + this.badgeNum, + this.topText, + this.badgeText, + this.showRedBadge = false, + this.isAutoDismiss = true}); - final Key key; + final Key? key; /// Tab文本 - final String text; + final String? text; /// 红点数字 - int badgeNum; + int? badgeNum; /// tab顶部文本信息 - String topText; + String? topText; /// 红点显示的文本 - String badgeText; + String? badgeText; /// 是否显示小红点,默认badgeNum没设置,不显示 bool showRedBadge; diff --git a/lib/src/components/tabbar/normal/brn_tabbar_controller.dart b/lib/src/components/tabbar/normal/brn_tabbar_controller.dart index e67c9153..b0337c54 100644 --- a/lib/src/components/tabbar/normal/brn_tabbar_controller.dart +++ b/lib/src/components/tabbar/normal/brn_tabbar_controller.dart @@ -1,3 +1,5 @@ + + import 'dart:async'; import 'package:flutter/material.dart'; @@ -6,7 +8,7 @@ class BrnTabbarController extends ChangeNotifier { /// /// 更多选项距离顶部距离 /// - double top; + double? top; /// /// 是否显示更多选项弹框 @@ -16,12 +18,12 @@ class BrnTabbarController extends ChangeNotifier { /// /// 屏幕高度 /// - double screenHeight; + double? screenHeight; /// /// 展开更多图层 /// - OverlayEntry entry; + OverlayEntry? entry; /// /// 选中的角标 @@ -45,7 +47,7 @@ class BrnTabbarController extends ChangeNotifier { } class CloseWindowEvent { - bool isShow = false; + bool? isShow = false; CloseWindowEvent({this.isShow}); } @@ -74,6 +76,6 @@ class BrnCloseWindowController { } void closeMoreWindow() { - _closeController?.add(CloseWindowEvent()); + _closeController.add(CloseWindowEvent()); } } diff --git a/lib/src/components/tag/brn_state_tag.dart b/lib/src/components/tag/brn_state_tag.dart index 6da94437..5b6f806b 100644 --- a/lib/src/components/tag/brn_state_tag.dart +++ b/lib/src/components/tag/brn_state_tag.dart @@ -15,17 +15,17 @@ import 'package:flutter/material.dart'; /// class BrnStateTag extends StatelessWidget { final String tagText; - final Color backgroundColor; - final Color textColor; final TagState tagState; + final Color? backgroundColor; + final Color? textColor; //默认为等待状态,黄色 const BrnStateTag( - {Key key, - this.tagText, + {Key? key, + required this.tagText, + this.tagState = TagState.waiting, this.backgroundColor, - this.textColor, - this.tagState = TagState.waiting}) + this.textColor,}) : super(key: key); @override diff --git a/lib/src/components/tag/brn_tag_custom.dart b/lib/src/components/tag/brn_tag_custom.dart index 1c7f04d0..6a8381db 100644 --- a/lib/src/components/tag/brn_tag_custom.dart +++ b/lib/src/components/tag/brn_tag_custom.dart @@ -20,10 +20,10 @@ class BrnTagCustom extends StatelessWidget { final String tagText; /// 标签的背景颜色 默认主题色 - final Color backgroundColor; + final Color? backgroundColor; /// 标签的文本颜色 默认F4的反白颜色 - final Color textColor; + final Color? textColor; /// 标签的圆角 默认为2 /// 如果同时设置了borderRadius、tagBorderRadius字段,优先使用tagBorderRadius字段设置圆角 @@ -42,15 +42,15 @@ class BrnTagCustom extends StatelessWidget { final double maxWidth; /// 标签边框 - final Border border; + final Border? border; BrnTagCustom({ - Key key, - this.tagText, + Key? key, + required this.tagText, this.textColor, this.backgroundColor, - this.tagBorderRadius, - this.textPadding, + this.tagBorderRadius = const BorderRadius.all(Radius.circular(2)), + this.textPadding = const EdgeInsets.only(bottom: 0.5, left: 3, right: 3, top: 0), this.border, this.fontSize = 11, this.fontWeight = FontWeight.normal, @@ -59,61 +59,46 @@ class BrnTagCustom extends StatelessWidget { ///快捷方式生成边框标签 BrnTagCustom.buildBorderTag({ - Key key, + Key? key, + required this.tagText, this.backgroundColor = Colors.transparent, - this.tagText = "", - this.textPadding = - const EdgeInsets.only(bottom: 3, left: 3, right: 3, top: 0), + this.textPadding = const EdgeInsets.only(bottom: 3, left: 3, right: 3, top: 0), this.fontSize = 11, this.fontWeight = FontWeight.normal, - this.tagBorderRadius, - Color textColor, - Color borderColor, + this.tagBorderRadius = const BorderRadius.all(Radius.circular(2)), + Color? textColor, + Color? borderColor, double borderWidth = 1, - double borderRadius = 3, }) : this.maxWidth = double.infinity, this.border = Border.all( - color: borderColor ?? - BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary, - width: borderWidth ?? 1, + color: borderColor ?? BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + width: borderWidth, ), - this.textColor = textColor ?? - BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, + this.textColor = + textColor ?? BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, super(key: key); @override Widget build(BuildContext context) { - BorderRadius bRadius = - tagBorderRadius ?? BorderRadius.all(Radius.circular(2)); return Container( constraints: BoxConstraints( maxWidth: maxWidth, ), decoration: BoxDecoration( color: backgroundColor ?? - BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary, + BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary, shape: BoxShape.rectangle, - borderRadius: bRadius, + borderRadius: tagBorderRadius, border: border), - padding: textPadding ?? - EdgeInsets.only(bottom: 0.5, left: 3, right: 3, top: 0), + padding: textPadding, child: Text( - tagText ?? "", + tagText, textAlign: TextAlign.center, overflow: TextOverflow.ellipsis, style: TextStyle( - fontSize: fontSize ?? 11, + fontSize: fontSize, color: textColor ?? - BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBaseInverse, + BrnThemeConfigurator.instance.getConfig().commonConfig.colorTextBaseInverse, fontWeight: fontWeight, ), )); diff --git a/lib/src/components/tag/tagview/brn_delete_tag.dart b/lib/src/components/tag/tagview/brn_delete_tag.dart index 4ea6cd9e..4e22b71e 100644 --- a/lib/src/components/tag/tagview/brn_delete_tag.dart +++ b/lib/src/components/tag/tagview/brn_delete_tag.dart @@ -12,34 +12,34 @@ import 'package:flutter/widgets.dart'; /// ignore: must_be_immutable class BrnDeleteTag extends StatefulWidget { /// 初始传入的标签,当传入controller的时候,应把初始标签放入controller的构造中 - final List tags; + final List? tags; /// 标签控制器,用于主动添加和删除标签,如果使用场景只需要删除标签并进行回调可以不传控制器 - final BrnDeleteTagController controller; + final BrnDeleteTagController? controller; /// 点击删除某个标签后的回调,参数包含 /// 剩余的标签集合 /// 被删除的标签内容 /// 被删除的标签索引 - final Function(List, String, int) onTagDelete; + final Function(List, String?, int)? onTagDelete; /// 垂直方向的间距 - final double verticalSpacing; + final double? verticalSpacing; /// 水平方向的间距 - final double horizontalSpacing; + final double? horizontalSpacing; /// 标签的字体颜色 - final TextStyle tagTextStyle; + final TextStyle? tagTextStyle; /// 标签的圆角 - final ShapeBorder shape; + final OutlinedBorder? shape; /// 标签背景色 - final Color backgroundColor; + final Color? backgroundColor; /// 删除图标的颜色 - final Color deleteIconColor; + final Color? deleteIconColor; /// true 流式展示,false 横向滑动展示,默认 true final bool softWrap; @@ -48,13 +48,13 @@ class BrnDeleteTag extends StatefulWidget { final EdgeInsets padding; /// 主题配置信息,包含标签背景色、文本颜色等字段,非必传 - BrnTagConfig themeData; + BrnTagConfig? themeData; /// delete Icon Size,不传默认使用 内置删除 icon 图片的的大小, - final Size deleteIconSize; + final Size? deleteIconSize; BrnDeleteTag( - {Key key, + {Key? key, this.tags, this.controller, this.onTagDelete, @@ -66,17 +66,17 @@ class BrnDeleteTag extends StatefulWidget { this.deleteIconColor, this.deleteIconSize, this.softWrap = true, - this.padding, + this.padding = const EdgeInsets.fromLTRB(20, 0, 20, 0), this.themeData}) : super(key: key) { themeData ??= BrnTagConfig(); - themeData = themeData.merge(BrnTagConfig( + themeData = themeData!.merge(BrnTagConfig( tagBackgroundColor: this.backgroundColor, tagTextStyle: BrnTextStyle.withStyle(tagTextStyle))); themeData = BrnThemeConfigurator.instance - .getConfig(configId: themeData.configId) + .getConfig(configId: themeData!.configId) .tagConfig - .merge(themeData); + .merge(this.themeData); } @override @@ -84,20 +84,19 @@ class BrnDeleteTag extends StatefulWidget { } class _BrnDeleteTagState extends State { - BrnDeleteTagController _controller; + late BrnDeleteTagController _controller; @override void initState() { super.initState(); - _controller = - widget.controller ?? BrnDeleteTagController(initTags: widget.tags); + _controller = widget.controller ?? BrnDeleteTagController(initTags: widget.tags); } @override Widget build(BuildContext context) { return Container( color: Colors.white, - child: ValueListenableBuilder( + child: ValueListenableBuilder>( valueListenable: _controller.notifier, builder: (context, value, _) { return _buildContent(value); @@ -107,8 +106,8 @@ class _BrnDeleteTagState extends State { /// 根据标签集合构建标签 UI Widget _buildContent(List tags) { - if (tags == null || tags.isEmpty) { - return Container(); + if (tags.isEmpty) { + return SizedBox.shrink(); } List itemList = []; @@ -118,28 +117,25 @@ class _BrnDeleteTagState extends State { tags[i], _deleteTag, deleteIconSize: widget.deleteIconSize, - style: widget.themeData.tagTextStyle?.generateTextStyle(), + style: widget.themeData!.tagTextStyle.generateTextStyle(), shape: widget.shape, - backgroundColor: widget.themeData?.tagBackgroundColor, + backgroundColor: widget.themeData!.tagBackgroundColor, deleteIconColor: widget.deleteIconColor, themeData: widget.themeData, )); } Widget result; - if (widget.softWrap ?? true) { + if (widget.softWrap) { result = Wrap( spacing: widget.horizontalSpacing ?? 10, - runSpacing: - widget.verticalSpacing != null ? widget.verticalSpacing - 16 : -6, + runSpacing: widget.verticalSpacing != null ? widget.verticalSpacing! - 16 : -6, alignment: WrapAlignment.start, children: itemList, ); } else { int tagIdx = 0; var finalTagList = itemList.map((tag) { - double rightPadding = (tagIdx == itemList.length - 1) - ? 0 - : widget.horizontalSpacing ?? 12; + double rightPadding = (tagIdx == itemList.length - 1) ? 0 : widget.horizontalSpacing ?? 12; var padding = Padding( child: tag, padding: EdgeInsets.only(right: rightPadding), @@ -158,7 +154,7 @@ class _BrnDeleteTagState extends State { return Container( color: Colors.white, - padding: widget.padding ?? EdgeInsets.fromLTRB(20, 0, 20, 0), + padding: widget.padding, alignment: Alignment.centerLeft, child: result, ); @@ -166,9 +162,9 @@ class _BrnDeleteTagState extends State { /// 删除指定 index 下标的标签,并且回调通知外部使用者 void _deleteTag(int index) { - String result = _controller.deleteForIndex(index); + String? result = _controller.deleteForIndex(index); if (widget.onTagDelete != null) { - widget.onTagDelete(_controller.tags, result, index); + widget.onTagDelete!(_controller.tags, result, index); } } } @@ -179,12 +175,12 @@ class DeleteTagItemWidget extends StatelessWidget { final int index; final String title; final Function(int) didDeleted; - final Size deleteIconSize; - final TextStyle style; - final ShapeBorder shape; - final Color backgroundColor; - final Color deleteIconColor; - BrnTagConfig themeData; + final Size? deleteIconSize; + final TextStyle? style; + final OutlinedBorder? shape; + final Color? backgroundColor; + final Color? deleteIconColor; + final BrnTagConfig? themeData; DeleteTagItemWidget(this.index, this.title, this.didDeleted, {this.deleteIconSize, @@ -199,20 +195,17 @@ class DeleteTagItemWidget extends StatelessWidget { return Chip( padding: EdgeInsets.fromLTRB(10, 0, -3, 0), labelPadding: EdgeInsets.fromLTRB(0, 0, -3, 0), - backgroundColor: themeData.tagBackgroundColor, + backgroundColor: themeData!.tagBackgroundColor, label: Text(this.title, - overflow: TextOverflow.ellipsis, - style: themeData?.tagTextStyle?.generateTextStyle()), + overflow: TextOverflow.ellipsis, style: themeData!.tagTextStyle.generateTextStyle()), shape: shape ?? - RoundedRectangleBorder( - borderRadius: BorderRadius.circular(themeData?.tagRadius)), + RoundedRectangleBorder(borderRadius: BorderRadius.circular(themeData!.tagRadius)), //删除图标 deleteIcon: deleteIconSize != null ? BrunoTools.getAssetSizeImage( - BrnAsset.ICON_CLOSE, deleteIconSize.width, deleteIconSize.height, + BrnAsset.iconClose, deleteIconSize!.width, deleteIconSize!.height, color: deleteIconColor) - : BrunoTools.getAssetImageWithColor( - BrnAsset.ICON_CLOSE, deleteIconColor), + : BrunoTools.getAssetImageWithColor(BrnAsset.iconClose, deleteIconColor), onDeleted: () { debugPrint('$index'); didDeleted(index); @@ -223,15 +216,15 @@ class DeleteTagItemWidget extends StatelessWidget { /// 标签控制器,用于主动添加和删除标签 class BrnDeleteTagController { - ValueNotifier> notifier; + late ValueNotifier> notifier; /// 控制器中存储的标签数据 - List _tags = List(); + List _tags = []; List get tags => notifier.value; - BrnDeleteTagController({List initTags}) { - _tags = initTags; + BrnDeleteTagController({List? initTags}) { + _tags = initTags ?? []; notifier = ValueNotifier(_tags); } @@ -260,8 +253,8 @@ class BrnDeleteTagController { } /// 删除指定 index 的标签,并返回其内容 - String deleteForIndex(int index) { - if (_tags != null && _tags.length > index) { + String? deleteForIndex(int index) { + if (_tags.length > index) { String result = _tags.removeAt(index); _asyncData(); return result; @@ -271,17 +264,14 @@ class BrnDeleteTagController { /// 删除某个具体内容的标签,成功返回 true,失败返回 false bool deleteForTag(String tag) { - if (_tags != null) { - bool result = _tags.remove(tag); - _asyncData(); - return result; - } else - return false; + bool result = _tags.remove(tag); + _asyncData(); + return result; } void _asyncData() { // notifier 中的 value 引用是 _tags 所以直接赋值 _tags 不会触发回调 - List values = List(); + List values = []; _tags.forEach((e) => values.add(e)); notifier.value = values; } diff --git a/lib/src/components/tag/tagview/brn_select_tag.dart b/lib/src/components/tag/tagview/brn_select_tag.dart index cba62a0c..62f01fe4 100644 --- a/lib/src/components/tag/tagview/brn_select_tag.dart +++ b/lib/src/components/tag/tagview/brn_select_tag.dart @@ -13,11 +13,10 @@ import 'package:flutter/material.dart'; /// ignore: must_be_immutable class BrnSelectTag extends StatefulWidget { /// 展示的标签列表 - @required final List tags; /// 选择tag的回调,返回选中 tag 的位置 - final void Function(List) onSelect; + final void Function(List)? onSelect; /// 水平间距,默认 12 final double spacing; @@ -26,22 +25,22 @@ class BrnSelectTag extends StatefulWidget { final double verticalSpacing; /// 普通标签的样式 - final TextStyle tagTextStyle; + final TextStyle? tagTextStyle; /// 选中的标签样式 - final TextStyle selectedTagTextStyle; + final TextStyle? selectedTagTextStyle; /// 普通标签背景色,默认 F0Color - final Color tagBackgroundColor; + final Color? tagBackgroundColor; /// 选中的标签背景色,默认 B0Color - final Color selectedTagBackgroundColor; + final Color? selectedTagBackgroundColor; - /// 标签宽度。默认 75 - final double tagWidth; + /// 标签宽度。默认全局配置宽度 75 + final double? tagWidth; - /// 标签高度。默认 34 - final double tagHeight; + /// 标签高度。默认全局配置高度 34 + final double? tagHeight; /// true 流式展示,false 横向滑动展示,默认 true final bool softWrap; @@ -56,13 +55,13 @@ class BrnSelectTag extends StatefulWidget { final bool isSingleSelect; /// 多选时的初始状态数组 - final List initTagState; + final List? initTagState; - BrnTagConfig themeData; + BrnTagConfig? themeData; BrnSelectTag({ - Key key, - @required this.tags, + Key? key, + required this.tags, this.onSelect, this.spacing = 12, this.verticalSpacing = 10, @@ -78,13 +77,12 @@ class BrnSelectTag extends StatefulWidget { this.alignment = Alignment.centerLeft, this.fixWidthMode = true, this.themeData, - }) : assert(tags != null), - super(key: key) { + }) : super(key: key) { if (isSingleSelect == true) { - assert(initTagState == null || (initTagState.length <= 1)); + assert(initTagState == null || (initTagState!.length <= 1)); } this.themeData ??= BrnTagConfig(); - this.themeData = this.themeData.merge(BrnTagConfig( + this.themeData = this.themeData!.merge(BrnTagConfig( tagBackgroundColor: this.tagBackgroundColor, tagTextStyle: BrnTextStyle.withStyle(this.tagTextStyle), selectTagTextStyle: BrnTextStyle.withStyle(this.selectedTagTextStyle), @@ -92,7 +90,7 @@ class BrnSelectTag extends StatefulWidget { tagHeight: this.tagHeight, selectedTagBackgroundColor: this.selectedTagBackgroundColor)); this.themeData = BrnThemeConfigurator.instance - .getConfig(configId: this.themeData.configId) + .getConfig(configId: this.themeData!.configId) .tagConfig .merge(this.themeData); } @@ -102,17 +100,15 @@ class BrnSelectTag extends StatefulWidget { } class _BrnSelectTagState extends State { - List _tagState; + List _tagState = []; @override void initState() { super.initState(); _tagState = widget.tags.map((name) => false).toList(); if (widget.initTagState != null) { - for (int index = 0; - index < min(widget.initTagState.length, widget.tags.length); - index++) { - _tagState[index] = widget.initTagState[index]; + for (int index = 0; index < min(widget.initTagState!.length, widget.tags.length); index++) { + _tagState[index] = widget.initTagState![index]; } } } @@ -120,7 +116,7 @@ class _BrnSelectTagState extends State { @override Widget build(BuildContext context) { Widget content; - if (widget.softWrap ?? true) { + if (widget.softWrap) { content = Wrap( runSpacing: widget.verticalSpacing, spacing: widget.spacing, @@ -157,13 +153,13 @@ class _BrnSelectTagState extends State { } List _tagWidgetList(context) { - List list = List(); + List list = []; for (int nameIndex = 0; nameIndex < widget.tags.length; nameIndex++) { Widget tagWidget = _tagWidgetAtIndex(nameIndex); GestureDetector gdt = GestureDetector( child: tagWidget, onTap: () { - if (widget.isSingleSelect ?? true) { + if (widget.isSingleSelect) { bool selected = _tagState[nameIndex]; if (selected) { return; @@ -183,7 +179,7 @@ class _BrnSelectTagState extends State { for (int index = 0; index < _tagState.length; index++) { if (_tagState[index]) _selectedIndexes.add(index); } - widget.onSelect(_selectedIndexes); + widget.onSelect!(_selectedIndexes); } }); list.add(gdt); @@ -199,15 +195,14 @@ class _BrnSelectTagState extends State { overflow: TextOverflow.ellipsis, ); Container container = Container( - constraints: BoxConstraints(minWidth: widget.themeData.tagMinWidth), + constraints: BoxConstraints(minWidth: widget.themeData!.tagMinWidth), decoration: BoxDecoration( color: selected - ? (widget.themeData?.selectedTagBackgroundColor - ?.withOpacity(0.12)) - : (widget.themeData?.tagBackgroundColor), - borderRadius: BorderRadius.circular(widget.themeData?.tagRadius)), - width: widget.fixWidthMode ? widget.themeData?.tagWidth : null, - height: widget.themeData?.tagHeight, + ? (widget.themeData!.selectedTagBackgroundColor.withOpacity(0.12)) + : (widget.themeData!.tagBackgroundColor), + borderRadius: BorderRadius.circular(widget.themeData!.tagRadius)), + width: widget.fixWidthMode ? widget.themeData!.tagWidth : null, + height: widget.themeData!.tagHeight, padding: EdgeInsets.only(left: 8, right: 8), child: Center(widthFactor: 1, child: tx), ); @@ -215,28 +210,24 @@ class _BrnSelectTagState extends State { } TextStyle _tagTextStyle() { - return widget.themeData?.tagTextStyle?.generateTextStyle(); + return widget.themeData!.tagTextStyle.generateTextStyle(); } TextStyle _selectedTextStyle() { - return widget.themeData?.selectTagTextStyle?.generateTextStyle(); + return widget.themeData!.selectTagTextStyle.generateTextStyle(); } @override void didUpdateWidget(BrnSelectTag oldWidget) { super.didUpdateWidget(oldWidget); // 如果两个数组不相等,重置选中状态 - if (!sameList(oldWidget.tags, widget.tags)) - _tagState = List.filled(widget.tags.length, false); + if (!sameList(oldWidget.tags, widget.tags)) _tagState = List.filled(widget.tags.length, false); } /// 比较两个数组内容是否一致,如果一致,返回 true,否则 false bool sameList(List first, List second) { - if (first == null || second == null || first.length != second.length) - return false; + if (first.length != second.length) return false; int index = 0; - return first.firstWhere((item) => item != second[index++], - orElse: () => null) == - null; + return first.firstWhere((item) => item != second[index++], orElse: () => '') == ''; } } diff --git a/lib/src/components/text/brn_expandable_text.dart b/lib/src/components/text/brn_expandable_text.dart index 5bf52d7b..1f59e249 100644 --- a/lib/src/components/text/brn_expandable_text.dart +++ b/lib/src/components/text/brn_expandable_text.dart @@ -35,20 +35,20 @@ class BrnExpandableText extends StatefulWidget { final String text; ///显示的最多行数 - final int maxLines; + final int? maxLines; /// 文本的样式 - final TextStyle textStyle; + final TextStyle? textStyle; /// 展开或者收起的时候的回调 - final TextExpandedCallback onExpanded; + final TextExpandedCallback? onExpanded; /// 更多按钮渐变色的初始色 默认白色 - final Color color; + final Color? color; const BrnExpandableText( - {Key key, - @required this.text, + {Key? key, + required this.text, this.maxLines = 1000000, this.textStyle, this.onExpanded, @@ -59,13 +59,7 @@ class BrnExpandableText extends StatefulWidget { } class _BrnExpandableTextState extends State { - bool _expanded; - - @override - void initState() { - super.initState(); - _expanded = false; - } + bool _expanded = false; @override Widget build(BuildContext context) { @@ -139,7 +133,7 @@ class _BrnExpandableTextState extends State { setState(() { _expanded = true; if (null != widget.onExpanded) { - widget.onExpanded(_expanded); + widget.onExpanded!(_expanded); } }); }, @@ -182,7 +176,7 @@ class _BrnExpandableTextState extends State { setState(() { _expanded = false; if (null != widget.onExpanded) { - widget.onExpanded(_expanded); + widget.onExpanded!(_expanded); } }); }); diff --git a/lib/src/components/toast/brn_toast.dart b/lib/src/components/toast/brn_toast.dart index a37558fe..41d4e9eb 100644 --- a/lib/src/components/toast/brn_toast.dart +++ b/lib/src/components/toast/brn_toast.dart @@ -2,164 +2,254 @@ import 'dart:math'; import 'package:flutter/material.dart'; +/// 位置枚举 +enum BrnToastGravity { + /// 底部显示 + bottom, + + /// 居中显示 + center, + + /// 顶部显示 + top, +} + +/// toast 显示时长 +class BrnDuration { + BrnDuration._(); + + /// toast 显示较短时间(1s) + static const Duration short = Duration(seconds: 1); + + /// toast 显示较长时间(3s) + static const Duration long = Duration(seconds: 3); +} + /// 通用的Toast组件 class BrnToast { - static const LENGTH_SHORT = 1; - static const LENGTH_LONG = 2; - static const BOTTOM = 0; - static const CENTER = 1; - static const TOP = 2; + /// Toast 距离顶部默认间距 + static const int _defaultTopOffset = 50; + + /// Toast 距离底部默认间距 + static const int _defaultBottomOffset = 50; - static _ToastView preToastView; + /// _ToastView + static _ToastView? preToastView; /// 显示在中间。如不设置duration则会自动根据内容长度来计算(更友好,最长5秒) - static void showInCenter(String text, BuildContext context, {int duration}) { - show(text, context, duration: duration, gravity: CENTER); + static void showInCenter( + {required String text, + required BuildContext context, + Duration? duration}) { + show( + text, + context, + duration: duration, + gravity: BrnToastGravity.center, + ); } /// 显示Toast,如不设置duration则会自动根据内容长度来计算(更友好,最长5秒) - static void show(String text, BuildContext context, - {int duration, - int gravity = BOTTOM, - Color backgroundColor = const Color(0xFF222222), - textStyle = const TextStyle(fontSize: 16, color: Colors.white), - double backgroundRadius = 8, - Image preIcon, - double verticalOffset, - VoidCallback onDismiss}) { - OverlayState overlayState = Overlay.of(context); - if (text == null || context == null || overlayState == null) { - return; - } + static void show( + String text, + BuildContext context, { + Duration? duration, + Color? background, + TextStyle? textStyle, + double? radius, + Image? preIcon, + double? verticalOffset, + VoidCallback? onDismiss, + BrnToastGravity? gravity, + }) { + final OverlayState? overlayState = Overlay.of(context); + if (overlayState == null) return; + preToastView?._dismiss(); preToastView = null; - verticalOffset = getRealVerticalOffset(verticalOffset, gravity, context); - // 自动根据内容长度决定显示时长,更加人性化 - int aiDuration = duration ?? min(text.length * 0.06 + 0.8, 5.0).ceil(); - - _ToastView toastView = _ToastView(); - toastView.overlayState = overlayState; - OverlayEntry overlayEntry; - overlayEntry = OverlayEntry(builder: (context) { - return _buildToastLayout(context, backgroundColor, backgroundRadius, - preIcon, text, textStyle, gravity, - verticalOffset: verticalOffset); - }); - toastView._overlayEntry = overlayEntry; + final double finalVerticalOffset = getVerticalOffset( + context: context, + gravity: gravity, + verticalOffset: verticalOffset, + ); + + /// 自动根据内容长度决定显示时长,更加人性化 + final int autoDuration = min(text.length * 0.06 + 0.8, 5.0).ceil(); + final Duration finalDuration = + duration ?? Duration(seconds: autoDuration); + final OverlayEntry overlayEntry = OverlayEntry( + builder: (context) { + return _ToastWidget( + widget: ToastChild( + background: background, + radius: radius, + msg: text, + leading: preIcon, + textStyle: textStyle, + gravity: gravity, + verticalOffset: finalVerticalOffset, + ), + ); + }, + ); + final _ToastView toastView = + _ToastView(overlayState: overlayState, overlayEntry: overlayEntry); preToastView = toastView; - toastView._show(aiDuration, onDismiss: onDismiss); + toastView._show( + duration: finalDuration, + onDismiss: onDismiss, + ); } - static double getRealVerticalOffset( - double verticalOffset, int gravity, BuildContext context) { - if (gravity == BrnToast.TOP) { - verticalOffset = - (verticalOffset ?? 0) + MediaQuery.of(context).viewInsets.top + 50; - } else if (gravity == BrnToast.BOTTOM) { - verticalOffset = - (verticalOffset ?? 0) + MediaQuery.of(context).viewInsets.bottom + 50; - } else { - verticalOffset = 0; + /// 获取默认设置的垂直间距 + static double getVerticalOffset({ + required BuildContext context, + BrnToastGravity? gravity, + double? verticalOffset, + }) { + final double _verticalOffset = verticalOffset ?? 0; + final double defaultOffset; + switch (gravity) { + case BrnToastGravity.bottom: + final offset = verticalOffset ?? _defaultTopOffset; + defaultOffset = MediaQuery.of(context).viewInsets.bottom + offset; + break; + case BrnToastGravity.top: + final offset = verticalOffset ?? _defaultBottomOffset; + defaultOffset = MediaQuery.of(context).viewInsets.top + offset; + break; + case BrnToastGravity.center: + default: + defaultOffset = verticalOffset ?? 0; } - return verticalOffset; - } -} -_ToastWidget _buildToastLayout( - BuildContext context, - Color background, - double backgroundRadius, - Image preIcon, - String msg, - TextStyle textStyle, - int gravity, - {double verticalOffset}) { - Alignment alignment = Alignment.center; - EdgeInsets padding; - if (gravity == BrnToast.BOTTOM) { - alignment = Alignment.bottomCenter; - padding = EdgeInsets.only(bottom: verticalOffset); - } else if (gravity == BrnToast.TOP) { - alignment = Alignment.topCenter; - padding = EdgeInsets.only(top: verticalOffset); + return defaultOffset + _verticalOffset; } - - return _ToastWidget( - widget: Container( - width: MediaQuery.of(context).size.width, - child: Container( - padding: padding, - alignment: alignment, - width: MediaQuery.of(context).size.width, - child: Container( - decoration: BoxDecoration( - color: background, - borderRadius: BorderRadius.circular(backgroundRadius), - ), - margin: EdgeInsets.symmetric(horizontal: 20), - padding: EdgeInsets.fromLTRB(18, 10, 18, 10), - child: RichText( - text: TextSpan(children: [ - preIcon != null - ? WidgetSpan( - alignment: PlaceholderAlignment.middle, - child: Padding( - padding: EdgeInsets.only(right: 6), - child: preIcon, - )) - : TextSpan(text: ""), - TextSpan(text: msg, style: textStyle), - ]), - ), - )), - ), - gravity: gravity); } class _ToastView { OverlayState overlayState; - OverlayEntry _overlayEntry; + OverlayEntry overlayEntry; bool _isVisible = false; - _show(int duration, {VoidCallback onDismiss}) async { + _ToastView({ + required this.overlayState, + required this.overlayEntry, + }); + + void _show({required Duration duration, VoidCallback? onDismiss}) async { _isVisible = true; - overlayState.insert(_overlayEntry); - await Future.delayed( - Duration(seconds: duration == null ? BrnToast.LENGTH_SHORT : duration)); - _dismiss(); - if (onDismiss != null) { - onDismiss(); - } + overlayState.insert(overlayEntry); + Future.delayed(duration, () { + _dismiss(); + onDismiss?.call(); + }); } - _dismiss() async { + void _dismiss() async { if (!_isVisible) { return; } _isVisible = false; - _overlayEntry?.remove(); + overlayEntry.remove(); } } -class _ToastWidget extends StatelessWidget { - final Widget widget; - final int gravity; +class ToastChild extends StatelessWidget { + const ToastChild({ + Key? key, + required this.msg, + required this.verticalOffset, + this.background, + this.radius, + this.leading, + this.gravity, + this.textStyle, + }) : super(key: key); + + Alignment get alignment { + switch (gravity) { + case BrnToastGravity.bottom: + return Alignment.bottomCenter; + case BrnToastGravity.top: + return Alignment.topCenter; + case BrnToastGravity.center: + default: + return Alignment.center; + } + } + + EdgeInsets get padding { + switch (gravity) { + case BrnToastGravity.bottom: + return EdgeInsets.only(bottom: verticalOffset); + case BrnToastGravity.top: + return EdgeInsets.only(top: verticalOffset); + case BrnToastGravity.center: + default: + return EdgeInsets.only(top: verticalOffset); + } + } + + final String msg; + final double verticalOffset; + final Color? background; + final double? radius; + final Image? leading; + final BrnToastGravity? gravity; + final TextStyle? textStyle; + + InlineSpan get leadingSpan { + if (leading == null) { + return const TextSpan(text: ""); + } + return WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding(padding: const EdgeInsets.only(right: 6), child: leading!), + ); + } - _ToastWidget({ - Key key, - @required this.widget, - @required this.gravity, + @override + Widget build(BuildContext context) { + return SizedBox( + width: MediaQuery.of(context).size.width, + child: Container( + padding: padding, + alignment: alignment, + width: MediaQuery.of(context).size.width, + child: Container( + decoration: BoxDecoration( + color: background ?? const Color(0xFF222222), + borderRadius: BorderRadius.circular(radius ?? 8), + ), + margin: const EdgeInsets.symmetric(horizontal: 20), + padding: const EdgeInsets.fromLTRB(18, 10, 18, 10), + child: RichText( + text: TextSpan(children: [ + leadingSpan, + TextSpan(text: msg, style: textStyle), + ]), + ), + ), + ), + ); + } +} + +class _ToastWidget extends StatelessWidget { + const _ToastWidget({ + Key? key, + required this.widget, }) : super(key: key); - // 使用IgnorePointer,方便手势透传过去 + final Widget widget; + + /// 使用IgnorePointer,方便手势透传过去 @override Widget build(BuildContext context) { return IgnorePointer( - child: Material( - color: Colors.transparent, - child: widget, - ), + child: Material(color: Colors.transparent, child: widget), ); } } diff --git a/lib/src/constants/brn_asset_constants.dart b/lib/src/constants/brn_asset_constants.dart index f2850b54..abb01801 100644 --- a/lib/src/constants/brn_asset_constants.dart +++ b/lib/src/constants/brn_asset_constants.dart @@ -1,4 +1,6 @@ class BrnAsset { + const BrnAsset._(); + static const String emptyState = "images/empty_state.png"; static const String stepTitle = 'images/img_step_title.png'; @@ -19,165 +21,164 @@ class BrnAsset { static const String iconBottomPickerRightTopBg = "images/icon_bottom_picker_right_top_bg.png"; - static const String ICON_ARROWUP_SELECT = "images/icon_arrow_up_selected.png"; - static const String ICON_REFRESH = "assets/images/icon_refresh.png"; - static const String ICON_ARROWDOWN_SELECT = + static const String iconArrowUpSelect = "images/icon_arrow_up_selected.png"; + static const String iconRefresh = "assets/images/icon_refresh.png"; + static const String iconArrowDownSelect = "images/icon_arrow_down_selected.png"; - static const String ICON_ARROWDOWN_UNSELECT = + static const String iconArrowDownUnSelect = "images/icon_arrow_down_unselected.png"; - static const String ICON_ARROW_RIGHT_1 = "icons/icon_right_arrow_1.png"; - static const String SELECT_CHECKED_STATUS = + static const String iconArrowRight = "icons/icon_right_arrow_1.png"; + static const String selectCheckedStatus = "images/select_checked_status.png"; - static const String SELECT_NORMAL_STATUS = "icons/normol_border.png"; - static const String ICON_SELECTED_UP_TRIANGLE = + static const String selectNormalStatus = "icons/normol_border.png"; + static const String iconSelectedUpTriangle = "icons/icon_selcted_triangle.png"; - static const String ICON_UNSELECT_DOWN_TRIANGLE = + static const String iconUnSelectDownTriangle = "icons/icon_unselected_triangle.png"; - static const String ICON_REQUIRE_RED = 'icons/icon_require_red.png'; - static const String ICON_RIGHT_ARROW = 'icons/icon_right_arrow.png'; - static const String ICON_BACK_WHITE = 'assets/icons/icon_back_white.png'; - static const String ICON_BACK_BLACK = 'assets/icons/icon_back_black.png'; - static const String ICON_STEP_2 = 'icons/icon_step_2.png'; - static const String ICON_STEP_3 = 'icons/icon_step_3.png'; - static const String ICON_STEP_4 = 'icons/icon_step_4.png'; - static const String ICON_STEP_5 = 'icons/icon_step_5.png'; - static const String ICON_STEP_DOING = 'icons/icon_step_doing.png'; - static const String ICON_STEP_COMPLETED = 'icons/icon_step_completed.png'; - - static const String ICON_DELETE_TEXT = 'icons/ic_delete_grey.png'; - static const String ICON_SEARCH = 'icons/ic_search.png'; - - static const String ICON_POPUP_CLOSE = 'icons/icon_popup_close.png'; - static const String ICON_CLOSE = 'icons/icon_close.png'; - static const String ICON_CALENDAR_PRE_MONTH = + static const String iconRequireRed = 'icons/icon_require_red.png'; + static const String iconRightArrow = 'icons/icon_right_arrow.png'; + static const String iconBackWhite = 'assets/icons/icon_back_white.png'; + static const String iconBackBlack = 'assets/icons/icon_back_black.png'; + static const String iconStep2 = 'icons/icon_step_2.png'; + static const String iconStep3 = 'icons/icon_step_3.png'; + static const String iconStep4 = 'icons/icon_step_4.png'; + static const String iconStep5 = 'icons/icon_step_5.png'; + static const String iconStepDoing = 'icons/icon_step_doing.png'; + static const String iconStepCompleted = 'icons/icon_step_completed.png'; + + static const String iconDeleteText = 'icons/ic_delete_grey.png'; + static const String iconSearch = 'icons/ic_search.png'; + + static const String iconPopupClose = 'icons/icon_popup_close.png'; + static const String iconClose = 'icons/icon_close.png'; + static const String iconCalendarPreMonth = 'icons/icon_calendar_pre_month.png'; - static const String ICON_CALENDAR_NEXT_MONTH = + static const String iconCalendarNextMonth = 'icons/icon_calendar_next_month.png'; - static const String ICON_UP_ARROW = 'icons/icon_up_arrow.png'; - static const String ICON_DOWN_ARROW = 'icons/icon_down_arrow.png'; - static const String ICON_TRASH_BIN = 'icons/icon_trash.png'; - static const String ICON_STAR_UNSELECT = 'icons/icon_star_unselect.png'; - static const String ICON_STAR_SELECT = 'icons/icon_star_select.png'; - static const String ICON_ADD_FORM_ITEM = 'icons/icon_add_form_item.png'; - static const String ICON_REMOVE_FORM_ITEM = 'icons/icon_remove_form_item.png'; + static const String iconUpArrow = 'icons/icon_up_arrow.png'; + static const String iconDownArrow = 'icons/icon_down_arrow.png'; + static const String iconTrashBin = 'icons/icon_trash.png'; + static const String iconStarUnSelect = 'icons/icon_star_unselect.png'; + static const String iconStarSelect = 'icons/icon_star_select.png'; + static const String iconAddFormItem = 'icons/icon_add_form_item.png'; + static const String iconRemoveFormItem = 'icons/icon_remove_form_item.png'; - static const String ICON_TRIANGLE_DOWN = 'icons/icon_triangle_down.png'; - static const String ICON_TRIANGLE_UP = 'icons/icon_triangle_up.png'; + static const String iconTriangleDown = 'icons/icon_triangle_down.png'; + static const String iconTriangleUp = 'icons/icon_triangle_up.png'; - static const String ICON_PAIR_INFO_QUESTION = + static const String iconPairInfoQuestion = 'icons/icon_pait_info_question.png'; - static const String ICON_PICKER_CLOSE = 'images/icon_guanbi.png'; + static const String iconPickerClose = 'images/icon_guanbi.png'; - static const String ICON_NOTICE = 'icons/icon_notice.png'; - static const String ICON_NOTICE_ARROW_BLUE = + static const String iconNotice = 'icons/icon_notice.png'; + static const String iconNoticeArrowBlue = 'icons/icon_notice_arrow_blue.png'; - static const String ICON_NOTICE_ARROW_GREEN = + static const String iconNoticeArrowGreen = 'icons/icon_notice_arrow_green.png'; - static const String ICON_NOTICE_ARROW_ORANGE = + static const String iconNoticeArrowOrange = 'icons/icon_notice_arrow_orange.png'; - static const String ICON_NOTICE_ARROW_RED = 'icons/icon_notice_arrow_red.png'; - static const String ICON_NOTICE_CLOSE_BLUE = + static const String iconNoticeArrowRed = 'icons/icon_notice_arrow_red.png'; + static const String iconNoticeCloseBlue = 'icons/icon_notice_close_blue.png'; - static const String ICON_NOTICE_CLOSE_GREEN = + static const String iconNoticeCloseGreen = 'icons/icon_notice_close_green.png'; - static const String ICON_NOTICE_CLOSE_ORANGE = + static const String iconNoticeCloseOrange = 'icons/icon_notice_close_orange.png'; - static const String ICON_NOTICE_CLOSE_RED = 'icons/icon_notice_close_red.png'; - static const String ICON_NOTICE_FAIL = 'icons/icon_notice_fail.png'; - static const String ICON_NOTICE_RUNNING = 'icons/icon_notice_running.png'; - static const String ICON_NOTICE_SUCCEED = 'icons/icon_notice_succeed.png'; - static const String ICON_NOTICE_WARNING = 'icons/icon_notice_warning.png'; + static const String iconNoticeCloseRed = 'icons/icon_notice_close_red.png'; + static const String iconNoticeFail = 'icons/icon_notice_fail.png'; + static const String iconNoticeRunning = 'icons/icon_notice_running.png'; + static const String iconNoticeSucceed = 'icons/icon_notice_succeed.png'; + static const String iconNoticeWarning = 'icons/icon_notice_warning.png'; - static const String ICON_OPERATION_OTHER_RIGHT = + static const String iconOperationOtherRight = 'icons/icon_operation_line_right.png'; - static const String ICON_OPERATION_OTHER_LEFT = + static const String iconOperationOtherLeft = 'icons/icon_operation_line_left.png'; - static const String ICON_RESULT_SUCCESS = 'icons/icon_result_success.png'; - static const String ICON_RESULT_ERROR = 'icons/icon_result_error.png'; - static const String ICON_STAR = 'icons/icon_star.png'; - static const String ICON_STAR_HALF = 'icons/icon_star_half.png'; - static const String ICON_UPARROW = 'icons/icon_uparrow.png'; - static const String ICOS_QRCODE_BG = 'assets/images/icon_qrcode_bg.png'; - static const String ICONS_QRCODE_FAILED = + static const String iconResultSuccess = 'icons/icon_result_success.png'; + static const String iconResultError = 'icons/icon_result_error.png'; + static const String iconStar = 'icons/icon_star.png'; + static const String iconStarHalf = 'icons/icon_star_half.png'; + static const String iconQrCodeBg = 'assets/images/icon_qrcode_bg.png'; + static const String iconsQrCodeFailed = '/assets/images/icon_qrcode_failed.png'; - static const String ICONS_REFRESH_WHITE = + static const String iconsRefreshWhite = 'assets/images/icon_refresh_white.png'; - static const String ICONS_AVATAR_NEW = '/assets/icons/img_avatar_new.png'; + static const String iconsAvatarNew = '/assets/icons/img_avatar_new.png'; - static const String ICON_AUDIOPALYER_PLAY = 'icons/icon_audioplayer_play.png'; - static const String ICON_AUDIOPALYER_PAUSE = + static const String iconAudioPlayer = 'icons/icon_audioplayer_play.png'; + static const String iconAudioPlayerPause = 'icons/icon_audioplayer_pause.png'; - static const String ICON_GREY_PLACE_HOLDER = 'icons/grey_place_holder.png'; + static const String iconGreyPlaceHolder = 'icons/grey_place_holder.png'; - static const String ICON_QUOTATION_MARK = 'icons/ic_quotation_mark.png'; + static const String iconQuotationMark = 'icons/ic_quotation_mark.png'; - static const String IMG_BACKGROUND_CARD = 'images/img_bg_card.png'; + static const String imgBackgroundCard = 'images/img_bg_card.png'; - static const String IMG_BG_BLUR = 'images/img_bg_blur.png'; + static const String imgBgBlur = 'images/img_bg_blur.png'; /// 用于图片右上角删除icon 的展示 - static const String ICON_DELETE = 'icons/icon_delete.png'; + static const String iconDelete = 'icons/icon_delete.png'; - static const String ICON_IM = 'images/icon_im_blue.png'; - static const String ICON_CALL = 'images/icon_call.png'; - static const String ICON_CALL_DISABLE = 'images/icon_call_disable.png'; - static const String PERSON_PLACE_HOLDER = + static const String iconIm = 'images/icon_im_blue.png'; + static const String iconCall = 'images/icon_call.png'; + static const String iconCallDisable = 'images/icon_call_disable.png'; + static const String personPlaceHolder = 'packages/bruno/assets/icons/img_avatar_new.png'; /// radio组件,用于单选和多选 - static const String ICON_RADIO_MULTI_SELECTED = + static const String iconRadioMultiSelected = 'icons/radio/multiple_selected.png'; - static const String ICON_RADIO_UNSELECTED = 'icons/radio/unselected.png'; - static const String ICON_RADIO_DISABLE_MULTI_SELECTED = + static const String iconRadioUnSelected = 'icons/radio/unselected.png'; + static const String iconRadioDisableMultiSelected = 'icons/radio/disable_multi_selected.png'; - static const String ICON_RADIO_DISABLE_UNSELECTED = + static const String iconRadioDisableUnselected = 'icons/radio/disable_unselected.png'; - static const String ICON_RADIO_SINGLE_SELECTED = + static const String iconRadioSingleSelected = 'icons/radio/single_selected.png'; - static const String ICON_RADIO_DISABLE_SINGLE_SELECTED = + static const String iconRadioDisableSingleSelected = 'icons/radio/disable_single_selected.png'; /// 评价组件--表情 - static const String ICON_APPRAISE_BAD_UNSELECTED = + static const String iconAppraiseBadUnselected = 'assets/images/icon_appraise_bad_unselected.png'; - static const String ICON_APPRAISE_NOT_GOOD_UNSELECTED = + static const String iconAppraiseNotGoodUnselected = 'assets/images/icon_appraise_not_good_unselected.png'; - static const String ICON_APPRAISE_OK_UNSELECTED = + static const String iconAppraiseOkUnselected = 'assets/images/icon_appraise_ok_unselected.png'; - static const String ICON_APPRAISE_GOOD_UNSELECTED = + static const String iconAppraiseGoodUnselected = 'assets/images/icon_appraise_good_unselected.png'; - static const String ICON_APPRAISE_SURPRISE_UNSELECTED = + static const String iconAppraiseSurpriseUnselected = 'assets/images/icon_appraise_surprise_unselected.png'; - static const String ICON_APPRAISE_BAD_DEFAULT = + static const String iconAppraiseBadDefault = 'assets/images/icon_appraise_bad_default.png'; - static const String ICON_APPRAISE_NOT_GOOD_DEFAULT = + static const String iconAppraiseNotGoodDefault = 'assets/images/icon_appraise_not_good_default.png'; - static const String ICON_APPRAISE_OK_DEFAULT = + static const String iconAppraiseOkDefault = 'assets/images/icon_appraise_ok_default.png'; - static const String ICON_APPRAISE_GOOD_DEFAULT = + static const String iconAppraiseGoodDefault = 'assets/images/icon_appraise_good_default.png'; - static const String ICON_APPRAISE_SURPRISE_DEFAULT = + static const String iconAppraiseSurpriseDefault = 'assets/images/icon_appraise_surprise_default.png'; - static const String ICON_APPRAISE_BAD_SELECTED = + static const String iconAppraiseBadSelected = 'assets/images/icon_appraise_bad_selected.png'; - static const String ICON_APPRAISE_NOT_GOOD_SELECTED = + static const String iconAppraiseNotGoodSelected = 'assets/images/icon_appraise_not_good_selected.png'; - static const String ICON_APPRAISE_OK_SELECTED = + static const String iconAppraiseOkSelected = 'assets/images/icon_appraise_ok_selected.png'; - static const String ICON_APPRAISE_GOOD_SELECTED = + static const String iconAppraiseGoodSelected = 'assets/images/icon_appraise_good_selected.png'; - static const String ICON_APPRAISE_SURPRISE_SELECTED = + static const String iconAppraiseSurpriseSelected = 'assets/images/icon_appraise_surprise_selected.png'; - static const String ICON_QUESTION = "icons/icon_question.png"; + static const String iconQuestion = "icons/icon_question.png"; /// 录入项icon - static const String ICON_ADD_DISABLE = "icons/icon_add_disable.png"; - static const String ICON_ADD_ENABLE = "icons/icon_add_enable.png"; + static const String iconAddDisable = "icons/icon_add_disable.png"; + static const String iconAddEnable = "icons/icon_add_enable.png"; - static const String ICON_MINUS_DISABLE = "icons/icon_minus_disable.png"; - static const String ICON_MINUS_ENABLE = "icons/icon_minus_enable.png"; + static const String iconMinusDisable = "icons/icon_minus_disable.png"; + static const String iconMinusEnable = "icons/icon_minus_enable.png"; } diff --git a/lib/src/constants/brn_constants.dart b/lib/src/constants/brn_constants.dart index 88b37bbe..f08bee66 100644 --- a/lib/src/constants/brn_constants.dart +++ b/lib/src/constants/brn_constants.dart @@ -1,6 +1,6 @@ class BrnShareItemConstants { /// 分享渠道名称列表 - static const List shareItemTitleList = [ + static const List shareItemTitleList = [ "微信", "朋友圈", "QQ", @@ -14,7 +14,7 @@ class BrnShareItemConstants { ]; /// 分享渠道图片地址列表 - static const List shareItemImagePathList = [ + static const List shareItemImagePathList = [ "images/icon_share_weChat.png", "images/icon_share_moments.png", "images/icon_share_qq.png", @@ -28,7 +28,7 @@ class BrnShareItemConstants { ]; /// 不可点击的分享渠道图片地址列表 - static const List disableShareItemImagePathList = [ + static const List disableShareItemImagePathList = [ "images/icon_share_weChat_disable.png", "images/icon_share_moments_disable.png", "images/icon_share_qq_disble.png", @@ -42,39 +42,47 @@ class BrnShareItemConstants { ]; /// 微信 - static const int SHARE_WEIXIN = 0; + static const int shareWeiXin = 0; /// 朋友圈 - static const int SHARE_FRIEND = 1; + static const int shareFriend = 1; /// qq - static const int SHARE_QQ = 2; + static const int shareQQ = 2; /// qq空间 - static const int SHARE_QZONE = 3; + static const int shareQZone = 3; /// 微博 - static const int SHARE_WEIBO = 4; + static const int shareWeiBo = 4; /// 链接 - static const int SHARE_LINK = 5; + static const int shareLink = 5; /// 短信 - static const int SHARE_SMS = 6; + static const int shareSms = 6; /// 剪贴板 - static const int SHARE_COPY_LINK = 7; + static const int shareCopyLink = 7; /// 浏览器 - static const int SHARE_BROWSER = 8; + static const int shareBrowser = 8; /// 相册 - static const int SHARE_SAVE_IMAGE = 9; + static const int shareSaveImage = 9; /// 自定义 - static const int SHARE_CUSTOM = 100; + static const int shareCustom = 100; } class BrnSelectionConstant { - static const int MAX_SELECT_COUNT = 65535; + static const int maxSelectCount = 65535; } + +class BrnButtonConstant { + /// 默认水平间距 + static const double horizontalPadding = 6; + + /// 默认垂直间距 + static const double verticalPadding = 8; +} \ No newline at end of file diff --git a/lib/src/constants/brn_fonts_constants.dart b/lib/src/constants/brn_fonts_constants.dart new file mode 100644 index 00000000..a6ecea8c --- /dev/null +++ b/lib/src/constants/brn_fonts_constants.dart @@ -0,0 +1,10 @@ +class BrnFonts { + const BrnFonts._(); + + static const double f12 = 12; + static const double f14 = 14; + static const double f16 = 16; + static const double f18 = 18; + static const double f20 = 20; + static const double f22 = 22; +} diff --git a/lib/src/constants/brn_strings_constants.dart b/lib/src/constants/brn_strings_constants.dart index 9dab7f23..5928c255 100644 --- a/lib/src/constants/brn_strings_constants.dart +++ b/lib/src/constants/brn_strings_constants.dart @@ -1,5 +1,7 @@ class BrnStrings { - //加载获取assets资源需要 + const BrnStrings._(); + + /// 加载获取 assets 资源需要 static const String flutterPackageName = "bruno"; static const String getDateFailed = "获取数据失败,请重试"; @@ -7,4 +9,5 @@ class BrnStrings { static const String noData = "暂无数据"; static const String noSearchData = "暂无搜索结果"; static const String clickPageRetry = "请点击页面重试"; + static const String loadingContent = '加载中...'; } diff --git a/lib/src/theme/base/brn_base_config.dart b/lib/src/theme/base/brn_base_config.dart index 860c0005..ccb9ad60 100644 --- a/lib/src/theme/base/brn_base_config.dart +++ b/lib/src/theme/base/brn_base_config.dart @@ -3,39 +3,50 @@ import 'package:bruno/src/theme/configs/brn_common_config.dart'; /// 组件配置基类 abstract class BrnBaseConfig { - String configId; - - BrnCommonConfig _currentLevelCommonConfig; - - BrnBaseConfig( - {this.configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID, - bool autoFlatConfig = false}) { + BrnBaseConfig({ + String configId = GLOBAL_CONFIG_ID, + bool autoFlatConfig = false, + }) : _configId = configId { if (autoFlatConfig) { initThemeConfig(configId); } } + String get configId => _configId; + String _configId; + BrnCommonConfig? _currentLevelCommonConfig; + /// 部分代码示意如下: - /// cardTitleConfig.detailTextStyle.merge(BrnTextStyle( - /// color: commonConfig.colorTextBase, - /// fontSize: commonConfig.fontSizeBase, - /// ).merge(detailTextStyle)); - /// 第一步 以commonConfig字段为基础merge detailTextStyle detailTextStyle 字段优先级高 - /// 当detailTextStyle中字段(如:color)为null时会使用commonConfig.colorTextBase - /// 第二步 以默认上一级配置为基础merge 第一步结果,当第一步中字段(如:color)为空时 , - /// 使用上一层级配置的color(cardTitleConfig.detailTextStyle.color) - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { + /// + /// ```dart + /// cardTitleConfig.detailTextStyle.merge( + /// BrnTextStyle( + /// color: commonConfig.colorTextBase, + /// fontSize: commonConfig.fontSizeBase, + /// ).merge(detailTextStyle), + /// ); + /// + /// - 以 `commonConfig` 字段为基础 merge `detailTextStyle`。 + /// `detailTextStyle` 字段优先级高,当detailTextStyle中字段(如 color)为 null 时 + /// 会使用 `commonConfig.colorTextBase`。 + /// - 以默认上一级配置为基础 merge 第一步的结果,当第一步中字段(如 color)为空时, + /// 使用上一层级配置的 color (`cardTitleConfig.detailTextStyle.color`)。 + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { _currentLevelCommonConfig = currentLevelCommonConfig; } /// 当自定义组件的配置时调用 - /// 根据自定义时传入的configId对配置字段打平 + /// 根据自定义时传入的 [configId] 对配置字段打平 void initThemeConfigPersonal() { initThemeConfig(configId); } BrnCommonConfig get commonConfig => _currentLevelCommonConfig ?? - BrnThemeConfigurator.instance.getConfig(configId: configId).commonConfig; + BrnThemeConfigurator.instance + .getConfig(configId: configId) + .commonConfig; } diff --git a/lib/src/theme/base/brn_default_config_utils.dart b/lib/src/theme/base/brn_default_config_utils.dart index e781d0be..26b02abf 100644 --- a/lib/src/theme/base/brn_default_config_utils.dart +++ b/lib/src/theme/base/brn_default_config_utils.dart @@ -1,15 +1,18 @@ -import 'package:bruno/bruno.dart'; import 'package:bruno/src/components/navbar/brn_appbar_theme.dart'; import 'package:bruno/src/components/picker/base/brn_picker_constants.dart'; +import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/constants/brn_strings_constants.dart'; -import 'package:bruno/src/theme/brn_theme.dart'; -import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/theme/base/brn_text_style.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart' + show BRUNO_CONFIG_ID; import 'package:bruno/src/theme/configs/brn_abnormal_state_config.dart'; import 'package:bruno/src/theme/configs/brn_action_sheet_config.dart'; +import 'package:bruno/src/theme/configs/brn_all_config.dart'; import 'package:bruno/src/theme/configs/brn_appbar_config.dart'; import 'package:bruno/src/theme/configs/brn_button_config.dart'; import 'package:bruno/src/theme/configs/brn_card_title_config.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; +import 'package:bruno/src/theme/configs/brn_dialog_config.dart'; import 'package:bruno/src/theme/configs/brn_form_config.dart'; import 'package:bruno/src/theme/configs/brn_gallery_detail_config.dart'; import 'package:bruno/src/theme/configs/brn_enhance_number_card_config.dart'; @@ -23,24 +26,30 @@ import 'package:flutter/services.dart'; /// Bruno默认配置 class BrnDefaultConfigUtils { - /// 默认全局配置 + const BrnDefaultConfigUtils._(); + + /// 默认全局配置 static BrnAllThemeConfig defaultAllConfig = BrnAllThemeConfig( - commonConfig: defaultCommonConfig, - formItemConfig: defaultFormItemConfig, - dialogConfig: defaultDialogConfig, - cardTitleConfig: defaultCardTitleConfig, - abnormalStateConfig: defaultAbnormalStateConfig, - tagConfig: defaultTagConfig, - appBarConfig: defaultAppBarConfig, - pairInfoTableConfig: defaultPairInfoTableConfig, - pairRichInfoGridConfig: defaultPairRichInfoGridConfig, - buttonConfig: defaultButtonConfig, - actionSheetConfig: defaultActionSheetConfig, - pickerConfig: defaultPickerConfig, - enhanceNumberCardConfig: defaultNumberInfoConfig, - tabBarConfig: defaultTabBarConfig, - selectionConfig: defaultSelectionConfig, - galleryDetailConfig: defaultGalleryDetailConfig); + commonConfig: defaultCommonConfig, + formItemConfig: defaultFormItemConfig, + dialogConfig: defaultDialogConfig, + cardTitleConfig: defaultCardTitleConfig, + abnormalStateConfig: defaultAbnormalStateConfig, + tagConfig: defaultTagConfig, + appBarConfig: defaultAppBarConfig, + pairInfoTableConfig: defaultPairInfoTableConfig, + pairRichInfoGridConfig: defaultPairRichInfoGridConfig, + buttonConfig: defaultButtonConfig, + actionSheetConfig: defaultActionSheetConfig, + pickerConfig: defaultPickerConfig, + enhanceNumberCardConfig: defaultEnhanceNumberInfoConfig, + tabBarConfig: defaultTabBarConfig, + selectionConfig: defaultSelectionConfig, + galleryDetailConfig: defaultGalleryDetailConfig, + ); + + + /// 全局默认配置 static BrnCommonConfig defaultCommonConfig = BrnCommonConfig( @@ -113,29 +122,29 @@ class BrnDefaultConfigUtils { /// 文本字号 /// /// 特殊数据展示,Bebas 数字字体,用于强吸引 - fontSizeBebas: 28, + fontSizeBebas: 28.0, /// 标题字体 /// 名称/页面大标题 - fontSizeHeadLg: 22, + fontSizeHeadLg: 22.0, /// 标题字体 /// 内容模块标题/一级标题 - fontSizeHead: 18, + fontSizeHead: 18.0, /// 子标题字体 /// 标题/录入文字/大按钮文字/二级标题 - fontSizeSubHead: 16, + fontSizeSubHead: 16.0, /// 基础字体 /// 内容副文本/普通说明文字 - fontSizeBase: 14, + fontSizeBase: 14.0, /// 辅助字体-普通 - fontSizeCaption: 12, + fontSizeCaption: 12.0, ///辅助字体-小 - fontSizeCaptionSm: 11, + fontSizeCaptionSm: 11.0, /// 圆角尺寸 radiusXs: 2.0, @@ -145,31 +154,31 @@ class BrnDefaultConfigUtils { /// 边框尺寸 borderWidthSm: 0.5, - borderWidthMd: 1, - borderWidthLg: 2, + borderWidthMd: 1.0, + borderWidthLg: 2.0, /// 水平间距 - hSpacingXs: 8, - hSpacingSm: 12, - hSpacingMd: 16, - hSpacingLg: 20, - hSpacingXl: 24, - hSpacingXxl: 42, + hSpacingXs: 8.0, + hSpacingSm: 12.0, + hSpacingMd: 16.0, + hSpacingLg: 20.0, + hSpacingXl: 24.0, + hSpacingXxl: 42.0, /// 垂直间距 - vSpacingXs: 4, - vSpacingSm: 8, - vSpacingMd: 12, - vSpacingLg: 14, - vSpacingXl: 16, - vSpacingXxl: 28, + vSpacingXs: 4.0, + vSpacingSm: 8.0, + vSpacingMd: 12.0, + vSpacingLg: 14.0, + vSpacingXl: 16.0, + vSpacingXxl: 28.0, /// 图标大小 - iconSizeXxs: 8, - iconSizeXs: 12, - iconSizeSm: 14, - iconSizeMd: 16, - iconSizeLg: 32, + iconSizeXxs: 8.0, + iconSizeXs: 12.0, + iconSizeSm: 14.0, + iconSizeMd: 16.0, + iconSizeLg: 32.0, ); ///******** 以下是子配置项 ********/// @@ -177,140 +186,167 @@ class BrnDefaultConfigUtils { /// 表单项默认配置 static BrnFormItemConfig defaultFormItemConfig = BrnFormItemConfig( headTitleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeHead), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeHead, + ), titleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), subTitleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextSecondary, - fontSize: defaultCommonConfig.fontSizeCaption), + color: defaultCommonConfig.colorTextSecondary, + fontSize: defaultCommonConfig.fontSizeCaption, + ), errorTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandError, - fontSize: defaultCommonConfig.fontSizeCaption), + color: defaultCommonConfig.brandError, + fontSize: defaultCommonConfig.fontSizeCaption, + ), hintTextStyle: BrnTextStyle( color: defaultCommonConfig.colorTextHint, fontSize: defaultCommonConfig.fontSizeSubHead, ), contentTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead), - optionsMiddlePadding: EdgeInsets.only(left: defaultCommonConfig.hSpacingMd), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), + optionsMiddlePadding: EdgeInsets.only( + left: defaultCommonConfig.hSpacingMd, + ), optionTextStyle: BrnTextStyle( - height: 1.3, - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead), + height: 1.3, + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), optionSelectedTextStyle: BrnTextStyle( - height: 1.3, - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeSubHead), + height: 1.3, + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), formPadding: EdgeInsets.only( - left: 0, - top: defaultCommonConfig.vSpacingLg, - right: defaultCommonConfig.hSpacingLg, - bottom: defaultCommonConfig.vSpacingLg), + left: 0.0, + top: defaultCommonConfig.vSpacingLg , + right: defaultCommonConfig.hSpacingLg , + bottom: defaultCommonConfig.vSpacingLg, + ), titlePaddingSm: EdgeInsets.only(left: 10), titlePaddingLg: EdgeInsets.only(left: defaultCommonConfig.hSpacingLg), subTitlePadding: EdgeInsets.only( - left: defaultCommonConfig.hSpacingLg, - top: defaultCommonConfig.vSpacingXs), + left: defaultCommonConfig.hSpacingLg, + top: defaultCommonConfig.vSpacingXs, + ), errorPadding: EdgeInsets.only( - left: defaultCommonConfig.hSpacingLg, - top: defaultCommonConfig.vSpacingXs), + left: defaultCommonConfig.hSpacingLg, + top: defaultCommonConfig.vSpacingXs, + ), disableTextStyle: BrnTextStyle( color: defaultCommonConfig.colorTextDisabled, fontSize: defaultCommonConfig.fontSizeSubHead, ), tipsTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextSecondary, - fontSize: defaultCommonConfig.fontSizeBase), + color: defaultCommonConfig.colorTextSecondary, + fontSize: defaultCommonConfig.fontSizeBase, + ), ); /// Dialog默认配置 static BrnDialogConfig defaultDialogConfig = BrnDialogConfig( - dialogWidth: 300, - radius: defaultCommonConfig.radiusLg, - iconPadding: EdgeInsets.only(top: defaultCommonConfig.vSpacingXxl), - titlePaddingSm: EdgeInsets.only( - top: 12, - left: defaultCommonConfig.hSpacingXxl, - right: defaultCommonConfig.hSpacingXxl), - titlePaddingLg: EdgeInsets.only( - top: 28, - left: defaultCommonConfig.hSpacingXxl, - right: defaultCommonConfig.hSpacingXxl), - titleTextStyle: BrnTextStyle( - fontWeight: FontWeight.w600, - fontSize: defaultCommonConfig.fontSizeHead, - color: defaultCommonConfig.colorTextBase), - titleTextAlign: TextAlign.center, - contentPaddingSm: EdgeInsets.only( - top: 8, - left: defaultCommonConfig.hSpacingXl, - right: defaultCommonConfig.hSpacingXl), - contentPaddingLg: EdgeInsets.only( - top: 28, - left: defaultCommonConfig.hSpacingXl, - right: defaultCommonConfig.hSpacingXl), - contentTextStyle: BrnTextStyle( - fontSize: defaultCommonConfig.fontSizeBase, - color: defaultCommonConfig.colorTextImportant, - decoration: TextDecoration.none, - ), - contentTextAlign: TextAlign.center, - warningPaddingSm: EdgeInsets.only( - top: 6, - left: defaultCommonConfig.hSpacingXl, - right: defaultCommonConfig.hSpacingXl), - warningPaddingLg: EdgeInsets.only( - top: 28, - left: defaultCommonConfig.hSpacingXl, - right: defaultCommonConfig.hSpacingXl), - warningTextAlign: TextAlign.center, - warningTextStyle: BrnTextStyle( - fontSize: defaultCommonConfig.fontSizeBase, - color: defaultCommonConfig.brandError, - decoration: TextDecoration.none, - ), - dividerPadding: EdgeInsets.only(top: 28), - mainActionTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontWeight: FontWeight.w600, - fontSize: defaultCommonConfig.fontSizeSubHead), - assistActionsTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontWeight: FontWeight.w600, - fontSize: defaultCommonConfig.fontSizeSubHead), - mainActionBackgroundColor: defaultCommonConfig.fillBase, - assistActionsBackgroundColor: defaultCommonConfig.fillBase, - bottomHeight: 44.0, - backgroundColor: defaultCommonConfig.fillBase); + dialogWidth: 300.0, + radius: defaultCommonConfig.radiusLg, + iconPadding: EdgeInsets.only(top: defaultCommonConfig.vSpacingXxl), + titlePaddingSm: EdgeInsets.only( + top: 12.0, + left: defaultCommonConfig.hSpacingXxl, + right: defaultCommonConfig.hSpacingXxl, + ), + titlePaddingLg: EdgeInsets.only( + top: 28.0, + left: defaultCommonConfig.hSpacingXxl, + right: defaultCommonConfig.hSpacingXxl, + ), + titleTextStyle: BrnTextStyle( + fontWeight: FontWeight.w600, + fontSize: defaultCommonConfig.fontSizeHead, + color: defaultCommonConfig.colorTextBase, + ), + titleTextAlign: TextAlign.center, + contentPaddingSm: EdgeInsets.only( + top: 8.0, + left: defaultCommonConfig.hSpacingXl, + right: defaultCommonConfig.hSpacingXl, + ), + contentPaddingLg: EdgeInsets.only( + top: 28.0, + left: defaultCommonConfig.hSpacingXl, + right: defaultCommonConfig.hSpacingXl, + ), + contentTextStyle: BrnTextStyle( + fontSize: defaultCommonConfig.fontSizeBase, + color: defaultCommonConfig.colorTextImportant, + decoration: TextDecoration.none, + ), + contentTextAlign: TextAlign.center, + warningPaddingSm: EdgeInsets.only( + top: 6.0, + left: defaultCommonConfig.hSpacingXl, + right: defaultCommonConfig.hSpacingXl, + ), + warningPaddingLg: EdgeInsets.only( + top: 28.0, + left: defaultCommonConfig.hSpacingXl, + right: defaultCommonConfig.hSpacingXl, + ), + warningTextAlign: TextAlign.center, + warningTextStyle: BrnTextStyle( + fontSize: defaultCommonConfig.fontSizeBase, + color: defaultCommonConfig.brandError, + decoration: TextDecoration.none, + ), + dividerPadding: EdgeInsets.only(top: 28.0), + mainActionTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontWeight: FontWeight.w600, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), + assistActionsTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontWeight: FontWeight.w600, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), + mainActionBackgroundColor: defaultCommonConfig.fillBase, + assistActionsBackgroundColor: defaultCommonConfig.fillBase, + bottomHeight: 44.0, + backgroundColor: defaultCommonConfig.fillBase, + ); /// 卡片标题配置 static BrnCardTitleConfig defaultCardTitleConfig = BrnCardTitleConfig( titleWithHeightTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeHead, - height: 25 / 18, - fontWeight: FontWeight.w600), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeHead, + height: 25.0 / 18.0, + fontWeight: FontWeight.w600, + ), titleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeHead, - fontWeight: FontWeight.w600), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeHead, + fontWeight: FontWeight.w600, + ), subtitleTextStyle: BrnTextStyle( color: defaultCommonConfig.colorTextSecondary, fontSize: defaultCommonConfig.fontSizeBase, ), detailTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + ), accessoryTextStyle: BrnTextStyle( color: defaultCommonConfig.colorTextSecondary, fontSize: defaultCommonConfig.fontSizeBase, ), cardTitlePadding: EdgeInsets.only( - top: defaultCommonConfig.vSpacingXl, - bottom: defaultCommonConfig.vSpacingMd), + top: defaultCommonConfig.vSpacingXl, + bottom: defaultCommonConfig.vSpacingMd, + ), alignment: PlaceholderAlignment.middle, cardBackgroundColor: defaultCommonConfig.fillBase, ); @@ -318,69 +354,81 @@ class BrnDefaultConfigUtils { /// 空页面配置 static BrnAbnormalStateConfig defaultAbnormalStateConfig = BrnAbnormalStateConfig( - titleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600), - contentTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextHint, - fontSize: defaultCommonConfig.fontSizeBase), - operateTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeBase), - btnRadius: 4, - doubleBrnTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeSubHead), - singleBrnTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBaseInverse, - fontSize: defaultCommonConfig.fontSizeSubHead, - ), - singleMinWidth: 160, - doubleMinWidth: 120); + titleTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + ), + contentTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextHint, + fontSize: defaultCommonConfig.fontSizeBase, + ), + operateTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeBase, + ), + btnRadius: 4, + doubleTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), + singleTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBaseInverse, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), + singleMinWidth: 160.0, + doubleMinWidth: 120.0, + ); /// 标签配置 static BrnTagConfig defaultTagConfig = BrnTagConfig( - tagTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeCaption), - selectTagTextStyle: BrnTextStyle( - fontWeight: FontWeight.w600, - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeCaption), - tagBackgroundColor: defaultCommonConfig.fillBody, - selectedTagBackgroundColor: defaultCommonConfig.brandPrimary, - tagRadius: defaultCommonConfig.radiusXs, - tagHeight: 34, - tagWidth: 75, - tagMinWidth: 75); + tagTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + selectTagTextStyle: BrnTextStyle( + fontWeight: FontWeight.w600, + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + tagBackgroundColor: defaultCommonConfig.fillBody, + selectedTagBackgroundColor: defaultCommonConfig.brandPrimary, + tagRadius: defaultCommonConfig.radiusXs, + tagHeight: 34.0, + tagWidth: 75.0, + tagMinWidth: 75.0, + ); + /// 导航栏配置 static BrnAppBarConfig defaultAppBarConfig = BrnAppBarConfig( - backgroundColor: Colors.white, - appBarHeight: BrnAppBarTheme.appBarHeight, - leadIconBuilder: () => Image.asset( - BrnAsset.ICON_BACK_BLACK, - package: BrnStrings.flutterPackageName, - width: BrnAppBarTheme.iconSize, - height: BrnAppBarTheme.iconSize, - fit: BoxFit.fitHeight, - ), - titleStyle: BrnTextStyle( - fontSize: BrnAppBarTheme.titleFontSize, - fontWeight: FontWeight.w600, - color: BrnAppBarTheme.lightTextColor), - actionsStyle: BrnTextStyle( - color: BrnAppBarTheme.lightTextColor, - fontSize: BrnAppBarTheme.actionFontSize, - fontWeight: FontWeight.w600), - titleMaxLength: BrnAppBarTheme.maxLength, - leftAndRightPadding: 20, - itemSpacing: BrnAppBarTheme.iconMargin, - titlePadding: EdgeInsets.zero, - iconSize: BrnAppBarTheme.iconSize, - configId: BrnThemeConfigurator.BRUNO_CONFIG_ID, - systemUiOverlayStyle: SystemUiOverlayStyle.dark); + backgroundColor: Colors.white, + appBarHeight: BrnAppBarTheme.appBarHeight, + leadIconBuilder: () => Image.asset( + BrnAsset.iconBackBlack, + package: BrnStrings.flutterPackageName, + width: BrnAppBarTheme.iconSize, + height: BrnAppBarTheme.iconSize, + fit: BoxFit.fitHeight, + ), + titleStyle: BrnTextStyle( + fontSize: BrnAppBarTheme.titleFontSize, + fontWeight: FontWeight.w600, + color: BrnAppBarTheme.lightTextColor, + ), + actionsStyle: BrnTextStyle( + color: BrnAppBarTheme.lightTextColor, + fontSize: BrnAppBarTheme.actionFontSize, + fontWeight: FontWeight.w600, + ), + titleMaxLength: BrnAppBarTheme.maxLength, + leftAndRightPadding: 20.0, + itemSpacing: BrnAppBarTheme.iconMargin, + titlePadding: EdgeInsets.zero, + iconSize: BrnAppBarTheme.iconSize, + configId: BRUNO_CONFIG_ID, + systemUiOverlayStyle: SystemUiOverlayStyle.dark, + ); /// 内容信息(两列)配置 static BrnPairInfoTableConfig defaultPairInfoTableConfig = @@ -388,63 +436,71 @@ class BrnDefaultConfigUtils { rowSpacing: 4, itemSpacing: 2, keyTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextSecondary, - fontSize: defaultCommonConfig.fontSizeBase), + color: defaultCommonConfig.colorTextSecondary, + fontSize: defaultCommonConfig.fontSizeBase, + ), valueTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + ), linkTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeBase), - configId: BrnThemeConfigurator.BRUNO_CONFIG_ID, + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeBase, + ), + configId: BRUNO_CONFIG_ID, ); /// 内容信息(一列)配置 static BrnPairRichInfoGridConfig defaultPairRichInfoGridConfig = BrnPairRichInfoGridConfig( - rowSpacing: 4, - itemSpacing: 2, - itemHeight: 20, + rowSpacing: 4.0, + itemSpacing: 2.0, + itemHeight: 20.0, keyTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextSecondary, - fontSize: defaultCommonConfig.fontSizeBase, - textBaseline: TextBaseline.ideographic), + color: defaultCommonConfig.colorTextSecondary, + fontSize: defaultCommonConfig.fontSizeBase, + textBaseline: TextBaseline.ideographic, + ), valueTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase, - textBaseline: TextBaseline.ideographic), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + textBaseline: TextBaseline.ideographic, + ), linkTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeBase, - textBaseline: TextBaseline.ideographic), - configId: BrnThemeConfigurator.BRUNO_CONFIG_ID, + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeBase, + textBaseline: TextBaseline.ideographic, + ), + configId: BRUNO_CONFIG_ID, ); /// 按钮配置 static BrnButtonConfig defaultButtonConfig = BrnButtonConfig( - bigButtonRadius: 6, - bigButtonHeight: 48, - bigButtonFontSize: 16, - smallButtonRadius: 4, - smallButtonHeight: 32, - smallButtonFontSize: 14, - configId: BrnThemeConfigurator.BRUNO_CONFIG_ID, + bigButtonRadius: 6.0, + bigButtonHeight: 48.0, + bigButtonFontSize: 16.0, + smallButtonRadius: 4.0, + smallButtonHeight: 32.0, + smallButtonFontSize: 14.0, + configId: BRUNO_CONFIG_ID, ); static BrnActionSheetConfig defaultActionSheetConfig = BrnActionSheetConfig( topRadius: defaultCommonConfig.radiusLg, titleStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextSecondary, - fontSize: defaultCommonConfig.fontSizeBase), + color: defaultCommonConfig.colorTextSecondary, + fontSize: defaultCommonConfig.fontSizeBase, + ), itemTitleStyle: BrnTextStyle( color: defaultCommonConfig.colorTextBase, fontSize: defaultCommonConfig.fontSizeSubHead, fontWeight: FontWeight.w600, ), itemTitleStyleLink: BrnTextStyle( - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600, - color: defaultCommonConfig.colorLink), + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + color: defaultCommonConfig.colorLink, + ), itemTitleStyleAlert: BrnTextStyle( color: defaultCommonConfig.brandError, fontSize: defaultCommonConfig.fontSizeSubHead, @@ -470,30 +526,34 @@ class BrnDefaultConfigUtils { fontSize: defaultCommonConfig.fontSizeSubHead, fontWeight: FontWeight.w600, ), - titlePadding: EdgeInsets.only(top: 16, bottom: 16, left: 60, right: 60), - contentPadding: EdgeInsets.only(top: 12, bottom: 12, left: 60, right: 60), + titlePadding: EdgeInsets.symmetric(horizontal: 60.0, vertical: 16.0), + contentPadding: EdgeInsets.symmetric(horizontal: 60.0, vertical: 12.0), ); static BrnPickerConfig defaultPickerConfig = BrnPickerConfig( - backgroundColor: PICKER_BACKGROUND_COLOR, + backgroundColor: pickerBackgroundColor, cancelTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), confirmTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeSubHead), + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), titleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600, - decoration: TextDecoration.none), - pickerHeight: PICKER_HEIGHT, - titleHeight: PICKER_TITLE_HEIGHT, - itemHeight: PICKER_ITEM_HEIGHT, + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + decoration: TextDecoration.none, + ), + pickerHeight: pickerHeight, + titleHeight: pickerTitleHeight, + itemHeight: pickerItemHeight, dividerColor: Color(0xFFF0F0F0), itemTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeHead), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeHead, + ), itemTextSelectedStyle: BrnTextStyle( color: defaultCommonConfig.brandPrimary, fontSize: defaultCommonConfig.fontSizeHead, @@ -503,119 +563,139 @@ class BrnDefaultConfigUtils { ); /// 数字增强信息配置 - static BrnEnhanceNumberCardConfig defaultNumberInfoConfig = + static BrnEnhanceNumberCardConfig defaultEnhanceNumberInfoConfig = BrnEnhanceNumberCardConfig( - runningSpace: 16, - itemRunningSpace: 8, - titleTextStyle: BrnTextStyle(fontSize: 28, fontWeight: FontWeight.w500), + runningSpace: 16.0, + itemRunningSpace: 8.0, + titleTextStyle: BrnTextStyle(fontSize: 28.0, fontWeight: FontWeight.w500), descTextStyle: BrnTextStyle( - fontSize: 12, color: defaultCommonConfig.colorTextSecondary), + fontSize: 12.0, + color: defaultCommonConfig.colorTextSecondary, + ), dividerWidth: 0.5, ); /// TabBar配置 static BrnTabBarConfig defaultTabBarConfig = BrnTabBarConfig( - tabHeight: 50, - indicatorHeight: 2, - indicatorWidth: 24, + backgroundColor: Colors.white, + tabHeight: 50.0, + indicatorHeight: 2.0, + indicatorWidth: 24.0, labelStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600), + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + ), unselectedLabelStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.normal), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.normal, + ), tagRadius: defaultCommonConfig.radiusSm, tagNormalTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeCaption), - tagNormalBgColor: defaultCommonConfig.brandPrimary.withAlpha(0x14), + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + tagNormalBgColor: defaultCommonConfig.fillBody, tagSelectedTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeCaption), - tagSelectedBgColor: defaultCommonConfig.fillBody, - tagSpacing: 12, + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + tagSelectedBgColor: defaultCommonConfig.brandPrimary.withAlpha(0x14), + tagSpacing: 12.0, preLineTagCount: 4, - tagHeight: 32, + tagHeight: 32.0, ); /// 筛选项配置 static BrnSelectionConfig defaultSelectionConfig = BrnSelectionConfig( - menuNormalTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase), - menuSelectedTextStyle: BrnTextStyle( - fontWeight: FontWeight.w600, - fontSize: defaultCommonConfig.fontSizeBase, - color: defaultCommonConfig.brandPrimary), - tagNormalTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeCaption), - tagSelectedTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeCaption, - fontWeight: FontWeight.w600, - ), - tagRadius: defaultCommonConfig.radiusSm, - tagNormalBackgroundColor: defaultCommonConfig.fillBody, - tagSelectedBackgroundColor: - defaultCommonConfig.brandPrimary.withOpacity(0.12), - rangeTitleTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600), - hintTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextHint, - fontSize: defaultCommonConfig.fontSizeBase), - inputTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase), - itemNormalTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase), - itemSelectedTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeBase, - fontWeight: FontWeight.w600, - ), - itemBoldTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase, - fontWeight: FontWeight.w600, - ), - lightSelectBgColor: Colors.white, - lightNormalBgColor: Colors.white, - middleSelectBgColor: Colors.white, - middleNormalBgColor: Color(0xFFF8F8F8), - deepSelectBgColor: Color(0xFFF8F8F8), - deepNormalBgColor: Color(0xFFF0F0F0), - resetTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextImportant, - fontSize: defaultCommonConfig.fontSizeCaption), - titleForMoreTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeBase, - fontWeight: FontWeight.w600, - ), - optionTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeBase), - moreTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextSecondary, - fontSize: defaultCommonConfig.fontSizeCaption, - ), - flayNormalTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead), - flatSelectedTextStyle: BrnTextStyle( - color: defaultCommonConfig.brandPrimary, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600), - flatBoldTextStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBase, - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600)); + menuNormalTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + ), + menuSelectedTextStyle: BrnTextStyle( + fontWeight: FontWeight.w600, + fontSize: defaultCommonConfig.fontSizeBase, + color: defaultCommonConfig.brandPrimary, + ), + tagNormalTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + tagSelectedTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeCaption, + fontWeight: FontWeight.w600, + ), + tagRadius: defaultCommonConfig.radiusSm, + tagNormalBackgroundColor: defaultCommonConfig.fillBody, + tagSelectedBackgroundColor: + defaultCommonConfig.brandPrimary.withOpacity(0.12), + rangeTitleTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + ), + hintTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextHint, + fontSize: defaultCommonConfig.fontSizeBase, + ), + inputTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + ), + itemNormalTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + ), + itemSelectedTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeBase, + fontWeight: FontWeight.w600, + ), + itemBoldTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + fontWeight: FontWeight.w600, + ), + lightSelectBgColor: Colors.white, + lightNormalBgColor: Colors.white, + middleSelectBgColor: Colors.white, + middleNormalBgColor: Color(0xFFF8F8F8), + deepSelectBgColor: Color(0xFFF8F8F8), + deepNormalBgColor: Color(0xFFF0F0F0), + resetTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextImportant, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + titleForMoreTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeBase, + fontWeight: FontWeight.w600, + ), + optionTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeBase, + ), + moreTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextSecondary, + fontSize: defaultCommonConfig.fontSizeCaption, + ), + flayerNormalTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + ), + flayerSelectedTextStyle: BrnTextStyle( + color: defaultCommonConfig.brandPrimary, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + ), + flayerBoldTextStyle: BrnTextStyle( + color: defaultCommonConfig.colorTextBase, + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + ), + ); /// 查看图片配置 static BrnGalleryDetailConfig defaultGalleryDetailConfig = @@ -626,29 +706,37 @@ class BrnDefaultConfigUtils { fontWeight: FontWeight.w600, ), appbarActionStyle: BrnTextStyle( - color: BrnAppBarTheme.lightTextColor, - fontSize: BrnAppBarTheme.actionFontSize, - fontWeight: FontWeight.w600), + color: BrnAppBarTheme.lightTextColor, + fontSize: BrnAppBarTheme.actionFontSize, + fontWeight: FontWeight.w600, + ), appbarBackgroundColor: Colors.black, appbarBrightness: Brightness.dark, - tabBarUnSelectedLabelStyle: - BrnTextStyle(fontSize: 16, color: Color(0XFFCCCCCC)), + tabBarUnSelectedLabelStyle: BrnTextStyle( + fontSize: 16.0, + color: Color(0XFFCCCCCC), + ), tabBarLabelStyle: BrnTextStyle( - fontSize: defaultCommonConfig.fontSizeSubHead, - fontWeight: FontWeight.w600, - color: defaultCommonConfig.colorTextBaseInverse), + fontSize: defaultCommonConfig.fontSizeSubHead, + fontWeight: FontWeight.w600, + color: defaultCommonConfig.colorTextBaseInverse, + ), tabBarBackgroundColor: Colors.black, pageBackgroundColor: Colors.black, bottomBackgroundColor: Color(0X88000000), titleStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBaseInverse, - fontSize: defaultCommonConfig.fontSizeHead, - fontWeight: FontWeight.w600), + color: defaultCommonConfig.colorTextBaseInverse, + fontSize: defaultCommonConfig.fontSizeHead, + fontWeight: FontWeight.w600, + ), contentStyle: BrnTextStyle( - color: Color(0xFFCCCCCC), fontSize: defaultCommonConfig.fontSizeBase), + color: Color(0xFFCCCCCC), + fontSize: defaultCommonConfig.fontSizeBase, + ), actionStyle: BrnTextStyle( - color: defaultCommonConfig.colorTextBaseInverse, - fontSize: defaultCommonConfig.fontSizeBase), + color: defaultCommonConfig.colorTextBaseInverse, + fontSize: defaultCommonConfig.fontSizeBase, + ), iconColor: Colors.white, ); } diff --git a/lib/src/theme/base/brn_text_style.dart b/lib/src/theme/base/brn_text_style.dart index 967027eb..dad190b7 100644 --- a/lib/src/theme/base/brn_text_style.dart +++ b/lib/src/theme/base/brn_text_style.dart @@ -2,14 +2,6 @@ import 'package:flutter/material.dart'; /// TextStyle处理类 用来将内部属性重新赋值进行copyWith 和 merge操作 class BrnTextStyle { - @required - Color color; - double fontSize; - FontWeight fontWeight; - TextDecoration decoration; - double height; - TextBaseline textBaseline; - BrnTextStyle({ this.color, this.fontSize, @@ -19,28 +11,23 @@ class BrnTextStyle { this.height, }); - BrnTextStyle.withStyle(TextStyle style) { + Color? color; + double? fontSize; + FontWeight? fontWeight; + TextDecoration? decoration; + double? height; + TextBaseline? textBaseline; + + BrnTextStyle.withStyle(TextStyle? style) { if (style == null) { return; } - if (style.color != null) { - this.color = style.color; - } - if (style.fontSize != null) { - this.fontSize = style.fontSize; - } - if (style?.fontWeight != null) { - this.fontWeight = style.fontWeight; - } - if (style?.decoration != null) { - this.decoration = style.decoration; - } - if (style?.height != null) { - this.height = style.height; - } - if (style?.textBaseline != null) { - this.textBaseline = style.textBaseline; - } + color = style.color ?? color; + fontSize = style.fontSize ?? fontSize; + fontWeight = style.fontWeight ?? fontWeight; + decoration = style.decoration ?? decoration; + height = style.height ?? height; + textBaseline = style.textBaseline ?? textBaseline; } TextStyle generateTextStyle() { @@ -54,37 +41,26 @@ class BrnTextStyle { ); } - void flatTextStyle(BrnTextStyle defaultTextStyle) { + void flatTextStyle(BrnTextStyle? defaultTextStyle) { if (defaultTextStyle == null) { return; } - if (defaultTextStyle.color != null) { - this.color ??= defaultTextStyle.color; - } - if (defaultTextStyle.fontSize != null) { - this.fontSize ??= defaultTextStyle.fontSize; - } - if (defaultTextStyle.fontWeight != null) { - this.fontWeight ??= defaultTextStyle.fontWeight; - } - if (defaultTextStyle.decoration != null) { - this.decoration ??= defaultTextStyle.decoration; - } - if (defaultTextStyle.height != null) { - this.height ??= defaultTextStyle.height; - } - if (defaultTextStyle.textBaseline != null) { - this.textBaseline ??= defaultTextStyle.textBaseline; - } + color ??= defaultTextStyle.color; + fontSize ??= defaultTextStyle.fontSize; + fontWeight ??= defaultTextStyle.fontWeight; + decoration ??= defaultTextStyle.decoration; + height ??= defaultTextStyle.height; + textBaseline ??= defaultTextStyle.textBaseline; } - BrnTextStyle copyWith( - {Color color, - double fontSize, - FontWeight fontWeight, - TextDecoration decoration, - double height, - TextBaseline textBaseline}) { + BrnTextStyle copyWith({ + Color? color, + double? fontSize, + FontWeight? fontWeight, + TextDecoration? decoration, + double? height, + TextBaseline? textBaseline, + }) { return BrnTextStyle( color: color ?? this.color, fontSize: fontSize ?? this.fontSize, @@ -95,7 +71,7 @@ class BrnTextStyle { ); } - BrnTextStyle merge(BrnTextStyle other) { + BrnTextStyle merge(BrnTextStyle? other) { if (other == null) return this; return copyWith( color: other.color, diff --git a/lib/src/theme/brn_initializer.dart b/lib/src/theme/brn_initializer.dart index a8f19d88..b90c0b5b 100644 --- a/lib/src/theme/brn_initializer.dart +++ b/lib/src/theme/brn_initializer.dart @@ -1,20 +1,13 @@ import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_all_config.dart'; -import 'package:bruno/src/theme/img/brn_theme_default_utils.dart'; -import 'package:bruno/src/theme/img/brn_theme_img_utils.dart'; - -///bruno初始化 +/// Bruno 初始化 class BrnInitializer { /// 手动注册时,默认注册渠道是 GLOBAL_CONFIG_ID - static register( - {BrnAllThemeConfig allThemeConfig, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID, - BrnThemeImgUtils brunoImgUtils}) { - /// 配置图片 - if (brunoImgUtils != null) { - BrnThemeImg.register(brunoImgUtils: brunoImgUtils); - } + static register({ + BrnAllThemeConfig? allThemeConfig, + String configId = GLOBAL_CONFIG_ID, + }) { /// 配置主题定制 BrnThemeConfigurator.instance.register(allThemeConfig, configId: configId); diff --git a/lib/src/theme/brn_theme.dart b/lib/src/theme/brn_theme.dart index ddabdd35..6300080e 100644 --- a/lib/src/theme/brn_theme.dart +++ b/lib/src/theme/brn_theme.dart @@ -1,4 +1,5 @@ /// theme export + library bruno_theme; export 'base/brn_base_config.dart'; @@ -22,5 +23,5 @@ export 'configs/brn_picker_config.dart'; export 'configs/brn_selection_config.dart'; export 'configs/brn_tabbar_config.dart'; export 'configs/brn_tag_config.dart'; -export 'img/brn_theme_default_utils.dart'; export 'brn_initializer.dart'; +export 'brn_theme_configurator.dart'; diff --git a/lib/src/theme/brn_theme_configurator.dart b/lib/src/theme/brn_theme_configurator.dart index 90fa0e4e..2449d465 100644 --- a/lib/src/theme/brn_theme_configurator.dart +++ b/lib/src/theme/brn_theme_configurator.dart @@ -1,33 +1,33 @@ -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/configs/brn_all_config.dart'; +const String BRUNO_CONFIG_ID = 'BRUNO_CONFIG_ID'; +const String GLOBAL_CONFIG_ID = 'GLOBAL_CONFIG_ID'; + class BrnThemeConfigurator { - static const String BRUNO_CONFIG_ID = 'BRUNO_CONFIG_ID'; - static const String GLOBAL_CONFIG_ID = 'GLOBAL_CONFIG_ID'; - static final BrnThemeConfigurator _instance = BrnThemeConfigurator._(); - Map globalConfig = Map(); + BrnThemeConfigurator._(){ + _checkAndInitBrunoConfig(); + } - BrnThemeConfigurator._(); + static final BrnThemeConfigurator _instance = BrnThemeConfigurator._(); static BrnThemeConfigurator get instance { return _instance; } - /// 手动注册时,默认注册渠道是 GLOBAL_CONFIG_ID - void register(BrnAllThemeConfig allThemeConfig, - {String configId = GLOBAL_CONFIG_ID}) { - assert(configId != null); - - /// 先赋值默认配置 - checkAndInitBrunoConfig(); + Map globalConfig = {}; - /// 打平内部字段 - allThemeConfig?.initThemeConfig(configId); - - /// 赋值传入配置 + /// 手动注册时,默认注册渠道是 GLOBAL_CONFIG_ID + void register( + BrnAllThemeConfig? allThemeConfig, { + String configId = GLOBAL_CONFIG_ID, + }) { + // 打平内部字段 if (allThemeConfig != null) { - instance.globalConfig[configId] = allThemeConfig; + // 赋值传入配置 + globalConfig[configId] = allThemeConfig + ..initThemeConfig(configId); } } @@ -36,26 +36,19 @@ class BrnThemeConfigurator { /// 2、若获取的为 null,则使用默认的全局配置。 /// 3、若没有配置 GLOBAL_CONFIG_ID ,则使用 BRUNO 的配置。 BrnAllThemeConfig getConfig({String configId = GLOBAL_CONFIG_ID}) { - assert(configId != null); - checkAndInitBrunoConfig(); - BrnAllThemeConfig allThemeConfig = globalConfig[configId]; - if (allThemeConfig == null) { - allThemeConfig = globalConfig[GLOBAL_CONFIG_ID]; - } - if (allThemeConfig == null) { - allThemeConfig = globalConfig[BRUNO_CONFIG_ID]; - } - return allThemeConfig; + BrnAllThemeConfig? allThemeConfig = globalConfig[configId] ?? + globalConfig[GLOBAL_CONFIG_ID] ?? + globalConfig[BRUNO_CONFIG_ID]; + assert(allThemeConfig != null, 'No suitable config found.'); + return allThemeConfig!; } /// 检查是否有默认配置 - bool isBrunoConfig() { - return globalConfig[BRUNO_CONFIG_ID] != null; - } + bool isBrunoConfig() => globalConfig[BRUNO_CONFIG_ID] != null; /// 没有默认配置 配置默认配置 - void checkAndInitBrunoConfig() { + void _checkAndInitBrunoConfig() { if (!isBrunoConfig()) { globalConfig[BRUNO_CONFIG_ID] = BrnDefaultConfigUtils.defaultAllConfig; } diff --git a/lib/src/theme/configs/brn_abnormal_state_config.dart b/lib/src/theme/configs/brn_abnormal_state_config.dart index 48265af7..67b829ff 100644 --- a/lib/src/theme/configs/brn_abnormal_state_config.dart +++ b/lib/src/theme/configs/brn_abnormal_state_config.dart @@ -1,139 +1,198 @@ import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; /// 描述: 空页面配置类 class BrnAbnormalStateConfig extends BrnBaseConfig { + BrnAbnormalStateConfig({ + BrnTextStyle? titleTextStyle, + BrnTextStyle? contentTextStyle, + BrnTextStyle? operateTextStyle, + double? btnRadius, + BrnTextStyle? singleTextStyle, + BrnTextStyle? doubleTextStyle, + double? singleMinWidth, + double? doubleMinWidth, + String configId = GLOBAL_CONFIG_ID, + }) : _titleTextStyle = titleTextStyle, + _contentTextStyle = contentTextStyle, + _operateTextStyle = operateTextStyle, + _btnRadius = btnRadius, + _singleTextStyle = singleTextStyle, + _doubleTextStyle = doubleTextStyle, + _singleMinWidth = singleMinWidth, + _doubleMinWidth = doubleMinWidth, + super(configId: configId); + /// 文案区域标题 - /// TextStyle(fontWeight: FontWeight.w600,color: [BrnCommonConfig.colorTextBase], fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle titleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _titleTextStyle; /// 文案区域内容 - /// TextStyle(color: [BrnCommonConfig.colorTextHint], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle contentTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextHint], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _contentTextStyle; /// 操作区域文本样式 - /// TextStyle(color: [BrnCommonConfig.brandPrimary], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle operateTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _operateTextStyle; /// 圆角 /// default value is [BrnCommonConfig.radiusSm] - double btnRadius; + double? _btnRadius; /// 单按钮文本样式 - /// default value is TextStyle(color: [BrnCommonConfig.colorTextBaseInverse], fontSize: [BrnCommonConfig.fontSizeSubHead] - BrnTextStyle singleBrnTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBaseInverse], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _singleTextStyle; /// 双按钮文本样式 - /// default value is TextStyle(color: [BrnCommonConfig.brandPrimary], fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle doubleBrnTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _doubleTextStyle; /// 单按钮的按钮最小宽度 - /// default value is 160 - double singleMinWidth; + /// 默认值为 160 + double? _singleMinWidth; /// 多按钮的按钮最小宽度 - /// default value is 120 - double doubleMinWidth; - - BrnAbnormalStateConfig( - {this.titleTextStyle, - this.contentTextStyle, - this.operateTextStyle, - this.btnRadius, - this.doubleBrnTextStyle, - this.singleBrnTextStyle, - this.singleMinWidth, - this.doubleMinWidth, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// 默认值为 120 + double? _doubleMinWidth; - @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + BrnTextStyle get titleTextStyle => + _titleTextStyle ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.titleTextStyle; - /// 用户全局组件配置 - BrnAbnormalStateConfig abnormalStateConfig = BrnThemeConfigurator.instance - .getConfig(configId: configId) - .abnormalStateConfig; + BrnTextStyle get contentTextStyle => + _contentTextStyle ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.contentTextStyle; - this.singleBrnTextStyle = abnormalStateConfig.singleBrnTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBaseInverse, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.singleBrnTextStyle)); + BrnTextStyle get operateTextStyle => + _operateTextStyle ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.operateTextStyle; - this.titleTextStyle = abnormalStateConfig.titleTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.titleTextStyle)); + double get btnRadius => + _btnRadius ?? BrnDefaultConfigUtils.defaultAbnormalStateConfig.btnRadius; - this.contentTextStyle = abnormalStateConfig.contentTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextHint, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.contentTextStyle)); + BrnTextStyle get singleTextStyle => + _singleTextStyle ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.singleTextStyle; - this.operateTextStyle = abnormalStateConfig.operateTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeBase) - .merge(this.operateTextStyle)); + BrnTextStyle get doubleTextStyle => + _doubleTextStyle ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.doubleTextStyle; - this.doubleBrnTextStyle = abnormalStateConfig.doubleBrnTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.doubleBrnTextStyle)); + double get singleMinWidth => + _singleMinWidth ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.singleMinWidth; - this.btnRadius ??= abnormalStateConfig.btnRadius; + double get doubleMinWidth => + _doubleMinWidth ?? + BrnDefaultConfigUtils.defaultAbnormalStateConfig.doubleMinWidth; - this.singleMinWidth ??= abnormalStateConfig.singleMinWidth; + @override + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); - this.doubleMinWidth ??= abnormalStateConfig.doubleMinWidth; + /// 用户全局组件配置 + BrnAbnormalStateConfig abnormalStateConfig = BrnThemeConfigurator.instance + .getConfig(configId: configId) + .abnormalStateConfig; + + _titleTextStyle = abnormalStateConfig.titleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_titleTextStyle), + ); + _contentTextStyle = abnormalStateConfig.contentTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextHint, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_contentTextStyle), + ); + _operateTextStyle = abnormalStateConfig.operateTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeBase, + ).merge(_operateTextStyle), + ); + _singleTextStyle = abnormalStateConfig.singleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBaseInverse, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_singleTextStyle), + ); + _doubleTextStyle = abnormalStateConfig.doubleTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_doubleTextStyle), + ); + _btnRadius ??= abnormalStateConfig._btnRadius; + _singleMinWidth ??= abnormalStateConfig._singleMinWidth; + _doubleMinWidth ??= abnormalStateConfig._doubleMinWidth; } BrnAbnormalStateConfig copyWith({ - BrnTextStyle titleTextStyle, - BrnTextStyle contentTextStyle, - BrnTextStyle operateTextStyle, - double btnRadius, - BrnTextStyle singleBrnTextStyle, - BrnTextStyle doubleBrnTextStyle, - double singleMinWidth, - double doubleMinWidth, + BrnTextStyle? titleTextStyle, + BrnTextStyle? contentTextStyle, + BrnTextStyle? operateTextStyle, + double? btnRadius, + BrnTextStyle? singleTextStyle, + BrnTextStyle? doubleTextStyle, + double? singleMinWidth, + double? doubleMinWidth, }) { return BrnAbnormalStateConfig( - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - contentTextStyle: contentTextStyle ?? this.contentTextStyle, - operateTextStyle: operateTextStyle ?? this.operateTextStyle, - btnRadius: btnRadius ?? this.btnRadius, - doubleBrnTextStyle: doubleBrnTextStyle ?? this.doubleBrnTextStyle, - singleBrnTextStyle: singleBrnTextStyle ?? this.singleBrnTextStyle, - singleMinWidth: singleMinWidth ?? this.singleMinWidth, - doubleMinWidth: doubleMinWidth ?? this.doubleMinWidth, + titleTextStyle: titleTextStyle ?? _titleTextStyle, + contentTextStyle: contentTextStyle ?? _contentTextStyle, + operateTextStyle: operateTextStyle ?? _operateTextStyle, + btnRadius: btnRadius ?? _btnRadius, + singleTextStyle: singleTextStyle ?? _singleTextStyle, + doubleTextStyle: doubleTextStyle ?? _doubleTextStyle, + singleMinWidth: singleMinWidth ?? _singleMinWidth, + doubleMinWidth: doubleMinWidth ?? _doubleMinWidth, ); } - BrnAbnormalStateConfig merge(BrnAbnormalStateConfig other) { + BrnAbnormalStateConfig merge(BrnAbnormalStateConfig? other) { if (other == null) return this; return copyWith( - titleTextStyle: - titleTextStyle?.merge(other.titleTextStyle) ?? other.titleTextStyle, - contentTextStyle: contentTextStyle?.merge(other.contentTextStyle) ?? - other.contentTextStyle, - operateTextStyle: operateTextStyle?.merge(other.operateTextStyle) ?? - other.operateTextStyle, - btnRadius: other.btnRadius, - doubleBrnTextStyle: doubleBrnTextStyle?.merge(other.doubleBrnTextStyle) ?? - other.doubleBrnTextStyle, - singleBrnTextStyle: singleBrnTextStyle?.merge(other.singleBrnTextStyle) ?? - other.singleBrnTextStyle, - singleMinWidth: other.singleMinWidth, - doubleMinWidth: other.doubleMinWidth, + titleTextStyle: titleTextStyle.merge(other._titleTextStyle), + contentTextStyle: contentTextStyle.merge(other._contentTextStyle), + operateTextStyle: operateTextStyle.merge(other._operateTextStyle), + btnRadius: other._btnRadius, + singleTextStyle: singleTextStyle.merge(other._singleTextStyle), + doubleTextStyle: doubleTextStyle.merge(other._doubleTextStyle), + singleMinWidth: other._singleMinWidth, + doubleMinWidth: other._doubleMinWidth, ); } } diff --git a/lib/src/theme/configs/brn_action_sheet_config.dart b/lib/src/theme/configs/brn_action_sheet_config.dart index 788b1ddb..b383cf94 100644 --- a/lib/src/theme/configs/brn_action_sheet_config.dart +++ b/lib/src/theme/configs/brn_action_sheet_config.dart @@ -1,4 +1,5 @@ import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; @@ -6,197 +7,270 @@ import 'package:flutter/material.dart'; /// BrnActionSheet 主题配置 class BrnActionSheetConfig extends BrnBaseConfig { - /// 遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultActionSheetConfig] - BrnActionSheetConfig( - {this.titleStyle, - this.itemTitleStyle, - this.itemTitleStyleLink, - this.itemTitleStyleAlert, - this.itemDescStyle, - this.itemDescStyleLink, - this.itemDescStyleAlert, - this.cancelStyle, - this.topRadius, - this.contentPadding, - this.titlePadding, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultActionSheetConfig] + BrnActionSheetConfig({ + BrnTextStyle? titleStyle, + BrnTextStyle? itemTitleStyle, + BrnTextStyle? itemTitleStyleLink, + BrnTextStyle? itemTitleStyleAlert, + BrnTextStyle? itemDescStyle, + BrnTextStyle? itemDescStyleLink, + BrnTextStyle? itemDescStyleAlert, + BrnTextStyle? cancelStyle, + double? topRadius, + EdgeInsets? contentPadding, + EdgeInsets? titlePadding, + String configId = GLOBAL_CONFIG_ID, + }) : _titleStyle = titleStyle, + _itemTitleStyle = itemTitleStyle, + _itemTitleStyleLink = itemTitleStyleLink, + _itemTitleStyleAlert = itemTitleStyleAlert, + _itemDescStyle = itemDescStyle, + _itemDescStyleLink = itemDescStyleLink, + _itemDescStyleAlert = itemDescStyleAlert, + _cancelStyle = cancelStyle, + _topRadius = topRadius, + _contentPadding = contentPadding, + _titlePadding = titlePadding, + super(configId: configId); /// ActionSheet 的顶部圆角 - /// default value is [BrnCommonConfig.radiusLg] - double topRadius; + /// 默认值为 [BrnCommonConfig.radiusLg] + double? _topRadius; /// 标题样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorTextSecondary],fontSize:[BrnCommonConfig.fontSizeBase]) - BrnTextStyle titleStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _titleStyle; /// 元素标题默认样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle itemTitleStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize:[BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _itemTitleStyle; /// 元素标题链接样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorLink],fontSize:[BrnCommonConfig.fontSizeSubHead],fontWeight: FontWeight.w600) - BrnTextStyle itemTitleStyleLink; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorLink], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemTitleStyleLink; /// 元素警示项标题样式 - /// default value is TextStyle(color:[BrnCommonConfig.brandError],fontSize:[BrnCommonConfig.fontSizeBase],fontWeight: FontWeight.w600) - BrnTextStyle itemTitleStyleAlert; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandError], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemTitleStyleAlert; /// 元素描述默认样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeCaption],fontWeight: FontWeight.w600) - BrnTextStyle itemDescStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemDescStyle; /// 元素标题描述链接样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorLink],fontSize:[BrnCommonConfig.fontSizeCaption],fontWeight: FontWeight.w600) - BrnTextStyle itemDescStyleLink; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorLink], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemDescStyleLink; /// 元素警示项标题描述样式 - /// default value is TextStyle(color:[BrnCommonConfig.brandError],fontSize:[BrnCommonConfig.fontSizeCaption],fontWeight: FontWeight.w600) - BrnTextStyle itemDescStyleAlert; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandError], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemDescStyleAlert; /// 取消按钮样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeSubHead],fontWeight: FontWeight.w600) - BrnTextStyle cancelStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _cancelStyle; /// 内容左右间距 - /// default value is EdgeInsets.only(top: 12, bottom: 12, left: 60, right: 60) - EdgeInsets contentPadding; + /// + /// EdgeInsets.symmetric(horizontal: 60, vertical: 12) + EdgeInsets? _contentPadding; - /// title 左右间距 - ///default value is EdgeInsets.only(top: 16, bottom: 16, left: 60, right: 60) - EdgeInsets titlePadding; + /// 标题左右间距 + /// + /// EdgeInsets.symmetric(horizontal: 60, vertical: 16) + EdgeInsets? _titlePadding; - @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + double get topRadius => + _topRadius ?? BrnDefaultConfigUtils.defaultActionSheetConfig.topRadius; - /// 用户全局组件配置 - BrnActionSheetConfig actionSheetConfig = BrnThemeConfigurator.instance - .getConfig(configId: configId) - .actionSheetConfig; + BrnTextStyle get titleStyle => + _titleStyle ?? BrnDefaultConfigUtils.defaultActionSheetConfig.titleStyle; - this.titlePadding ??= actionSheetConfig.titlePadding; - - this.contentPadding ??= actionSheetConfig.contentPadding; - - this.titleStyle = actionSheetConfig.titleStyle.merge(BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeBase) - .merge(this.titleStyle)); - - this.itemTitleStyle = actionSheetConfig.itemTitleStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.itemTitleStyle)); - - this.itemTitleStyleLink = actionSheetConfig.itemTitleStyleLink.merge( - BrnTextStyle( - color: commonConfig.colorLink, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.itemTitleStyleLink)); - - this.itemTitleStyleAlert = actionSheetConfig.itemTitleStyleAlert.merge( - BrnTextStyle( - color: commonConfig.brandError, - fontSize: commonConfig.fontSizeBase) - .merge(this.itemTitleStyleAlert)); - - this.itemDescStyle = actionSheetConfig.itemDescStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeCaption) - .merge(this.itemDescStyle)); - - this.itemDescStyleLink = actionSheetConfig.itemDescStyleLink.merge( - BrnTextStyle( - color: commonConfig.colorLink, - fontSize: commonConfig.fontSizeCaption) - .merge(this.itemDescStyleLink)); - - this.itemDescStyleAlert = actionSheetConfig.itemDescStyleAlert.merge( - BrnTextStyle( - color: commonConfig.brandError, - fontSize: commonConfig.fontSizeCaption) - .merge(this.itemDescStyleAlert)); - - this.cancelStyle = actionSheetConfig.cancelStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.cancelStyle)); - - this.topRadius ??= commonConfig.radiusLg; - } + BrnTextStyle get itemTitleStyle => + _itemTitleStyle ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.itemTitleStyle; - BrnActionSheetConfig copyWith({ - /// ActionSheet 的顶部圆角 - double topRadius, + BrnTextStyle get itemTitleStyleLink => + _itemTitleStyleLink ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.itemTitleStyleLink; - /// 标题样式 - BrnTextStyle titleStyle, + BrnTextStyle get itemTitleStyleAlert => + _itemTitleStyleAlert ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.itemTitleStyleAlert; - /// 元素标题默认样式 - BrnTextStyle itemTitleStyle, + BrnTextStyle get itemDescStyle => + _itemDescStyle ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.itemDescStyle; - /// 元素标题链接样式 - BrnTextStyle itemTitleStyleLink, + BrnTextStyle get itemDescStyleLink => + _itemDescStyleLink ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.itemDescStyleLink; - /// 元素警示项标题样式 - BrnTextStyle itemTitleStyleAlert, + BrnTextStyle get itemDescStyleAlert => + _itemDescStyleAlert ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.itemDescStyleAlert; - /// 元素描述默认样式 - BrnTextStyle itemDescStyle, + BrnTextStyle get cancelStyle => + _cancelStyle ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.cancelStyle; - /// 元素标题描述链接样式 - BrnTextStyle itemDescStyleLink, + EdgeInsets get contentPadding => + _contentPadding ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.contentPadding; + + EdgeInsets get titlePadding => + _titlePadding ?? + BrnDefaultConfigUtils.defaultActionSheetConfig.titlePadding; + + @override + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); + + /// 用户全局组件配置 + BrnActionSheetConfig actionSheetConfig = BrnThemeConfigurator.instance + .getConfig(configId: configId) + .actionSheetConfig; - /// 元素警示项标题描述样式 - BrnTextStyle itemDescStyleAlert, + _titlePadding ??= actionSheetConfig.titlePadding; + _contentPadding ??= actionSheetConfig.contentPadding; + _titleStyle = actionSheetConfig.titleStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeBase, + ).merge(_titleStyle), + ); + _itemTitleStyle = actionSheetConfig.itemTitleStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_itemTitleStyle), + ); + _itemTitleStyleLink = actionSheetConfig.itemTitleStyleLink.merge( + BrnTextStyle( + color: commonConfig.colorLink, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_itemTitleStyleLink), + ); + _itemTitleStyleAlert = actionSheetConfig.itemTitleStyleAlert.merge( + BrnTextStyle( + color: commonConfig.brandError, + fontSize: commonConfig.fontSizeBase, + ).merge(_itemTitleStyleAlert), + ); + _itemDescStyle = actionSheetConfig.itemDescStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeCaption, + ).merge(_itemDescStyle), + ); + _itemDescStyleLink = actionSheetConfig.itemDescStyleLink.merge( + BrnTextStyle( + color: commonConfig.colorLink, + fontSize: commonConfig.fontSizeCaption, + ).merge(_itemDescStyleLink), + ); + _itemDescStyleAlert = actionSheetConfig.itemDescStyleAlert.merge( + BrnTextStyle( + color: commonConfig.brandError, + fontSize: commonConfig.fontSizeCaption, + ).merge(_itemDescStyleAlert), + ); + _cancelStyle = actionSheetConfig.cancelStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_cancelStyle), + ); + _topRadius ??= commonConfig.radiusLg; + } - /// 取消按钮样式 - BrnTextStyle cancelStyle, - EdgeInsets contentPadding, - EdgeInsets titlePadding, + BrnActionSheetConfig copyWith({ + double? topRadius, + BrnTextStyle? titleStyle, + BrnTextStyle? itemTitleStyle, + BrnTextStyle? itemTitleStyleLink, + BrnTextStyle? itemTitleStyleAlert, + BrnTextStyle? itemDescStyle, + BrnTextStyle? itemDescStyleLink, + BrnTextStyle? itemDescStyleAlert, + BrnTextStyle? cancelStyle, + EdgeInsets? contentPadding, + EdgeInsets? titlePadding, }) { return BrnActionSheetConfig( - titleStyle: titleStyle ?? this.titleStyle, - itemTitleStyle: itemTitleStyle ?? this.itemTitleStyle, - itemTitleStyleLink: itemTitleStyleLink ?? this.itemTitleStyleLink, - itemTitleStyleAlert: itemTitleStyleAlert ?? this.itemTitleStyleAlert, - itemDescStyle: itemDescStyle ?? this.itemDescStyle, - itemDescStyleLink: itemDescStyleLink ?? this.itemDescStyleLink, - itemDescStyleAlert: itemDescStyleAlert ?? this.itemDescStyleAlert, - cancelStyle: cancelStyle ?? this.cancelStyle, - topRadius: topRadius ?? this.topRadius, - contentPadding: contentPadding ?? this.contentPadding, - titlePadding: titlePadding ?? this.titlePadding); + titleStyle: titleStyle ?? _titleStyle, + itemTitleStyle: itemTitleStyle ?? _itemTitleStyle, + itemTitleStyleLink: itemTitleStyleLink ?? _itemTitleStyleLink, + itemTitleStyleAlert: itemTitleStyleAlert ?? _itemTitleStyleAlert, + itemDescStyle: itemDescStyle ?? _itemDescStyle, + itemDescStyleLink: itemDescStyleLink ?? _itemDescStyleLink, + itemDescStyleAlert: itemDescStyleAlert ?? _itemDescStyleAlert, + cancelStyle: cancelStyle ?? _cancelStyle, + topRadius: topRadius ?? _topRadius, + contentPadding: contentPadding ?? _contentPadding, + titlePadding: titlePadding ?? _titlePadding, + ); } - BrnActionSheetConfig merge(BrnActionSheetConfig other) { + BrnActionSheetConfig merge(BrnActionSheetConfig? other) { if (other == null) return this; return copyWith( - titleStyle: this.titleStyle?.merge(other.titleStyle) ?? other.titleStyle, - itemTitleStyle: this.itemTitleStyle?.merge(other.itemTitleStyle) ?? - other.itemTitleStyle, - itemTitleStyleLink: - this.itemTitleStyleLink?.merge(other.itemTitleStyleLink) ?? - other.itemTitleStyleLink, - itemTitleStyleAlert: - this.itemTitleStyleAlert?.merge(other.itemTitleStyleAlert) ?? - other.itemTitleStyleAlert, - itemDescStyle: - this.itemDescStyle?.merge(other.itemDescStyle) ?? other.itemDescStyle, - itemDescStyleLink: - this.itemDescStyleLink?.merge(other.itemDescStyleLink) ?? - other.itemDescStyleLink, - itemDescStyleAlert: - this.itemDescStyleAlert?.merge(other.itemDescStyleAlert) ?? - other.itemDescStyleAlert, - cancelStyle: - this.cancelStyle?.merge(other.cancelStyle) ?? other.cancelStyle, - topRadius: other.topRadius, - contentPadding: other.contentPadding, - titlePadding: other.titlePadding, + titleStyle: titleStyle.merge(other._titleStyle), + itemTitleStyle: itemTitleStyle.merge(other._itemTitleStyle), + itemTitleStyleLink: itemTitleStyleLink.merge(other._itemTitleStyleLink), + itemTitleStyleAlert: itemTitleStyleAlert.merge(other._itemTitleStyleAlert), + itemDescStyle: itemDescStyle.merge(other._itemDescStyle), + itemDescStyleLink: itemDescStyleLink.merge(other._itemDescStyleLink), + itemDescStyleAlert: itemDescStyleAlert.merge(other._itemDescStyleAlert), + cancelStyle: cancelStyle.merge(other._cancelStyle), + topRadius: other._topRadius, + contentPadding: other._contentPadding, + titlePadding: other._titlePadding, ); } } diff --git a/lib/src/theme/configs/brn_all_config.dart b/lib/src/theme/configs/brn_all_config.dart index d3292b26..fe244f36 100644 --- a/lib/src/theme/configs/brn_all_config.dart +++ b/lib/src/theme/configs/brn_all_config.dart @@ -1,100 +1,225 @@ -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/bruno.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_abnormal_state_config.dart'; +import 'package:bruno/src/theme/configs/brn_action_sheet_config.dart'; +import 'package:bruno/src/theme/configs/brn_appbar_config.dart'; +import 'package:bruno/src/theme/configs/brn_button_config.dart'; +import 'package:bruno/src/theme/configs/brn_card_title_config.dart'; +import 'package:bruno/src/theme/configs/brn_common_config.dart'; +import 'package:bruno/src/theme/configs/brn_dialog_config.dart'; +import 'package:bruno/src/theme/configs/brn_enhance_number_card_config.dart'; +import 'package:bruno/src/theme/configs/brn_form_config.dart'; +import 'package:bruno/src/theme/configs/brn_gallery_detail_config.dart'; +import 'package:bruno/src/theme/configs/brn_pair_info_config.dart'; +import 'package:bruno/src/theme/configs/brn_picker_config.dart'; +import 'package:bruno/src/theme/configs/brn_selection_config.dart'; +import 'package:bruno/src/theme/configs/brn_tabbar_config.dart'; +import 'package:bruno/src/theme/configs/brn_tag_config.dart'; /// 描述: 全局配置 /// /// 当用户使用时对单个组件自定义配置,优先走单个组件特定配置(作用范围档次使用) -/// 当用户配置组件通用配置时如[BrnDialogConfig]优先使用该配置 -/// 若没有配置组件通用配置,走[BrnCommonConfig]全局配置 -/// 如果以上都没有配置走Bruno默认配置即[BrnDefaultConfigUtils]中配置 +/// 当用户配置组件通用配置时如 [BrnDialogConfig] 优先使用该配置 +/// 若没有配置组件通用配置,走 [BrnCommonConfig] 全局配置 +/// 如果以上都没有配置走 Bruno 默认配置,即 [BrnDefaultConfigUtils] 中的配置 /// 当没有配置组件的特定属性时使用上一级特定配置 -/// class BrnAllThemeConfig { - BrnCommonConfig commonConfig; - BrnAppBarConfig appBarConfig; - BrnButtonConfig buttonConfig; - BrnDialogConfig dialogConfig; - BrnCardTitleConfig cardTitleConfig; - BrnAbnormalStateConfig abnormalStateConfig; - BrnTagConfig tagConfig; - BrnPairInfoTableConfig pairInfoTableConfig; - BrnPairRichInfoGridConfig pairRichInfoGridConfig; - BrnActionSheetConfig actionSheetConfig; - BrnPickerConfig pickerConfig; - BrnEnhanceNumberCardConfig enhanceNumberCardConfig; - BrnTabBarConfig tabBarConfig; - BrnFormItemConfig formItemConfig; - BrnSelectionConfig selectionConfig; - BrnGalleryDetailConfig galleryDetailConfig; - - BrnAllThemeConfig( - {this.commonConfig, - this.appBarConfig, - this.buttonConfig, - this.dialogConfig, - this.formItemConfig, - this.cardTitleConfig, - this.abnormalStateConfig, - this.tagConfig, - this.pairInfoTableConfig, - this.pairRichInfoGridConfig, - this.actionSheetConfig, - this.pickerConfig, - this.enhanceNumberCardConfig, - this.tabBarConfig, - this.selectionConfig, - this.galleryDetailConfig, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}); + BrnAllThemeConfig({ + BrnCommonConfig? commonConfig, + BrnAppBarConfig? appBarConfig, + BrnButtonConfig? buttonConfig, + BrnDialogConfig? dialogConfig, + BrnFormItemConfig? formItemConfig, + BrnCardTitleConfig? cardTitleConfig, + BrnAbnormalStateConfig? abnormalStateConfig, + BrnTagConfig? tagConfig, + BrnPairInfoTableConfig? pairInfoTableConfig, + BrnPairRichInfoGridConfig? pairRichInfoGridConfig, + BrnActionSheetConfig? actionSheetConfig, + BrnPickerConfig? pickerConfig, + BrnEnhanceNumberCardConfig? enhanceNumberCardConfig, + BrnTabBarConfig? tabBarConfig, + BrnSelectionConfig? selectionConfig, + BrnGalleryDetailConfig? galleryDetailConfig, + String configId = GLOBAL_CONFIG_ID, + }) : _commonConfig = commonConfig, + _appBarConfig = appBarConfig, + _buttonConfig = buttonConfig, + _dialogConfig = dialogConfig, + _formItemConfig = formItemConfig, + _cardTitleConfig = cardTitleConfig, + _abnormalStateConfig = abnormalStateConfig, + _tagConfig = tagConfig, + _pairInfoTableConfig = pairInfoTableConfig, + _pairRichInfoGridConfig = pairRichInfoGridConfig, + _actionSheetConfig = actionSheetConfig, + _pickerConfig = pickerConfig, + _enhanceNumberCardConfig = enhanceNumberCardConfig, + _tabBarConfig = tabBarConfig, + _selectionConfig = selectionConfig, + _galleryDetailConfig = galleryDetailConfig; + + BrnCommonConfig? _commonConfig; + + BrnCommonConfig get commonConfig => + _commonConfig ?? BrnDefaultConfigUtils.defaultCommonConfig; + + BrnAppBarConfig? _appBarConfig; + + BrnAppBarConfig get appBarConfig => + _appBarConfig ?? BrnDefaultConfigUtils.defaultAppBarConfig; + + BrnButtonConfig? _buttonConfig; + + BrnButtonConfig get buttonConfig => + _buttonConfig ?? BrnDefaultConfigUtils.defaultButtonConfig; + + BrnDialogConfig? _dialogConfig; + + BrnDialogConfig get dialogConfig => + _dialogConfig ?? BrnDefaultConfigUtils.defaultDialogConfig; + + BrnCardTitleConfig? _cardTitleConfig; + + BrnCardTitleConfig get cardTitleConfig => + _cardTitleConfig ?? BrnDefaultConfigUtils.defaultCardTitleConfig; + + BrnAbnormalStateConfig? _abnormalStateConfig; + + BrnAbnormalStateConfig get abnormalStateConfig => + _abnormalStateConfig ?? BrnDefaultConfigUtils.defaultAbnormalStateConfig; + + BrnTagConfig? _tagConfig; + + BrnTagConfig get tagConfig => + _tagConfig ?? BrnDefaultConfigUtils.defaultTagConfig; + + BrnPairInfoTableConfig? _pairInfoTableConfig; + + BrnPairInfoTableConfig get pairInfoTableConfig => + _pairInfoTableConfig ?? BrnDefaultConfigUtils.defaultPairInfoTableConfig; + + BrnPairRichInfoGridConfig? _pairRichInfoGridConfig; + + BrnPairRichInfoGridConfig get pairRichInfoGridConfig => + _pairRichInfoGridConfig ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig; + + BrnActionSheetConfig? _actionSheetConfig; + + BrnActionSheetConfig get actionSheetConfig => + _actionSheetConfig ?? BrnDefaultConfigUtils.defaultActionSheetConfig; + + BrnPickerConfig? _pickerConfig; + + BrnPickerConfig get pickerConfig => + _pickerConfig ?? BrnDefaultConfigUtils.defaultPickerConfig; + + BrnEnhanceNumberCardConfig? _enhanceNumberCardConfig; + + BrnEnhanceNumberCardConfig get enhanceNumberCardConfig => + _enhanceNumberCardConfig ?? + BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig; + + BrnTabBarConfig? _tabBarConfig; + + BrnTabBarConfig get tabBarConfig => + _tabBarConfig ?? BrnDefaultConfigUtils.defaultTabBarConfig; + + BrnFormItemConfig? _formItemConfig; + + BrnFormItemConfig get formItemConfig => + _formItemConfig ?? BrnDefaultConfigUtils.defaultFormItemConfig; + + BrnSelectionConfig? _selectionConfig; + + BrnSelectionConfig get selectionConfig => + _selectionConfig ?? BrnDefaultConfigUtils.defaultSelectionConfig; + + BrnGalleryDetailConfig? _galleryDetailConfig; + + BrnGalleryDetailConfig get galleryDetailConfig => + _galleryDetailConfig ?? BrnDefaultConfigUtils.defaultGalleryDetailConfig; void initThemeConfig(String configId) { - this.commonConfig ??= BrnCommonConfig(); - this.appBarConfig ??= BrnAppBarConfig(); - this.buttonConfig ??= BrnButtonConfig(); - this.dialogConfig ??= BrnDialogConfig(); - this.formItemConfig ??= BrnFormItemConfig(); - this.cardTitleConfig ??= BrnCardTitleConfig(); - this.abnormalStateConfig ??= BrnAbnormalStateConfig(); - this.tagConfig ??= BrnTagConfig(); - this.appBarConfig ??= BrnAppBarConfig(); - this.pairInfoTableConfig ??= BrnPairInfoTableConfig(); - this.pairRichInfoGridConfig ??= BrnPairRichInfoGridConfig(); - this.actionSheetConfig ??= BrnActionSheetConfig(); - this.pickerConfig ??= BrnPickerConfig(); - this.enhanceNumberCardConfig ??= BrnEnhanceNumberCardConfig(); - this.tabBarConfig ??= BrnTabBarConfig(); - this.selectionConfig ??= BrnSelectionConfig(); - this.galleryDetailConfig ??= BrnGalleryDetailConfig(); - - commonConfig?.initThemeConfig(configId); - appBarConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - buttonConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - dialogConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - formItemConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - cardTitleConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - abnormalStateConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - tagConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - pairInfoTableConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - pairRichInfoGridConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - selectionConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - actionSheetConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - pickerConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - enhanceNumberCardConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - tabBarConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); - galleryDetailConfig?.initThemeConfig(configId, - currentLevelCommonConfig: commonConfig); + this._commonConfig ??= BrnCommonConfig(); + this._appBarConfig ??= BrnAppBarConfig(); + this._buttonConfig ??= BrnButtonConfig(); + this._dialogConfig ??= BrnDialogConfig(); + this._formItemConfig ??= BrnFormItemConfig(); + this._cardTitleConfig ??= BrnCardTitleConfig(); + this._abnormalStateConfig ??= BrnAbnormalStateConfig(); + this._tagConfig ??= BrnTagConfig(); + this._appBarConfig ??= BrnAppBarConfig(); + this._pairInfoTableConfig ??= BrnPairInfoTableConfig(); + this._pairRichInfoGridConfig ??= BrnPairRichInfoGridConfig(); + this._actionSheetConfig ??= BrnActionSheetConfig(); + this._pickerConfig ??= BrnPickerConfig(); + this._enhanceNumberCardConfig ??= BrnEnhanceNumberCardConfig(); + this._tabBarConfig ??= BrnTabBarConfig(); + this._selectionConfig ??= BrnSelectionConfig(); + this._galleryDetailConfig ??= BrnGalleryDetailConfig(); + + commonConfig.initThemeConfig(configId); + appBarConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + buttonConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + dialogConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + formItemConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + cardTitleConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + abnormalStateConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + tagConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + pairInfoTableConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + pairRichInfoGridConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + selectionConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + actionSheetConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + pickerConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + enhanceNumberCardConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + tabBarConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); + galleryDetailConfig.initThemeConfig( + configId, + currentLevelCommonConfig: commonConfig, + ); } } diff --git a/lib/src/theme/configs/brn_appbar_config.dart b/lib/src/theme/configs/brn_appbar_config.dart index 4633f6c6..bc2323b4 100644 --- a/lib/src/theme/configs/brn_appbar_config.dart +++ b/lib/src/theme/configs/brn_appbar_config.dart @@ -1,7 +1,11 @@ -import 'package:bruno/bruno.dart'; import 'package:bruno/src/components/navbar/brn_appbar_theme.dart'; +import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/constants/brn_strings_constants.dart'; -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; +import 'package:bruno/src/theme/base/brn_text_style.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/theme/configs/brn_common_config.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; @@ -9,201 +13,259 @@ typedef BrnWidgetBuilder = Widget Function(); /// Appbar主题配置 class BrnAppBarConfig extends BrnBaseConfig { - /// BrnAppBar 主题配置,遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultAppBarConfig] - BrnAppBarConfig( - {this.backgroundColor, - this.appBarHeight, - this.leadIconBuilder, - this.titleStyle, - this.actionsStyle, - this.titleMaxLength, - this.leftAndRightPadding, - this.itemSpacing, - this.titlePadding, - this.iconSize, - this.flexibleSpace, - this.systemUiOverlayStyle, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); - - BrnAppBarConfig.dark( - {this.backgroundColor, - this.appBarHeight, - this.leadIconBuilder, - this.titleStyle, - this.actionsStyle, - this.titleMaxLength, - this.leftAndRightPadding, - this.itemSpacing, - this.titlePadding, - this.iconSize, - this.flexibleSpace, - this.systemUiOverlayStyle, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId) { - this.systemUiOverlayStyle = SystemUiOverlayStyle.light; - this.backgroundColor = Color(0xff2E313B); - this.leadIconBuilder = () => Image.asset( - BrnAsset.ICON_BACK_WHITE, - package: BrnStrings.flutterPackageName, - width: BrnAppBarTheme.iconSize, - height: BrnAppBarTheme.iconSize, - fit: BoxFit.fitHeight, - ); - this.titleStyle = BrnTextStyle( - fontSize: BrnAppBarTheme.titleFontSize, - fontWeight: FontWeight.w600, - color: BrnAppBarTheme.darkTextColor); - this.actionsStyle = BrnTextStyle( - color: BrnAppBarTheme.darkTextColor, - fontSize: BrnAppBarTheme.actionFontSize, - fontWeight: FontWeight.w600); + /// BrnAppBar 主题配置,遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultAppBarConfig] + BrnAppBarConfig({ + Color? backgroundColor, + double? appBarHeight, + BrnWidgetBuilder? leadIconBuilder, + BrnTextStyle? titleStyle, + BrnTextStyle? actionsStyle, + int? titleMaxLength, + double? leftAndRightPadding, + double? itemSpacing, + EdgeInsets? titlePadding, + double? iconSize, + SystemUiOverlayStyle? systemUiOverlayStyle, + String configId = GLOBAL_CONFIG_ID, + }) : _backgroundColor = backgroundColor, + _appBarHeight = appBarHeight, + _leadIconBuilder = leadIconBuilder, + _titleStyle = titleStyle, + _actionsStyle = actionsStyle, + _titleMaxLength = titleMaxLength, + _leftAndRightPadding = leftAndRightPadding, + _itemSpacing = itemSpacing, + _titlePadding = titlePadding, + _iconSize = iconSize, + _systemUiOverlayStyle = systemUiOverlayStyle, + super(configId: configId); + + BrnAppBarConfig.dark({ + double? appBarHeight, + int? titleMaxLength, + double? leftAndRightPadding, + double? itemSpacing, + EdgeInsets? titlePadding, + double? iconSize, + String configId = GLOBAL_CONFIG_ID, + }) : _appBarHeight = appBarHeight, + _titleMaxLength = titleMaxLength, + _leftAndRightPadding = leftAndRightPadding, + _itemSpacing = itemSpacing, + _titlePadding = titlePadding, + _iconSize = iconSize, + super(configId: configId) { + _backgroundColor = Color(0xff2E313B); + _leadIconBuilder = () => Image.asset( + BrnAsset.iconBackWhite, + package: BrnStrings.flutterPackageName, + width: BrnAppBarTheme.iconSize, + height: BrnAppBarTheme.iconSize, + fit: BoxFit.fitHeight, + ); + _titleStyle = BrnTextStyle( + fontSize: BrnAppBarTheme.titleFontSize, + fontWeight: FontWeight.w600, + color: BrnAppBarTheme.darkTextColor, + ); + _actionsStyle = BrnTextStyle( + color: BrnAppBarTheme.darkTextColor, + fontSize: BrnAppBarTheme.actionFontSize, + fontWeight: FontWeight.w600, + ); + _systemUiOverlayStyle = SystemUiOverlayStyle.light; } - BrnAppBarConfig.light( - {this.backgroundColor, - this.appBarHeight, - this.leadIconBuilder, - this.titleStyle, - this.actionsStyle, - this.titleMaxLength, - this.leftAndRightPadding, - this.itemSpacing, - this.titlePadding, - this.iconSize, - this.flexibleSpace, - this.systemUiOverlayStyle, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId) { - this.systemUiOverlayStyle = SystemUiOverlayStyle.dark; - this.backgroundColor = Colors.white; - this.leadIconBuilder = () => Image.asset( - BrnAsset.ICON_BACK_BLACK, - package: BrnStrings.flutterPackageName, - width: BrnAppBarTheme.iconSize, - height: BrnAppBarTheme.iconSize, - fit: BoxFit.fitHeight, - ); - this.titleStyle = BrnTextStyle( - fontSize: BrnAppBarTheme.titleFontSize, - fontWeight: FontWeight.w600, - color: BrnAppBarTheme.lightTextColor); - this.actionsStyle = BrnTextStyle( - color: BrnAppBarTheme.lightTextColor, - fontSize: BrnAppBarTheme.actionFontSize, - fontWeight: FontWeight.w600); + BrnAppBarConfig.light({ + double? appBarHeight, + int? titleMaxLength, + double? leftAndRightPadding, + double? itemSpacing, + EdgeInsets? titlePadding, + double? iconSize, + String configId = GLOBAL_CONFIG_ID, + }) : _appBarHeight = appBarHeight, + _titleMaxLength = titleMaxLength, + _leftAndRightPadding = leftAndRightPadding, + _itemSpacing = itemSpacing, + _titlePadding = titlePadding, + _iconSize = iconSize, + super(configId: configId) { + _backgroundColor = Colors.white; + _leadIconBuilder = () => Image.asset( + BrnAsset.iconBackBlack, + package: BrnStrings.flutterPackageName, + width: BrnAppBarTheme.iconSize, + height: BrnAppBarTheme.iconSize, + fit: BoxFit.fitHeight, + ); + _titleStyle = BrnTextStyle( + fontSize: BrnAppBarTheme.titleFontSize, + fontWeight: FontWeight.w600, + color: BrnAppBarTheme.lightTextColor, + ); + _actionsStyle = BrnTextStyle( + color: BrnAppBarTheme.lightTextColor, + fontSize: BrnAppBarTheme.actionFontSize, + fontWeight: FontWeight.w600, + ); + _systemUiOverlayStyle = SystemUiOverlayStyle.dark; } - /// AppBar的背景色 - Color backgroundColor; + /// AppBar 的背景色 + Color? _backgroundColor; + + Color get backgroundColor => + _backgroundColor ?? + BrnDefaultConfigUtils.defaultAppBarConfig.backgroundColor; + + /// AppBar 的高度 + double? _appBarHeight; - /// AppBar的高度 - double appBarHeight; + double get appBarHeight => + _appBarHeight ?? BrnDefaultConfigUtils.defaultAppBarConfig.appBarHeight; /// 返回按钮的child widget,一般为Image - BrnWidgetBuilder leadIconBuilder; + BrnWidgetBuilder? _leadIconBuilder; + + BrnWidgetBuilder get leadIconBuilder => + _leadIconBuilder ?? + BrnDefaultConfigUtils.defaultAppBarConfig.leadIconBuilder; + + /// 标题样式,仅当直接 title 设置为 String 生效 + /// + /// **注意**:`fontSize` 必须传大小,否则报错 + BrnTextStyle? _titleStyle; + + BrnTextStyle get titleStyle => + _titleStyle ?? BrnDefaultConfigUtils.defaultAppBarConfig.titleStyle; - /// 标题样式,仅当直接title设置为String生效,[注意]:`fontSize`必须传大小,否则报错 - BrnTextStyle titleStyle; + /// 右侧文字按钮样式,仅当直接actions里面元素为BrnTextAction类型生效 + /// + /// **注意**:`fontSize` 必须传大小,否则报错 + /// + /// BrnTextStyle( + /// color: AppBarBrightness(brightness).textColor, + /// fontSize: BrnAppBarTheme.actionFontSize, + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _actionsStyle; - /// 右侧文字按钮样式,仅当直接actions里面元素为BrnTextAction类型生效[注意]:`fontSize`必须传大小,否则报错 - /// default value is TextStyle(color: AppBarBrightness(brightness).textColor,fontSize: BrnAppBarTheme.actionFontSize,fontWeight: FontWeight.w600) - BrnTextStyle actionsStyle; + BrnTextStyle get actionsStyle => + _actionsStyle ?? BrnDefaultConfigUtils.defaultAppBarConfig.actionsStyle; - /// AppBar title的最大字符数 8 - int titleMaxLength; + /// AppBar title 的最大字符数 8 + int? _titleMaxLength; + + int get titleMaxLength => + _titleMaxLength ?? + BrnDefaultConfigUtils.defaultAppBarConfig.titleMaxLength; /// 左右边距 - double leftAndRightPadding; + double? _leftAndRightPadding; + + double get leftAndRightPadding => + _leftAndRightPadding ?? + BrnDefaultConfigUtils.defaultAppBarConfig.leftAndRightPadding; /// 元素间间距 - double itemSpacing; + double? _itemSpacing; + + double get itemSpacing => + _itemSpacing ?? BrnDefaultConfigUtils.defaultAppBarConfig.itemSpacing; /// title的padding - EdgeInsets titlePadding; + EdgeInsets? _titlePadding; + + EdgeInsets get titlePadding => + _titlePadding ?? BrnDefaultConfigUtils.defaultAppBarConfig.titlePadding; /// leadIcon 宽高,需要相同 - /// default value is 20 - double iconSize; + /// 默认为 20 + double? _iconSize; - ///[AppBar]中flexibleSpace - Widget flexibleSpace; + double get iconSize => + _iconSize ?? BrnDefaultConfigUtils.defaultAppBarConfig.iconSize; /// statusBar 样式 - /// default value is SystemUiOverlayStyle.dark - SystemUiOverlayStyle systemUiOverlayStyle; + /// 默认为 [SystemUiOverlayStyle.dark] + SystemUiOverlayStyle? _systemUiOverlayStyle; + + SystemUiOverlayStyle get systemUiOverlayStyle => + _systemUiOverlayStyle ?? + BrnDefaultConfigUtils.defaultAppBarConfig.systemUiOverlayStyle; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局组件配置 BrnAppBarConfig appbarConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .appBarConfig; - this.backgroundColor ??= appbarConfig?.backgroundColor; - this.appBarHeight ??= appbarConfig?.appBarHeight; - this.leadIconBuilder ??= appbarConfig?.leadIconBuilder; - this.titleStyle = appbarConfig.titleStyle.merge(titleStyle); - this.actionsStyle = appbarConfig.actionsStyle.merge(actionsStyle); - this.titleMaxLength ??= appbarConfig?.titleMaxLength; - this.leftAndRightPadding ??= appbarConfig?.leftAndRightPadding; - this.itemSpacing ??= appbarConfig?.itemSpacing; - this.titlePadding ??= appbarConfig?.titlePadding; - this.iconSize ??= appbarConfig?.iconSize; - this.flexibleSpace ??= appbarConfig?.flexibleSpace; - this.systemUiOverlayStyle ??= appbarConfig?.systemUiOverlayStyle; + _backgroundColor ??= appbarConfig._backgroundColor; + _appBarHeight ??= appbarConfig._appBarHeight; + _leadIconBuilder ??= appbarConfig._leadIconBuilder; + _titleStyle = appbarConfig.titleStyle.merge(_titleStyle); + _actionsStyle = appbarConfig.actionsStyle.merge(_actionsStyle); + _titleMaxLength ??= appbarConfig._titleMaxLength; + _leftAndRightPadding ??= appbarConfig._leftAndRightPadding; + _itemSpacing ??= appbarConfig._itemSpacing; + _titlePadding ??= appbarConfig._titlePadding; + _iconSize ??= appbarConfig._iconSize; + _systemUiOverlayStyle ??= appbarConfig._systemUiOverlayStyle; } BrnAppBarConfig copyWith({ - Color backgroundColor, - double appBarHeight, - BrnWidgetBuilder leadIconBuilder, - BrnTextStyle titleStyle, - BrnTextStyle actionsStyle, - int titleMaxLength, - double leftAndRightPadding, - double itemSpacing, - EdgeInsets titlePading, - double iconSize, - Widget flexibleSpace, - SystemUiOverlayStyle systemUiOverlayStyle, + Color? backgroundColor, + double? appBarHeight, + BrnWidgetBuilder? leadIconBuilder, + BrnTextStyle? titleStyle, + BrnTextStyle? actionsStyle, + int? titleMaxLength, + double? leftAndRightPadding, + double? itemSpacing, + EdgeInsets? titlePadding, + double? iconSize, + SystemUiOverlayStyle? systemUiOverlayStyle, }) { return BrnAppBarConfig( - backgroundColor: backgroundColor ?? this.backgroundColor, - appBarHeight: appBarHeight ?? this.appBarHeight, - leadIconBuilder: leadIconBuilder ?? this.leadIconBuilder, - titleStyle: titleStyle ?? this.titleStyle, - actionsStyle: actionsStyle ?? this.actionsStyle, - titleMaxLength: titleMaxLength ?? this.titleMaxLength, - leftAndRightPadding: leftAndRightPadding ?? this.leftAndRightPadding, - itemSpacing: itemSpacing ?? this.itemSpacing, - titlePadding: titlePading ?? this.titlePadding, - iconSize: iconSize ?? this.iconSize, - flexibleSpace: flexibleSpace ?? this.flexibleSpace, - systemUiOverlayStyle: - systemUiOverlayStyle ?? this.systemUiOverlayStyle); + backgroundColor: backgroundColor ?? _backgroundColor, + appBarHeight: appBarHeight ?? _appBarHeight, + leadIconBuilder: leadIconBuilder ?? _leadIconBuilder, + titleStyle: titleStyle ?? _titleStyle, + actionsStyle: actionsStyle ?? _actionsStyle, + titleMaxLength: titleMaxLength ?? _titleMaxLength, + leftAndRightPadding: leftAndRightPadding ?? _leftAndRightPadding, + itemSpacing: itemSpacing ?? _itemSpacing, + titlePadding: titlePadding ?? _titlePadding, + iconSize: iconSize ?? _iconSize, + systemUiOverlayStyle: systemUiOverlayStyle ?? _systemUiOverlayStyle, + ); } - BrnAppBarConfig merge(BrnAppBarConfig other) { + BrnAppBarConfig merge(BrnAppBarConfig? other) { if (other == null) return this; return copyWith( - backgroundColor: other.backgroundColor, - appBarHeight: other.appBarHeight, - leadIconBuilder: other.leadIconBuilder, - titleStyle: - this.titleStyle?.merge(other.titleStyle) ?? other.titleStyle, - actionsStyle: - this.actionsStyle?.merge(other.actionsStyle) ?? other.actionsStyle, - titleMaxLength: other.titleMaxLength, - leftAndRightPadding: other.leftAndRightPadding, - itemSpacing: other.itemSpacing, - titlePading: other.titlePadding, - iconSize: other.iconSize, - flexibleSpace: other.flexibleSpace, - systemUiOverlayStyle: other.systemUiOverlayStyle); + backgroundColor: other._backgroundColor, + appBarHeight: other._appBarHeight, + leadIconBuilder: other._leadIconBuilder, + titleStyle: titleStyle.merge(other._titleStyle), + actionsStyle: actionsStyle.merge(other._actionsStyle), + titleMaxLength: other._titleMaxLength, + leftAndRightPadding: other._leftAndRightPadding, + itemSpacing: other._itemSpacing, + titlePadding: other._titlePadding, + iconSize: other._iconSize, + systemUiOverlayStyle: other._systemUiOverlayStyle, + ); } } diff --git a/lib/src/theme/configs/brn_button_config.dart b/lib/src/theme/configs/brn_button_config.dart index b57dc912..d6e29919 100644 --- a/lib/src/theme/configs/brn_button_config.dart +++ b/lib/src/theme/configs/brn_button_config.dart @@ -1,79 +1,119 @@ -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/theme/configs/brn_common_config.dart'; /// 按钮基础配置 class BrnButtonConfig extends BrnBaseConfig { - ///遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultButtonConfig] + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultButtonConfig] BrnButtonConfig({ - this.bigButtonRadius, - this.bigButtonHeight, - this.bigButtonFontSize, - this.smallButtonRadius, - this.smallButtonHeight, - this.smallButtonFontSize, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId); + double? bigButtonRadius, + double? bigButtonHeight, + double? bigButtonFontSize, + double? smallButtonRadius, + double? smallButtonHeight, + double? smallButtonFontSize, + String configId = GLOBAL_CONFIG_ID, + }) : _bigButtonRadius = bigButtonRadius, + _bigButtonHeight = bigButtonHeight, + _bigButtonFontSize = bigButtonFontSize, + _smallButtonRadius = smallButtonRadius, + _smallButtonHeight = smallButtonHeight, + _smallButtonFontSize = smallButtonFontSize, + super(configId: configId); - /// default value is 6 - double bigButtonRadius; + /// 默认为 6 + double? _bigButtonRadius; - /// default value is 48 - double bigButtonHeight; + double get bigButtonRadius => + _bigButtonRadius ?? + BrnDefaultConfigUtils.defaultButtonConfig.bigButtonRadius; - /// default value is 16 - double bigButtonFontSize; + /// 默认为 48 + double? _bigButtonHeight; - /// default value is 4 - double smallButtonRadius; + double get bigButtonHeight => + _bigButtonHeight ?? + BrnDefaultConfigUtils.defaultButtonConfig.bigButtonHeight; - /// default value is 32 - double smallButtonHeight; + /// 默认为 16 + double? _bigButtonFontSize; - /// default value is 14 - double smallButtonFontSize; + double get bigButtonFontSize => + _bigButtonFontSize ?? + BrnDefaultConfigUtils.defaultButtonConfig.bigButtonFontSize; + + /// 默认为 4 + double? _smallButtonRadius; + + double get smallButtonRadius => + _smallButtonRadius ?? + BrnDefaultConfigUtils.defaultButtonConfig.smallButtonRadius; + + /// 默认为 32 + double? _smallButtonHeight; + + double get smallButtonHeight => + _smallButtonHeight ?? + BrnDefaultConfigUtils.defaultButtonConfig.smallButtonHeight; + + /// 默认为 14 + double? _smallButtonFontSize; + + double get smallButtonFontSize => + _smallButtonFontSize ?? + BrnDefaultConfigUtils.defaultButtonConfig.smallButtonFontSize; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); BrnButtonConfig userConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .buttonConfig; - this.bigButtonRadius ??= userConfig?.bigButtonRadius; - this.bigButtonHeight ??= userConfig?.bigButtonHeight; - this.bigButtonFontSize ??= userConfig?.bigButtonFontSize; - this.smallButtonRadius ??= userConfig?.smallButtonRadius; - this.smallButtonHeight ??= userConfig?.smallButtonHeight; - this.smallButtonFontSize ??= userConfig?.smallButtonFontSize; + _bigButtonRadius ??= userConfig._bigButtonRadius; + _bigButtonHeight ??= userConfig._bigButtonHeight; + _bigButtonFontSize ??= userConfig._bigButtonFontSize; + _smallButtonRadius ??= userConfig._smallButtonRadius; + _smallButtonHeight ??= userConfig._smallButtonHeight; + _smallButtonFontSize ??= userConfig._smallButtonFontSize; } - BrnButtonConfig copyWith( - {double bigButtonRadius, - double bigButtonHeight, - double bigButtonFontSize, - double smallButtonRadius, - double smallButtonHeight, - double smallButtonFontSize}) { + BrnButtonConfig copyWith({ + double? bigButtonRadius, + double? bigButtonHeight, + double? bigButtonFontSize, + double? smallButtonRadius, + double? smallButtonHeight, + double? smallButtonFontSize, + }) { return BrnButtonConfig( - bigButtonRadius: bigButtonRadius ?? this.bigButtonRadius, - bigButtonHeight: bigButtonHeight ?? this.bigButtonHeight, - bigButtonFontSize: bigButtonFontSize ?? this.bigButtonFontSize, - smallButtonRadius: smallButtonRadius ?? this.smallButtonRadius, - smallButtonHeight: smallButtonHeight ?? this.smallButtonHeight, - smallButtonFontSize: smallButtonFontSize ?? this.smallButtonFontSize, + bigButtonRadius: bigButtonRadius ?? _bigButtonRadius, + bigButtonHeight: bigButtonHeight ?? _bigButtonHeight, + bigButtonFontSize: bigButtonFontSize ?? _bigButtonFontSize, + smallButtonRadius: smallButtonRadius ?? _smallButtonRadius, + smallButtonHeight: smallButtonHeight ?? _smallButtonHeight, + smallButtonFontSize: smallButtonFontSize ?? _smallButtonFontSize, ); } - BrnButtonConfig merge(BrnButtonConfig other) { + BrnButtonConfig merge(BrnButtonConfig? other) { if (other == null) return this; return copyWith( - bigButtonRadius: other.bigButtonRadius, - bigButtonHeight: other.bigButtonHeight, - bigButtonFontSize: other.bigButtonFontSize, - smallButtonRadius: other.smallButtonRadius, - smallButtonHeight: other.smallButtonHeight, - smallButtonFontSize: other.smallButtonFontSize); + bigButtonRadius: other._bigButtonRadius, + bigButtonHeight: other._bigButtonHeight, + bigButtonFontSize: other._bigButtonFontSize, + smallButtonRadius: other._smallButtonRadius, + smallButtonHeight: other._smallButtonHeight, + smallButtonFontSize: other._smallButtonFontSize, + ); } } diff --git a/lib/src/theme/configs/brn_card_title_config.dart b/lib/src/theme/configs/brn_card_title_config.dart index 84a32fd7..95ea6a70 100644 --- a/lib/src/theme/configs/brn_card_title_config.dart +++ b/lib/src/theme/configs/brn_card_title_config.dart @@ -1,3 +1,4 @@ +import 'package:bruno/bruno.dart'; import 'package:bruno/src/theme/base/brn_base_config.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; @@ -6,143 +7,206 @@ import 'package:flutter/material.dart'; /// 卡片标题 配置类 class BrnCardTitleConfig extends BrnBaseConfig { + BrnCardTitleConfig({ + BrnTextStyle? titleWithHeightTextStyle, + BrnTextStyle? detailTextStyle, + BrnTextStyle? accessoryTextStyle, + EdgeInsets? cardTitlePadding, + BrnTextStyle? titleTextStyle, + BrnTextStyle? subtitleTextStyle, + PlaceholderAlignment? alignment, + Color? cardBackgroundColor, + String configId = GLOBAL_CONFIG_ID, + }) : _titleWithHeightTextStyle = titleWithHeightTextStyle, + _detailTextStyle = detailTextStyle, + _accessoryTextStyle = accessoryTextStyle, + _cardTitlePadding = cardTitlePadding, + _titleTextStyle = titleTextStyle, + _subtitleTextStyle = subtitleTextStyle, + _alignment = alignment, + _cardBackgroundColor = cardBackgroundColor, + super(configId: configId); + /// 标题外边距间距 - /// EdgeInsets.only(top: [BrnCommonConfig.vSpacingXl],bottom: [BrnCommonConfig.vSpacingMd]) - EdgeInsets cardTitlePadding; + /// + /// EdgeInsets.only( + /// top: [BrnCommonConfig.vSpacingXl], + /// bottom: [BrnCommonConfig.vSpacingMd], + /// ) + EdgeInsets? _cardTitlePadding; + + EdgeInsets get cardTitlePadding => + _cardTitlePadding ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.cardTitlePadding; /// 标题文本样式 - /// BrnTextStyle(fontSize: [BrnCommonConfig.fontSizeHead],height: 25 / 18,fontWeight: FontWeight.w600,color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle titleWithHeightTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// fontWeight: FontWeight.w600, + /// height: 25 / 18, + /// ) + BrnTextStyle? _titleWithHeightTextStyle; + + BrnTextStyle get titleWithHeightTextStyle => + _titleWithHeightTextStyle ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.titleWithHeightTextStyle; /// 标题文本样式 - /// BrnTextStyle(fontSize: [BrnCommonConfig.fontSizeHead],fontWeight: FontWeight.w600,color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle titleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _titleTextStyle; + + BrnTextStyle get titleTextStyle => + _titleTextStyle ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.titleTextStyle; /// 标题右边的副标题文本样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase],color: [BrnCommonConfig.colorTextSecondary]) - BrnTextStyle subtitleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _subtitleTextStyle; + + BrnTextStyle get subtitleTextStyle => + _subtitleTextStyle ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.subtitleTextStyle; /// 详情文本样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase], color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle detailTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _detailTextStyle; + + BrnTextStyle get detailTextStyle => + _detailTextStyle ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.detailTextStyle; /// 辅助文本样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase],color: [BrnCommonConfig.colorTextSecondary],) - BrnTextStyle accessoryTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _accessoryTextStyle; + + BrnTextStyle get accessoryTextStyle => + _accessoryTextStyle ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.accessoryTextStyle; /// 对齐方式 - /// PlaceholderAlignment.middle - PlaceholderAlignment alignment; + /// 默认为 [PlaceholderAlignment.middle] + PlaceholderAlignment? _alignment; + + PlaceholderAlignment get alignment => + _alignment ?? BrnDefaultConfigUtils.defaultCardTitleConfig.alignment; /// 卡片背景 - /// [BrnCommonConfig.fillBase] - Color cardBackgroundColor; - - BrnCardTitleConfig( - {this.titleWithHeightTextStyle, - this.detailTextStyle, - this.accessoryTextStyle, - this.cardTitlePadding, - this.titleTextStyle, - this.subtitleTextStyle, - this.alignment, - this.cardBackgroundColor, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// 默认为 [BrnCommonConfig.fillBase] + Color? _cardBackgroundColor; + + Color get cardBackgroundColor => + _cardBackgroundColor ?? + BrnDefaultConfigUtils.defaultCardTitleConfig.cardBackgroundColor; /// cardTitleConfig 获取逻辑详见 [BrnThemeConfigurator.getConfig] 方法 @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); BrnCardTitleConfig cardTitleConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .cardTitleConfig; - this.cardBackgroundColor ??= commonConfig.fillBase; - - if (this.cardTitlePadding == null) { - this.cardTitlePadding = EdgeInsets.only( - left: cardTitleConfig.cardTitlePadding.left, - top: commonConfig.vSpacingXl, - right: cardTitleConfig.cardTitlePadding.right, - bottom: commonConfig.vSpacingMd); - } - - this.titleWithHeightTextStyle = cardTitleConfig.titleWithHeightTextStyle - .merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeHead) - .merge(this.titleWithHeightTextStyle)); - - this.titleTextStyle = cardTitleConfig.titleTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeHead, - ).merge(this.titleTextStyle)); - - this.subtitleTextStyle = - cardTitleConfig.subtitleTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase, - ).merge(this.subtitleTextStyle)); - - this.accessoryTextStyle = - cardTitleConfig.accessoryTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeHead, - ).merge(this.accessoryTextStyle)); - - this.detailTextStyle = cardTitleConfig.detailTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase, - ).merge(this.detailTextStyle)); - - this.alignment ??= cardTitleConfig.alignment; + _cardBackgroundColor ??= commonConfig.fillBase; + _cardTitlePadding ??= EdgeInsets.only( + left: cardTitleConfig.cardTitlePadding.left, + top: commonConfig.vSpacingXl, + right: cardTitleConfig.cardTitlePadding.right, + bottom: commonConfig.vSpacingMd, + ); + _titleWithHeightTextStyle = cardTitleConfig.titleWithHeightTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeHead, + ).merge(_titleWithHeightTextStyle), + ); + _titleTextStyle = cardTitleConfig.titleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeHead, + ).merge(_titleTextStyle), + ); + _subtitleTextStyle = cardTitleConfig.subtitleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_subtitleTextStyle), + ); + _accessoryTextStyle = cardTitleConfig.accessoryTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeHead, + ).merge(_accessoryTextStyle), + ); + _detailTextStyle = cardTitleConfig.detailTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_detailTextStyle), + ); + _alignment ??= cardTitleConfig._alignment; } - BrnCardTitleConfig copyWith( - {EdgeInsets cardTitlePadding, - BrnTextStyle titleWithHeightTextStyle, - BrnTextStyle titleTextStyle, - BrnTextStyle subtitleTextStyle, - BrnTextStyle detailTextStyle, - BrnTextStyle accessoryTextStyle, - PlaceholderAlignment alignment, - Color cardBackgroundColor}) { + BrnCardTitleConfig copyWith({ + EdgeInsets? cardTitlePadding, + BrnTextStyle? titleWithHeightTextStyle, + BrnTextStyle? titleTextStyle, + BrnTextStyle? subtitleTextStyle, + BrnTextStyle? detailTextStyle, + BrnTextStyle? accessoryTextStyle, + PlaceholderAlignment? alignment, + Color? cardBackgroundColor, + }) { return BrnCardTitleConfig( - cardTitlePadding: cardTitlePadding ?? this.cardTitlePadding, - titleWithHeightTextStyle: - titleWithHeightTextStyle ?? this.titleWithHeightTextStyle, - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - subtitleTextStyle: subtitleTextStyle ?? this.subtitleTextStyle, - detailTextStyle: detailTextStyle ?? this.detailTextStyle, - accessoryTextStyle: accessoryTextStyle ?? this.accessoryTextStyle, - alignment: alignment ?? this.alignment, - cardBackgroundColor: cardBackgroundColor ?? this.cardBackgroundColor); + cardTitlePadding: cardTitlePadding ?? _cardTitlePadding, + titleWithHeightTextStyle: + titleWithHeightTextStyle ?? _titleWithHeightTextStyle, + titleTextStyle: titleTextStyle ?? _titleTextStyle, + subtitleTextStyle: subtitleTextStyle ?? _subtitleTextStyle, + detailTextStyle: detailTextStyle ?? _detailTextStyle, + accessoryTextStyle: accessoryTextStyle ?? _accessoryTextStyle, + alignment: alignment ?? _alignment, + cardBackgroundColor: cardBackgroundColor ?? _cardBackgroundColor, + ); } - BrnCardTitleConfig merge(BrnCardTitleConfig other) { + BrnCardTitleConfig merge(BrnCardTitleConfig? other) { if (other == null) return this; return copyWith( - cardTitlePadding: other.cardTitlePadding, - titleWithHeightTextStyle: this - .titleWithHeightTextStyle - ?.merge(other.titleWithHeightTextStyle) ?? - other.titleWithHeightTextStyle, - titleTextStyle: this.titleTextStyle?.merge(other.titleTextStyle) ?? - other.titleTextStyle, - subtitleTextStyle: - this.subtitleTextStyle?.merge(other.subtitleTextStyle) ?? - other.subtitleTextStyle, - detailTextStyle: this.detailTextStyle?.merge(other.detailTextStyle) ?? - other.detailTextStyle, - accessoryTextStyle: - this.accessoryTextStyle?.merge(other.accessoryTextStyle) ?? - other.accessoryTextStyle, - alignment: other.alignment, - cardBackgroundColor: other.cardBackgroundColor, + cardTitlePadding: other._cardTitlePadding, + titleWithHeightTextStyle: + titleWithHeightTextStyle.merge(other._titleWithHeightTextStyle), + titleTextStyle: titleTextStyle.merge(other._titleTextStyle), + subtitleTextStyle: subtitleTextStyle.merge(other._subtitleTextStyle), + detailTextStyle: detailTextStyle.merge(other._detailTextStyle), + accessoryTextStyle: accessoryTextStyle.merge(other._accessoryTextStyle), + alignment: other._alignment, + cardBackgroundColor: other._cardBackgroundColor, ); } } diff --git a/lib/src/theme/configs/brn_common_config.dart b/lib/src/theme/configs/brn_common_config.dart index 5464eac7..fa652fff 100644 --- a/lib/src/theme/configs/brn_common_config.dart +++ b/lib/src/theme/configs/brn_common_config.dart @@ -1,381 +1,660 @@ -import 'dart:ui'; - import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:flutter/painting.dart'; -/// 描述: 全局配置 -/// 配置属性 色值、字体大小、间距、圆角 - +/// 描述: 全局配置 +/// 配置属性:色值、字体大小、间距、圆角 class BrnCommonConfig extends BrnBaseConfig { - static const double hd = 1; // 基本单位 + BrnCommonConfig({ + Color? brandPrimary, + Color? brandPrimaryTap, + Color? brandSuccess, + Color? brandWarning, + Color? brandError, + Color? brandImportant, + Color? brandImportantValue, + Color? brandAuxiliary, + Color? colorTextBase, + Color? colorTextImportant, + Color? colorTextBaseInverse, + Color? colorTextSecondary, + Color? colorTextDisabled, + Color? colorTextHint, + Color? colorLink, + Color? fillBase, + Color? fillBody, + Color? fillMask, + Color? borderColorBase, + Color? dividerColorBase, + double? fontSizeBebas, + double? fontSizeHeadLg, + double? fontSizeBase, + double? fontSizeHead, + double? fontSizeSubHead, + double? fontSizeCaption, + double? fontSizeCaptionSm, + double? radiusXs, + double? radiusSm, + double? radiusMd, + double? radiusLg, + double? borderWidthSm, + double? borderWidthMd, + double? borderWidthLg, + double? hSpacingXs, + double? hSpacingSm, + double? hSpacingMd, + double? hSpacingLg, + double? hSpacingXl, + double? hSpacingXxl, + double? vSpacingXs, + double? vSpacingSm, + double? vSpacingMd, + double? vSpacingLg, + double? vSpacingXl, + double? vSpacingXxl, + double? iconSizeXxs, + double? iconSizeXs, + double? iconSizeSm, + double? iconSizeMd, + double? iconSizeLg, + String configId = GLOBAL_CONFIG_ID, + }) : _brandPrimary = brandPrimary, + _brandPrimaryTap = brandPrimaryTap, + _brandSuccess = brandSuccess, + _brandWarning = brandWarning, + _brandError = brandError, + _brandImportant = brandImportant, + _brandImportantValue = brandImportantValue, + _brandAuxiliary = brandAuxiliary, + _colorTextBase = colorTextBase, + _colorTextImportant = colorTextImportant, + _colorTextBaseInverse = colorTextBaseInverse, + _colorTextSecondary = colorTextSecondary, + _colorTextDisabled = colorTextDisabled, + _colorTextHint = colorTextHint, + _colorLink = colorLink, + _fillBase = fillBase, + _fillBody = fillBody, + _fillMask = fillMask, + _borderColorBase = borderColorBase, + _dividerColorBase = dividerColorBase, + _fontSizeBebas = fontSizeBebas, + _fontSizeHeadLg = fontSizeHeadLg, + _fontSizeBase = fontSizeBase, + _fontSizeHead = fontSizeHead, + _fontSizeSubHead = fontSizeSubHead, + _fontSizeCaption = fontSizeCaption, + _fontSizeCaptionSm = fontSizeCaptionSm, + _radiusXs = radiusXs, + _radiusSm = radiusSm, + _radiusMd = radiusMd, + _radiusLg = radiusLg, + _borderWidthSm = borderWidthSm, + _borderWidthMd = borderWidthMd, + _borderWidthLg = borderWidthLg, + _hSpacingXs = hSpacingXs, + _hSpacingSm = hSpacingSm, + _hSpacingMd = hSpacingMd, + _hSpacingLg = hSpacingLg, + _hSpacingXl = hSpacingXl, + _hSpacingXxl = hSpacingXxl, + _vSpacingXs = vSpacingXs, + _vSpacingSm = vSpacingSm, + _vSpacingMd = vSpacingMd, + _vSpacingLg = vSpacingLg, + _vSpacingXl = vSpacingXl, + _vSpacingXxl = vSpacingXxl, + _iconSizeXxs = iconSizeXxs, + _iconSizeXs = iconSizeXs, + _iconSizeSm = iconSizeSm, + _iconSizeMd = iconSizeMd, + _iconSizeLg = iconSizeLg, + super(configId: configId); - ///*******************色彩********************* + BrnCommonConfig.autoFlatConfig({ + Color? brandPrimary, + Color? brandPrimaryTap, + Color? brandSuccess, + Color? brandWarning, + Color? brandError, + Color? brandImportant, + Color? brandImportantValue, + Color? brandAuxiliary, + Color? colorTextBase, + Color? colorTextImportant, + Color? colorTextBaseInverse, + Color? colorTextSecondary, + Color? colorTextDisabled, + Color? colorTextHint, + Color? colorLink, + Color? fillBase, + Color? fillBody, + Color? fillMask, + Color? borderColorBase, + Color? dividerColorBase, + double? fontSizeBebas, + double? fontSizeHeadLg, + double? fontSizeBase, + double? fontSizeHead, + double? fontSizeSubHead, + double? fontSizeCaption, + double? fontSizeCaptionSm, + double? radiusXs, + double? radiusSm, + double? radiusMd, + double? radiusLg, + double? borderWidthSm, + double? borderWidthMd, + double? borderWidthLg, + double? hSpacingXs, + double? hSpacingSm, + double? hSpacingMd, + double? hSpacingLg, + double? hSpacingXl, + double? hSpacingXxl, + double? vSpacingXs, + double? vSpacingSm, + double? vSpacingMd, + double? vSpacingLg, + double? vSpacingXl, + double? vSpacingXxl, + double? iconSizeXxs, + double? iconSizeXs, + double? iconSizeSm, + double? iconSizeMd, + double? iconSizeLg, + String configId = GLOBAL_CONFIG_ID, + }) : _brandPrimary = brandPrimary, + _brandPrimaryTap = brandPrimaryTap, + _brandSuccess = brandSuccess, + _brandWarning = brandWarning, + _brandError = brandError, + _brandImportant = brandImportant, + _brandImportantValue = brandImportantValue, + _brandAuxiliary = brandAuxiliary, + _colorTextBase = colorTextBase, + _colorTextImportant = colorTextImportant, + _colorTextBaseInverse = colorTextBaseInverse, + _colorTextSecondary = colorTextSecondary, + _colorTextDisabled = colorTextDisabled, + _colorTextHint = colorTextHint, + _colorLink = colorLink, + _fillBase = fillBase, + _fillBody = fillBody, + _fillMask = fillMask, + _borderColorBase = borderColorBase, + _dividerColorBase = dividerColorBase, + _fontSizeBebas = fontSizeBebas, + _fontSizeHeadLg = fontSizeHeadLg, + _fontSizeBase = fontSizeBase, + _fontSizeHead = fontSizeHead, + _fontSizeSubHead = fontSizeSubHead, + _fontSizeCaption = fontSizeCaption, + _fontSizeCaptionSm = fontSizeCaptionSm, + _radiusXs = radiusXs, + _radiusSm = radiusSm, + _radiusMd = radiusMd, + _radiusLg = radiusLg, + _borderWidthSm = borderWidthSm, + _borderWidthMd = borderWidthMd, + _borderWidthLg = borderWidthLg, + _hSpacingXs = hSpacingXs, + _hSpacingSm = hSpacingSm, + _hSpacingMd = hSpacingMd, + _hSpacingLg = hSpacingLg, + _hSpacingXl = hSpacingXl, + _hSpacingXxl = hSpacingXxl, + _vSpacingXs = vSpacingXs, + _vSpacingSm = vSpacingSm, + _vSpacingMd = vSpacingMd, + _vSpacingLg = vSpacingLg, + _vSpacingXl = vSpacingXl, + _vSpacingXxl = vSpacingXxl, + _iconSizeXxs = iconSizeXxs, + _iconSizeXs = iconSizeXs, + _iconSizeSm = iconSizeSm, + _iconSizeMd = iconSizeMd, + _iconSizeLg = iconSizeLg, + super(configId: configId, autoFlatConfig: true); + + /// 基本单位 + static const double hd = 1; + +/////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////// 色彩 ///////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// + +//////////////////////////////////// 品牌色 ///////////////////////////////////// - /// 品牌色相关 - /// /// 品牌色 - /// default value is Color(0xFF0984F9) - Color brandPrimary; + /// 默认为 Color(0xFF0984F9) + Color? _brandPrimary; /// 主题色按下效果 - /// default value is Color(0x190984F9) - Color brandPrimaryTap; + /// 默认为 Color(0x190984F9) + Color? _brandPrimaryTap; /// 成功色 - /// default value is Color(0xFF00AE66) - Color brandSuccess; + /// 默认为 Color(0xFF00AE66) + Color? _brandSuccess; /// 警告色 - /// default value is Color(0xFFFAAD14) - Color brandWarning; + /// 默认为 Color(0xFFFAAD14) + Color? _brandWarning; /// 失败色 - /// default value is Color(0xFFFA3F3F) - Color brandError; + /// 默认为 Color(0xFFFA3F3F) + Color? _brandError; /// 重要-多用于红点色 - /// default value is Color(0xFFFA3F3F) - Color brandImportant; + /// 默认为 Color(0xFFFA3F3F) + Color? _brandImportant; /// 重要数值色 - /// default value is Color(0xFFFF5722) - Color brandImportantValue; + /// 默认为 Color(0xFFFF5722) + Color? _brandImportantValue; /// 辅助色 - /// default value is Color(0xFF44C2FF) - Color brandAuxiliary; + /// 默认为 Color(0xFF44C2FF) + Color? _brandAuxiliary; /// 文本色相关 /// /// 基础文字纯黑色 - /// default value is Color(0xFF222222) - Color colorTextBase; + /// 默认为 Color(0xFF222222) + Color? _colorTextBase; /// 基础文字重要色 - /// default value is Color(0xFF666666) - Color colorTextImportant; + /// 默认为 Color(0xFF666666) + Color? _colorTextImportant; /// 基础文字-反色 - /// default value is Color(0xFFFFFFFF) - Color colorTextBaseInverse; + /// 默认为 Color(0xFFFFFFFF) + Color? _colorTextBaseInverse; /// 辅助文字色 - /// default value is Color(0xFF999999) - Color colorTextSecondary; + /// 默认为 Color(0xFF999999) + Color? _colorTextSecondary; /// 失效或不可更改文字色 - /// default value is Color(0xFF999999) - Color colorTextDisabled; + /// 默认为 Color(0xFF999999) + Color? _colorTextDisabled; /// 文本框提示暗文文字色 - /// default value is Color(0xFFCCCCCC) - Color colorTextHint; + /// 默认为 Color(0xFFCCCCCC) + Color? _colorTextHint; /// 跟随主题色[brandPrimary] - Color colorLink; + Color? _colorLink; /// 背景色相关 /// /// 组件背景色 - /// default value is Color(0xFFFFFFFF) - Color fillBase; + /// 默认为 Color(0xFFFFFFFF) + Color? _fillBase; /// 页面背景色 - /// default value is Color(0xFFF8F8F8) - Color fillBody; + /// 默认为 Color(0xFFF8F8F8) + Color? _fillBody; /// 遮罩背景 - /// default value is Color(0x99000000) - Color fillMask; + /// 默认为 Color(0x99000000) + Color? _fillMask; /// 边框色 - /// default value is Color(0xFFF0F0F0) - Color borderColorBase; + /// 默认为 Color(0xFFF0F0F0) + Color? _borderColorBase; /// 分割线色 - /// default value is Color(0xFFF0F0F0) - Color dividerColorBase; + /// 默认为 Color(0xFFF0F0F0) + Color? _dividerColorBase; + +/////////////////////////////////////////////////////////////////////////////// +///////////////////////////////////// 尺寸 ///////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// /// 文本字号 /// /// 特殊数据展示,Bebas 数字字体,用于强吸引 /// default value is 28 - double fontSizeBebas; + double? _fontSizeBebas; /// 标题字体 /// 名称/页面大标题 - /// default value is 22 - double fontSizeHeadLg; + /// 默认为 22 + double? _fontSizeHeadLg; /// 标题字体 /// 内容模块标题/一级标题 - /// default value is 18 - double fontSizeHead; + /// 默认为 18 + double? _fontSizeHead; /// 子标题字体 /// 标题/录入文字/大按钮文字/二级标题 - /// default value is 16 - double fontSizeSubHead; + /// 默认为 16 + double? _fontSizeSubHead; /// 基础字体 /// 内容副文本/普通说明文字 - /// default value is 14 - double fontSizeBase; + /// 默认为 14 + double? _fontSizeBase; /// 辅助字体-普通 - /// default value is 12 - double fontSizeCaption; + /// 默认为 12 + double? _fontSizeCaption; ///辅助字体-小 - /// default value is 11 - double fontSizeCaptionSm; + /// 默认为 11 + double? _fontSizeCaptionSm; /// 圆角尺寸 - /// default value is 2.0 - double radiusXs; + /// 默认为 2.0 + double? _radiusXs; - /// default value is 4.0 - double radiusSm; + /// 默认为 4.0 + double? _radiusSm; - /// default value is 6.0 - double radiusMd; + /// 默认为 6.0 + double? _radiusMd; - /// default value is 8.0 - double radiusLg; + /// 默认为 8.0 + double? _radiusLg; /// 边框尺寸 /// - /// default 0.5 - double borderWidthSm; + /// 默认为 0.5 + double? _borderWidthSm; - /// default 1 - double borderWidthMd; + /// 默认为 1 + double? _borderWidthMd; - /// default 2 - double borderWidthLg; + /// 默认为 2 + double? _borderWidthLg; /// 水平间距 - /// - /// default 8 - double hSpacingXs; + /// 默认为 8 + double? _hSpacingXs; - /// default 12 - double hSpacingSm; + /// 默认为 12 + double? _hSpacingSm; - /// default 16 - double hSpacingMd; + /// 默认为 16 + double? _hSpacingMd; - /// default 20 - double hSpacingLg; + /// 默认为 20 + double? _hSpacingLg; - /// default 24 - double hSpacingXl; + /// 默认为 24 + double? _hSpacingXl; - /// default 42 - double hSpacingXxl; + /// 默认为 42 + double? _hSpacingXxl; /// 垂直间距 - /// - /// default 4 - double vSpacingXs; + /// 默认为 4 + double? _vSpacingXs; - /// default 8 - double vSpacingSm; + /// 默认为 8 + double? _vSpacingSm; - /// default 12 - double vSpacingMd; + /// 默认为 12 + double? _vSpacingMd; - /// default 14 - double vSpacingLg; + /// 默认为 14 + double? _vSpacingLg; - /// default 16 - double vSpacingXl; + /// 默认为 16 + double? _vSpacingXl; - /// default 28 - double vSpacingXxl; + /// 默认为 28 + double? _vSpacingXxl; /// 图标尺寸 + /// 默认为 8 + double? _iconSizeXxs; - /// default 8 - double iconSizeXxs; + /// 默认为 12 + double? _iconSizeXs; - /// default 12 - double iconSizeXs; + /// 默认为 14 + double? _iconSizeSm; - /// default 14 - double iconSizeSm; + /// 默认为 16 + double? _iconSizeMd; - /// default 16 - double iconSizeMd; + /// 默认为 32 + double? _iconSizeLg; - /// default 32 - double iconSizeLg; + Color get brandPrimary => + _brandPrimary ?? BrnDefaultConfigUtils.defaultCommonConfig.brandPrimary; - BrnCommonConfig({ - this.brandPrimary, - this.brandPrimaryTap, - this.brandSuccess, - this.brandWarning, - this.brandError, - this.brandImportant, - this.brandImportantValue, - this.brandAuxiliary, - this.colorTextBase, - this.colorTextImportant, - this.colorTextBaseInverse, - this.colorTextSecondary, - this.colorTextDisabled, - this.colorTextHint, - this.colorLink, - this.fillBase, - this.fillBody, - this.fillMask, - this.borderColorBase, - this.dividerColorBase, - this.fontSizeBebas, - this.fontSizeHeadLg, - this.fontSizeBase, - this.fontSizeHead, - this.fontSizeSubHead, - this.fontSizeCaption, - this.fontSizeCaptionSm, - this.radiusXs, - this.radiusSm, - this.radiusMd, - this.radiusLg, - this.borderWidthSm, - this.borderWidthMd, - this.borderWidthLg, - this.hSpacingXs, - this.hSpacingSm, - this.hSpacingMd, - this.hSpacingLg, - this.hSpacingXl, - this.hSpacingXxl, - this.vSpacingXs, - this.vSpacingSm, - this.vSpacingMd, - this.vSpacingLg, - this.vSpacingXl, - this.vSpacingXxl, - this.iconSizeXxs, - this.iconSizeXs, - this.iconSizeSm, - this.iconSizeMd, - this.iconSizeLg, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId); + Color get brandPrimaryTap => + _brandPrimaryTap ?? + BrnDefaultConfigUtils.defaultCommonConfig.brandPrimaryTap; - BrnCommonConfig.autoFlatConfig({ - this.brandPrimary, - this.brandPrimaryTap, - this.brandSuccess, - this.brandWarning, - this.brandError, - this.brandImportant, - this.brandImportantValue, - this.brandAuxiliary, - this.colorTextBase, - this.colorTextImportant, - this.colorTextBaseInverse, - this.colorTextSecondary, - this.colorTextDisabled, - this.colorTextHint, - this.colorLink, - this.fillBase, - this.fillBody, - this.fillMask, - this.borderColorBase, - this.dividerColorBase, - this.fontSizeBebas, - this.fontSizeHeadLg, - this.fontSizeBase, - this.fontSizeHead, - this.fontSizeSubHead, - this.fontSizeCaption, - this.fontSizeCaptionSm, - this.radiusXs, - this.radiusSm, - this.radiusMd, - this.radiusLg, - this.borderWidthSm, - this.borderWidthMd, - this.borderWidthLg, - this.hSpacingXs, - this.hSpacingSm, - this.hSpacingMd, - this.hSpacingLg, - this.hSpacingXl, - this.hSpacingXxl, - this.vSpacingXs, - this.vSpacingSm, - this.vSpacingMd, - this.vSpacingLg, - this.vSpacingXl, - this.vSpacingXxl, - this.iconSizeXxs, - this.iconSizeXs, - this.iconSizeSm, - this.iconSizeMd, - this.iconSizeLg, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId, autoFlatConfig: true); - - /// 优先级 [GLOBAL_CONFIG_ID] 获取配置 > [BRUNO_CONFIG_ID] 获取配置 + Color get brandSuccess => + _brandSuccess ?? BrnDefaultConfigUtils.defaultCommonConfig.brandSuccess; + + Color get brandWarning => + _brandWarning ?? BrnDefaultConfigUtils.defaultCommonConfig.brandWarning; + + Color get brandError => + _brandError ?? BrnDefaultConfigUtils.defaultCommonConfig.brandError; + + Color get brandImportant => + _brandImportant ?? + BrnDefaultConfigUtils.defaultCommonConfig.brandImportant; + + Color get brandImportantValue => + _brandImportantValue ?? + BrnDefaultConfigUtils.defaultCommonConfig.brandImportantValue; + + Color get brandAuxiliary => + _brandAuxiliary ?? + BrnDefaultConfigUtils.defaultCommonConfig.brandAuxiliary; + + Color get colorTextBase => + _colorTextBase ?? BrnDefaultConfigUtils.defaultCommonConfig.colorTextBase; + + Color get colorTextImportant => + _colorTextImportant ?? + BrnDefaultConfigUtils.defaultCommonConfig.colorTextImportant; + + Color get colorTextBaseInverse => + _colorTextBaseInverse ?? + BrnDefaultConfigUtils.defaultCommonConfig.colorTextBaseInverse; + + Color get colorTextSecondary => + _colorTextSecondary ?? + BrnDefaultConfigUtils.defaultCommonConfig.colorTextSecondary; + + Color get colorTextDisabled => + _colorTextDisabled ?? + BrnDefaultConfigUtils.defaultCommonConfig.colorTextDisabled; + + Color get colorTextHint => + _colorTextHint ?? BrnDefaultConfigUtils.defaultCommonConfig.colorTextHint; + + Color get colorLink => + _colorLink ?? BrnDefaultConfigUtils.defaultCommonConfig.colorLink; + + Color get fillBase => + _fillBase ?? BrnDefaultConfigUtils.defaultCommonConfig.fillBase; + + Color get fillBody => + _fillBody ?? BrnDefaultConfigUtils.defaultCommonConfig.fillBody; + + Color get fillMask => + _fillMask ?? BrnDefaultConfigUtils.defaultCommonConfig.fillMask; + + Color get borderColorBase => + _borderColorBase ?? + BrnDefaultConfigUtils.defaultCommonConfig.borderColorBase; + + Color get dividerColorBase => + _dividerColorBase ?? + BrnDefaultConfigUtils.defaultCommonConfig.dividerColorBase; + + double get fontSizeBebas => + _fontSizeBebas ?? BrnDefaultConfigUtils.defaultCommonConfig.fontSizeBebas; + + double get fontSizeHeadLg => + _fontSizeHeadLg ?? + BrnDefaultConfigUtils.defaultCommonConfig.fontSizeHeadLg; + + double get fontSizeHead => + _fontSizeHead ?? BrnDefaultConfigUtils.defaultCommonConfig.fontSizeHead; + + double get fontSizeSubHead => + _fontSizeSubHead ?? + BrnDefaultConfigUtils.defaultCommonConfig.fontSizeSubHead; + + double get fontSizeBase => + _fontSizeBase ?? BrnDefaultConfigUtils.defaultCommonConfig.fontSizeBase; + + double get fontSizeCaption => + _fontSizeCaption ?? + BrnDefaultConfigUtils.defaultCommonConfig.fontSizeCaption; + + double get fontSizeCaptionSm => + _fontSizeCaptionSm ?? + BrnDefaultConfigUtils.defaultCommonConfig.fontSizeCaptionSm; + + double get radiusXs => + _radiusXs ?? BrnDefaultConfigUtils.defaultCommonConfig.radiusXs; + + double get radiusSm => + _radiusSm ?? BrnDefaultConfigUtils.defaultCommonConfig.radiusSm; + + double get radiusMd => + _radiusMd ?? BrnDefaultConfigUtils.defaultCommonConfig.radiusMd; + + double get radiusLg => + _radiusLg ?? BrnDefaultConfigUtils.defaultCommonConfig.radiusLg; + + double get borderWidthSm => + _borderWidthSm ?? BrnDefaultConfigUtils.defaultCommonConfig.borderWidthSm; + + double get borderWidthMd => + _borderWidthMd ?? BrnDefaultConfigUtils.defaultCommonConfig.borderWidthMd; + + double get borderWidthLg => + _borderWidthLg ?? BrnDefaultConfigUtils.defaultCommonConfig.borderWidthLg; + + double get hSpacingXs => + _hSpacingXs ?? BrnDefaultConfigUtils.defaultCommonConfig.hSpacingXs; + + double get hSpacingSm => + _hSpacingSm ?? BrnDefaultConfigUtils.defaultCommonConfig.hSpacingSm; + + double get hSpacingMd => + _hSpacingMd ?? BrnDefaultConfigUtils.defaultCommonConfig.hSpacingMd; + + double get hSpacingLg => + _hSpacingLg ?? BrnDefaultConfigUtils.defaultCommonConfig.hSpacingLg; + + double get hSpacingXl => + _hSpacingXl ?? BrnDefaultConfigUtils.defaultCommonConfig.hSpacingXl; + + double get hSpacingXxl => + _hSpacingXxl ?? BrnDefaultConfigUtils.defaultCommonConfig.hSpacingXxl; + + double get vSpacingXs => + _vSpacingXs ?? BrnDefaultConfigUtils.defaultCommonConfig.vSpacingXs; + + double get vSpacingSm => + _vSpacingSm ?? BrnDefaultConfigUtils.defaultCommonConfig.vSpacingSm; + + double get vSpacingMd => + _vSpacingMd ?? BrnDefaultConfigUtils.defaultCommonConfig.vSpacingMd; + + double get vSpacingLg => + _vSpacingLg ?? BrnDefaultConfigUtils.defaultCommonConfig.vSpacingLg; + + double get vSpacingXl => + _vSpacingXl ?? BrnDefaultConfigUtils.defaultCommonConfig.vSpacingXl; + + double get vSpacingXxl => + _vSpacingXxl ?? BrnDefaultConfigUtils.defaultCommonConfig.vSpacingXxl; + + double get iconSizeXxs => + _iconSizeXxs ?? BrnDefaultConfigUtils.defaultCommonConfig.iconSizeXxs; + + double get iconSizeXs => + _iconSizeXs ?? BrnDefaultConfigUtils.defaultCommonConfig.iconSizeXs; + + double get iconSizeSm => + _iconSizeSm ?? BrnDefaultConfigUtils.defaultCommonConfig.iconSizeSm; + + double get iconSizeMd => + _iconSizeMd ?? BrnDefaultConfigUtils.defaultCommonConfig.iconSizeMd; + + double get iconSizeLg => + _iconSizeLg ?? BrnDefaultConfigUtils.defaultCommonConfig.iconSizeLg; + + /// 优先级 [GLOBAL_CONFIG_ID] 获取配置 > [BRUNO_CONFIG_ID] 获取配置 @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); + /// 获取合适的 完整配置(BrnAllConfig) - this.colorTextBase ??= commonConfig.colorTextBase; - this.colorTextImportant ??= commonConfig.colorTextImportant; - this.colorTextBaseInverse ??= commonConfig.colorTextBaseInverse; - this.colorTextSecondary ??= commonConfig.colorTextSecondary; - this.colorTextHint ??= commonConfig.colorTextHint; - this.colorTextDisabled ??= commonConfig.colorTextDisabled; - this.brandAuxiliary ??= commonConfig.brandAuxiliary; - this.colorLink ??= commonConfig.colorLink; - this.fillBase ??= commonConfig.fillBase; - this.fillBody ??= commonConfig.fillBody; - this.fillMask ??= commonConfig.fillMask; - this.brandPrimary ??= commonConfig.brandPrimary; - this.brandPrimaryTap ??= commonConfig.brandPrimaryTap; - this.brandSuccess ??= commonConfig.brandSuccess; - this.brandWarning ??= commonConfig.brandWarning; - this.brandError ??= commonConfig.brandError; - this.brandImportant ??= commonConfig.brandImportant; - this.brandImportantValue ??= commonConfig.brandImportantValue; - this.borderColorBase ??= commonConfig.borderColorBase; - this.dividerColorBase ??= commonConfig.dividerColorBase; - this.fontSizeBebas ??= commonConfig.fontSizeBebas; - this.fontSizeHeadLg ??= commonConfig.fontSizeHeadLg; - this.fontSizeBase ??= commonConfig.fontSizeBase; - this.fontSizeHead ??= commonConfig.fontSizeHead; - this.fontSizeSubHead ??= commonConfig.fontSizeSubHead; - this.fontSizeCaption ??= commonConfig.fontSizeCaption; - this.fontSizeCaptionSm ??= commonConfig.fontSizeCaptionSm; - this.radiusXs ??= commonConfig.radiusXs; - this.radiusSm ??= commonConfig.radiusSm; - this.radiusMd ??= commonConfig.radiusMd; - this.radiusLg ??= commonConfig.radiusLg; - this.borderWidthSm ??= commonConfig.borderWidthSm; - this.borderWidthMd ??= commonConfig.borderWidthMd; - this.borderWidthLg ??= commonConfig.borderWidthLg; - this.hSpacingXs ??= commonConfig.hSpacingXs; - this.hSpacingSm ??= commonConfig.hSpacingSm; - this.hSpacingMd ??= commonConfig.hSpacingMd; - this.hSpacingLg ??= commonConfig.hSpacingLg; - this.hSpacingXl ??= commonConfig.hSpacingXl; - this.hSpacingXxl ??= commonConfig.hSpacingXxl; - this.vSpacingXs ??= commonConfig.vSpacingXs; - this.vSpacingSm ??= commonConfig.vSpacingSm; - this.vSpacingMd ??= commonConfig.vSpacingMd; - this.vSpacingLg ??= commonConfig.vSpacingLg; - this.vSpacingXl ??= commonConfig.vSpacingXl; - this.vSpacingXxl ??= commonConfig.vSpacingXxl; - this.iconSizeXxs ??= commonConfig.iconSizeXxs; - this.iconSizeXs ??= commonConfig.iconSizeXs; - this.iconSizeSm ??= commonConfig.iconSizeSm; - this.iconSizeMd ??= commonConfig.iconSizeMd; - this.iconSizeLg ??= commonConfig.iconSizeLg; + _colorTextBase ??= commonConfig._colorTextBase; + _colorTextImportant ??= commonConfig._colorTextImportant; + _colorTextBaseInverse ??= commonConfig._colorTextBaseInverse; + _colorTextSecondary ??= commonConfig._colorTextSecondary; + _colorTextHint ??= commonConfig._colorTextHint; + _colorTextDisabled ??= commonConfig._colorTextDisabled; + _brandAuxiliary ??= commonConfig._brandAuxiliary; + _colorLink ??= commonConfig._colorLink; + _fillBase ??= commonConfig._fillBase; + _fillBody ??= commonConfig._fillBody; + _fillMask ??= commonConfig._fillMask; + _brandPrimary ??= commonConfig._brandPrimary; + _brandPrimaryTap ??= commonConfig._brandPrimaryTap; + _brandSuccess ??= commonConfig._brandSuccess; + _brandWarning ??= commonConfig._brandWarning; + _brandError ??= commonConfig._brandError; + _brandImportant ??= commonConfig._brandImportant; + _brandImportantValue ??= commonConfig._brandImportantValue; + _borderColorBase ??= commonConfig._borderColorBase; + _dividerColorBase ??= commonConfig._dividerColorBase; + _fontSizeBebas ??= commonConfig._fontSizeBebas; + _fontSizeHeadLg ??= commonConfig._fontSizeHeadLg; + _fontSizeBase ??= commonConfig._fontSizeBase; + _fontSizeHead ??= commonConfig._fontSizeHead; + _fontSizeSubHead ??= commonConfig._fontSizeSubHead; + _fontSizeCaption ??= commonConfig._fontSizeCaption; + _fontSizeCaptionSm ??= commonConfig._fontSizeCaptionSm; + _radiusXs ??= commonConfig._radiusXs; + _radiusSm ??= commonConfig._radiusSm; + _radiusMd ??= commonConfig._radiusMd; + _radiusLg ??= commonConfig._radiusLg; + _borderWidthSm ??= commonConfig._borderWidthSm; + _borderWidthMd ??= commonConfig._borderWidthMd; + _borderWidthLg ??= commonConfig._borderWidthLg; + _hSpacingXs ??= commonConfig._hSpacingXs; + _hSpacingSm ??= commonConfig._hSpacingSm; + _hSpacingMd ??= commonConfig._hSpacingMd; + _hSpacingLg ??= commonConfig._hSpacingLg; + _hSpacingXl ??= commonConfig._hSpacingXl; + _hSpacingXxl ??= commonConfig._hSpacingXxl; + _vSpacingXs ??= commonConfig._vSpacingXs; + _vSpacingSm ??= commonConfig._vSpacingSm; + _vSpacingMd ??= commonConfig._vSpacingMd; + _vSpacingLg ??= commonConfig._vSpacingLg; + _vSpacingXl ??= commonConfig._vSpacingXl; + _vSpacingXxl ??= commonConfig._vSpacingXxl; + _iconSizeXxs ??= commonConfig._iconSizeXxs; + _iconSizeXs ??= commonConfig._iconSizeXs; + _iconSizeSm ??= commonConfig._iconSizeSm; + _iconSizeMd ??= commonConfig._iconSizeMd; + _iconSizeLg ??= commonConfig._iconSizeLg; } } diff --git a/lib/src/theme/configs/brn_dialog_config.dart b/lib/src/theme/configs/brn_dialog_config.dart index 3529ec86..cab28d71 100644 --- a/lib/src/theme/configs/brn_dialog_config.dart +++ b/lib/src/theme/configs/brn_dialog_config.dart @@ -1,125 +1,285 @@ import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; import 'package:flutter/material.dart'; -/// 描述: Dialog 弹框主配置类 - +/// 描述: Dialog 弹框主配置类 class BrnDialogConfig extends BrnBaseConfig { + BrnDialogConfig({ + double? dialogWidth, + double? radius, + EdgeInsets? iconPadding, + EdgeInsets? titlePaddingSm, + EdgeInsets? titlePaddingLg, + BrnTextStyle? titleTextStyle, + TextAlign? titleTextAlign, + EdgeInsets? contentPaddingSm, + EdgeInsets? contentPaddingLg, + BrnTextStyle? contentTextStyle, + TextAlign? contentTextAlign, + EdgeInsets? warningPaddingSm, + EdgeInsets? warningPaddingLg, + BrnTextStyle? warningTextStyle, + TextAlign? warningTextAlign, + EdgeInsets? dividerPadding, + BrnTextStyle? mainActionTextStyle, + BrnTextStyle? assistActionsTextStyle, + Color? mainActionBackgroundColor, + Color? assistActionsBackgroundColor, + double? bottomHeight, + Color? backgroundColor, + String configId = GLOBAL_CONFIG_ID, + }) : _dialogWidth = dialogWidth, + _radius = radius, + _iconPadding = iconPadding, + _titlePaddingSm = titlePaddingSm, + _titlePaddingLg = titlePaddingLg, + _titleTextStyle = titleTextStyle, + _titleTextAlign = titleTextAlign, + _contentPaddingSm = contentPaddingSm, + _contentPaddingLg = contentPaddingLg, + _contentTextStyle = contentTextStyle, + _contentTextAlign = contentTextAlign, + _warningPaddingSm = warningPaddingSm, + _warningPaddingLg = warningPaddingLg, + _warningTextStyle = warningTextStyle, + _warningTextAlign = warningTextAlign, + _dividerPadding = dividerPadding, + _mainActionTextStyle = mainActionTextStyle, + _assistActionsTextStyle = assistActionsTextStyle, + _mainActionBackgroundColor = mainActionBackgroundColor, + _assistActionsBackgroundColor = assistActionsBackgroundColor, + _bottomHeight = bottomHeight, + _backgroundColor = backgroundColor, + super(configId: configId); + /// Dialog 宽度 - /// default 300 - double dialogWidth; + /// 默认为 300 + double? _dialogWidth; + + double get dialogWidth => + _dialogWidth ?? BrnDefaultConfigUtils.defaultDialogConfig.dialogWidth; /// Dialog 四周圆角 - /// default 8.0 use [BrnCommonConfig.radiusLg] - double radius; + /// 默认为 [BrnCommonConfig.radiusLg] + double? _radius; + + double get radius => + _radius ?? BrnDefaultConfigUtils.defaultDialogConfig.radius; - /// Dialog icon 距离顶部的边距 仅有顶部间距 - /// default EdgeInsets.only(top: [BrnCommonConfig.vSpacingXxl]) - EdgeInsets iconPadding; + /// Dialog icon 距离顶部的边距 + /// + /// EdgeInsets.only(top: [BrnCommonConfig.vSpacingXxl]) + EdgeInsets? _iconPadding; + + EdgeInsets get iconPadding => + _iconPadding ?? BrnDefaultConfigUtils.defaultDialogConfig.iconPadding; - /// title 当顶部 有 icon时四周间距,无底部间距 - /// default EdgeInsets.only(top: 12, left: [BrnCommonConfig.hSpacingXxl], right: [BrnCommonConfig.hSpacingXxl]) - EdgeInsets titlePaddingSm; + /// title 在顶部有 icon 时的边距 + /// + /// EdgeInsets.only( + /// top: 12, + /// left: [BrnCommonConfig.hSpacingXxl], + /// right: [BrnCommonConfig.hSpacingXxl], + /// ) + EdgeInsets? _titlePaddingSm; + + EdgeInsets get titlePaddingSm => + _titlePaddingSm ?? + BrnDefaultConfigUtils.defaultDialogConfig.titlePaddingSm; + + /// title 当顶部无 icon 时的边距 + /// + /// EdgeInsets.only( + /// top: 28, + /// left: [BrnCommonConfig.hSpacingXxl], + /// right: [BrnCommonConfig.hSpacingXxl], + /// ) + EdgeInsets? _titlePaddingLg; - /// title 当顶部 无 icon时四周间距,无底部间距 - /// default EdgeInsets.only(top: 28, left: [BrnCommonConfig.hSpacingXxl], right: [BrnCommonConfig.hSpacingXxl]) - EdgeInsets titlePaddingLg; + EdgeInsets get titlePaddingLg => + _titlePaddingLg ?? + BrnDefaultConfigUtils.defaultDialogConfig.titlePaddingLg; /// title 标题样式 - /// default BrnTextStyle(fontWeight: FontWeight.w600, fontSize: [ BrnCommonConfig.fontSizeHead], color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle titleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _titleTextStyle; + + BrnTextStyle get titleTextStyle => + _titleTextStyle ?? + BrnDefaultConfigUtils.defaultDialogConfig.titleTextStyle; /// 标题的文字对齐 - /// default TextAlign.center - TextAlign titleTextAlign; + /// 默认为 [TextAlign.center] + TextAlign? _titleTextAlign; - /// content 当顶部 有 title或者icon时四周间距,无底部间距 - /// default EdgeInsets.only(top: 8, lecontentPaddingSmft: [BrnCommonConfig.hSpacingXl], right: [BrnCommonConfig.hSpacingXl]) - EdgeInsets contentPaddingSm; + TextAlign get titleTextAlign => + _titleTextAlign ?? + BrnDefaultConfigUtils.defaultDialogConfig.titleTextAlign; - /// content 当顶部 无 title或者icon时四周间距,无底部间距 - /// default EdgeInsets.only(top: 28, left: [BrnCommonConfig.hSpacingXl], right: [BrnCommonConfig.hSpacingXl]) - EdgeInsets contentPaddingLg; + /// content 当顶部有 title 或者 icon 时的边距 + /// + /// EdgeInsets.only( + /// top: 8, + /// left: [BrnCommonConfig.hSpacingXl], + /// right: [BrnCommonConfig.hSpacingXl], + /// ) + EdgeInsets? _contentPaddingSm; + + EdgeInsets get contentPaddingSm => + _contentPaddingSm ?? + BrnDefaultConfigUtils.defaultDialogConfig.contentPaddingSm; + + /// content 当顶部无 title 或者 icon 时的边距 + /// + /// EdgeInsets.only( + /// top: 28, + /// left: [BrnCommonConfig.hSpacingXl], + /// right: [BrnCommonConfig.hSpacingXl], + /// ) + EdgeInsets? _contentPaddingLg; + + EdgeInsets get contentPaddingLg => + _contentPaddingLg ?? + BrnDefaultConfigUtils.defaultDialogConfig.contentPaddingLg; /// message 内容样式 - /// default BrnTextStyle(fontSize: [BrnCommonConfig.fontSizeBase], color: [BrnCommonConfig.colorTextImportant]) - BrnTextStyle contentTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextImportant], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _contentTextStyle; + + BrnTextStyle get contentTextStyle => + _contentTextStyle ?? + BrnDefaultConfigUtils.defaultDialogConfig.contentTextStyle; /// 内容文字的对齐 - /// default TextAlign.center - TextAlign contentTextAlign; + /// 默认为 [TextAlign.center] + TextAlign? _contentTextAlign; - /// warning 当顶部 有 title/icon/content时四周边距,无底部间距 - /// default EdgeInsets.only(top: 6, left: [BrnCommonConfig.hSpacingXl], right: [BrnCommonConfig.hSpacingXl]) - EdgeInsets warningPaddingSm; + TextAlign get contentTextAlign => + _contentTextAlign ?? + BrnDefaultConfigUtils.defaultDialogConfig.contentTextAlign; - /// warning 当顶部 无 title/icon/content时四周边距,无底部间距 - /// default EdgeInsets.only(top: 28, left: [BrnCommonConfig.hSpacingXl], right: [BrnCommonConfig.hSpacingXl]) - EdgeInsets warningPaddingLg; + /// warning 当顶部有 title/icon/content 时的边距 + /// + /// EdgeInsets.only( + /// top: 6, + /// left: [BrnCommonConfig.hSpacingXl], + /// right: [BrnCommonConfig.hSpacingXl], + /// ) + EdgeInsets? _warningPaddingSm; + + EdgeInsets get warningPaddingSm => + _warningPaddingSm ?? + BrnDefaultConfigUtils.defaultDialogConfig.warningPaddingSm; + + /// warning 当顶部无 title/icon/content 时的边距 + /// + /// EdgeInsets.only( + /// top: 28, + /// left: [BrnCommonConfig.hSpacingXl], + /// right: [BrnCommonConfig.hSpacingXl], + /// ) + EdgeInsets? _warningPaddingLg; + + EdgeInsets get warningPaddingLg => + _warningPaddingLg ?? + BrnDefaultConfigUtils.defaultDialogConfig.warningPaddingLg; /// 警告样式 - /// default BrnTextStyle(fontSize: [BrnCommonConfig.fontSizeBase], color: [BrnCommonConfig.brandError]) - BrnTextStyle warningTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandError], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _warningTextStyle; + + BrnTextStyle get warningTextStyle => + _warningTextStyle ?? + BrnDefaultConfigUtils.defaultDialogConfig.warningTextStyle; /// 警示文案文字的对齐 - /// default TextAlign.center - TextAlign warningTextAlign; + /// 默认为 [TextAlign.center] + TextAlign? _warningTextAlign; + + TextAlign get warningTextAlign => + _warningTextAlign ?? + BrnDefaultConfigUtils.defaultDialogConfig.warningTextAlign; /// action 顶部 divider 的上方边距 - /// default EdgeInsets.only(top: 28) - EdgeInsets dividerPadding; + /// + /// EdgeInsets.only(top: 28) + EdgeInsets? _dividerPadding; + + EdgeInsets get dividerPadding => + _dividerPadding ?? + BrnDefaultConfigUtils.defaultDialogConfig.dividerPadding; /// 主色调按钮样式 - /// default BrnTextStyle(color: [BrnCommonConfig.brandPrimary], fontWeight: FontWeight.w600, fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle mainActionTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _mainActionTextStyle; + + BrnTextStyle get mainActionTextStyle => + _mainActionTextStyle ?? + BrnDefaultConfigUtils.defaultDialogConfig.mainActionTextStyle; /// 主色调按钮的背景 - /// default [BrnCommonConfig.fillBase] - Color mainActionBackgroundColor; + /// 默认为 [BrnCommonConfig.fillBase] + Color? _mainActionBackgroundColor; + + Color get mainActionBackgroundColor => + _mainActionBackgroundColor ?? + BrnDefaultConfigUtils.defaultDialogConfig.mainActionBackgroundColor; /// 其他按钮的样式(超2个时按钮样式) - /// BrnTextStyle(color: [BrnCommonConfig.colorTextBase], fontWeight: FontWeight.w600,fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle assistActionsTextStyle; + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _assistActionsTextStyle; + + BrnTextStyle get assistActionsTextStyle => + _assistActionsTextStyle ?? + BrnDefaultConfigUtils.defaultDialogConfig.assistActionsTextStyle; /// 其他按钮的背景 - /// default [BrnCommonConfig.fillBase] - Color assistActionsBackgroundColor; + /// 默认为 [BrnCommonConfig.fillBase] + Color? _assistActionsBackgroundColor; + + Color get assistActionsBackgroundColor => + _assistActionsBackgroundColor ?? + BrnDefaultConfigUtils.defaultDialogConfig.assistActionsBackgroundColor; /// 底部按钮高度 - /// default 44.0 - double bottomHeight; + /// 默认为 44.0 + double? _bottomHeight; + + double get bottomHeight => + _bottomHeight ?? BrnDefaultConfigUtils.defaultDialogConfig.bottomHeight; /// Dialog背景 - /// default [BrnCommonConfig.fillBase] - Color backgroundColor; - - BrnDialogConfig( - {this.dialogWidth, - this.radius, - this.iconPadding, - this.titlePaddingSm, - this.titlePaddingLg, - this.titleTextStyle, - this.titleTextAlign, - this.contentPaddingSm, - this.contentPaddingLg, - this.contentTextStyle, - this.contentTextAlign, - this.warningPaddingSm, - this.warningPaddingLg, - this.warningTextStyle, - this.warningTextAlign, - this.dividerPadding, - this.mainActionTextStyle, - this.assistActionsTextStyle, - this.mainActionBackgroundColor, - this.assistActionsBackgroundColor, - this.bottomHeight, - this.backgroundColor, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// 默认为 [BrnCommonConfig.fillBase] + Color? _backgroundColor; + + Color get backgroundColor => + _backgroundColor ?? + BrnDefaultConfigUtils.defaultDialogConfig.backgroundColor; /// 按优先级,打平 【Bruno 内置配置】 < 【用户全局的默认配置】 < 【用户特殊配置】 < 【临时组件配置】 /// @@ -129,201 +289,183 @@ class BrnDialogConfig extends BrnBaseConfig { /// ③ 如果全局配置中的配置同样为 null 则根据 [configId] 取出全局配置。 /// ④ 如果没有配置 [configId] 的全局配置,则使用 Bruno 默认的配置 @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局组件配置 BrnDialogConfig dialogConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .dialogConfig; - this.dialogWidth ??= dialogConfig?.dialogWidth; - - this.radius ??= commonConfig.radiusLg; - - if (this.titlePaddingSm == null) { - this.titlePaddingSm = EdgeInsets.only( - left: commonConfig.hSpacingXxl, - right: commonConfig.hSpacingXxl, - top: dialogConfig.titlePaddingSm.top, - bottom: dialogConfig.titlePaddingSm.bottom); - } - - if (this.titlePaddingLg == null) { - this.titlePaddingLg = EdgeInsets.only( - left: commonConfig.hSpacingXxl, - right: commonConfig.hSpacingXxl, - top: dialogConfig.titlePaddingLg.top, - bottom: dialogConfig.titlePaddingLg.bottom); - } - - if (this.iconPadding == null) { - this.iconPadding = EdgeInsets.only( - left: dialogConfig.iconPadding.left, - top: commonConfig.vSpacingXxl, - right: dialogConfig.iconPadding.right, - bottom: dialogConfig.iconPadding.bottom); - } - - this.titleTextStyle = dialogConfig.titleTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeHead) - .merge(this.titleTextStyle)); - - this.contentTextStyle = dialogConfig.contentTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextImportant, - fontSize: commonConfig.fontSizeBase) - .merge(this.contentTextStyle)); - - this.warningTextStyle = dialogConfig.warningTextStyle.merge(BrnTextStyle( - color: commonConfig.brandError, fontSize: commonConfig.fontSizeBase) - .merge(this.warningTextStyle)); - - this.mainActionTextStyle = dialogConfig.mainActionTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.mainActionTextStyle)); - - this.assistActionsTextStyle = dialogConfig.assistActionsTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.assistActionsTextStyle)); - - if (this.contentPaddingSm == null) { - this.contentPaddingSm = EdgeInsets.only( - left: commonConfig.hSpacingXl, - right: commonConfig.hSpacingXl, - top: dialogConfig.contentPaddingSm.top, - bottom: dialogConfig.contentPaddingSm.bottom); - } - - if (this.contentPaddingLg == null) { - this.contentPaddingLg = EdgeInsets.only( - left: commonConfig.hSpacingXl, - right: commonConfig.hSpacingXl, - top: dialogConfig.contentPaddingLg.top, - bottom: dialogConfig.contentPaddingLg.bottom); - } - - if (this.warningPaddingSm == null) { - this.warningPaddingSm = EdgeInsets.only( - left: commonConfig.hSpacingXl, - right: commonConfig.hSpacingXl, - top: dialogConfig.warningPaddingSm.top, - bottom: dialogConfig.warningPaddingSm.bottom); - } - - if (this.warningPaddingLg == null) { - this.warningPaddingLg = EdgeInsets.only( - left: commonConfig.hSpacingXl, - right: commonConfig.hSpacingXl, - top: dialogConfig.warningPaddingLg.top, - bottom: dialogConfig.warningPaddingLg.bottom); - } - - this.titleTextAlign ??= dialogConfig?.titleTextAlign; - - this.contentTextAlign ??= dialogConfig?.contentTextAlign; - - this.warningTextAlign ??= dialogConfig?.warningTextAlign; - - this.mainActionBackgroundColor ??= commonConfig.fillBase; - - this.assistActionsBackgroundColor ??= commonConfig.fillBase; - - this.bottomHeight ??= dialogConfig?.bottomHeight; - - this.dividerPadding ??= dialogConfig?.dividerPadding; - - this.backgroundColor ??= commonConfig.fillBase; + _dialogWidth ??= dialogConfig.dialogWidth; + _radius ??= commonConfig.radiusLg; + _titlePaddingSm ??= EdgeInsets.only( + left: commonConfig.hSpacingXxl, + right: commonConfig.hSpacingXxl, + top: dialogConfig.titlePaddingSm.top, + bottom: dialogConfig.titlePaddingSm.bottom, + ); + _titlePaddingLg ??= EdgeInsets.only( + left: commonConfig.hSpacingXxl, + right: commonConfig.hSpacingXxl, + top: dialogConfig.titlePaddingLg.top, + bottom: dialogConfig.titlePaddingLg.bottom, + ); + _iconPadding ??= EdgeInsets.only( + left: dialogConfig.iconPadding.left, + top: commonConfig.vSpacingXxl, + right: dialogConfig.iconPadding.right, + bottom: dialogConfig.iconPadding.bottom, + ); + _titleTextStyle = dialogConfig.titleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeHead, + ).merge(_titleTextStyle), + ); + _contentTextStyle = dialogConfig.contentTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextImportant, + fontSize: commonConfig.fontSizeBase, + ).merge(_contentTextStyle), + ); + _warningTextStyle = dialogConfig.warningTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandError, + fontSize: commonConfig.fontSizeBase, + ).merge(_warningTextStyle), + ); + _mainActionTextStyle = dialogConfig.mainActionTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_mainActionTextStyle), + ); + _assistActionsTextStyle = dialogConfig.assistActionsTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_assistActionsTextStyle), + ); + _contentPaddingSm ??= EdgeInsets.only( + left: commonConfig.hSpacingXl, + right: commonConfig.hSpacingXl, + top: dialogConfig.contentPaddingSm.top, + bottom: dialogConfig.contentPaddingSm.bottom, + ); + _contentPaddingSm ??= EdgeInsets.only( + left: commonConfig.hSpacingXl, + right: commonConfig.hSpacingXl, + top: dialogConfig.contentPaddingLg.top, + bottom: dialogConfig.contentPaddingLg.bottom, + ); + _warningPaddingSm ??= EdgeInsets.only( + left: commonConfig.hSpacingXl, + right: commonConfig.hSpacingXl, + top: dialogConfig.warningPaddingSm.top, + bottom: dialogConfig.warningPaddingSm.bottom, + ); + _warningPaddingLg ??= EdgeInsets.only( + left: commonConfig.hSpacingXl, + right: commonConfig.hSpacingXl, + top: dialogConfig.warningPaddingLg.top, + bottom: dialogConfig.warningPaddingLg.bottom, + ); + _titleTextAlign ??= dialogConfig.titleTextAlign; + _contentTextAlign ??= dialogConfig.contentTextAlign; + _warningTextAlign ??= dialogConfig.warningTextAlign; + _mainActionBackgroundColor ??= commonConfig.fillBase; + _assistActionsBackgroundColor ??= commonConfig.fillBase; + _bottomHeight ??= dialogConfig.bottomHeight; + _dividerPadding ??= dialogConfig.dividerPadding; + _backgroundColor ??= commonConfig.fillBase; } - BrnDialogConfig copyWith( - {double dialogWidth, - double radius, - EdgeInsets iconPadding, - EdgeInsets titlePaddingSm, - EdgeInsets titlePaddingLg, - BrnTextStyle titleTextStyle, - TextAlign titleTextAlign, - EdgeInsets contentPaddingSm, - EdgeInsets contentPaddingLg, - BrnTextStyle contentTextStyle, - TextAlign contentTextAlign, - EdgeInsets warningPaddingSm, - EdgeInsets warningPaddingLg, - BrnTextStyle warningTextStyle, - TextAlign warningTextAlign, - EdgeInsets dividerPadding, - BrnTextStyle mainActionTextStyle, - BrnTextStyle assistActionsTextStyle, - Color mainActionBackgroundColor, - Color assistActionsBackgroundColor, - double bottomHeight, - Color backgroundColor}) { + BrnDialogConfig copyWith({ + double? dialogWidth, + double? radius, + EdgeInsets? iconPadding, + EdgeInsets? titlePaddingSm, + EdgeInsets? titlePaddingLg, + BrnTextStyle? titleTextStyle, + TextAlign? titleTextAlign, + EdgeInsets? contentPaddingSm, + EdgeInsets? contentPaddingLg, + BrnTextStyle? contentTextStyle, + TextAlign? contentTextAlign, + EdgeInsets? warningPaddingSm, + EdgeInsets? warningPaddingLg, + BrnTextStyle? warningTextStyle, + TextAlign? warningTextAlign, + EdgeInsets? dividerPadding, + BrnTextStyle? mainActionTextStyle, + BrnTextStyle? assistActionsTextStyle, + Color? mainActionBackgroundColor, + Color? assistActionsBackgroundColor, + double? bottomHeight, + Color? backgroundColor, + }) { return BrnDialogConfig( - dialogWidth: dialogWidth ?? this.dialogWidth, - radius: radius ?? this.radius, - iconPadding: iconPadding ?? this.iconPadding, - titlePaddingSm: titlePaddingSm ?? this.titlePaddingSm, - titlePaddingLg: titlePaddingLg ?? this.titlePaddingLg, - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - titleTextAlign: titleTextAlign ?? this.titleTextAlign, - contentPaddingSm: contentPaddingSm ?? this.contentPaddingSm, - contentPaddingLg: contentPaddingLg ?? this.contentPaddingLg, - contentTextStyle: contentTextStyle ?? this.contentTextStyle, - contentTextAlign: contentTextAlign ?? this.contentTextAlign, - warningPaddingSm: warningPaddingSm ?? this.warningPaddingSm, - warningPaddingLg: warningPaddingLg ?? this.warningPaddingLg, - warningTextStyle: warningTextStyle ?? this.warningTextStyle, - warningTextAlign: warningTextAlign ?? this.warningTextAlign, - dividerPadding: dividerPadding ?? this.dividerPadding, - mainActionTextStyle: mainActionTextStyle ?? this.mainActionTextStyle, - assistActionsTextStyle: - assistActionsTextStyle ?? this.assistActionsTextStyle, - mainActionBackgroundColor: - mainActionBackgroundColor ?? this.mainActionBackgroundColor, - assistActionsBackgroundColor: - assistActionsBackgroundColor ?? this.assistActionsBackgroundColor, - bottomHeight: bottomHeight ?? this.bottomHeight, - backgroundColor: backgroundColor ?? this.backgroundColor); + dialogWidth: dialogWidth ?? _dialogWidth, + radius: radius ?? _radius, + iconPadding: iconPadding ?? _iconPadding, + titlePaddingSm: titlePaddingSm ?? _titlePaddingSm, + titlePaddingLg: titlePaddingLg ?? _titlePaddingLg, + titleTextStyle: titleTextStyle ?? _titleTextStyle, + titleTextAlign: titleTextAlign ?? _titleTextAlign, + contentPaddingSm: contentPaddingSm ?? _contentPaddingSm, + contentPaddingLg: contentPaddingLg ?? _contentPaddingLg, + contentTextStyle: contentTextStyle ?? _contentTextStyle, + contentTextAlign: contentTextAlign ?? _contentTextAlign, + warningPaddingSm: warningPaddingSm ?? _warningPaddingSm, + warningPaddingLg: warningPaddingLg ?? _warningPaddingLg, + warningTextStyle: warningTextStyle ?? _warningTextStyle, + warningTextAlign: warningTextAlign ?? _warningTextAlign, + dividerPadding: dividerPadding ?? _dividerPadding, + mainActionTextStyle: mainActionTextStyle ?? _mainActionTextStyle, + assistActionsTextStyle: assistActionsTextStyle ?? _assistActionsTextStyle, + mainActionBackgroundColor: + mainActionBackgroundColor ?? _mainActionBackgroundColor, + assistActionsBackgroundColor: + assistActionsBackgroundColor ?? _assistActionsBackgroundColor, + bottomHeight: bottomHeight ?? _bottomHeight, + backgroundColor: backgroundColor ?? _backgroundColor, + ); } - BrnDialogConfig merge(BrnDialogConfig other) { + BrnDialogConfig merge(BrnDialogConfig? other) { if (other == null) return this; return copyWith( - dialogWidth: other.dialogWidth, - radius: other.radius, - iconPadding: other.iconPadding, - titlePaddingSm: other.titlePaddingSm, - titlePaddingLg: other.titlePaddingLg, - titleTextStyle: - titleTextStyle?.merge(other.titleTextStyle) ?? other.titleTextStyle, - titleTextAlign: other.titleTextAlign, - contentPaddingSm: other.contentPaddingSm, - contentPaddingLg: other.contentPaddingLg, - contentTextStyle: contentTextStyle?.merge(other.contentTextStyle) ?? - other.contentTextStyle, - contentTextAlign: other.contentTextAlign, - warningPaddingSm: other.warningPaddingSm, - warningPaddingLg: other.warningPaddingLg, - warningTextStyle: warningTextStyle?.merge(other.warningTextStyle) ?? - other.warningTextStyle, - warningTextAlign: other.warningTextAlign, - dividerPadding: other.dividerPadding, - mainActionTextStyle: - mainActionTextStyle?.merge(other.mainActionTextStyle) ?? - other.mainActionTextStyle, - assistActionsTextStyle: - assistActionsTextStyle?.merge(other.assistActionsTextStyle) ?? - other.assistActionsTextStyle, - mainActionBackgroundColor: other.mainActionBackgroundColor, - assistActionsBackgroundColor: other.assistActionsBackgroundColor, - bottomHeight: other.bottomHeight, - backgroundColor: other.backgroundColor); + dialogWidth: other._dialogWidth, + radius: other._radius, + iconPadding: other._iconPadding, + titlePaddingSm: other._titlePaddingSm, + titlePaddingLg: other._titlePaddingLg, + titleTextStyle: titleTextStyle.merge(other._titleTextStyle), + titleTextAlign: other._titleTextAlign, + contentPaddingSm: other._contentPaddingSm, + contentPaddingLg: other._contentPaddingLg, + contentTextStyle: contentTextStyle.merge(other._contentTextStyle), + contentTextAlign: other._contentTextAlign, + warningPaddingSm: other._warningPaddingSm, + warningPaddingLg: other._warningPaddingLg, + warningTextStyle: warningTextStyle.merge(other._warningTextStyle), + warningTextAlign: other._warningTextAlign, + dividerPadding: other._dividerPadding, + mainActionTextStyle: + mainActionTextStyle.merge(other._mainActionTextStyle), + assistActionsTextStyle: + assistActionsTextStyle.merge(other._assistActionsTextStyle), + mainActionBackgroundColor: other._mainActionBackgroundColor, + assistActionsBackgroundColor: other._assistActionsBackgroundColor, + bottomHeight: other._bottomHeight, + backgroundColor: other._backgroundColor, + ); } } diff --git a/lib/src/theme/configs/brn_enhance_number_card_config.dart b/lib/src/theme/configs/brn_enhance_number_card_config.dart index 231d8faa..12c261aa 100644 --- a/lib/src/theme/configs/brn_enhance_number_card_config.dart +++ b/lib/src/theme/configs/brn_enhance_number_card_config.dart @@ -1,78 +1,106 @@ -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; +import 'package:bruno/src/theme/base/brn_text_style.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/theme/configs/brn_common_config.dart'; /// 强化数字展示组件配置 class BrnEnhanceNumberCardConfig extends BrnBaseConfig { - ///遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultNumberInfoConfig] + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig] BrnEnhanceNumberCardConfig({ - this.runningSpace, - this.itemRunningSpace, - this.titleTextStyle, - this.descTextStyle, - this.dividerWidth, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId); + double? runningSpace, + double? itemRunningSpace, + BrnTextStyle? titleTextStyle, + BrnTextStyle? descTextStyle, + double? dividerWidth, + String configId: GLOBAL_CONFIG_ID, + }) : _runningSpace = runningSpace, + _itemRunningSpace = itemRunningSpace, + _titleTextStyle = titleTextStyle, + _descTextStyle = descTextStyle, + _dividerWidth = dividerWidth, + super(configId: configId); - ///如果超过一行,行间距 - double runningSpace; + /// 如果超过一行,行间距 + double? _runningSpace; - ///Item的上半部分和下半部分的间距 - double itemRunningSpace; + double get runningSpace => + _runningSpace ?? + BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig.runningSpace; - double dividerWidth; + /// Item的上半部分和下半部分的间距 + double? _itemRunningSpace; - BrnTextStyle titleTextStyle; + double get itemRunningSpace => + _itemRunningSpace ?? + BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig.itemRunningSpace; - BrnTextStyle descTextStyle; + double? _dividerWidth; + + double get dividerWidth => + _dividerWidth ?? + BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig.dividerWidth; + BrnTextStyle? _titleTextStyle; + + BrnTextStyle get titleTextStyle => + _titleTextStyle ?? + BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig.titleTextStyle; + BrnTextStyle? _descTextStyle; + + BrnTextStyle get descTextStyle => + _descTextStyle ?? + BrnDefaultConfigUtils.defaultEnhanceNumberInfoConfig.descTextStyle; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); BrnEnhanceNumberCardConfig userConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .enhanceNumberCardConfig; - this.runningSpace ??= userConfig.runningSpace; - this.itemRunningSpace ??= userConfig.itemRunningSpace; - this.dividerWidth ??= userConfig.dividerWidth; - - this.titleTextStyle = userConfig.titleTextStyle.merge( - BrnTextStyle(color: commonConfig.colorTextBase) - .merge(this.titleTextStyle)); - - this.descTextStyle = userConfig.descTextStyle.merge( - BrnTextStyle(color: commonConfig.colorTextSecondary) - .merge(this.descTextStyle)); + _runningSpace ??= userConfig._runningSpace; + _itemRunningSpace ??= userConfig._itemRunningSpace; + _dividerWidth ??= userConfig._dividerWidth; + _titleTextStyle = userConfig.titleTextStyle.merge( + BrnTextStyle(color: commonConfig.colorTextBase).merge(_titleTextStyle), + ); + _descTextStyle = userConfig.descTextStyle.merge( + BrnTextStyle(color: commonConfig.colorTextSecondary).merge(_descTextStyle), + ); } BrnEnhanceNumberCardConfig copyWith({ - double runningSpace, - double itemRunningSpace, - double dividerWidth, - BrnTextStyle titleTextStyle, - BrnTextStyle descTextStyle, + double? runningSpace, + double? itemRunningSpace, + double? dividerWidth, + BrnTextStyle? titleTextStyle, + BrnTextStyle? descTextStyle, }) { return BrnEnhanceNumberCardConfig( - runningSpace: runningSpace ?? this.runningSpace, - itemRunningSpace: itemRunningSpace ?? this.itemRunningSpace, - dividerWidth: dividerWidth ?? this.dividerWidth, - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - descTextStyle: descTextStyle ?? this.descTextStyle, + runningSpace: runningSpace ?? _runningSpace, + itemRunningSpace: itemRunningSpace ?? _itemRunningSpace, + dividerWidth: dividerWidth ?? _dividerWidth, + titleTextStyle: titleTextStyle ?? _titleTextStyle, + descTextStyle: descTextStyle ?? _descTextStyle, ); } - BrnEnhanceNumberCardConfig merge(BrnEnhanceNumberCardConfig other) { + BrnEnhanceNumberCardConfig merge(BrnEnhanceNumberCardConfig? other) { if (other == null) return this; return copyWith( - runningSpace: other.runningSpace, - itemRunningSpace: other.itemRunningSpace, - dividerWidth: other.dividerWidth, - titleTextStyle: - titleTextStyle?.merge(other.titleTextStyle) ?? other.titleTextStyle, - descTextStyle: - descTextStyle?.merge(other.descTextStyle) ?? other.descTextStyle, + runningSpace: other._runningSpace, + itemRunningSpace: other._itemRunningSpace, + dividerWidth: other._dividerWidth, + titleTextStyle: titleTextStyle.merge(other._titleTextStyle), + descTextStyle: descTextStyle.merge(other._descTextStyle), ); } } diff --git a/lib/src/theme/configs/brn_form_config.dart b/lib/src/theme/configs/brn_form_config.dart index 93cbd523..0a932215 100644 --- a/lib/src/theme/configs/brn_form_config.dart +++ b/lib/src/theme/configs/brn_form_config.dart @@ -1,99 +1,238 @@ import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; import 'package:flutter/material.dart'; /// 描述: form 表单项主配置类 - class BrnFormItemConfig extends BrnBaseConfig { + /// 遵循全局配置 + /// 默认为 [BrnDefaultConfigUtils.defaultFormItemConfig] + BrnFormItemConfig({ + BrnTextStyle? titleTextStyle, + BrnTextStyle? subTitleTextStyle, + BrnTextStyle? errorTextStyle, + BrnTextStyle? hintTextStyle, + BrnTextStyle? contentTextStyle, + EdgeInsets? formPadding, + EdgeInsets? titlePaddingSm, + EdgeInsets? titlePaddingLg, + EdgeInsets? optionsMiddlePadding, + EdgeInsets? subTitlePadding, + EdgeInsets? errorPadding, + BrnTextStyle? disableTextStyle, + BrnTextStyle? tipsTextStyle, + BrnTextStyle? headTitleTextStyle, + BrnTextStyle? optionTextStyle, + BrnTextStyle? optionSelectedTextStyle, + String configId = GLOBAL_CONFIG_ID, + }) : _titleTextStyle = titleTextStyle, + _subTitleTextStyle = subTitleTextStyle, + _errorTextStyle = errorTextStyle, + _hintTextStyle = hintTextStyle, + _contentTextStyle = contentTextStyle, + _formPadding = formPadding, + _titlePaddingSm = titlePaddingSm, + _titlePaddingLg = titlePaddingLg, + _optionsMiddlePadding = optionsMiddlePadding, + _subTitlePadding = subTitlePadding, + _errorPadding = errorPadding, + _disableTextStyle = disableTextStyle, + _tipsTextStyle = tipsTextStyle, + _headTitleTextStyle = headTitleTextStyle, + _optionTextStyle = optionTextStyle, + _optionSelectedTextStyle = optionSelectedTextStyle, + super(configId: configId); + + BrnFormItemConfig.generatorFromConfigId(String configId) { + initThemeConfig(configId); + } + /// 左侧标题文本样式 - /// default BrnTextStyle(color: [BrnCommonConfig.colorTextBase],fontSize: [BrnCommonConfig.fontSizeHead]) - BrnTextStyle headTitleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// ) + BrnTextStyle? _headTitleTextStyle; /// 左侧标题文本样式 - /// default BrnTextStyle(color: [BrnCommonConfig.colorTextBase],fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle titleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _titleTextStyle; /// 左侧辅助文本样式 - /// default BrnTextStyle(color: [BrnCommonConfig.colorTextSecondary], fontSize: [BrnCommonConfig.fontSizeCaption]) - BrnTextStyle subTitleTextStyle; - - /// 左侧Error文本样式 - /// default BrnTextStyle(color: [BrnCommonConfig.brandError], fontSize: [BrnCommonConfig.fontSizeCaption]) - BrnTextStyle errorTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// ) + BrnTextStyle? _subTitleTextStyle; + + /// 左侧 Error 文本样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandError], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// ) + BrnTextStyle? _errorTextStyle; /// 右侧 输入、选择提示文本样式 - /// default BrnTextStyle(color: [BrnCommonConfig.colorTextHint], fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle hintTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextHint], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _hintTextStyle; /// 右侧 主要内容样式 - /// default BrnTextStyle([BrnCommonConfig.colorTextBase]), fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle contentTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _contentTextStyle; /// 表单项 当有星号标识 上下右边距 - /// default EdgeInsets.only(left: 0, top: [BrnCommonConfig.vSpacingLg], right: [BrnCommonConfig.hSpacingLg], bottom: [BrnCommonConfig.vSpacingLg]) - EdgeInsets formPadding; + /// + /// EdgeInsets.only( + /// left: 0, + /// top: [BrnCommonConfig.vSpacingLg], + /// right: [BrnCommonConfig.hSpacingLg], + /// bottom: [BrnCommonConfig.vSpacingLg], + /// ) + EdgeInsets? _formPadding; /// 表单项 当有星号标识 左边距 - /// default EdgeInsets.only(left: 10) - EdgeInsets titlePaddingSm; + /// + /// EdgeInsets.only(left: 10) + EdgeInsets? _titlePaddingSm; /// 表单项 当无星号标识 左右边距 - /// default EdgeInsets.only(left: [BrnCommonConfig.hSpacingLg]) - EdgeInsets titlePaddingLg; + /// + /// EdgeInsets.only(left: [BrnCommonConfig.hSpacingLg]) + EdgeInsets? _titlePaddingLg; /// 选项之间间距 单选 or 多选 - /// default EdgeInsets.only(left: [BrnCommonConfig.hSpacingMd]) - EdgeInsets optionsMiddlePadding; + /// + /// EdgeInsets.only(left: [BrnCommonConfig.hSpacingMd]) + EdgeInsets? _optionsMiddlePadding; /// 选项普通文本样式 - /// TextStyle(color: [BrnCommonConfig.colorTextBase], height: 1.3, fontSize: [BrnCommonConfig.fontSizeSubHead],) - BrnTextStyle optionTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// height: 1.3, + /// ) + BrnTextStyle? _optionTextStyle; /// 选项选中文本样式 - /// TextStyle(color: [BrnCommonConfig.brandPrimary], height: 1.3, fontSize: [BrnCommonConfig.fontSizeSubHead],) - BrnTextStyle optionSelectedTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// height: 1.3, + /// ) + BrnTextStyle? _optionSelectedTextStyle; /// 子标题 左上间距 - /// default EdgeInsets.only(left: [BrnCommonConfig.hSpacingLg], top: [BrnCommonConfig.vSpacingXs]) - EdgeInsets subTitlePadding; + /// + /// EdgeInsets.only( + /// left: [BrnCommonConfig.hSpacingLg], + /// top: [BrnCommonConfig.vSpacingXs], + /// ) + EdgeInsets? _subTitlePadding; /// error提示 左上间距 - /// EdgeInsets.only(left: [BrnCommonConfig.hSpacingLg], top: [BrnCommonConfig.vSpacingXs]) - EdgeInsets errorPadding; + /// + /// EdgeInsets.only( + /// left: [BrnCommonConfig.hSpacingLg], + /// top: [BrnCommonConfig.vSpacingXs], + /// ) + EdgeInsets? _errorPadding; /// 不可修改内容展示 - /// BrnTextStyle(color: [BrnCommonConfig.colorTextDisabled],fontSize: [BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle disableTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextDisabled], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _disableTextStyle; /// 提示文本样式 - /// BrnTextStyle(color: [BrnCommonConfig.colorTextSecondary], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle tipsTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _tipsTextStyle; - BrnFormItemConfig.generatorFromConfigId(String configId) { - initThemeConfig(configId); - } + BrnTextStyle get headTitleTextStyle => + _headTitleTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.headTitleTextStyle; + + BrnTextStyle get titleTextStyle => + _titleTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.titleTextStyle; + + BrnTextStyle get subTitleTextStyle => + _subTitleTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.subTitleTextStyle; + + BrnTextStyle get errorTextStyle => + _errorTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.errorTextStyle; + + BrnTextStyle get hintTextStyle => + _hintTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.hintTextStyle; + + BrnTextStyle get contentTextStyle => + _contentTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.contentTextStyle; + + EdgeInsets get formPadding => + _formPadding ?? BrnDefaultConfigUtils.defaultFormItemConfig.formPadding; + + EdgeInsets get titlePaddingSm => + _titlePaddingSm ?? + BrnDefaultConfigUtils.defaultFormItemConfig.titlePaddingSm; + + EdgeInsets get titlePaddingLg => + _titlePaddingLg ?? + BrnDefaultConfigUtils.defaultFormItemConfig.titlePaddingLg; + + EdgeInsets get optionsMiddlePadding => + _optionsMiddlePadding ?? + BrnDefaultConfigUtils.defaultFormItemConfig.optionsMiddlePadding; + + BrnTextStyle get optionTextStyle => + _optionTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.optionTextStyle; + + BrnTextStyle get optionSelectedTextStyle => + _optionSelectedTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.optionSelectedTextStyle; - BrnFormItemConfig( - {this.titleTextStyle, - this.subTitleTextStyle, - this.errorTextStyle, - this.hintTextStyle, - this.contentTextStyle, - this.formPadding, - this.titlePaddingSm, - this.titlePaddingLg, - this.optionsMiddlePadding, - this.subTitlePadding, - this.errorPadding, - this.disableTextStyle, - this.tipsTextStyle, - this.headTitleTextStyle, - this.optionTextStyle, - this.optionSelectedTextStyle, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + EdgeInsets get subTitlePadding => + _subTitlePadding ?? + BrnDefaultConfigUtils.defaultFormItemConfig.subTitlePadding; + + EdgeInsets get errorPadding => + _errorPadding ?? BrnDefaultConfigUtils.defaultFormItemConfig.errorPadding; + + BrnTextStyle get disableTextStyle => + _disableTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.disableTextStyle; + + BrnTextStyle get tipsTextStyle => + _tipsTextStyle ?? + BrnDefaultConfigUtils.defaultFormItemConfig.tipsTextStyle; /// 举例: /// ① 尝试获取最近的配置 [topRadius] 若配不为 null,直接使用该配置. @@ -101,173 +240,162 @@ class BrnFormItemConfig extends BrnBaseConfig { /// ③ 如果全局配置中的配置同样为 null 则根据 [configId] 取出全局配置。 /// ④ 如果没有配置 [configId] 的全局配置,则使用 Bruno 默认的配置 @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局form组件配置 BrnFormItemConfig formItemThemeData = BrnThemeConfigurator.instance .getConfig(configId: configId) .formItemConfig; - this.titlePaddingSm ??= formItemThemeData.titlePaddingSm; - - this.titlePaddingLg ??= formItemThemeData.titlePaddingLg; - - this.optionSelectedTextStyle = - formItemThemeData.optionSelectedTextStyle.merge(BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeSubHead, - ).merge(this.optionSelectedTextStyle)); - - this.optionTextStyle = formItemThemeData.optionTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.optionTextStyle)); - - this.headTitleTextStyle = formItemThemeData.headTitleTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeHead) - .merge(this.headTitleTextStyle)); - - if (this.errorPadding == null) { - this.errorPadding = EdgeInsets.only( - left: commonConfig.hSpacingLg, - right: formItemThemeData.errorPadding.right, - top: commonConfig.vSpacingXs, - bottom: formItemThemeData.errorPadding.bottom, - ); - } - - if (this.subTitlePadding == null) { - this.subTitlePadding = EdgeInsets.only( - left: commonConfig.hSpacingLg, - right: formItemThemeData.subTitlePadding.right, - top: commonConfig.vSpacingXs, - bottom: formItemThemeData.subTitlePadding.bottom, - ); - } - - if (this.formPadding == null) { - this.formPadding = EdgeInsets.only( - left: formItemThemeData.formPadding.left, - right: commonConfig.hSpacingLg, - top: commonConfig.vSpacingLg, - bottom: commonConfig.vSpacingLg); - } - - this.tipsTextStyle = formItemThemeData.tipsTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeBase) - .merge(this.tipsTextStyle)); - - this.disableTextStyle = formItemThemeData.disableTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextDisabled, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.disableTextStyle)); - - this.contentTextStyle = formItemThemeData.contentTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.contentTextStyle)); - - this.hintTextStyle = formItemThemeData.hintTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextHint, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.hintTextStyle)); - - this.titleTextStyle = formItemThemeData.titleTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.titleTextStyle)); - - this.subTitleTextStyle = formItemThemeData.subTitleTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeCaption) - .merge(this.subTitleTextStyle)); - - this.errorTextStyle = formItemThemeData.errorTextStyle.merge(BrnTextStyle( - color: commonConfig.brandError, - fontSize: commonConfig.fontSizeCaption) - .merge(this.errorTextStyle)); - - this.optionsMiddlePadding ??= formItemThemeData?.optionsMiddlePadding; + _titlePaddingSm ??= formItemThemeData.titlePaddingSm; + _titlePaddingLg ??= formItemThemeData.titlePaddingLg; + _optionSelectedTextStyle = formItemThemeData.optionSelectedTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_optionSelectedTextStyle), + ); + _optionTextStyle = formItemThemeData.optionTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_optionTextStyle), + ); + _headTitleTextStyle = formItemThemeData.headTitleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeHead, + ).merge(_headTitleTextStyle), + ); + _errorPadding ??= EdgeInsets.only( + left: commonConfig.hSpacingLg, + right: formItemThemeData.errorPadding.right, + top: commonConfig.vSpacingXs, + bottom: formItemThemeData.errorPadding.bottom, + ); + _subTitlePadding ??= EdgeInsets.only( + left: commonConfig.hSpacingLg, + right: formItemThemeData.subTitlePadding.right, + top: commonConfig.vSpacingXs, + bottom: formItemThemeData.subTitlePadding.bottom, + ); + _formPadding ??= EdgeInsets.only( + left: formItemThemeData.formPadding.left, + right: commonConfig.hSpacingLg, + top: commonConfig.vSpacingLg, + bottom: commonConfig.vSpacingLg, + ); + _tipsTextStyle = formItemThemeData.tipsTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeBase, + ).merge(_tipsTextStyle), + ); + _disableTextStyle = formItemThemeData.disableTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextDisabled, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_disableTextStyle), + ); + _contentTextStyle = formItemThemeData.contentTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_contentTextStyle), + ); + _hintTextStyle = formItemThemeData.hintTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextHint, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_hintTextStyle), + ); + _titleTextStyle = formItemThemeData.titleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_titleTextStyle), + ); + _subTitleTextStyle = formItemThemeData.subTitleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeCaption, + ).merge(_subTitleTextStyle), + ); + _errorTextStyle = formItemThemeData.errorTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandError, + fontSize: commonConfig.fontSizeCaption, + ).merge(_errorTextStyle), + ); + _optionsMiddlePadding ??= formItemThemeData.optionsMiddlePadding; } BrnFormItemConfig copyWith({ - BrnTextStyle titleTextStyle, - BrnTextStyle subTitleTextStyle, - BrnTextStyle errorTextStyle, - BrnTextStyle hintTextStyle, - BrnTextStyle contentTextStyle, - EdgeInsets formPadding, - EdgeInsets titlePaddingSm, - EdgeInsets titlePaddingLg, - EdgeInsets optionsMiddlePadding, - EdgeInsets subTitlePadding, - EdgeInsets errorPadding, - BrnTextStyle disableTextStyle, - BrnTextStyle tipsTextStyle, - BrnTextStyle headTitleTextStyle, - BrnTextStyle optionTextStyle, - BrnTextStyle optionSelectedTextStyle, + BrnTextStyle? titleTextStyle, + BrnTextStyle? subTitleTextStyle, + BrnTextStyle? errorTextStyle, + BrnTextStyle? hintTextStyle, + BrnTextStyle? contentTextStyle, + EdgeInsets? formPadding, + EdgeInsets? titlePaddingSm, + EdgeInsets? titlePaddingLg, + EdgeInsets? optionsMiddlePadding, + EdgeInsets? subTitlePadding, + EdgeInsets? errorPadding, + BrnTextStyle? disableTextStyle, + BrnTextStyle? tipsTextStyle, + BrnTextStyle? headTitleTextStyle, + BrnTextStyle? optionTextStyle, + BrnTextStyle? optionSelectedTextStyle, }) { return BrnFormItemConfig( - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - subTitleTextStyle: subTitleTextStyle ?? this.subTitleTextStyle, - errorTextStyle: errorTextStyle ?? this.errorTextStyle, - hintTextStyle: hintTextStyle ?? this.hintTextStyle, - contentTextStyle: contentTextStyle ?? this.contentTextStyle, - formPadding: formPadding ?? this.formPadding, - titlePaddingSm: titlePaddingSm ?? this.titlePaddingSm, - titlePaddingLg: titlePaddingLg ?? this.titlePaddingLg, - optionsMiddlePadding: optionsMiddlePadding ?? this.optionsMiddlePadding, - subTitlePadding: subTitlePadding ?? this.subTitlePadding, - errorPadding: errorPadding ?? this.errorPadding, - disableTextStyle: disableTextStyle ?? this.disableTextStyle, - tipsTextStyle: tipsTextStyle ?? this.tipsTextStyle, - headTitleTextStyle: headTitleTextStyle ?? this.headTitleTextStyle, - optionTextStyle: optionTextStyle ?? this.optionTextStyle, + titleTextStyle: titleTextStyle ?? _titleTextStyle, + subTitleTextStyle: subTitleTextStyle ?? _subTitleTextStyle, + errorTextStyle: errorTextStyle ?? _errorTextStyle, + hintTextStyle: hintTextStyle ?? _hintTextStyle, + contentTextStyle: contentTextStyle ?? _contentTextStyle, + formPadding: formPadding ?? _formPadding, + titlePaddingSm: titlePaddingSm ?? _titlePaddingSm, + titlePaddingLg: titlePaddingLg ?? _titlePaddingLg, + optionsMiddlePadding: optionsMiddlePadding ?? _optionsMiddlePadding, + subTitlePadding: subTitlePadding ?? _subTitlePadding, + errorPadding: errorPadding ?? _errorPadding, + disableTextStyle: disableTextStyle ?? _disableTextStyle, + tipsTextStyle: tipsTextStyle ?? _tipsTextStyle, + headTitleTextStyle: headTitleTextStyle ?? _headTitleTextStyle, + optionTextStyle: optionTextStyle ?? _optionTextStyle, optionSelectedTextStyle: - optionSelectedTextStyle ?? this.optionSelectedTextStyle, + optionSelectedTextStyle ?? _optionSelectedTextStyle, ); } - BrnFormItemConfig merge(BrnFormItemConfig other) { + BrnFormItemConfig merge(BrnFormItemConfig? other) { if (other == null) return this; return copyWith( - titleTextStyle: - titleTextStyle?.merge(other.titleTextStyle) ?? other.titleTextStyle, - subTitleTextStyle: subTitleTextStyle?.merge(other.subTitleTextStyle) ?? - other.subTitleTextStyle, - errorTextStyle: - errorTextStyle?.merge(other.errorTextStyle) ?? other.errorTextStyle, - hintTextStyle: - hintTextStyle?.merge(other.hintTextStyle) ?? other.hintTextStyle, - contentTextStyle: contentTextStyle?.merge(other.contentTextStyle) ?? - other.contentTextStyle, - formPadding: other.formPadding, - titlePaddingSm: other.titlePaddingSm, - titlePaddingLg: other.titlePaddingLg, - optionsMiddlePadding: other.optionsMiddlePadding, - subTitlePadding: other.subTitlePadding, - errorPadding: other.errorPadding, - disableTextStyle: disableTextStyle?.merge(other.disableTextStyle) ?? - other.disableTextStyle, - tipsTextStyle: - tipsTextStyle?.merge(other.tipsTextStyle) ?? other.tipsTextStyle, - headTitleTextStyle: - headTitleTextStyle?.merge(other.headTitleTextStyle) ?? - other.headTitleTextStyle, - optionTextStyle: optionTextStyle?.merge(other.optionTextStyle) ?? - other.optionTextStyle, - optionSelectedTextStyle: - optionSelectedTextStyle?.merge(other.optionSelectedTextStyle) ?? - other.optionSelectedTextStyle); + titleTextStyle: titleTextStyle.merge(other._titleTextStyle), + subTitleTextStyle: subTitleTextStyle.merge(other._subTitleTextStyle), + errorTextStyle: errorTextStyle.merge(other._errorTextStyle), + hintTextStyle: hintTextStyle.merge(other._hintTextStyle), + contentTextStyle: contentTextStyle.merge(other._contentTextStyle), + formPadding: other._formPadding, + titlePaddingSm: other._titlePaddingSm, + titlePaddingLg: other._titlePaddingLg, + optionsMiddlePadding: other._optionsMiddlePadding, + subTitlePadding: other._subTitlePadding, + errorPadding: other._errorPadding, + disableTextStyle: disableTextStyle.merge(other._disableTextStyle), + tipsTextStyle: tipsTextStyle.merge(other._tipsTextStyle), + headTitleTextStyle: headTitleTextStyle.merge(other._headTitleTextStyle), + optionTextStyle: optionTextStyle.merge(other._optionTextStyle), + optionSelectedTextStyle: + optionSelectedTextStyle.merge(other._optionSelectedTextStyle), + ); } } diff --git a/lib/src/theme/configs/brn_gallery_detail_config.dart b/lib/src/theme/configs/brn_gallery_detail_config.dart index daa027a9..b7155350 100644 --- a/lib/src/theme/configs/brn_gallery_detail_config.dart +++ b/lib/src/theme/configs/brn_gallery_detail_config.dart @@ -1,7 +1,6 @@ -import 'dart:ui'; - import 'package:bruno/src/components/navbar/brn_appbar_theme.dart'; import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; @@ -9,265 +8,331 @@ import 'package:flutter/material.dart'; /// 查看大图配置 class BrnGalleryDetailConfig extends BrnBaseConfig { + /// 遵循全局配置 + /// 默认为 [BrnDefaultConfigUtils.defaultGalleryDetailConfig] + BrnGalleryDetailConfig({ + BrnTextStyle? appbarTitleStyle, + BrnTextStyle? appbarActionStyle, + Color? appbarBackgroundColor, + Brightness? appbarBrightness, + BrnTextStyle? tabBarUnSelectedLabelStyle, + BrnTextStyle? tabBarLabelStyle, + Color? tabBarBackgroundColor, + Color? pageBackgroundColor, + Color? bottomBackgroundColor, + BrnTextStyle? titleStyle, + BrnTextStyle? contentStyle, + BrnTextStyle? actionStyle, + Color? iconColor, + String configId = GLOBAL_CONFIG_ID, + }) : _appbarTitleStyle = appbarTitleStyle, + _appbarActionStyle = appbarActionStyle, + _appbarBackgroundColor = appbarBackgroundColor, + _appbarBrightness = appbarBrightness, + _tabBarUnSelectedLabelStyle = tabBarUnSelectedLabelStyle, + _tabBarLabelStyle = tabBarLabelStyle, + _tabBarBackgroundColor = tabBarBackgroundColor, + _pageBackgroundColor = pageBackgroundColor, + _bottomBackgroundColor = bottomBackgroundColor, + _titleStyle = titleStyle, + _contentStyle = contentStyle, + _actionStyle = actionStyle, + _iconColor = iconColor, + super(configId: configId); + + /// 黑色主题 + BrnGalleryDetailConfig.dark({ + String configId = GLOBAL_CONFIG_ID, + }) : super(configId: configId) { + _appbarTitleStyle = BrnTextStyle(color: commonConfig.colorTextBaseInverse); + _appbarActionStyle = BrnTextStyle(color: BrnAppBarTheme.lightTextColor); + _appbarBackgroundColor = Colors.black; + _appbarBrightness = Brightness.dark; + _tabBarUnSelectedLabelStyle = BrnTextStyle(color: Color(0XFFCCCCCC)); + _tabBarLabelStyle = BrnTextStyle(color: commonConfig.colorTextBaseInverse); + _tabBarBackgroundColor = Colors.black; + _pageBackgroundColor = Colors.black; + _bottomBackgroundColor = Color(0X88000000); + _titleStyle = BrnTextStyle(color: commonConfig.colorTextBaseInverse); + _contentStyle = BrnTextStyle(color: Color(0xFFCCCCCC)); + _actionStyle = BrnTextStyle(color: commonConfig.colorTextBaseInverse); + _iconColor = Colors.white; + } + + /// 白色主题 + BrnGalleryDetailConfig.light({ + String configId = GLOBAL_CONFIG_ID, + }) : super(configId: configId) { + _appbarTitleStyle = BrnTextStyle(color: commonConfig.colorTextBase); + _appbarActionStyle = BrnTextStyle(color: commonConfig.colorTextBase); + _appbarBackgroundColor = commonConfig.fillBody; + _appbarBrightness = Brightness.light; + _tabBarUnSelectedLabelStyle = BrnTextStyle( + color: commonConfig.colorTextBase, + ); + _tabBarLabelStyle = BrnTextStyle(color: commonConfig.brandPrimary); + _tabBarBackgroundColor = commonConfig.fillBody; + _pageBackgroundColor = commonConfig.fillBody; + _bottomBackgroundColor = commonConfig.fillBody.withOpacity(.85); + _titleStyle = BrnTextStyle(color: commonConfig.colorTextBase); + _contentStyle = BrnTextStyle(color: commonConfig.colorTextBase); + _actionStyle = BrnTextStyle(color: commonConfig.colorTextSecondary); + _iconColor = commonConfig.colorTextSecondary; + } + /// appbar brightness待定 /// appbar 标题样式 - /// default value is TextStyle(color: [BrnCommonConfig.colorTextBaseInverse],fontSize: [BrnCommonConfig.fontSizeHead],fontWeight: FontWeight.w600) - BrnTextStyle appbarTitleStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBaseInverse], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _appbarTitleStyle; /// 右侧操作区域文案样式 - /// default value is TextStyle(color: AppBarBrightness(brightness).textColor,fontSize: BrnAppBarTheme.actionFontSize,fontWeight: FontWeight.w600) - BrnTextStyle appbarActionStyle; + /// + /// BrnTextStyle( + /// color: AppBarBrightness(brightness).textColor, + /// fontSize: BrnAppBarTheme.actionFontSize, + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _appbarActionStyle; /// appBar 背景色 - /// default value is Colors.black - Color appbarBackgroundColor; + /// 默认为 Colors.black + Color? _appbarBackgroundColor; /// appbar brightness - /// default value is [Brightness.dark] - Brightness appbarBrightness; + /// 默认为 [Brightness.dark] + Brightness? _appbarBrightness; /// tabBar 标题普通样式 - /// default value is TextStyle(fontSize: [BrnCommonConfig.fontSizeSubHead], color: Colors.red) - BrnTextStyle tabBarUnSelectedLabelStyle; + /// + /// BrnTextStyle( + /// color: Colors.red, + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _tabBarUnSelectedLabelStyle; /// tabBar 标题选中样式 - /// default value is TextStyle(fontSize: [BrnCommonConfig.fontSizeSubHead],fontWeight: FontWeight.w600,color: [BrnCommonConfig.colorTextBaseInverse]) - BrnTextStyle tabBarLabelStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBaseInverse], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _tabBarLabelStyle; /// tabBar 背景色 - /// default value is Colors.black - Color tabBarBackgroundColor; + /// 默认为 Colors.black + Color? _tabBarBackgroundColor; /// 页面 背景色 - /// default value is Colors.black - Color pageBackgroundColor; + /// 默认为 Colors.black + Color? _pageBackgroundColor; /// 底部内容区域的背景色 - /// default value is Color(0X88000000) - Color bottomBackgroundColor; - - /// 标题文案样式 TextStyle(color: [BrnCommonConfig.colorTextBaseInverse],fontSize: [BrnCommonConfig.fontSizeHead],fontWeight: FontWeight.w600) - /// default value is - BrnTextStyle titleStyle; + /// 默认为 Color(0x88000000) + Color? _bottomBackgroundColor; + + /// 标题文案样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBaseInverse], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _titleStyle; /// 内容文案样式 - /// default value is TextStyle(color: Color(0xFFCCCCCC), fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle contentStyle; + /// + /// BrnTextStyle( + /// color: Color(0xFFCCCCCC), + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _contentStyle; /// 右侧展开收起样式 - /// default value is TextStyle(color: [BrnCommonConfig.colorTextBaseInverse],fontSize: [BrnCommonConfig.fontSizeBase],) - BrnTextStyle actionStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBaseInverse], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _actionStyle; /// icon 颜色 - /// default value is Colors.white - Color iconColor; - - BrnGalleryDetailConfig( - {this.appbarTitleStyle, - this.appbarActionStyle, - this.appbarBackgroundColor, - this.appbarBrightness, - this.tabBarUnSelectedLabelStyle, - this.tabBarLabelStyle, - this.tabBarBackgroundColor, - this.pageBackgroundColor, - this.bottomBackgroundColor, - this.titleStyle, - this.contentStyle, - this.actionStyle, - this.iconColor, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// 默认为 Colors.white + Color? _iconColor; - /// 黑色主题 - BrnGalleryDetailConfig.dark( - {this.appbarTitleStyle, - this.appbarActionStyle, - this.appbarBackgroundColor, - this.appbarBrightness, - this.tabBarUnSelectedLabelStyle, - this.tabBarLabelStyle, - this.tabBarBackgroundColor, - this.pageBackgroundColor, - this.bottomBackgroundColor, - this.titleStyle, - this.contentStyle, - this.actionStyle, - this.iconColor, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId) { - this.appbarTitleStyle = - BrnTextStyle(color: commonConfig.colorTextBaseInverse); - this.appbarActionStyle = BrnTextStyle(color: BrnAppBarTheme.lightTextColor); - this.appbarBackgroundColor = Colors.black; - this.appbarBrightness = Brightness.dark; - this.tabBarUnSelectedLabelStyle = BrnTextStyle(color: Color(0XFFCCCCCC)); - this.tabBarLabelStyle = - BrnTextStyle(color: commonConfig.colorTextBaseInverse); - this.tabBarBackgroundColor = Colors.black; - this.pageBackgroundColor = Colors.black; - this.bottomBackgroundColor = Color(0X88000000); - this.titleStyle = BrnTextStyle(color: commonConfig.colorTextBaseInverse); - this.contentStyle = BrnTextStyle(color: Color(0xFFCCCCCC)); - this.actionStyle = BrnTextStyle(color: commonConfig.colorTextBaseInverse); - this.iconColor = Colors.white; - } + BrnTextStyle get appbarTitleStyle => + _appbarTitleStyle ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.appbarTitleStyle; - /// 白色主题 - BrnGalleryDetailConfig.light( - {this.appbarTitleStyle, - this.appbarActionStyle, - this.appbarBackgroundColor, - this.appbarBrightness, - this.tabBarUnSelectedLabelStyle, - this.tabBarLabelStyle, - this.tabBarBackgroundColor, - this.pageBackgroundColor, - this.bottomBackgroundColor, - this.titleStyle, - this.contentStyle, - this.actionStyle, - this.iconColor, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId) { - this.appbarTitleStyle = BrnTextStyle(color: commonConfig.colorTextBase); - this.appbarActionStyle = BrnTextStyle(color: commonConfig.colorTextBase); - this.appbarBackgroundColor = commonConfig.fillBody; - this.appbarBrightness = Brightness.light; - this.tabBarUnSelectedLabelStyle = - BrnTextStyle(color: commonConfig.colorTextBase); - this.tabBarLabelStyle = BrnTextStyle(color: commonConfig.brandPrimary); - this.tabBarBackgroundColor = commonConfig.fillBody; - this.pageBackgroundColor = commonConfig.fillBody; - this.bottomBackgroundColor = commonConfig.fillBody.withOpacity(0.85); - this.titleStyle = BrnTextStyle(color: commonConfig.colorTextBase); - this.contentStyle = BrnTextStyle(color: commonConfig.colorTextBase); - this.actionStyle = BrnTextStyle(color: commonConfig.colorTextSecondary); - this.iconColor = commonConfig.colorTextSecondary; - } + BrnTextStyle get appbarActionStyle => + _appbarActionStyle ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.appbarActionStyle; - @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + Color get appbarBackgroundColor => + _appbarBackgroundColor ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.appbarBackgroundColor; - /// 用户全局组件配置 - BrnGalleryDetailConfig galleryDetailConfig = BrnThemeConfigurator.instance - .getConfig(configId: configId) - .galleryDetailConfig; + Brightness get appbarBrightness => + _appbarBrightness ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.appbarBrightness; - this.appbarTitleStyle = galleryDetailConfig.appbarTitleStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBaseInverse, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.appbarTitleStyle)); + BrnTextStyle get tabBarUnSelectedLabelStyle => + _tabBarUnSelectedLabelStyle ?? + BrnDefaultConfigUtils + .defaultGalleryDetailConfig.tabBarUnSelectedLabelStyle; - this.appbarActionStyle = - galleryDetailConfig.appbarActionStyle.merge(this.appbarActionStyle); + BrnTextStyle get tabBarLabelStyle => + _tabBarLabelStyle ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.tabBarLabelStyle; - this.appbarBrightness ??= galleryDetailConfig.appbarBrightness; + Color get tabBarBackgroundColor => + _tabBarBackgroundColor ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.tabBarBackgroundColor; - this.appbarBackgroundColor ??= galleryDetailConfig.appbarBackgroundColor; + Color get pageBackgroundColor => + _pageBackgroundColor ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.pageBackgroundColor; - this.tabBarUnSelectedLabelStyle = galleryDetailConfig - .tabBarUnSelectedLabelStyle - .merge(BrnTextStyle(fontSize: commonConfig.fontSizeSubHead)) - .merge(this.tabBarUnSelectedLabelStyle); + Color get bottomBackgroundColor => + _bottomBackgroundColor ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.bottomBackgroundColor; - this.tabBarLabelStyle = galleryDetailConfig.tabBarLabelStyle - .merge(BrnTextStyle( - color: commonConfig.colorTextBaseInverse, - fontSize: commonConfig.fontSizeSubHead)) - .merge(this.tabBarLabelStyle); + BrnTextStyle get titleStyle => + _titleStyle ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.titleStyle; - this.tabBarBackgroundColor ??= galleryDetailConfig.tabBarBackgroundColor; + BrnTextStyle get contentStyle => + _contentStyle ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.contentStyle; - this.pageBackgroundColor ??= galleryDetailConfig.pageBackgroundColor; + BrnTextStyle get actionStyle => + _actionStyle ?? + BrnDefaultConfigUtils.defaultGalleryDetailConfig.actionStyle; - this.bottomBackgroundColor ??= galleryDetailConfig.bottomBackgroundColor; + Color get iconColor => + _iconColor ?? BrnDefaultConfigUtils.defaultGalleryDetailConfig.iconColor; - this.titleStyle = galleryDetailConfig.titleStyle - .merge(BrnTextStyle( - color: commonConfig.colorTextBaseInverse, - fontSize: commonConfig.fontSizeHead)) - .merge(this.titleStyle); + @override + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); - this.contentStyle = galleryDetailConfig.contentStyle - .merge(BrnTextStyle(fontSize: commonConfig.fontSizeBase)) - .merge(this.contentStyle); + /// 用户全局组件配置 + BrnGalleryDetailConfig galleryDetailConfig = BrnThemeConfigurator.instance + .getConfig(configId: configId) + .galleryDetailConfig; - this.actionStyle = galleryDetailConfig.actionStyle - .merge(BrnTextStyle( + _appbarTitleStyle = galleryDetailConfig.appbarTitleStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBaseInverse, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_appbarTitleStyle), + ); + _appbarActionStyle = galleryDetailConfig.appbarActionStyle.merge( + _appbarActionStyle, + ); + _appbarBrightness ??= galleryDetailConfig.appbarBrightness; + _appbarBackgroundColor ??= galleryDetailConfig.appbarBackgroundColor; + _tabBarUnSelectedLabelStyle = galleryDetailConfig.tabBarUnSelectedLabelStyle + .merge(BrnTextStyle(fontSize: commonConfig.fontSizeSubHead)) + .merge(_tabBarUnSelectedLabelStyle); + _tabBarLabelStyle = galleryDetailConfig.tabBarLabelStyle + .merge( + BrnTextStyle( color: commonConfig.colorTextBaseInverse, - fontSize: commonConfig.fontSizeBase)) - .merge(this.actionStyle); - - this.iconColor ??= galleryDetailConfig.iconColor; + fontSize: commonConfig.fontSizeSubHead, + ), + ) + .merge(_tabBarLabelStyle); + _tabBarBackgroundColor ??= galleryDetailConfig._tabBarBackgroundColor; + _pageBackgroundColor ??= galleryDetailConfig._pageBackgroundColor; + _bottomBackgroundColor ??= galleryDetailConfig._bottomBackgroundColor; + _titleStyle = galleryDetailConfig.titleStyle + .merge( + BrnTextStyle( + color: commonConfig.colorTextBaseInverse, + fontSize: commonConfig.fontSizeHead, + ), + ) + .merge(_titleStyle); + _contentStyle = galleryDetailConfig.contentStyle + .merge(BrnTextStyle(fontSize: commonConfig.fontSizeBase)) + .merge(_contentStyle); + _actionStyle = galleryDetailConfig.actionStyle + .merge( + BrnTextStyle( + color: commonConfig.colorTextBaseInverse, + fontSize: commonConfig.fontSizeBase, + ), + ) + .merge(_actionStyle); + _iconColor ??= galleryDetailConfig._iconColor; } BrnGalleryDetailConfig copyWith({ - BrnTextStyle appbarTitleStyle, - BrnTextStyle appbarActionStyle, - Color appbarBackgroundColor, - Brightness appbarBrightness, - BrnTextStyle tabBarUnSelectedLabelStyle, - Color tabBarUnselectedLabelColor, - BrnTextStyle tabBarLabelStyle, - Color tabBarLabelColor, - Color tabBarBackgroundColor, - Color indicatorColor, - Color pageBackgroundColor, - Color bottomBackgroundColor, - BrnTextStyle titleStyle, - BrnTextStyle contentStyle, - BrnTextStyle actionStyle, - Color iconColor, + BrnTextStyle? appbarTitleStyle, + BrnTextStyle? appbarActionStyle, + Color? appbarBackgroundColor, + Brightness? appbarBrightness, + BrnTextStyle? tabBarUnSelectedLabelStyle, + Color? tabBarUnselectedLabelColor, + BrnTextStyle? tabBarLabelStyle, + Color? tabBarLabelColor, + Color? tabBarBackgroundColor, + Color? indicatorColor, + Color? pageBackgroundColor, + Color? bottomBackgroundColor, + BrnTextStyle? titleStyle, + BrnTextStyle? contentStyle, + BrnTextStyle? actionStyle, + Color? iconColor, }) { return BrnGalleryDetailConfig( - appbarTitleStyle: appbarTitleStyle ?? this.appbarTitleStyle, - appbarActionStyle: appbarActionStyle ?? this.appbarActionStyle, - appbarBackgroundColor: - appbarBackgroundColor ?? this.appbarBackgroundColor, - appbarBrightness: appbarBrightness ?? this.appbarBrightness, + appbarTitleStyle: appbarTitleStyle ?? _appbarTitleStyle, + appbarActionStyle: appbarActionStyle ?? _appbarActionStyle, + appbarBackgroundColor: appbarBackgroundColor ?? _appbarBackgroundColor, + appbarBrightness: appbarBrightness ?? _appbarBrightness, tabBarUnSelectedLabelStyle: - tabBarUnSelectedLabelStyle ?? this.tabBarUnSelectedLabelStyle, - tabBarLabelStyle: tabBarLabelStyle ?? this.tabBarLabelStyle, - tabBarBackgroundColor: - tabBarBackgroundColor ?? this.tabBarBackgroundColor, - pageBackgroundColor: pageBackgroundColor ?? this.pageBackgroundColor, - bottomBackgroundColor: - bottomBackgroundColor ?? this.bottomBackgroundColor, - titleStyle: titleStyle ?? this.titleStyle, - contentStyle: contentStyle ?? this.contentStyle, - actionStyle: actionStyle ?? this.actionStyle, - iconColor: iconColor ?? this.iconColor, + tabBarUnSelectedLabelStyle ?? _tabBarUnSelectedLabelStyle, + tabBarLabelStyle: tabBarLabelStyle ?? _tabBarLabelStyle, + tabBarBackgroundColor: tabBarBackgroundColor ?? _tabBarBackgroundColor, + pageBackgroundColor: pageBackgroundColor ?? _pageBackgroundColor, + bottomBackgroundColor: bottomBackgroundColor ?? _bottomBackgroundColor, + titleStyle: titleStyle ?? _titleStyle, + contentStyle: contentStyle ?? _contentStyle, + actionStyle: actionStyle ?? _actionStyle, + iconColor: iconColor ?? _iconColor, ); } - BrnGalleryDetailConfig merge(BrnGalleryDetailConfig other) { + BrnGalleryDetailConfig merge(BrnGalleryDetailConfig? other) { if (other == null) return this; return copyWith( - appbarTitleStyle: appbarTitleStyle?.merge(other.appbarTitleStyle) ?? - other.appbarTitleStyle, - appbarActionStyle: appbarActionStyle?.merge(other.appbarActionStyle) ?? - other.appbarActionStyle, - appbarBackgroundColor: other.appbarBackgroundColor, - appbarBrightness: other.appbarBrightness, + appbarTitleStyle: appbarTitleStyle.merge(other._appbarTitleStyle), + appbarActionStyle: appbarActionStyle.merge(other._appbarActionStyle), + appbarBackgroundColor: other._appbarBackgroundColor, + appbarBrightness: other._appbarBrightness, tabBarUnSelectedLabelStyle: - tabBarUnSelectedLabelStyle?.merge(other.tabBarUnSelectedLabelStyle) ?? - other.tabBarUnSelectedLabelStyle, - tabBarLabelStyle: tabBarLabelStyle?.merge(other.tabBarLabelStyle) ?? - other.tabBarLabelStyle, - tabBarBackgroundColor: other.tabBarBackgroundColor, - pageBackgroundColor: other.pageBackgroundColor, - bottomBackgroundColor: other.bottomBackgroundColor, - titleStyle: titleStyle?.merge(other.titleStyle) ?? other.titleStyle, - contentStyle: - contentStyle?.merge(other.contentStyle) ?? other.contentStyle, - actionStyle: actionStyle?.merge(other.actionStyle) ?? other.actionStyle, - iconColor: other.iconColor, + tabBarUnSelectedLabelStyle.merge(other._tabBarUnSelectedLabelStyle), + tabBarLabelStyle: tabBarLabelStyle.merge(other._tabBarLabelStyle), + tabBarBackgroundColor: other._tabBarBackgroundColor, + pageBackgroundColor: other._pageBackgroundColor, + bottomBackgroundColor: other._bottomBackgroundColor, + titleStyle: titleStyle.merge(other._titleStyle), + contentStyle: contentStyle.merge(other._contentStyle), + actionStyle: actionStyle.merge(other._actionStyle), + iconColor: other._iconColor, ); } } diff --git a/lib/src/theme/configs/brn_pair_info_config.dart b/lib/src/theme/configs/brn_pair_info_config.dart index cb55dfb5..987dfb67 100644 --- a/lib/src/theme/configs/brn_pair_info_config.dart +++ b/lib/src/theme/configs/brn_pair_info_config.dart @@ -1,134 +1,233 @@ -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; +import 'package:bruno/src/theme/base/brn_text_style.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/theme/configs/brn_common_config.dart'; -///BrnPairInfoTable的配置文件 全局配置 +/// BrnPairInfoTable 的配置文件 全局配置 class BrnPairInfoTableConfig extends BrnBaseConfig { - ///遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultPairInfoTableConfig] + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultPairInfoTableConfig] BrnPairInfoTableConfig({ - this.rowSpacing, - this.itemSpacing, - this.keyTextStyle, - this.valueTextStyle, - this.linkTextStyle, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId); + double? rowSpacing, + double? itemSpacing, + BrnTextStyle? keyTextStyle, + BrnTextStyle? valueTextStyle, + BrnTextStyle? linkTextStyle, + String configId: GLOBAL_CONFIG_ID, + }) : _rowSpacing = rowSpacing, + _itemSpacing = itemSpacing, + _keyTextStyle = keyTextStyle, + _valueTextStyle = valueTextStyle, + _linkTextStyle = linkTextStyle, + super(configId: configId); /// 行间距 纵向 - double rowSpacing; + double? _rowSpacing; /// BrnInfoModal 属性配置 行间距 - double itemSpacing; + double? _itemSpacing; /// BrnInfoModal key文字样式 - /// TextStyle(fontWeight: FontWeight.w400,color: [BrnCommonConfig.colorTextSecondary], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle keyTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w400, + /// ) + BrnTextStyle? _keyTextStyle; /// BrnInfoModal value文字样式 - /// TextStyle(fontWeight: FontWeight.w400,color: [BrnCommonConfig.colorTextBase], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle valueTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w400, + /// ) + BrnTextStyle? _valueTextStyle; /// BrnInfoModal 链接文字样式 - /// TextStyle(fontWeight: FontWeight.w400,color: [BrnCommonConfig.brandPrimary], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle linkTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontWeight: FontWeight.w400, + /// fontSize: [BrnCommonConfig.fontSizeBase] + /// ) + BrnTextStyle? _linkTextStyle; + + double get rowSpacing => + _rowSpacing ?? + BrnDefaultConfigUtils.defaultPairInfoTableConfig.rowSpacing; + + double get itemSpacing => + _itemSpacing ?? + BrnDefaultConfigUtils.defaultPairInfoTableConfig.itemSpacing; + + BrnTextStyle get keyTextStyle => + _keyTextStyle ?? + BrnDefaultConfigUtils.defaultPairInfoTableConfig.keyTextStyle; + + BrnTextStyle get valueTextStyle => + _valueTextStyle ?? + BrnDefaultConfigUtils.defaultPairInfoTableConfig.valueTextStyle; + + BrnTextStyle get linkTextStyle => + _linkTextStyle ?? + BrnDefaultConfigUtils.defaultPairInfoTableConfig.linkTextStyle; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局组件配置 BrnPairInfoTableConfig pairInfoTableConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .pairInfoTableConfig; - this.rowSpacing ??= pairInfoTableConfig?.rowSpacing; - - this.keyTextStyle = pairInfoTableConfig.keyTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeBase) - .merge(this.keyTextStyle)); - - this.valueTextStyle = pairInfoTableConfig.valueTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.valueTextStyle)); - - this.linkTextStyle = pairInfoTableConfig.linkTextStyle.merge(BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeBase) - .merge(this.linkTextStyle)); - - this.itemSpacing ??= pairInfoTableConfig?.itemSpacing; + _rowSpacing ??= pairInfoTableConfig._rowSpacing; + _keyTextStyle = pairInfoTableConfig.keyTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeBase, + ).merge(_keyTextStyle), + ); + _valueTextStyle = pairInfoTableConfig.valueTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_valueTextStyle), + ); + _linkTextStyle = pairInfoTableConfig.linkTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeBase, + ).merge(_linkTextStyle), + ); + _itemSpacing ??= pairInfoTableConfig._itemSpacing; } - BrnPairInfoTableConfig copyWith( - {double rowSpacing, - double itemSpacing, - BrnTextStyle keyTextStyle, - BrnTextStyle valueTextStyle, - BrnTextStyle linkTextStyle}) { + BrnPairInfoTableConfig copyWith({ + double? rowSpacing, + double? itemSpacing, + BrnTextStyle? keyTextStyle, + BrnTextStyle? valueTextStyle, + BrnTextStyle? linkTextStyle, + }) { return BrnPairInfoTableConfig( - rowSpacing: rowSpacing ?? this.rowSpacing, - itemSpacing: itemSpacing ?? this.itemSpacing, - keyTextStyle: keyTextStyle ?? this.keyTextStyle, - valueTextStyle: valueTextStyle ?? this.valueTextStyle, - linkTextStyle: linkTextStyle ?? this.linkTextStyle, + rowSpacing: rowSpacing ?? _rowSpacing, + itemSpacing: itemSpacing ?? _itemSpacing, + keyTextStyle: keyTextStyle ?? _keyTextStyle, + valueTextStyle: valueTextStyle ?? _valueTextStyle, + linkTextStyle: linkTextStyle ?? _linkTextStyle, ); } - BrnPairInfoTableConfig merge(BrnPairInfoTableConfig other) { + BrnPairInfoTableConfig merge(BrnPairInfoTableConfig? other) { if (other == null) return this; return copyWith( - rowSpacing: other.rowSpacing, - itemSpacing: other.itemSpacing, - keyTextStyle: - keyTextStyle?.merge(other.keyTextStyle) ?? other.keyTextStyle, - valueTextStyle: - valueTextStyle?.merge(other.valueTextStyle) ?? other.valueTextStyle, - linkTextStyle: - linkTextStyle?.merge(other.linkTextStyle) ?? other.linkTextStyle, + rowSpacing: other._rowSpacing, + itemSpacing: other._itemSpacing, + keyTextStyle: keyTextStyle.merge(other._keyTextStyle), + valueTextStyle: valueTextStyle.merge(other._valueTextStyle), + linkTextStyle: linkTextStyle.merge(other._linkTextStyle), ); } } class BrnPairRichInfoGridConfig extends BrnBaseConfig { - ///遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultPairRichInfoGridConfig] + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultPairRichInfoGridConfig] BrnPairRichInfoGridConfig({ - this.rowSpacing, - this.itemSpacing, - this.itemHeight, - this.keyTextStyle, - this.valueTextStyle, - this.linkTextStyle, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId); + double? rowSpacing, + double? itemSpacing, + double? itemHeight, + BrnTextStyle? keyTextStyle, + BrnTextStyle? valueTextStyle, + BrnTextStyle? linkTextStyle, + String configId: GLOBAL_CONFIG_ID, + }) : _rowSpacing = rowSpacing, + _itemSpacing = itemSpacing, + _itemHeight = itemHeight, + _keyTextStyle = keyTextStyle, + _valueTextStyle = valueTextStyle, + _linkTextStyle = linkTextStyle, + super(configId: configId); /// 行间距 纵向 - double rowSpacing; + double? _rowSpacing; /// 元素间距 横向 - double itemSpacing; + double? _itemSpacing; /// 元素高度 - double itemHeight; + double? _itemHeight; /// key文字样式 - /// TextStyle(fontWeight: FontWeight.w400,color: [BrnCommonConfig.colorTextSecondary], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle keyTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w400, + /// ) + BrnTextStyle? _keyTextStyle; /// value文字样式 - /// TextStyle(fontWeight: FontWeight.w400,color: [BrnCommonConfig.colorTextBase], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle valueTextStyle; + /// + /// BrnTextStyle( + /// fontWeight: FontWeight.w400, + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _valueTextStyle; /// 链接文字样式 - /// TextStyle(fontWeight: FontWeight.w400,color: [BrnCommonConfig.brandPrimary], fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle linkTextStyle; + /// + /// BrnTextStyle( + /// fontWeight: FontWeight.w400, + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _linkTextStyle; + + double get rowSpacing => + _rowSpacing ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig.rowSpacing; + + double get itemSpacing => + _itemSpacing ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig.itemSpacing; + + double get itemHeight => + _itemHeight ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig.itemHeight; + + BrnTextStyle get keyTextStyle => + _keyTextStyle ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig.keyTextStyle; + + BrnTextStyle get valueTextStyle => + _valueTextStyle ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig.valueTextStyle; + + BrnTextStyle get linkTextStyle => + _linkTextStyle ?? + BrnDefaultConfigUtils.defaultPairRichInfoGridConfig.linkTextStyle; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局组件配置 BrnPairRichInfoGridConfig pairRichInfoGridConfig = BrnThemeConfigurator @@ -136,58 +235,57 @@ class BrnPairRichInfoGridConfig extends BrnBaseConfig { .getConfig(configId: configId) .pairRichInfoGridConfig; - this.rowSpacing ??= pairRichInfoGridConfig?.rowSpacing; - this.itemSpacing ??= pairRichInfoGridConfig?.itemSpacing; - this.itemHeight ??= pairRichInfoGridConfig?.itemHeight; - - this.keyTextStyle = pairRichInfoGridConfig.keyTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeBase, - ).merge(this.keyTextStyle)); - - this.valueTextStyle = pairRichInfoGridConfig.valueTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.valueTextStyle)); - - this.linkTextStyle = pairRichInfoGridConfig.linkTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeBase) - .merge(this.linkTextStyle)); + _rowSpacing ??= pairRichInfoGridConfig._rowSpacing; + _itemSpacing ??= pairRichInfoGridConfig._itemSpacing; + _itemHeight ??= pairRichInfoGridConfig._itemHeight; + _keyTextStyle = pairRichInfoGridConfig.keyTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeBase, + ).merge(_keyTextStyle), + ); + _valueTextStyle = pairRichInfoGridConfig.valueTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_valueTextStyle), + ); + _linkTextStyle = pairRichInfoGridConfig.linkTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeBase, + ).merge(_linkTextStyle), + ); } - BrnPairRichInfoGridConfig copyWith( - {double rowSpacing, - double itemSpacing, - double itemHeight, - BrnTextStyle keyTextStyle, - BrnTextStyle valueTextStyle, - BrnTextStyle linkTextStyle, - BrnTextStyle titleTextsStyle}) { + BrnPairRichInfoGridConfig copyWith({ + double? rowSpacing, + double? itemSpacing, + double? itemHeight, + BrnTextStyle? keyTextStyle, + BrnTextStyle? valueTextStyle, + BrnTextStyle? linkTextStyle, + BrnTextStyle? titleTextsStyle, + }) { return BrnPairRichInfoGridConfig( - rowSpacing: rowSpacing ?? this.rowSpacing, - itemSpacing: itemSpacing ?? this.itemSpacing, - itemHeight: itemHeight ?? this.itemHeight, - keyTextStyle: keyTextStyle ?? this.keyTextStyle, - valueTextStyle: valueTextStyle ?? this.valueTextStyle, - linkTextStyle: linkTextStyle ?? this.linkTextStyle, + rowSpacing: rowSpacing ?? _rowSpacing, + itemSpacing: itemSpacing ?? _itemSpacing, + itemHeight: itemHeight ?? _itemHeight, + keyTextStyle: keyTextStyle ?? _keyTextStyle, + valueTextStyle: valueTextStyle ?? _valueTextStyle, + linkTextStyle: linkTextStyle ?? _linkTextStyle, ); } - BrnPairRichInfoGridConfig merge(BrnPairRichInfoGridConfig other) { - if (BrnPairRichInfoGridConfig == null) return this; + BrnPairRichInfoGridConfig merge(BrnPairRichInfoGridConfig? other) { + if (other == null) return this; return copyWith( - rowSpacing: other.rowSpacing, - itemSpacing: other.itemSpacing, - itemHeight: other.itemHeight, - keyTextStyle: - keyTextStyle?.merge(other.keyTextStyle) ?? other.keyTextStyle, - valueTextStyle: - valueTextStyle?.merge(other.valueTextStyle) ?? other.valueTextStyle, - linkTextStyle: - linkTextStyle?.merge(other.linkTextStyle) ?? other.linkTextStyle, + rowSpacing: other._rowSpacing, + itemSpacing: other._itemSpacing, + itemHeight: other._itemHeight, + keyTextStyle: keyTextStyle.merge(other._keyTextStyle), + valueTextStyle: valueTextStyle.merge(other._valueTextStyle), + linkTextStyle: linkTextStyle.merge(other._linkTextStyle), ); } } diff --git a/lib/src/theme/configs/brn_picker_config.dart b/lib/src/theme/configs/brn_picker_config.dart index a15bf8e1..92b903ba 100644 --- a/lib/src/theme/configs/brn_picker_config.dart +++ b/lib/src/theme/configs/brn_picker_config.dart @@ -1,4 +1,5 @@ import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; @@ -6,154 +7,231 @@ import 'package:flutter/material.dart'; /// 选择器配置 class BrnPickerConfig extends BrnBaseConfig { - ///遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultPickerConfig] - BrnPickerConfig( - {this.backgroundColor, - this.cancelTextStyle, - this.confirmTextStyle, - this.titleTextStyle, - this.pickerHeight, - this.titleHeight, - this.itemHeight, - this.itemTextStyle, - this.itemTextSelectedStyle, - this.dividerColor, - this.cornerRadius, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); - - /// DatePicker's background color. value is [PICKER_BACKGROUND_COLOR] - Color backgroundColor; - - /// cancel text style - /// Default style is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeSubHead]). - BrnTextStyle cancelTextStyle; - - /// confirm text style - /// Default style is TextStyle(color:[BrnCommonConfig.brandPrimary],fontSize:[BrnCommonConfig.fontSizeSubHead]). - BrnTextStyle confirmTextStyle; - - /// title style - /// Default style is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeSubHead],fontWidget:FontWeight.w600). - BrnTextStyle titleTextStyle; - - /// The value of DatePicker's height. - /// default value is [PICKER_HEIGHT] - double pickerHeight; - - /// The value of DatePicker's title height. - /// default value is [PICKER_TITLE_HEIGHT] - double titleHeight; - - /// The value of DatePicker's column height. - /// default value is [PICKER_ITEM_HEIGHT] - double itemHeight; - - /// The value of DatePicker's column [TextStyle]. - /// Default style is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeHead]). - BrnTextStyle itemTextStyle; - - /// The value of DatePicker's column selected [TextStyle]. - /// Default style is TextStyle(color:[BrnCommonConfig.brandPrimary],fontSize:[BrnCommonConfig.fontSizeHead],fontWidget:FontWeight.w600). - BrnTextStyle itemTextSelectedStyle; - - Color dividerColor; - double cornerRadius; + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultPickerConfig] + BrnPickerConfig({ + Color? backgroundColor, + BrnTextStyle? cancelTextStyle, + BrnTextStyle? confirmTextStyle, + BrnTextStyle? titleTextStyle, + double? pickerHeight, + double? titleHeight, + double? itemHeight, + BrnTextStyle? itemTextStyle, + BrnTextStyle? itemTextSelectedStyle, + Color? dividerColor, + double? cornerRadius, + String configId = GLOBAL_CONFIG_ID, + }) : _backgroundColor = backgroundColor, + _cancelTextStyle = cancelTextStyle, + _confirmTextStyle = confirmTextStyle, + _titleTextStyle = titleTextStyle, + _pickerHeight = pickerHeight, + _titleHeight = titleHeight, + _itemHeight = itemHeight, + _itemTextStyle = itemTextStyle, + _itemTextSelectedStyle = itemTextSelectedStyle, + _dividerColor = dividerColor, + _cornerRadius = cornerRadius, + super(configId: configId); + + /// 日期选择器的背景色 + /// 默认为 [PICKER_BACKGROUND_COLOR] + Color? _backgroundColor; + + /// 取消文字的样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _cancelTextStyle; + + /// 确认文字的样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _confirmTextStyle; + + /// 标题文字的样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWidget:FontWeight.w600, + /// ) + BrnTextStyle? _titleTextStyle; + + /// 日期选择器的高度 + /// 默认为 [PICKER_HEIGHT] + double? _pickerHeight; + + /// 日期选择器标题的高度 + /// 默认为 [PICKER_TITLE_HEIGHT] + double? _titleHeight; + + /// 日期选择器列表的高度 + /// 默认为 [PICKER_ITEM_HEIGHT] + double? _itemHeight; + + /// 日期选择器列表的文字样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// ) + BrnTextStyle? _itemTextStyle; + + /// 日期选择器列表选中的文字样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeHead], + /// fontWidget: FontWeight.w600, + /// ) + BrnTextStyle? _itemTextSelectedStyle; + + Color? _dividerColor; + double? _cornerRadius; + + Color get backgroundColor => + _backgroundColor ?? + BrnDefaultConfigUtils.defaultPickerConfig.backgroundColor; + + BrnTextStyle get cancelTextStyle => + _cancelTextStyle ?? + BrnDefaultConfigUtils.defaultPickerConfig.cancelTextStyle; + + BrnTextStyle get confirmTextStyle => + _confirmTextStyle ?? + BrnDefaultConfigUtils.defaultPickerConfig.confirmTextStyle; + + BrnTextStyle get titleTextStyle => + _titleTextStyle ?? + BrnDefaultConfigUtils.defaultPickerConfig.titleTextStyle; + + double get pickerHeight => + _pickerHeight ?? BrnDefaultConfigUtils.defaultPickerConfig.pickerHeight; + + double get titleHeight => + _titleHeight ?? BrnDefaultConfigUtils.defaultPickerConfig.titleHeight; + + double get itemHeight => + _itemHeight ?? BrnDefaultConfigUtils.defaultPickerConfig.itemHeight; + + BrnTextStyle get itemTextStyle => + _itemTextStyle ?? BrnDefaultConfigUtils.defaultPickerConfig.itemTextStyle; + + BrnTextStyle get itemTextSelectedStyle => + _itemTextSelectedStyle ?? + BrnDefaultConfigUtils.defaultPickerConfig.itemTextSelectedStyle; + + Color get dividerColor => + _dividerColor ?? BrnDefaultConfigUtils.defaultPickerConfig.dividerColor; + + double get cornerRadius => + _cornerRadius ?? BrnDefaultConfigUtils.defaultPickerConfig.cornerRadius; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局组件配置 BrnPickerConfig pickerConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .pickerConfig; - this.backgroundColor ??= pickerConfig.backgroundColor; - this.pickerHeight ??= pickerConfig.pickerHeight; - this.titleHeight ??= pickerConfig.titleHeight; - this.itemHeight ??= pickerConfig.itemHeight; - this.dividerColor ??= pickerConfig.dividerColor; - this.cornerRadius ??= pickerConfig.cornerRadius; - - this.titleTextStyle = pickerConfig.titleTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.titleTextStyle)); - - this.cancelTextStyle = pickerConfig.cancelTextStyle - .merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead)) - .merge(this.cancelTextStyle); - - this.confirmTextStyle = pickerConfig.confirmTextStyle.merge(BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.confirmTextStyle)); - - this.itemTextStyle = pickerConfig.itemTextStyle.merge(BrnTextStyle( + _backgroundColor ??= pickerConfig.backgroundColor; + _pickerHeight ??= pickerConfig.pickerHeight; + _titleHeight ??= pickerConfig.titleHeight; + _itemHeight ??= pickerConfig.itemHeight; + _dividerColor ??= pickerConfig.dividerColor; + _cornerRadius ??= pickerConfig.cornerRadius; + _titleTextStyle = pickerConfig.titleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_titleTextStyle), + ); + _cancelTextStyle = pickerConfig.cancelTextStyle + .merge( + BrnTextStyle( color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeHead) - .merge(this.itemTextStyle)); - - this.itemTextSelectedStyle = pickerConfig.itemTextSelectedStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeHead) - .merge(this.itemTextSelectedStyle)); + fontSize: commonConfig.fontSizeSubHead, + ), + ) + .merge(_cancelTextStyle); + _confirmTextStyle = pickerConfig.confirmTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_confirmTextStyle), + ); + _itemTextStyle = pickerConfig.itemTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeHead, + ).merge(_itemTextStyle), + ); + _itemTextSelectedStyle = pickerConfig.itemTextSelectedStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeHead, + ).merge(_itemTextSelectedStyle), + ); } - BrnPickerConfig copyWith( - {Color backgroundColor, - BrnTextStyle cancelTextStyle, - BrnTextStyle confirmTextStyle, - BrnTextStyle titleTextStyle, - double pickerHeight, - double titleHeight, - double itemHeight, - BrnTextStyle itemTextStyle, - BrnTextStyle itemTextSelectedStyle, - Color dividerColor, - double cornerRadius}) { + BrnPickerConfig copyWith({ + Color? backgroundColor, + BrnTextStyle? cancelTextStyle, + BrnTextStyle? confirmTextStyle, + BrnTextStyle? titleTextStyle, + double? pickerHeight, + double? titleHeight, + double? itemHeight, + BrnTextStyle? itemTextStyle, + BrnTextStyle? itemTextSelectedStyle, + Color? dividerColor, + double? cornerRadius, + }) { return BrnPickerConfig( - backgroundColor: backgroundColor ?? this.backgroundColor, - cancelTextStyle: cancelTextStyle ?? this.cancelTextStyle, - confirmTextStyle: confirmTextStyle ?? this.confirmTextStyle, - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - pickerHeight: pickerHeight ?? this.pickerHeight, - titleHeight: titleHeight ?? this.titleHeight, - itemHeight: itemHeight ?? this.itemHeight, - itemTextStyle: itemTextStyle ?? this.itemTextStyle, - itemTextSelectedStyle: - itemTextSelectedStyle ?? this.itemTextSelectedStyle, - dividerColor: dividerColor ?? this.dividerColor, - cornerRadius: cornerRadius ?? this.cornerRadius, + backgroundColor: backgroundColor ?? _backgroundColor, + cancelTextStyle: cancelTextStyle ?? _cancelTextStyle, + confirmTextStyle: confirmTextStyle ?? _confirmTextStyle, + titleTextStyle: titleTextStyle ?? _titleTextStyle, + pickerHeight: pickerHeight ?? _pickerHeight, + titleHeight: titleHeight ?? _titleHeight, + itemHeight: itemHeight ?? _itemHeight, + itemTextStyle: itemTextStyle ?? _itemTextStyle, + itemTextSelectedStyle: itemTextSelectedStyle ?? _itemTextSelectedStyle, + dividerColor: dividerColor ?? _dividerColor, + cornerRadius: cornerRadius ?? _cornerRadius, ); } - BrnPickerConfig merge(BrnPickerConfig other) { + BrnPickerConfig merge(BrnPickerConfig? other) { if (other == null) return this; return copyWith( - backgroundColor: other.backgroundColor, - cancelTextStyle: this.cancelTextStyle?.merge(other.cancelTextStyle) ?? - other.cancelTextStyle, - confirmTextStyle: - this.confirmTextStyle?.merge(other.confirmTextStyle) ?? - other.confirmTextStyle, - titleTextStyle: this.titleTextStyle?.merge(other.titleTextStyle) ?? - other.titleTextStyle, - pickerHeight: other.pickerHeight, - titleHeight: other.titleHeight, - itemHeight: other.itemHeight, - itemTextStyle: this.itemTextStyle?.merge(other.itemTextStyle) ?? - other.itemTextStyle, - itemTextSelectedStyle: - this.itemTextSelectedStyle?.merge(other.itemTextSelectedStyle) ?? - other.itemTextSelectedStyle, - dividerColor: other.dividerColor, - cornerRadius: other.cornerRadius); + backgroundColor: other._backgroundColor, + cancelTextStyle: cancelTextStyle.merge(other._cancelTextStyle), + confirmTextStyle: confirmTextStyle.merge(other._confirmTextStyle), + titleTextStyle: titleTextStyle.merge(other._titleTextStyle), + pickerHeight: other._pickerHeight, + titleHeight: other._titleHeight, + itemHeight: other._itemHeight, + itemTextStyle: itemTextStyle.merge(other._itemTextStyle), + itemTextSelectedStyle: + itemTextSelectedStyle.merge(other._itemTextSelectedStyle), + dividerColor: other._dividerColor, + cornerRadius: other._cornerRadius, + ); } } diff --git a/lib/src/theme/configs/brn_selection_config.dart b/lib/src/theme/configs/brn_selection_config.dart index 190f3266..1dc0019b 100644 --- a/lib/src/theme/configs/brn_selection_config.dart +++ b/lib/src/theme/configs/brn_selection_config.dart @@ -1,378 +1,577 @@ -import 'dart:ui'; - import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; +import 'package:flutter/painting.dart'; /// 筛选项 配置类 - class BrnSelectionConfig extends BrnBaseConfig { + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.defaultSelectionConfig] + BrnSelectionConfig({ + BrnTextStyle? menuNormalTextStyle, + BrnTextStyle? menuSelectedTextStyle, + BrnTextStyle? tagNormalTextStyle, + BrnTextStyle? tagSelectedTextStyle, + double? tagRadius, + Color? tagNormalBackgroundColor, + Color? tagSelectedBackgroundColor, + BrnTextStyle? hintTextStyle, + BrnTextStyle? rangeTitleTextStyle, + BrnTextStyle? inputTextStyle, + BrnTextStyle? itemNormalTextStyle, + BrnTextStyle? itemSelectedTextStyle, + BrnTextStyle? itemBoldTextStyle, + Color? deepNormalBgColor, + Color? deepSelectBgColor, + Color? middleNormalBgColor, + Color? middleSelectBgColor, + Color? lightNormalBgColor, + Color? lightSelectBgColor, + BrnTextStyle? resetTextStyle, + BrnTextStyle? titleForMoreTextStyle, + BrnTextStyle? optionTextStyle, + BrnTextStyle? moreTextStyle, + BrnTextStyle? flayerNormalTextStyle, + BrnTextStyle? flayerSelectedTextStyle, + BrnTextStyle? flayerBoldTextStyle, + String configId = GLOBAL_CONFIG_ID, + }) : _menuNormalTextStyle = menuNormalTextStyle, + _menuSelectedTextStyle = menuSelectedTextStyle, + _tagNormalTextStyle = tagNormalTextStyle, + _tagSelectedTextStyle = tagSelectedTextStyle, + _tagRadius = tagRadius, + _tagNormalBackgroundColor = tagNormalBackgroundColor, + _tagSelectedBackgroundColor = tagSelectedBackgroundColor, + _hintTextStyle = hintTextStyle, + _rangeTitleTextStyle = rangeTitleTextStyle, + _inputTextStyle = inputTextStyle, + _itemNormalTextStyle = itemNormalTextStyle, + _itemSelectedTextStyle = itemSelectedTextStyle, + _itemBoldTextStyle = itemBoldTextStyle, + _deepNormalBgColor = deepNormalBgColor, + _deepSelectBgColor = deepSelectBgColor, + _middleNormalBgColor = middleNormalBgColor, + _middleSelectBgColor = middleSelectBgColor, + _lightNormalBgColor = lightNormalBgColor, + _lightSelectBgColor = lightSelectBgColor, + _resetTextStyle = resetTextStyle, + _titleForMoreTextStyle = titleForMoreTextStyle, + _optionTextStyle = optionTextStyle, + _moreTextStyle = moreTextStyle, + _flayerNormalTextStyle = flayerNormalTextStyle, + _flayerSelectedTextStyle = flayerSelectedTextStyle, + _flayerBoldTextStyle = flayerBoldTextStyle, + super(configId: configId); + /// menu 正常文本样式 - /// TextStyle(fontWeight: FontWeight.normal ,fontSize: [BrnCommonConfig.fontSizeBase],color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle menuNormalTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.normal, + /// ) + BrnTextStyle? _menuNormalTextStyle; /// menu 选中文本样式 - /// TextStyle(fontWeight: FontWeight.w600,fontSize: [BrnCommonConfig.fontSizeBase],color: [BrnCommonConfig.brandPrimary]) - BrnTextStyle menuSelectedTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _menuSelectedTextStyle; /// tag 正常文本样式 - /// TextStyle(fontWeight: FontWeight.w400,fontSize: [BrnCommonConfig.fontSizeCaption],color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle tagNormalTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// fontWeight: FontWeight.w400, + /// ) + BrnTextStyle? _tagNormalTextStyle; /// tag 选中文本样式 - /// TextStyle(fontWeight: FontWeight.w600,fontSize: [BrnCommonConfig.fontSizeCaption],color: [BrnCommonConfig.brandPrimary]) - BrnTextStyle tagSelectedTextStyle; - - /// tag圆角 - /// default value is [BrnCommonConfig.radiusSm] - double tagRadius; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _tagSelectedTextStyle; + + /// tag 圆角 + /// 默认为 [BrnCommonConfig.radiusSm] + double? _tagRadius; /// tag 正常背景色 - /// default value is [BrnCommonConfig.fillBody] - Color tagNormalBackgroundColor; + /// 默认为 [BrnCommonConfig.fillBody] + Color? _tagNormalBackgroundColor; /// tag 选中背景色 - /// [BrnCommonConfig.brandPrimary].withOpacity(0.12) - Color tagSelectedBackgroundColor; + /// 默认为 [BrnCommonConfig.brandPrimary].withOpacity(0.12) + Color? _tagSelectedBackgroundColor; /// 输入选项标题文本样式 - /// TextStyle(fontWeight : FontWeight.w600,fontSize: [BrnCommonConfig.fontSizeSubHead], color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle rangeTitleTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _rangeTitleTextStyle; /// 输入提示文本样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase], color: [BrnCommonConfig.colorTextHint]) - BrnTextStyle hintTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextHint], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _hintTextStyle; /// 输入框默认文本样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase], color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle inputTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _inputTextStyle; /// item 正常字体样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase],color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle itemNormalTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _itemNormalTextStyle; /// item 选中文本样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase],fontWeight: FontWeight.w600,color: [BrnCommonConfig.brandPrimary]) - BrnTextStyle itemSelectedTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemSelectedTextStyle; /// item 仅加粗样式 - /// TextStyle(fontSize: [BrnCommonConfig.fontSizeBase],fontWeight: FontWeight.w600,color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle itemBoldTextStyle; - - /// 三级item 背景色 - /// Color(0xFFF0F0F0) - Color deepNormalBgColor; - - /// 三级item 选中背景色 - /// Color(0xFFF8F8F8) - Color deepSelectBgColor; - - /// 二级item 背景色 - /// Color(0xFFF8F8F8) - Color middleNormalBgColor; - - /// 二级item 选中背景色 - /// Colors.white - Color middleSelectBgColor; - - /// 一级item 背景色 - /// Colors.white - Color lightNormalBgColor; - - /// 一级item 选中背景色 - /// Colors.white - Color lightSelectBgColor; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _itemBoldTextStyle; + + /// 三级 item 背景色 + /// 默认为 Color(0xFFF0F0F0) + Color? _deepNormalBgColor; + + /// 三级 item 选中背景色 + /// 默认为 Color(0xFFF8F8F8) + Color? _deepSelectBgColor; + + /// 二级 item 背景色 + /// 默认为 Color(0xFFF8F8F8) + Color? _middleNormalBgColor; + + /// 二级 item 选中背景色 + /// 默认为 Colors.white + Color? _middleSelectBgColor; + + /// 一级 item 背景色 + /// 默认为 Colors.white + Color? _lightNormalBgColor; + + /// 一级 item 选中背景色 + /// 默认为 Colors.white + Color? _lightSelectBgColor; /// 重置按钮颜色 - /// TextStyle(color: [BrnCommonConfig.colorTextImportant],fontSize: [BrnCommonConfig.fontSizeCaption]) - BrnTextStyle resetTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextImportant], + /// fontSize: [BrnCommonConfig.fontSizeCaption] + /// ) + BrnTextStyle? _resetTextStyle; /// 更多筛选-标题文本样式 - /// TextStyle(color: [BrnCommonConfig.colorTextBase],fontSize: [BrnCommonConfig.fontSizeBase],fontWeight: FontWeight.w600) - BrnTextStyle titleForMoreTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _titleForMoreTextStyle; /// 选项-显示文本 - /// TextStyle(color: [BrnCommonConfig.brandPrimary],fontSize: [BrnCommonConfig.fontSizeBase]) - BrnTextStyle optionTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeBase], + /// ) + BrnTextStyle? _optionTextStyle; /// 更多文本样式 - /// TextStyle(color: [BrnCommonConfig.colorTextSecondary],fontSize: [BrnCommonConfig.fontSizeCaption]) - BrnTextStyle moreTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextSecondary], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// ) + BrnTextStyle? _moreTextStyle; /// 跳转二级页-正常文本样式 - /// TextStyle(color: [BrnCommonConfig.colorTextBase],fontSize: [BrnCommonConfig.fontSizeSubHead],fontWeight: FontWeight.normal) - BrnTextStyle flayNormalTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.normal, + /// ) + BrnTextStyle? _flayerNormalTextStyle; /// 跳转二级页-选中文本样式 - /// TextStyle(color: [BrnCommonConfig.brandPrimary],fontSize: [BrnCommonConfig.fontSizeSubHead],fontWeight: FontWeight.w600) - BrnTextStyle flatSelectedTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _flayerSelectedTextStyle; /// 跳转二级页-加粗文本样式 - /// TextStyle(color: [BrnCommonConfig.colorTextBase],fontSize: [BrnCommonConfig.fontSizeSubHead],fontWeight: FontWeight.w600) - BrnTextStyle flatBoldTextStyle; - - BrnSelectionConfig( - {this.menuNormalTextStyle, - this.menuSelectedTextStyle, - this.tagNormalTextStyle, - this.tagSelectedTextStyle, - this.tagRadius, - this.tagNormalBackgroundColor, - this.tagSelectedBackgroundColor, - this.hintTextStyle, - this.rangeTitleTextStyle, - this.inputTextStyle, - this.itemNormalTextStyle, - this.itemSelectedTextStyle, - this.itemBoldTextStyle, - this.deepNormalBgColor, - this.deepSelectBgColor, - this.middleNormalBgColor, - this.middleSelectBgColor, - this.lightNormalBgColor, - this.lightSelectBgColor, - this.resetTextStyle, - this.titleForMoreTextStyle, - this.optionTextStyle, - this.moreTextStyle, - this.flayNormalTextStyle, - this.flatSelectedTextStyle, - this.flatBoldTextStyle, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// fontWeight: FontWeight.w600 + /// ) + BrnTextStyle? _flayerBoldTextStyle; + + BrnTextStyle get menuNormalTextStyle => + _menuNormalTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.menuNormalTextStyle; + + BrnTextStyle get menuSelectedTextStyle => + _menuSelectedTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.menuSelectedTextStyle; + + BrnTextStyle get tagNormalTextStyle => + _tagNormalTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.tagNormalTextStyle; + + BrnTextStyle get tagSelectedTextStyle => + _tagSelectedTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.tagSelectedTextStyle; + + double get tagRadius => + _tagRadius ?? BrnDefaultConfigUtils.defaultSelectionConfig.tagRadius; + + Color get tagNormalBackgroundColor => + _tagNormalBackgroundColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.tagNormalBackgroundColor; + + Color get tagSelectedBackgroundColor => + _tagSelectedBackgroundColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.tagSelectedBackgroundColor; + + BrnTextStyle get rangeTitleTextStyle => + _rangeTitleTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.rangeTitleTextStyle; + + BrnTextStyle get hintTextStyle => + _hintTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.hintTextStyle; + + BrnTextStyle get inputTextStyle => + _inputTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.inputTextStyle; + + BrnTextStyle get itemNormalTextStyle => + _itemNormalTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.itemNormalTextStyle; + + BrnTextStyle get itemSelectedTextStyle => + _itemSelectedTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.itemSelectedTextStyle; + + BrnTextStyle get itemBoldTextStyle => + _itemBoldTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.itemBoldTextStyle; + + Color get deepNormalBgColor => + _deepNormalBgColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.deepNormalBgColor; + + Color get deepSelectBgColor => + _deepSelectBgColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.deepSelectBgColor; + + Color get middleNormalBgColor => + _middleNormalBgColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.middleNormalBgColor; + + Color get middleSelectBgColor => + _middleSelectBgColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.middleSelectBgColor; + + Color get lightNormalBgColor => + _lightNormalBgColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.lightNormalBgColor; + + Color get lightSelectBgColor => + _lightSelectBgColor ?? + BrnDefaultConfigUtils.defaultSelectionConfig.lightSelectBgColor; + + BrnTextStyle get resetTextStyle => + _resetTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.resetTextStyle; + + BrnTextStyle get titleForMoreTextStyle => + _titleForMoreTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.titleForMoreTextStyle; + + BrnTextStyle get optionTextStyle => + _optionTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.optionTextStyle; + + BrnTextStyle get moreTextStyle => + _moreTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.moreTextStyle; + + BrnTextStyle get flayerNormalTextStyle => + _flayerNormalTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.flayerNormalTextStyle; + + BrnTextStyle get flayerSelectedTextStyle => + _flayerSelectedTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.flayerSelectedTextStyle; + + BrnTextStyle get flayerBoldTextStyle => + _flayerBoldTextStyle ?? + BrnDefaultConfigUtils.defaultSelectionConfig.flayerBoldTextStyle; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); /// 用户全局筛选配置 BrnSelectionConfig selectionConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .selectionConfig; - lightSelectBgColor ??= selectionConfig.lightSelectBgColor; - - lightNormalBgColor ??= selectionConfig.lightNormalBgColor; - - middleSelectBgColor ??= selectionConfig.middleSelectBgColor; - - middleNormalBgColor ??= selectionConfig.middleNormalBgColor; - - deepSelectBgColor ??= selectionConfig.deepSelectBgColor; - - deepNormalBgColor ??= selectionConfig.deepNormalBgColor; - - tagSelectedBackgroundColor ??= commonConfig.brandPrimary.withOpacity(0.12); - - tagNormalBackgroundColor ??= commonConfig.fillBody; - - tagRadius ??= commonConfig.radiusSm; - - this.flatBoldTextStyle = selectionConfig.flatBoldTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.flatBoldTextStyle)); - - this.flatSelectedTextStyle = selectionConfig.flatSelectedTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.flatSelectedTextStyle)); - - this.flayNormalTextStyle = selectionConfig.flayNormalTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.flayNormalTextStyle)); - - this.moreTextStyle = selectionConfig.moreTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextSecondary, - fontSize: commonConfig.fontSizeCaption) - .merge(this.moreTextStyle)); - - this.optionTextStyle = selectionConfig.optionTextStyle.merge(BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeBase) - .merge(this.optionTextStyle)); - - this.titleForMoreTextStyle = selectionConfig.titleForMoreTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.titleForMoreTextStyle)); - - this.resetTextStyle = selectionConfig.resetTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextImportant, - fontSize: commonConfig.fontSizeCaption) - .merge(this.resetTextStyle)); - - this.itemBoldTextStyle = selectionConfig.itemBoldTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.itemBoldTextStyle)); - - this.itemSelectedTextStyle = selectionConfig.itemSelectedTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeBase) - .merge(this.itemSelectedTextStyle)); - - this.itemNormalTextStyle = selectionConfig.itemNormalTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.itemNormalTextStyle)); - - this.inputTextStyle = selectionConfig.inputTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.inputTextStyle)); - - this.hintTextStyle = selectionConfig.hintTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextHint, - fontSize: commonConfig.fontSizeBase) - .merge(this.hintTextStyle)); - - this.rangeTitleTextStyle = selectionConfig.rangeTitleTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.rangeTitleTextStyle)); - - this.tagSelectedTextStyle = selectionConfig.tagSelectedTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeCaption) - .merge(this.tagSelectedTextStyle)); - - this.tagNormalTextStyle = selectionConfig.tagNormalTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeCaption) - .merge(this.tagNormalTextStyle)); - - this.menuNormalTextStyle = selectionConfig.menuNormalTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeBase) - .merge(this.menuNormalTextStyle)); - - this.menuSelectedTextStyle = selectionConfig.menuSelectedTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeBase) - .merge(this.menuSelectedTextStyle)); + _lightSelectBgColor ??= selectionConfig._lightSelectBgColor; + _lightNormalBgColor ??= selectionConfig._lightNormalBgColor; + _middleSelectBgColor ??= selectionConfig._middleSelectBgColor; + _middleNormalBgColor ??= selectionConfig._middleNormalBgColor; + _deepSelectBgColor ??= selectionConfig._deepSelectBgColor; + _deepNormalBgColor ??= selectionConfig._deepNormalBgColor; + _tagSelectedBackgroundColor ??= + commonConfig.brandPrimary.withOpacity(0.12); + _tagNormalBackgroundColor ??= commonConfig.fillBody; + _tagRadius ??= commonConfig.radiusSm; + _flayerBoldTextStyle = selectionConfig.flayerBoldTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_flayerBoldTextStyle), + ); + _flayerSelectedTextStyle = selectionConfig.flayerSelectedTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_flayerSelectedTextStyle), + ); + _flayerNormalTextStyle = selectionConfig.flayerNormalTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_flayerNormalTextStyle), + ); + _moreTextStyle = selectionConfig.moreTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextSecondary, + fontSize: commonConfig.fontSizeCaption, + ).merge(_moreTextStyle), + ); + _optionTextStyle = selectionConfig.optionTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeBase, + ).merge(_optionTextStyle), + ); + _titleForMoreTextStyle = selectionConfig.titleForMoreTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_titleForMoreTextStyle), + ); + _resetTextStyle = selectionConfig.resetTextStyle.merge(BrnTextStyle( + color: commonConfig.colorTextImportant, + fontSize: commonConfig.fontSizeCaption, + ).merge(_resetTextStyle)); + _itemBoldTextStyle = selectionConfig.itemBoldTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_itemBoldTextStyle), + ); + _itemSelectedTextStyle = selectionConfig.itemSelectedTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeBase, + ).merge(_itemSelectedTextStyle), + ); + _itemNormalTextStyle = selectionConfig.itemNormalTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_itemNormalTextStyle), + ); + _inputTextStyle = selectionConfig.inputTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_inputTextStyle), + ); + _hintTextStyle = selectionConfig.hintTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextHint, + fontSize: commonConfig.fontSizeBase, + ).merge(_hintTextStyle), + ); + _rangeTitleTextStyle = selectionConfig.rangeTitleTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_rangeTitleTextStyle), + ); + _tagSelectedTextStyle = selectionConfig.tagSelectedTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeCaption, + ).merge(_tagSelectedTextStyle), + ); + _tagNormalTextStyle = selectionConfig.tagNormalTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeCaption, + ).merge(_tagNormalTextStyle), + ); + _menuNormalTextStyle = selectionConfig.menuNormalTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeBase, + ).merge(_menuNormalTextStyle), + ); + _menuSelectedTextStyle = selectionConfig.menuSelectedTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeBase, + ).merge(_menuSelectedTextStyle), + ); } BrnSelectionConfig copyWith({ - BrnTextStyle menuNormalTextStyle, - BrnTextStyle menuSelectedTextStyle, - BrnTextStyle tagTextStyle, - BrnTextStyle tagSelectedTextStyle, - double tagRadius, - Color tagBackgroundColor, - Color tagSelectedBackgroundColor, - BrnTextStyle hintTextStyle, - BrnTextStyle rangeTitleTextStyle, - BrnTextStyle inputTextStyle, - BrnTextStyle itemNormalTextStyle, - BrnTextStyle itemSelectedTextStyle, - BrnTextStyle itemBoldTextStyle, - Color deepNormalBgColor, - Color deepSelectBgColor, - Color middleNormalBgColor, - Color middleSelectBgColor, - Color lightNormalBgColor, - Color lightSelectBgColor, - BrnTextStyle resetTextStyle, - BrnTextStyle titleForMoreTextStyle, - BrnTextStyle optionTextStyle, - BrnTextStyle moreTextStyle, - BrnTextStyle flayNormalTextStyle, - BrnTextStyle flatSelectedTextStyle, - BrnTextStyle flatBoldTextStyle, + BrnTextStyle? menuNormalTextStyle, + BrnTextStyle? menuSelectedTextStyle, + BrnTextStyle? tagTextStyle, + BrnTextStyle? tagSelectedTextStyle, + double? tagRadius, + Color? tagBackgroundColor, + Color? tagSelectedBackgroundColor, + BrnTextStyle? hintTextStyle, + BrnTextStyle? rangeTitleTextStyle, + BrnTextStyle? inputTextStyle, + BrnTextStyle? itemNormalTextStyle, + BrnTextStyle? itemSelectedTextStyle, + BrnTextStyle? itemBoldTextStyle, + Color? deepNormalBgColor, + Color? deepSelectBgColor, + Color? middleNormalBgColor, + Color? middleSelectBgColor, + Color? lightNormalBgColor, + Color? lightSelectBgColor, + BrnTextStyle? resetTextStyle, + BrnTextStyle? titleForMoreTextStyle, + BrnTextStyle? optionTextStyle, + BrnTextStyle? moreTextStyle, + BrnTextStyle? flayerNormalTextStyle, + BrnTextStyle? flayerSelectedTextStyle, + BrnTextStyle? flayerBoldTextStyle, }) { return BrnSelectionConfig( - menuNormalTextStyle: menuNormalTextStyle ?? this.menuNormalTextStyle, - menuSelectedTextStyle: - menuSelectedTextStyle ?? this.menuSelectedTextStyle, - tagNormalTextStyle: tagTextStyle ?? this.tagNormalTextStyle, - tagSelectedTextStyle: tagSelectedTextStyle ?? this.tagSelectedTextStyle, - tagRadius: tagRadius ?? this.tagRadius, - tagNormalBackgroundColor: - tagBackgroundColor ?? this.tagNormalBackgroundColor, - tagSelectedBackgroundColor: - tagSelectedBackgroundColor ?? this.tagSelectedBackgroundColor, - hintTextStyle: hintTextStyle ?? this.hintTextStyle, - rangeTitleTextStyle: rangeTitleTextStyle ?? this.rangeTitleTextStyle, - inputTextStyle: inputTextStyle ?? this.inputTextStyle, - itemNormalTextStyle: itemNormalTextStyle ?? this.itemNormalTextStyle, - itemSelectedTextStyle: - itemSelectedTextStyle ?? this.itemSelectedTextStyle, - itemBoldTextStyle: itemBoldTextStyle ?? this.itemBoldTextStyle, - deepNormalBgColor: deepNormalBgColor ?? this.deepNormalBgColor, - deepSelectBgColor: deepSelectBgColor ?? this.deepSelectBgColor, - middleNormalBgColor: middleNormalBgColor ?? this.middleNormalBgColor, - middleSelectBgColor: middleSelectBgColor ?? this.middleSelectBgColor, - lightNormalBgColor: lightNormalBgColor ?? this.lightNormalBgColor, - lightSelectBgColor: lightSelectBgColor ?? this.lightSelectBgColor, - resetTextStyle: resetTextStyle ?? this.resetTextStyle, - titleForMoreTextStyle: - titleForMoreTextStyle ?? this.titleForMoreTextStyle, - optionTextStyle: optionTextStyle ?? this.optionTextStyle, - moreTextStyle: moreTextStyle ?? this.moreTextStyle, - flayNormalTextStyle: flayNormalTextStyle ?? this.flayNormalTextStyle, - flatSelectedTextStyle: - flatSelectedTextStyle ?? this.flatSelectedTextStyle, - flatBoldTextStyle: flatBoldTextStyle ?? this.flatBoldTextStyle); + menuNormalTextStyle: menuNormalTextStyle ?? _menuNormalTextStyle, + menuSelectedTextStyle: menuSelectedTextStyle ?? _menuSelectedTextStyle, + tagNormalTextStyle: tagTextStyle ?? _tagNormalTextStyle, + tagSelectedTextStyle: tagSelectedTextStyle ?? _tagSelectedTextStyle, + tagRadius: tagRadius ?? _tagRadius, + tagNormalBackgroundColor: tagBackgroundColor ?? _tagNormalBackgroundColor, + tagSelectedBackgroundColor: + tagSelectedBackgroundColor ?? _tagSelectedBackgroundColor, + hintTextStyle: hintTextStyle ?? _hintTextStyle, + rangeTitleTextStyle: rangeTitleTextStyle ?? _rangeTitleTextStyle, + inputTextStyle: inputTextStyle ?? _inputTextStyle, + itemNormalTextStyle: itemNormalTextStyle ?? _itemNormalTextStyle, + itemSelectedTextStyle: itemSelectedTextStyle ?? _itemSelectedTextStyle, + itemBoldTextStyle: itemBoldTextStyle ?? _itemBoldTextStyle, + deepNormalBgColor: deepNormalBgColor ?? _deepNormalBgColor, + deepSelectBgColor: deepSelectBgColor ?? _deepSelectBgColor, + middleNormalBgColor: middleNormalBgColor ?? _middleNormalBgColor, + middleSelectBgColor: middleSelectBgColor ?? _middleSelectBgColor, + lightNormalBgColor: lightNormalBgColor ?? _lightNormalBgColor, + lightSelectBgColor: lightSelectBgColor ?? _lightSelectBgColor, + resetTextStyle: resetTextStyle ?? _resetTextStyle, + titleForMoreTextStyle: titleForMoreTextStyle ?? _titleForMoreTextStyle, + optionTextStyle: optionTextStyle ?? _optionTextStyle, + moreTextStyle: moreTextStyle ?? _moreTextStyle, + flayerNormalTextStyle: flayerNormalTextStyle ?? _flayerNormalTextStyle, + flayerSelectedTextStyle: + flayerSelectedTextStyle ?? _flayerSelectedTextStyle, + flayerBoldTextStyle: flayerBoldTextStyle ?? _flayerBoldTextStyle, + ); } BrnSelectionConfig merge(BrnSelectionConfig other) { return copyWith( - menuNormalTextStyle: this.menuNormalTextStyle?.merge(other.menuNormalTextStyle) ?? - other.menuNormalTextStyle, - menuSelectedTextStyle: - this.menuSelectedTextStyle?.merge(other.menuSelectedTextStyle) ?? - other.menuSelectedTextStyle, - tagTextStyle: this.tagNormalTextStyle?.merge(other.tagNormalTextStyle) ?? - other.tagNormalTextStyle, - tagSelectedTextStyle: - this.tagSelectedTextStyle?.merge(other.tagSelectedTextStyle) ?? - other.tagSelectedTextStyle, - tagRadius: other.tagRadius, - tagBackgroundColor: other.tagNormalBackgroundColor, - tagSelectedBackgroundColor: other.tagSelectedBackgroundColor, - hintTextStyle: this.hintTextStyle?.merge(other.hintTextStyle) ?? - other.hintTextStyle, - rangeTitleTextStyle: this.rangeTitleTextStyle?.merge(other.rangeTitleTextStyle) ?? - other.rangeTitleTextStyle, - inputTextStyle: this.inputTextStyle?.merge(other.inputTextStyle) ?? - other.inputTextStyle, - itemNormalTextStyle: - this.itemNormalTextStyle?.merge(other.itemNormalTextStyle) ?? - other.itemNormalTextStyle, - itemSelectedTextStyle: - this.itemSelectedTextStyle?.merge(other.itemSelectedTextStyle) ?? - other.itemSelectedTextStyle, - itemBoldTextStyle: this.itemBoldTextStyle?.merge(other.itemBoldTextStyle) ?? - other.itemBoldTextStyle, - deepNormalBgColor: other.deepNormalBgColor, - deepSelectBgColor: other.deepSelectBgColor, - middleNormalBgColor: other.middleNormalBgColor, - middleSelectBgColor: other.middleSelectBgColor, - lightNormalBgColor: other.lightNormalBgColor, - lightSelectBgColor: other.lightSelectBgColor, - resetTextStyle: this.resetTextStyle?.merge(other.resetTextStyle) ?? other.resetTextStyle, - titleForMoreTextStyle: this.titleForMoreTextStyle?.merge(other.titleForMoreTextStyle) ?? other.titleForMoreTextStyle, - optionTextStyle: this.optionTextStyle?.merge(other.optionTextStyle) ?? other.optionTextStyle, - moreTextStyle: this.moreTextStyle?.merge(other.moreTextStyle) ?? other.moreTextStyle, - flayNormalTextStyle: this.flayNormalTextStyle?.merge(other.flayNormalTextStyle) ?? other.flayNormalTextStyle, - flatSelectedTextStyle: this.flatSelectedTextStyle?.merge(other.flatSelectedTextStyle) ?? other.flatSelectedTextStyle, - flatBoldTextStyle: this.flatBoldTextStyle?.merge(other.flatBoldTextStyle) ?? other.flatBoldTextStyle); + menuNormalTextStyle: menuNormalTextStyle.merge(other._menuNormalTextStyle), + menuSelectedTextStyle: + menuSelectedTextStyle.merge(other._menuSelectedTextStyle), + tagTextStyle: tagNormalTextStyle.merge(other._tagNormalTextStyle), + tagSelectedTextStyle: + tagSelectedTextStyle.merge(other._tagSelectedTextStyle), + tagRadius: other._tagRadius, + tagBackgroundColor: other._tagNormalBackgroundColor, + tagSelectedBackgroundColor: other._tagSelectedBackgroundColor, + hintTextStyle: hintTextStyle.merge(other._hintTextStyle), + rangeTitleTextStyle: rangeTitleTextStyle.merge(other._rangeTitleTextStyle), + inputTextStyle: inputTextStyle.merge(other._inputTextStyle), + itemNormalTextStyle: itemNormalTextStyle.merge(other._itemNormalTextStyle), + itemSelectedTextStyle: + itemSelectedTextStyle.merge(other._itemSelectedTextStyle), + itemBoldTextStyle: itemBoldTextStyle.merge(other._itemBoldTextStyle), + deepNormalBgColor: other._deepNormalBgColor, + deepSelectBgColor: other._deepSelectBgColor, + middleNormalBgColor: other._middleNormalBgColor, + middleSelectBgColor: other._middleSelectBgColor, + lightNormalBgColor: other._lightNormalBgColor, + lightSelectBgColor: other._lightSelectBgColor, + resetTextStyle: resetTextStyle.merge(other._resetTextStyle), + titleForMoreTextStyle: + titleForMoreTextStyle.merge(other._titleForMoreTextStyle), + optionTextStyle: optionTextStyle.merge(other._optionTextStyle), + moreTextStyle: moreTextStyle.merge(other._moreTextStyle), + flayerNormalTextStyle: + flayerNormalTextStyle.merge(other._flayerNormalTextStyle), + flayerSelectedTextStyle: + flayerSelectedTextStyle.merge(other._flayerSelectedTextStyle), + flayerBoldTextStyle: flayerBoldTextStyle.merge(other._flayerBoldTextStyle), + ); } } diff --git a/lib/src/theme/configs/brn_tabbar_config.dart b/lib/src/theme/configs/brn_tabbar_config.dart index 6c5145cc..457ae2c8 100644 --- a/lib/src/theme/configs/brn_tabbar_config.dart +++ b/lib/src/theme/configs/brn_tabbar_config.dart @@ -1,189 +1,272 @@ -import 'dart:ui'; - -import 'package:bruno/src/theme/brn_theme.dart'; +import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; +import 'package:bruno/src/theme/base/brn_text_style.dart'; +import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/theme/configs/brn_common_config.dart'; import 'package:flutter/material.dart'; /// TabBar配置类 class BrnTabBarConfig extends BrnBaseConfig { - ///遵循外部主题配置,Bruno默认配置[BrnDefaultConfigUtils.defaultNumberInfoConfig] + /// 遵循外部主题配置 + /// 默认为 [BrnDefaultConfigUtils.tabBarConfig] BrnTabBarConfig({ - this.tabHeight, - this.indicatorHeight, - this.indicatorWidth, - this.labelStyle, - this.unselectedLabelStyle, - this.backgroundColor, - this.tagNormalTextStyle, - this.tagNormalBgColor, - this.tagSelectedTextStyle, - this.tagSelectedBgColor, - this.tagRadius, - this.tagSpacing, - this.preLineTagCount, - this.tagHeight, - String configId: BrnThemeConfigurator.GLOBAL_CONFIG_ID, - }) : super(configId: configId); - - /// Tabbar的整体高度 - /// default value is 50 - double tabHeight; + double? tabHeight, + double? indicatorHeight, + double? indicatorWidth, + BrnTextStyle? labelStyle, + BrnTextStyle? unselectedLabelStyle, + Color? backgroundColor, + BrnTextStyle? tagNormalTextStyle, + Color? tagNormalBgColor, + BrnTextStyle? tagSelectedTextStyle, + Color? tagSelectedBgColor, + double? tagRadius, + double? tagSpacing, + int? preLineTagCount, + double? tagHeight, + String configId: GLOBAL_CONFIG_ID, + }) : _tabHeight = tabHeight, + _indicatorHeight = indicatorHeight, + _indicatorWidth = indicatorWidth, + _labelStyle = labelStyle, + _unselectedLabelStyle = unselectedLabelStyle, + _backgroundColor = backgroundColor, + _tagNormalTextStyle = tagNormalTextStyle, + _tagNormalBgColor = tagNormalBgColor, + _tagSelectedTextStyle = tagSelectedTextStyle, + _tagSelectedBgColor = tagSelectedBgColor, + _tagRadius = tagRadius, + _tagSpacing = tagSpacing, + _preLineTagCount = preLineTagCount, + _tagHeight = tagHeight, + super(configId: configId); + + /// TabBar 的整体高度 + /// 默认为 50 + double? _tabHeight; /// 指示器的高度 - /// default value is 2 - double indicatorHeight; + /// 默认为 2 + double? _indicatorHeight; /// 指示器的宽度 - /// default value is 24 - double indicatorWidth; + /// 默认为 24 + double? _indicatorWidth; - /// 选中Tab文本的样式 - /// default value is TextStyle(color:[BrnCommonConfig.brandPrimary],fontSize:[BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle labelStyle; + /// 选中 Tab 文本的样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _labelStyle; - /// 未选中Tab文本的样式 - /// default value is TextStyle(color:[BrnCommonConfig.colorTextBase],fontSize:[BrnCommonConfig.fontSizeSubHead]) - BrnTextStyle unselectedLabelStyle; + /// 未选中 Tab 文本的样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeSubHead], + /// ) + BrnTextStyle? _unselectedLabelStyle; /// 背景色 - /// default value is [BrnCommonConfig.fillBase] - Color backgroundColor; + /// 默认为 [BrnCommonConfig.fillBase] + Color? _backgroundColor; /// 标签字体样式 - /// default value is BrnTextStyle(color: [BrnCommonConfig.colorTextBase], fontSize: [BrnCommonConfig.fontSizeCaption]) - BrnTextStyle tagNormalTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// ) + BrnTextStyle? _tagNormalTextStyle; /// 标签背景色 - /// default value is [BrnCommonConfig.brandPrimary].withAlpha(0x14), - Color tagNormalBgColor; + /// 默认为 [BrnCommonConfig.brandPrimary].withAlpha(0x14), + Color? _tagNormalBgColor; /// 标签字体样式 - /// default value is BrnTextStyle(color:[BrnCommonConfig.brandPrimary], fontSize: [BrnCommonConfig.fontSizeCaption]) - BrnTextStyle tagSelectedTextStyle; + /// + /// BrnTextStyle( + /// color:[BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// ) + BrnTextStyle? _tagSelectedTextStyle; /// 标签选中背景色 - /// default value is [BrnCommonConfig.fillBody] - Color tagSelectedBgColor; + /// 默认为 [BrnCommonConfig.fillBody] + Color? _tagSelectedBgColor; /// tag圆角 - /// default value is [BrnCommonConfig.radiusSm] - double tagRadius; + /// 默认为 [BrnCommonConfig.radiusSm] + double? _tagRadius; /// tag间距 - /// default value is 12 - double tagSpacing; + /// 默认为 12 + double? _tagSpacing; /// 每行的tag数 - /// default value is 4 - int preLineTagCount; + /// 默认为 4 + int? _preLineTagCount; /// tag高度 - /// default value is 32 - double tagHeight; + /// 默认为 32 + double? _tagHeight; + + double get tabHeight => + _tabHeight ?? BrnDefaultConfigUtils.defaultTabBarConfig.tabHeight; + + double get indicatorHeight => + _indicatorHeight ?? + BrnDefaultConfigUtils.defaultTabBarConfig.indicatorHeight; + + double get indicatorWidth => + _indicatorWidth ?? + BrnDefaultConfigUtils.defaultTabBarConfig.indicatorWidth; + + BrnTextStyle get labelStyle => + _labelStyle ?? BrnDefaultConfigUtils.defaultTabBarConfig.labelStyle; + + BrnTextStyle get unselectedLabelStyle => + _unselectedLabelStyle ?? + BrnDefaultConfigUtils.defaultTabBarConfig.unselectedLabelStyle; + + Color get backgroundColor => + _backgroundColor ?? + BrnDefaultConfigUtils.defaultTabBarConfig.backgroundColor; + + BrnTextStyle get tagNormalTextStyle => + _tagNormalTextStyle ?? + BrnDefaultConfigUtils.defaultTabBarConfig.tagNormalTextStyle; + + Color get tagNormalBgColor => + _tagNormalBgColor ?? + BrnDefaultConfigUtils.defaultTabBarConfig.tagNormalBgColor; + + BrnTextStyle get tagSelectedTextStyle => + _tagSelectedTextStyle ?? + BrnDefaultConfigUtils.defaultTabBarConfig.tagSelectedTextStyle; + + Color get tagSelectedBgColor => + _tagSelectedBgColor ?? + BrnDefaultConfigUtils.defaultTabBarConfig.tagSelectedBgColor; + + double get tagRadius => + _tagRadius ?? BrnDefaultConfigUtils.defaultTabBarConfig.tagRadius; + + double get tagSpacing => + _tagSpacing ?? BrnDefaultConfigUtils.defaultTabBarConfig.tagSpacing; + + int get preLineTagCount => + _preLineTagCount ?? + BrnDefaultConfigUtils.defaultTabBarConfig.preLineTagCount; + + double get tagHeight => + _tagHeight ?? BrnDefaultConfigUtils.defaultTabBarConfig.tagHeight; @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); BrnTabBarConfig tabBarConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .tabBarConfig; - this.tabHeight ??= tabBarConfig.tabHeight; - this.indicatorHeight ??= tabBarConfig.indicatorHeight; - this.indicatorWidth ??= tabBarConfig.indicatorWidth; - - this.labelStyle = tabBarConfig.labelStyle.merge(BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.labelStyle)); - - this.unselectedLabelStyle = tabBarConfig.unselectedLabelStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeSubHead) - .merge(this.unselectedLabelStyle)); - - this.backgroundColor ??= tabBarConfig.backgroundColor; - - this.tagNormalTextStyle = tabBarConfig.tagNormalTextStyle.merge( - BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeCaption) - .merge(this.tagNormalTextStyle)); - - this.tagSelectedTextStyle = tabBarConfig.tagSelectedTextStyle.merge( - BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeCaption) - .merge(this.tagSelectedTextStyle)); - - this.tagNormalBgColor ??= tabBarConfig.tagNormalBgColor; - this.tagSelectedBgColor ??= tabBarConfig.tagSelectedBgColor; - this.tagRadius ??= commonConfig.radiusSm; - this.tagSpacing ??= tabBarConfig.tagSpacing; - this.preLineTagCount ??= tabBarConfig.preLineTagCount; - this.tagHeight ??= tabBarConfig.tagHeight; + _tabHeight ??= tabBarConfig._tabHeight; + _indicatorHeight ??= tabBarConfig._indicatorHeight; + _indicatorWidth ??= tabBarConfig._indicatorWidth; + _labelStyle = tabBarConfig.labelStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_labelStyle), + ); + _unselectedLabelStyle = tabBarConfig.unselectedLabelStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeSubHead, + ).merge(_unselectedLabelStyle), + ); + _backgroundColor ??= tabBarConfig._backgroundColor; + _tagNormalTextStyle = tabBarConfig.tagNormalTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeCaption, + ).merge(_tagNormalTextStyle), + ); + _tagSelectedTextStyle = tabBarConfig.tagSelectedTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeCaption, + ).merge(_tagSelectedTextStyle), + ); + _tagNormalBgColor ??= tabBarConfig._tagNormalBgColor; + _tagSelectedBgColor ??= tabBarConfig._tagSelectedBgColor; + _tagRadius ??= commonConfig.radiusSm; + _tagSpacing ??= tabBarConfig._tagSpacing; + _preLineTagCount ??= tabBarConfig._preLineTagCount; + _tagHeight ??= tabBarConfig._tagHeight; } BrnTabBarConfig copyWith({ - double tabHeight, - double indicatorHeight, - double indicatorWidth, - BrnTextStyle labelStyle, - BrnTextStyle unselectedLabelStyle, - Color backgroundColor, - BrnTextStyle tagNormalTextStyle, - Color tagNormalColor, - BrnTextStyle tagSelectedTextStyle, - Color tagSelectedColor, - double tagRadius, - double tagSpacing, - int preLineTagSize, - double tagHeight, + double? tabHeight, + double? indicatorHeight, + double? indicatorWidth, + BrnTextStyle? labelStyle, + BrnTextStyle? unselectedLabelStyle, + Color? backgroundColor, + BrnTextStyle? tagNormalTextStyle, + Color? tagNormalColor, + BrnTextStyle? tagSelectedTextStyle, + Color? tagSelectedColor, + double? tagRadius, + double? tagSpacing, + int? preLineTagSize, + double? tagHeight, }) { return BrnTabBarConfig( - tabHeight: tabHeight ?? this.tabHeight, - indicatorHeight: indicatorHeight ?? this.indicatorHeight, - indicatorWidth: indicatorWidth ?? this.indicatorWidth, - labelStyle: labelStyle ?? this.labelStyle, - unselectedLabelStyle: unselectedLabelStyle ?? this.unselectedLabelStyle, - backgroundColor: backgroundColor ?? this.backgroundColor, - tagNormalTextStyle: tagNormalTextStyle ?? this.tagNormalTextStyle, - tagNormalBgColor: tagNormalColor ?? this.tagNormalBgColor, - tagSelectedTextStyle: tagSelectedTextStyle ?? this.tagSelectedTextStyle, - tagSelectedBgColor: tagSelectedColor ?? this.tagSelectedBgColor, - tagRadius: tagRadius ?? this.tagRadius, - tagSpacing: tagSpacing ?? this.tagSpacing, - preLineTagCount: preLineTagSize ?? this.preLineTagCount, - tagHeight: tagHeight ?? this.tagHeight, + tabHeight: tabHeight ?? _tabHeight, + indicatorHeight: indicatorHeight ?? _indicatorHeight, + indicatorWidth: indicatorWidth ?? _indicatorWidth, + labelStyle: labelStyle ?? _labelStyle, + unselectedLabelStyle: unselectedLabelStyle ?? _unselectedLabelStyle, + backgroundColor: backgroundColor ?? _backgroundColor, + tagNormalTextStyle: tagNormalTextStyle ?? _tagNormalTextStyle, + tagNormalBgColor: tagNormalColor ?? _tagNormalBgColor, + tagSelectedTextStyle: tagSelectedTextStyle ?? _tagSelectedTextStyle, + tagSelectedBgColor: tagSelectedColor ?? _tagSelectedBgColor, + tagRadius: tagRadius ?? _tagRadius, + tagSpacing: tagSpacing ?? _tagSpacing, + preLineTagCount: preLineTagSize ?? _preLineTagCount, + tagHeight: tagHeight ?? _tagHeight, ); } - BrnTabBarConfig merge(BrnTabBarConfig other) { + BrnTabBarConfig merge(BrnTabBarConfig? other) { if (other == null) return this; return copyWith( - tabHeight: other.tabHeight, - indicatorHeight: other.indicatorHeight, - indicatorWidth: other.indicatorWidth, - labelStyle: this.labelStyle?.merge(other.labelStyle) ?? other.labelStyle, + tabHeight: other._tabHeight, + indicatorHeight: other._indicatorHeight, + indicatorWidth: other._indicatorWidth, + labelStyle: labelStyle.merge(other._labelStyle), unselectedLabelStyle: - this.unselectedLabelStyle?.merge(other.unselectedLabelStyle) ?? - other.unselectedLabelStyle, - backgroundColor: other.backgroundColor, - tagNormalTextStyle: - this.tagNormalTextStyle?.merge(other.tagNormalTextStyle) ?? - other.tagNormalTextStyle, - tagNormalColor: other.tagNormalBgColor, + unselectedLabelStyle.merge(other._unselectedLabelStyle), + backgroundColor: other._backgroundColor, + tagNormalTextStyle: tagNormalTextStyle.merge(other._tagNormalTextStyle), + tagNormalColor: other._tagNormalBgColor, tagSelectedTextStyle: - this.tagSelectedTextStyle?.merge(other.tagSelectedTextStyle) ?? - other.tagSelectedTextStyle, - tagSelectedColor: other.tagSelectedBgColor, - tagRadius: other.tagRadius, - tagSpacing: other.tagSpacing, - preLineTagSize: other.preLineTagCount, - tagHeight: other.tagHeight, + tagSelectedTextStyle.merge(other._tagSelectedTextStyle), + tagSelectedColor: other._tagSelectedBgColor, + tagRadius: other._tagRadius, + tagSpacing: other._tagSpacing, + preLineTagSize: other._preLineTagCount, + tagHeight: other._tagHeight, ); } } diff --git a/lib/src/theme/configs/brn_tag_config.dart b/lib/src/theme/configs/brn_tag_config.dart index ceda9a6c..6af4dae1 100644 --- a/lib/src/theme/configs/brn_tag_config.dart +++ b/lib/src/theme/configs/brn_tag_config.dart @@ -1,121 +1,168 @@ -import 'dart:ui'; - import 'package:bruno/src/theme/base/brn_base_config.dart'; +import 'package:bruno/src/theme/base/brn_default_config_utils.dart'; import 'package:bruno/src/theme/base/brn_text_style.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:bruno/src/theme/configs/brn_common_config.dart'; +import 'package:flutter/painting.dart'; /// 标签配置类 class BrnTagConfig extends BrnBaseConfig { - /// tag文本样式 - /// default TextStyle(fontSize: [BrnCommonConfig.fontSizeCaption],color: [BrnCommonConfig.colorTextBase]) - BrnTextStyle tagTextStyle; + BrnTagConfig({ + BrnTextStyle? tagTextStyle, + BrnTextStyle? selectTagTextStyle, + double? tagRadius, + Color? tagBackgroundColor, + Color? selectedTagBackgroundColor, + double? tagHeight, + double? tagWidth, + double? tagMinWidth, + String configId = GLOBAL_CONFIG_ID, + }) : _tagTextStyle = tagTextStyle, + _selectTagTextStyle = selectTagTextStyle, + _tagRadius = tagRadius, + _tagBackgroundColor = tagBackgroundColor, + _selectedTagBackgroundColor = selectedTagBackgroundColor, + _tagHeight = tagHeight, + _tagWidth = tagWidth, + _tagMinWidth = tagMinWidth, + super(configId: configId); + + /// tag 文本样式 + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.colorTextBase], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// ) + BrnTextStyle? _tagTextStyle; /// tag选中文本样式 - /// default TextStyle(fontWeight: FontWeight.w600,fontSize: [BrnCommonConfig.fontSizeCaption],color: [BrnCommonConfig.brandPrimary]) - BrnTextStyle selectTagTextStyle; + /// + /// BrnTextStyle( + /// color: [BrnCommonConfig.brandPrimary], + /// fontSize: [BrnCommonConfig.fontSizeCaption], + /// fontWeight: FontWeight.w600, + /// ) + BrnTextStyle? _selectTagTextStyle; /// 标签背景色 /// default [BrnCommonConfig.fillBody] - Color tagBackgroundColor; + Color? _tagBackgroundColor; /// 选中背景色 /// default [BrnCommonConfig.brandPrimary] - Color selectedTagBackgroundColor; + Color? _selectedTagBackgroundColor; /// 标签圆角 - /// default value is [BrnCommonConfig.radiusXs] - double tagRadius; + /// 默认为 [BrnCommonConfig.radiusXs] + double? _tagRadius; /// 标签高度,跟 fixWidthMode 无关 - /// default value is 34 - double tagHeight; + /// 默认为 34 + double? _tagHeight; /// 标签宽度,且仅在组件设置了固定宽度(fixWidthMode 为 true)时才生效 - /// default value is 75 - double tagWidth; + /// 默认为 75 + double? _tagWidth; /// 标签最小宽度 - /// default value is 75 - double tagMinWidth; - - BrnTagConfig( - {this.tagTextStyle, - this.selectTagTextStyle, - this.tagRadius, - this.tagBackgroundColor, - this.selectedTagBackgroundColor, - this.tagHeight, - this.tagWidth, - this.tagMinWidth, - String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) - : super(configId: configId); + /// 默认为 75 + double? _tagMinWidth; - @override - void initThemeConfig(String configId, - {BrnCommonConfig currentLevelCommonConfig}) { - super.initThemeConfig(configId, - currentLevelCommonConfig: currentLevelCommonConfig); + BrnTextStyle get tagTextStyle => + _tagTextStyle ?? BrnDefaultConfigUtils.defaultTagConfig.tagTextStyle; - /// 用户全局组件配置 - BrnTagConfig tagConfig = - BrnThemeConfigurator.instance.getConfig(configId: configId).tagConfig; + BrnTextStyle get selectTagTextStyle => + _selectTagTextStyle ?? + BrnDefaultConfigUtils.defaultTagConfig.selectTagTextStyle; + + Color get tagBackgroundColor => + _tagBackgroundColor ?? + BrnDefaultConfigUtils.defaultTagConfig.tagBackgroundColor; - this.tagHeight ??= tagConfig.tagHeight; + Color get selectedTagBackgroundColor => + _selectedTagBackgroundColor ?? + BrnDefaultConfigUtils.defaultTagConfig.selectedTagBackgroundColor; - this.tagWidth ??= tagConfig.tagWidth; - this.tagMinWidth ??= tagConfig.tagMinWidth; + double get tagRadius => + _tagRadius ?? BrnDefaultConfigUtils.defaultTagConfig.tagRadius; - this.tagRadius ??= commonConfig.radiusXs; + double get tagHeight => + _tagHeight ?? BrnDefaultConfigUtils.defaultTagConfig.tagHeight; - this.tagBackgroundColor ??= commonConfig.fillBody; + double get tagWidth => + _tagWidth ?? BrnDefaultConfigUtils.defaultTagConfig.tagWidth; - this.selectedTagBackgroundColor ??= commonConfig.brandPrimary; + double get tagMinWidth => + _tagMinWidth ?? BrnDefaultConfigUtils.defaultTagConfig.tagMinWidth; - this.tagTextStyle = tagConfig.tagTextStyle.merge(BrnTextStyle( - color: commonConfig.colorTextBase, - fontSize: commonConfig.fontSizeCaption) - .merge(this.tagTextStyle)); + @override + void initThemeConfig( + String configId, { + BrnCommonConfig? currentLevelCommonConfig, + }) { + super.initThemeConfig( + configId, + currentLevelCommonConfig: currentLevelCommonConfig, + ); + + /// 用户全局组件配置 + BrnTagConfig tagConfig = + BrnThemeConfigurator.instance.getConfig(configId: configId).tagConfig; - this.selectTagTextStyle = tagConfig.selectTagTextStyle.merge(BrnTextStyle( - color: commonConfig.brandPrimary, - fontSize: commonConfig.fontSizeCaption) - .merge(this.selectTagTextStyle)); + _tagHeight ??= tagConfig._tagHeight; + _tagWidth ??= tagConfig._tagWidth; + _tagMinWidth ??= tagConfig._tagMinWidth; + _tagRadius ??= commonConfig.radiusXs; + _tagBackgroundColor ??= commonConfig.fillBody; + _selectedTagBackgroundColor ??= commonConfig.brandPrimary; + _tagTextStyle = tagConfig.tagTextStyle.merge( + BrnTextStyle( + color: commonConfig.colorTextBase, + fontSize: commonConfig.fontSizeCaption, + ).merge(_tagTextStyle), + ); + _selectTagTextStyle = tagConfig.selectTagTextStyle.merge( + BrnTextStyle( + color: commonConfig.brandPrimary, + fontSize: commonConfig.fontSizeCaption, + ).merge(_selectTagTextStyle), + ); } - BrnTagConfig copyWith( - {BrnTextStyle textStyle, - BrnTextStyle selectTextStyle, - double radius, - Color backgroundColor, - Color selectedBackgroundColor, - double height, - double width, - double tagMinWidth}) { + BrnTagConfig copyWith({ + BrnTextStyle? textStyle, + BrnTextStyle? selectTextStyle, + double? radius, + Color? backgroundColor, + Color? selectedBackgroundColor, + double? height, + double? width, + double? tagMinWidth, + }) { return BrnTagConfig( - tagTextStyle: textStyle ?? this.tagTextStyle, - selectTagTextStyle: selectTextStyle ?? this.selectTagTextStyle, - tagRadius: radius ?? this.tagRadius, - tagBackgroundColor: backgroundColor ?? this.tagBackgroundColor, - selectedTagBackgroundColor: - selectedBackgroundColor ?? this.selectedTagBackgroundColor, - tagHeight: height ?? this.tagHeight, - tagWidth: width ?? this.tagWidth, - tagMinWidth: tagMinWidth ?? this.tagMinWidth); + tagTextStyle: textStyle ?? _tagTextStyle, + selectTagTextStyle: selectTextStyle ?? _selectTagTextStyle, + tagRadius: radius ?? _tagRadius, + tagBackgroundColor: backgroundColor ?? _tagBackgroundColor, + selectedTagBackgroundColor: + selectedBackgroundColor ?? _selectedTagBackgroundColor, + tagHeight: height ?? _tagHeight, + tagWidth: width ?? _tagWidth, + tagMinWidth: tagMinWidth ?? _tagMinWidth, + ); } - BrnTagConfig merge(BrnTagConfig other) { + BrnTagConfig merge(BrnTagConfig? other) { + if (other == null) return this; return copyWith( - textStyle: - this.tagTextStyle?.merge(other.tagTextStyle) ?? other.tagTextStyle, - selectTextStyle: - this.selectTagTextStyle?.merge(other.selectTagTextStyle) ?? - other.selectTagTextStyle, - radius: other.tagRadius, - backgroundColor: other.tagBackgroundColor, - selectedBackgroundColor: other.selectedTagBackgroundColor, - height: other.tagHeight, - width: other.tagWidth, - tagMinWidth: other.tagMinWidth); + textStyle: tagTextStyle.merge(other._tagTextStyle), + selectTextStyle: selectTagTextStyle.merge(other._selectTagTextStyle), + radius: other._tagRadius, + backgroundColor: other._tagBackgroundColor, + selectedBackgroundColor: other._selectedTagBackgroundColor, + height: other._tagHeight, + width: other._tagWidth, + tagMinWidth: other._tagMinWidth, + ); } } diff --git a/lib/src/theme/img/brn_theme_default_utils.dart b/lib/src/theme/img/brn_theme_default_utils.dart deleted file mode 100644 index a8c8b0f6..00000000 --- a/lib/src/theme/img/brn_theme_default_utils.dart +++ /dev/null @@ -1,69 +0,0 @@ -import 'dart:ui'; - -import 'package:bruno/src/constants/brn_asset_constants.dart'; -import 'package:bruno/src/theme/img/brn_theme_img_utils.dart'; -import 'package:bruno/src/utils/brn_tools.dart'; -import 'package:flutter/material.dart'; - -class BrnThemeImg { - BrnThemeImgUtils _defaultBrunoImg; - - static BrnThemeImg _instance; - - BrnThemeImg._(BrnThemeImgUtils brunoImgUtils) { - this._defaultBrunoImg = brunoImgUtils ?? BrnDefaultThemeImgUtil(); - } - - factory BrnThemeImg.register({BrnThemeImgUtils brunoImgUtils}) { - _instance = BrnThemeImg._(brunoImgUtils); - return _instance; - } - - static BrnThemeImg get instance { - if (_instance == null) { - BrnThemeImg.register(); - } - return _instance; - } - - Image get ARROW_REFRESH_UP => - _defaultBrunoImg?.getARROW_REFRESH_UP() ?? - BrunoTools.getAssetImage(BrnAsset.refreshArrowUp); - - Image get ARROW_REFRESH_DOWN => - _defaultBrunoImg?.getARROW_REFRESH_DOWN() ?? - BrunoTools.getAssetImage(BrnAsset.refreshArrowDown); - - Image get CHECKED_STATUS => - _defaultBrunoImg?.getCHECKED_STATUS() ?? - BrunoTools.getAssetImage(BrnAsset.SELECT_CHECKED_STATUS); - - Image get STEP_ICON { - return _defaultBrunoImg?.getStepIcon() ?? - BrunoTools.getAssetImage(BrnAsset.stepTitle); - } -} - -///默认link绿 -class BrnDefaultThemeImgUtil extends BrnThemeImgUtils { - @override - Image getARROW_REFRESH_UP() { - return BrunoTools.getAssetImageWithBandColor(BrnAsset.refreshArrowUp); - } - - @override - Image getARROW_REFRESH_DOWN() { - return BrunoTools.getAssetImageWithBandColor(BrnAsset.refreshArrowDown); - } - - @override - Image getCHECKED_STATUS() { - return BrunoTools.getAssetImageWithBandColor( - BrnAsset.SELECT_CHECKED_STATUS); - } - - @override - Image getStepIcon() { - return BrunoTools.getAssetImageWithBandColor(BrnAsset.stepTitle); - } -} diff --git a/lib/src/theme/img/brn_theme_img_utils.dart b/lib/src/theme/img/brn_theme_img_utils.dart deleted file mode 100644 index a553f15d..00000000 --- a/lib/src/theme/img/brn_theme_img_utils.dart +++ /dev/null @@ -1,17 +0,0 @@ -import 'dart:ui'; - -import 'package:flutter/material.dart'; - -abstract class BrnThemeImgUtils { - /// 下啦刷新的向上icon - Image getARROW_REFRESH_UP(); - - /// 下啦刷新的向下icon - Image getARROW_REFRESH_DOWN(); - - /// 选中与否的Icon - Image getCHECKED_STATUS(); - - /// 步骤的title - Image getStepIcon(); -} diff --git a/lib/src/utils/brn_event_bus.dart b/lib/src/utils/brn_event_bus.dart index b59fa39a..9d3832a6 100644 --- a/lib/src/utils/brn_event_bus.dart +++ b/lib/src/utils/brn_event_bus.dart @@ -11,28 +11,42 @@ import 'dart:async'; /// filter events. /// /// github: https://github.com/marcojakob/dart-event-bus -/// class EventBus { - StreamController _streamController; - - /// Controller for the event bus stream. - StreamController get streamController => _streamController; - /// Creates an [EventBus]. /// /// If [sync] is true, events are passed directly to the stream's listeners /// during a [fire] call. If false (the default), the event will be passed to /// the listeners at a later time, after the code creating the event has /// completed. - EventBus({bool sync = false}) - : _streamController = StreamController.broadcast(sync: sync); + EventBus({ + bool sync = false, + }) : _streamController = StreamController.broadcast(sync: sync); /// Instead of using the default [StreamController] you can use this constructor /// to pass your own controller. /// /// An example would be to use an RxDart Subject as the controller. - EventBus.customController(StreamController controller) - : _streamController = controller; + EventBus.customController( + StreamController controller, + ) : _streamController = controller; + + static EventBus? _instance; + + factory EventBus._() { + if(_instance == null) { + _instance = EventBus(); + } + return _instance!; + } + + static EventBus get instance { + return EventBus._(); + } + + StreamController _streamController; + + /// Controller for the event bus stream. + StreamController get streamController => _streamController; /// Listens for events of Type [T] and its subtypes. /// @@ -46,40 +60,24 @@ class EventBus { /// /// Each listener is handled independently, and if they pause, only the pausing /// listener is affected. A paused listener will buffer events internally until - /// unpaused or canceled. So it's usually better to just cancel and later + /// resumed or cancelled. So it's usually better to just cancel and later /// subscribe again (avoids memory leak). /// Stream on() { if (T == dynamic) { - return streamController.stream; - } else { - return streamController.stream.where((event) => event is T).cast(); + return streamController.stream as Stream; } + return streamController.stream.where((dynamic e) => e is T).cast(); } /// Fires a new event on the event bus with the specified [event]. - /// void fire(event) { streamController.add(event); } /// Destroy this [EventBus]. This is generally only in a testing context. - /// void destroy() { _streamController.close(); } - static EventBus _instance; - - factory EventBus.init() { - _instance = EventBus(); - return _instance; - } - - static EventBus get instance { - if (_instance == null) { - EventBus.init(); - } - return _instance; - } } diff --git a/lib/src/utils/brn_multi_click_util.dart b/lib/src/utils/brn_multi_click_util.dart index a278b235..b2d6f36b 100644 --- a/lib/src/utils/brn_multi_click_util.dart +++ b/lib/src/utils/brn_multi_click_util.dart @@ -1,10 +1,12 @@ class BrnMultiClickUtils { - static DateTime _lastClickTime; + const BrnMultiClickUtils._(); - static bool isMultiClick({int intervalMilliseconds}) { + static DateTime? _lastClickTime; + + static bool isMultiClick({int intervalMilliseconds = 500}) { if (_lastClickTime == null || - DateTime.now().difference(_lastClickTime) > - Duration(milliseconds: intervalMilliseconds ?? 500)) { + DateTime.now().difference(_lastClickTime!) > + Duration(milliseconds: intervalMilliseconds)) { _lastClickTime = DateTime.now(); return false; } diff --git a/lib/src/utils/brn_rich_text.dart b/lib/src/utils/brn_rich_text.dart index ae864d1e..8f2d5018 100644 --- a/lib/src/utils/brn_rich_text.dart +++ b/lib/src/utils/brn_rich_text.dart @@ -1,36 +1,34 @@ import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:bruno/src/utils/css/brn_core_funtion.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; -/// 福文本填充生成器 +/// 富文本填充生成器 -/// 超链接的点击回调 -typedef BrnRichTextLinkClick = void Function(String text, String link); - -///用于链式去生成福文本样式的文案 如果是直接的标签可以用css +/// 用于链式去生成富文本样式的文案 如果是直接的标签可以用css class BrnRichTextGenerator { - BrnRichTextGenerator() { - _spanList = List(); - _maxLine = 100; - } + BrnRichTextGenerator(); - List _spanList; - int _maxLine; - TextOverflow _overflow; + List _spanList = []; + int _maxLine = 100; + TextOverflow? _overflow; /// 添加超链接部分的文案 - /// text是显示的文案 - /// url是超链接的url - /// fontsize是显示大小 + /// text 是显示的文案 + /// url 是超链接的 url + /// fontsize 是显示大小 /// richTextLinkClick 是超链接点击的回调 - BrnRichTextGenerator addTextWithLink(String text, - {String url, - TextStyle textStyle, - Color linkColor, - double fontSize, - FontWeight fontWeight, - BrnRichTextLinkClick richTextLinkClick}) { - _spanList.add(TextSpan( + BrnRichTextGenerator addTextWithLink( + String text, { + String? url, + TextStyle? textStyle, + Color? linkColor, + double? fontSize, + FontWeight? fontWeight, + BrnHyperLinkCallback? richTextLinkClick, + }) { + _spanList.add( + TextSpan( style: textStyle ?? TextStyle( color: linkColor ?? @@ -41,56 +39,63 @@ class BrnRichTextGenerator { fontWeight: fontWeight ?? FontWeight.normal, fontSize: fontSize ?? 16, ), - text: text ?? "", + text: text, recognizer: TapGestureRecognizer() ..onTap = () { if (richTextLinkClick != null) { richTextLinkClick(text, url); } - })); + }, + ), + ); return this; } /// 添加自定义文案 /// fontsize 是文案大小 默认是16 /// color 是文案的颜色 默认是深黑色 - BrnRichTextGenerator addText(String text, - {TextStyle textStyle, - double fontSize, - Color color, - FontWeight fontWeight}) { - _spanList.add(TextSpan( - text: text ?? "", + BrnRichTextGenerator addText( + String text, { + TextStyle? textStyle, + double? fontSize, + Color? color, + FontWeight? fontWeight, + }) { + _spanList.add( + TextSpan( + text: text, style: textStyle ?? TextStyle( - color: color ?? - BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .colorTextBase, - fontSize: fontSize ?? 16, - fontWeight: fontWeight ?? FontWeight.normal))); + color: color ?? + BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .colorTextBase, + fontSize: fontSize ?? 16, + fontWeight: fontWeight ?? FontWeight.normal, + ), + ), + ); return this; } /// 添加Icon - BrnRichTextGenerator addIcon(Widget icon, {PlaceholderAlignment alignment}) { + BrnRichTextGenerator addIcon( + Widget? icon, { + PlaceholderAlignment? alignment, + }) { _spanList.add( WidgetSpan( - child: icon != null - ? icon - : Container( - height: 0, - width: 0, - ), - alignment: alignment ?? PlaceholderAlignment.top), + alignment: alignment ?? PlaceholderAlignment.top, + child: icon ?? const SizedBox.shrink(), + ), ); return this; } /// 设置最多文案显示几行 默认是100行 BrnRichTextGenerator setMaxLines(int maxLine) { - if (maxLine != null && maxLine > 0) { + if (maxLine > 0) { _maxLine = maxLine; } return this; @@ -98,17 +103,14 @@ class BrnRichTextGenerator { /// 设置最多文案显示几行 默认是100行 BrnRichTextGenerator setTextOverflow(TextOverflow overflow) { - this._overflow = overflow; + _overflow = overflow; return this; } /// build出福文本 Widget build() { if (_spanList.isEmpty) { - return Container( - height: 0, - width: 0, - ); + return const SizedBox.shrink(); } return ExcludeSemantics( excluding: true, diff --git a/lib/src/utils/brn_text_util.dart b/lib/src/utils/brn_text_util.dart index 424c2837..18cb2692 100644 --- a/lib/src/utils/brn_text_util.dart +++ b/lib/src/utils/brn_text_util.dart @@ -1,17 +1,17 @@ -import 'dart:ui'; - import 'package:bruno/src/utils/brn_tools.dart'; import 'package:flutter/widgets.dart'; class BrnTextUtil { + const BrnTextUtil._(); + /// 根据 TextStyle 计算 text 宽度。 static Size textSize(String text, TextStyle style) { if (BrunoTools.isEmpty(text)) return Size(0, 0); final TextPainter textPainter = TextPainter( - text: TextSpan(text: text, style: style), - maxLines: 1, - textDirection: TextDirection.ltr) - ..layout(minWidth: 0, maxWidth: double.infinity); + text: TextSpan(text: text, style: style), + maxLines: 1, + textDirection: TextDirection.ltr, + )..layout(minWidth: 0, maxWidth: double.infinity); return textPainter.size; } } diff --git a/lib/src/utils/brn_tools.dart b/lib/src/utils/brn_tools.dart index b5b63290..a5d90958 100644 --- a/lib/src/utils/brn_tools.dart +++ b/lib/src/utils/brn_tools.dart @@ -4,22 +4,26 @@ import 'package:bruno/src/theme/configs/brn_common_config.dart'; import 'package:flutter/material.dart'; class BrunoTools { + const BrunoTools._(); + /// 将 icon 根据主题色变色后返回 - static Image getAssetImageWithBandColor(String assetFilePath, - {String configId = BrnThemeConfigurator.GLOBAL_CONFIG_ID}) { - BrnCommonConfig commonConfig = BrnThemeConfigurator.instance + static Image getAssetImageWithBandColor( + String assetFilePath, { + String configId = GLOBAL_CONFIG_ID, + }) { + final BrnCommonConfig? commonConfig = BrnThemeConfigurator.instance .getConfig(configId: configId) .commonConfig; - if (!assetFilePath.startsWith("assets")) { - assetFilePath = "assets/$assetFilePath"; + if (!assetFilePath.startsWith('assets')) { + assetFilePath = 'assets/$assetFilePath'; } - return getAssetImageWithColor(assetFilePath, commonConfig.brandPrimary); + return getAssetImageWithColor(assetFilePath, commonConfig?.brandPrimary); } /// 将 icon 根据传入颜色变后返回 - static Image getAssetImageWithColor(String assetFilePath, Color color) { - if (!assetFilePath.startsWith("assets")) { - assetFilePath = "assets/$assetFilePath"; + static Image getAssetImageWithColor(String assetFilePath, Color? color) { + if (!assetFilePath.startsWith('assets')) { + assetFilePath = 'assets/$assetFilePath'; } return Image.asset( assetFilePath, @@ -29,13 +33,16 @@ class BrunoTools { ); } - /// imgAssetPath: assets资源文件路径 - /// package 访问某个package里的资源,这里默认flutter_alliance_package - /// scale: 与所用的png资源是icon_2x.png (scale=2.0),icon_3x.png(scale=3.0) - static Image getAssetImage(String assetFilePath, - {BoxFit fit, bool gaplessPlayback = false}) { - if (!assetFilePath.startsWith("assets")) { - assetFilePath = "assets/$assetFilePath"; + /// [assetFilePath] assets 资源文件路径 + /// [package] 访问某个 package 里的资源,这里默认为 'bruno' + /// [scale] 与所用的 png 资源是 icon_2x.png (scale=2.0),icon_3x.png(scale=3.0) + static Image getAssetImage( + String assetFilePath, { + BoxFit? fit, + bool gaplessPlayback = false, + }) { + if (!assetFilePath.startsWith('assets')) { + assetFilePath = 'assets/$assetFilePath'; } return Image.asset( assetFilePath, @@ -47,8 +54,8 @@ class BrunoTools { } static Image getAssetScaleImage(String assetFilePath) { - if (!assetFilePath.startsWith("assets")) { - assetFilePath = "assets/$assetFilePath"; + if (!assetFilePath.startsWith('assets')) { + assetFilePath = 'assets/$assetFilePath'; } return Image.asset( assetFilePath, @@ -56,10 +63,14 @@ class BrunoTools { ); } - static Image getAssetSizeImage(String assetFilePath, double w, double h, - {Color color}) { - if (!assetFilePath.startsWith("assets")) { - assetFilePath = "assets/$assetFilePath"; + static Image getAssetSizeImage( + String assetFilePath, + double w, + double h, { + Color? color, + }) { + if (!assetFilePath.startsWith('assets')) { + assetFilePath = 'assets/$assetFilePath'; } return Image.asset( assetFilePath, @@ -71,46 +82,48 @@ class BrunoTools { ); } - //从16进制数字字符串,生成Color,例如EDF0F3 - static Color colorFromHexString(String s) { + /// 从16进制数字字符串,生成Color,例如EDF0F3 + static Color colorFromHexString(String? s) { if (s == null || s.length != 6 || int.tryParse(s, radix: 16) == null) { return Colors.black; } return Color(int.parse(s, radix: 16) + 0xFF000000); } - // 获取本地AssetImage - /// [imgAssetPath]: assets资源文件路径 + /// 获取本地 [AssetImage] + /// [assetFilePath] assets资源文件路径 static ImageProvider getAssetImageProvider(String assetFilePath) { - if (!assetFilePath.startsWith("assets")) { - assetFilePath = "assets/$assetFilePath"; + if (!assetFilePath.startsWith('assets')) { + assetFilePath = 'assets/$assetFilePath'; } - AssetImage asimg = AssetImage( + final AssetImage image = AssetImage( assetFilePath, package: BrnStrings.flutterPackageName, ); - return asimg; + return image; } /// 根据 TextStyle 计算 text 宽度。 static Size textSize(String text, TextStyle style) { if (isEmpty(text)) return Size(0, 0); final TextPainter textPainter = TextPainter( - text: TextSpan(text: text, style: style), - maxLines: 1, - textDirection: TextDirection.ltr) - ..layout(minWidth: 0, maxWidth: double.infinity); + text: TextSpan(text: text, style: style), + maxLines: 1, + textDirection: TextDirection.ltr, + )..layout(minWidth: 0, maxWidth: double.infinity); return textPainter.size; } /// 判空 - static bool isEmpty(Object obj) { + static bool isEmpty(Object? obj) { if (obj is String) { return obj.isEmpty; - } else if (obj is Iterable) { + } + if (obj is Iterable) { return obj.isEmpty; - } else if (obj is Map) { + } + if (obj is Map) { return obj.length == 0; } return obj == null; @@ -118,7 +131,7 @@ class BrunoTools { /// 去掉最后一位小数 //static double formatNumRemoveLastNum(double num){ -// int count = num.toString().length - num.toString().lastIndexOf(".") - 1; +// int count = num.toString().length - num.toString().lastIndexOf('.') - 1; // if(count >1){ // // } diff --git a/lib/src/utils/css/brn_core_funtion.dart b/lib/src/utils/css/brn_core_funtion.dart index 56baaf45..3aa03742 100644 --- a/lib/src/utils/css/brn_core_funtion.dart +++ b/lib/src/utils/css/brn_core_funtion.dart @@ -4,38 +4,40 @@ import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:xml/xml_events.dart' as xml; -typedef BrnHyperLinkCallback = Function(String text, String url); +/// 超链接的点击回调 +typedef BrnHyperLinkCallback = void Function(String text, String? url); -//用于将标签转为 style +/// 用于将标签转为 style class BrnConvert { - //超链接的点击回调 - BrnHyperLinkCallback _linkCallBack; - - //标签的集合 - Iterable _eventList = []; - - //标签对应的style - List stack = []; - - //外部传入的默认文本样式 - TextStyle _defaultStyle; - - BrnConvert(String cssContent, - {Function linkCallBack, TextStyle defaultStyle}) { + BrnConvert( + String cssContent, { + BrnHyperLinkCallback? linkCallBack, + TextStyle? defaultStyle, + }) { _eventList = xml.parseEvents(cssContent); _linkCallBack = linkCallBack ?? null; _defaultStyle = defaultStyle; } - //转换的思路:将 开始标签 的属性转为 合适的style, 并将其存入集合中 - // font开始标签目前支持的属性:color、weight、size - // a开始标签支持的属性:href - // 文本标签 去获取style集合的最后一个元素 并应用style样式 - // 结束标签 则将集合的最后一个元素删除 + /// 超链接的点击回调 + BrnHyperLinkCallback? _linkCallBack; + + /// 外部传入的默认文本样式 + TextStyle? _defaultStyle; + /// 标签的集合 + Iterable _eventList = []; + + /// 标签对应的style + List<_Tag> stack = []; + + /// 转换的思路:将 开始标签 的属性转为 合适的style, 并将其存入集合中 + /// a开始标签支持的属性:href + /// 文本标签 去获取style集合的最后一个元素 并应用style样式 + /// 结束标签 则将集合的最后一个元素删除 List convert() { - //优先使用外部提供的样式 - TextStyle style = _defaultStyle ?? + // 优先使用外部提供的样式 + final TextStyle style = _defaultStyle ?? TextStyle( fontSize: 14, decoration: TextDecoration.none, @@ -46,51 +48,54 @@ class BrnConvert { .colorTextImportant, ); - List spans = []; + final List spans = []; _eventList.forEach((xmlEvent) { if (xmlEvent is xml.XmlStartElementEvent) { if (!xmlEvent.isSelfClosing) { - Tag tag = Tag(); + final _Tag tag = _Tag(); TextStyle textStyle = style.copyWith(); - if (xmlEvent.name == "font") { + if (xmlEvent.name == 'font') { xmlEvent.attributes.forEach((attr) { switch (attr.name) { - case "color": - Color textColor = - BrnConvertUtil.generateColorByString(attr.value); - textStyle = textStyle.apply(color: textColor); + case 'color': + textStyle = textStyle.apply( + color: BrnConvertUtil.generateColorByString(attr.value), + ); break; - case "weight": + case 'weight': FontWeight fontWeight = BrnConvertUtil.generateFontWidgetByString(attr.value); textStyle = textStyle.apply( - fontWeightDelta: - fontWeight.index - FontWeight.normal.index); + fontWeightDelta: fontWeight.index - FontWeight.normal.index, + ); break; - case "size": - double size = BrnConvertUtil.generateFontSize(attr.value); - textStyle = textStyle.apply(fontSizeDelta: size - 13); + case 'size': + textStyle = textStyle.apply( + fontSizeDelta: + BrnConvertUtil.generateFontSize(attr.value) - 13, + ); break; } }); tag.isLink = false; } - if (xmlEvent.name == "strong") { + if (xmlEvent.name == 'strong') { tag.isLink = false; textStyle = textStyle.apply(fontWeightDelta: 2); } - if (xmlEvent.name == "a") { + if (xmlEvent.name == 'a') { tag.isLink = true; xmlEvent.attributes.forEach((attr) { switch (attr.name) { - case "href": + case 'href': textStyle = textStyle.apply( - color: BrnThemeConfigurator.instance - .getConfig() - .commonConfig - .brandPrimary); + color: BrnThemeConfigurator.instance + .getConfig() + .commonConfig + .brandPrimary, + ); tag.linkUrl = attr.value; break; } @@ -100,14 +105,14 @@ class BrnConvert { tag.style = textStyle; stack.add(tag); } else { - if (xmlEvent.name == "br") { - spans.add(TextSpan(text: "\n")); + if (xmlEvent.name == 'br') { + spans.add(TextSpan(text: '\n')); } } } if (xmlEvent is xml.XmlTextEvent) { - Tag tag = Tag(); + _Tag tag = _Tag(); tag.style = style.copyWith(); if (stack.isNotEmpty) { tag = stack.last; @@ -117,9 +122,9 @@ class BrnConvert { } if (xmlEvent is xml.XmlEndElementEvent) { - Tag top = stack.removeLast(); + _Tag top = stack.removeLast(); if (top.name != xmlEvent.name) { - debugPrint("Error format HTML"); + debugPrint('Error format HTML'); return; } } @@ -128,24 +133,23 @@ class BrnConvert { return spans; } - TextSpan _createTextSpan(String text, Tag tag) { - if (text.isEmpty) return TextSpan(text: ""); - TapGestureRecognizer tapGestureRecognizer = TapGestureRecognizer(); - tapGestureRecognizer.onTap = () { - if (_linkCallBack != null) { - _linkCallBack(text, tag.linkUrl); - } - }; + TextSpan _createTextSpan(String text, _Tag tag) { + if (text.isEmpty) return TextSpan(text: ''); + final TapGestureRecognizer recognizer = TapGestureRecognizer() + ..onTap = () { + _linkCallBack?.call(text, tag.linkUrl); + }; return TextSpan( - style: tag.style, - text: text, - recognizer: tag.isLink ? tapGestureRecognizer : null); + style: tag.style, + text: text, + recognizer: tag.isLink ? recognizer : null, + ); } } -class Tag { - String name; - TextStyle style; - String linkUrl; +class _Tag { + String? name; + TextStyle? style; + String? linkUrl; bool isLink = false; } diff --git a/lib/src/utils/css/brn_css_2_text.dart b/lib/src/utils/css/brn_css_2_text.dart index dd35d20f..beb13bde 100644 --- a/lib/src/utils/css/brn_css_2_text.dart +++ b/lib/src/utils/css/brn_css_2_text.dart @@ -3,24 +3,36 @@ import 'package:flutter/material.dart'; /// 将CSS格式的标签转为文本 class BrnCSS2Text { - static TextSpan toTextSpan(String htmlContent, - {BrnHyperLinkCallback linksCallback, TextStyle defaultStyle}) { + const BrnCSS2Text._(); + + static TextSpan toTextSpan( + String htmlContent, { + BrnHyperLinkCallback? linksCallback, + TextStyle? defaultStyle, + }) { return TextSpan( - children: BrnConvert(htmlContent, - linkCallBack: linksCallback, defaultStyle: defaultStyle) - .convert(), + children: BrnConvert( + htmlContent, + linkCallBack: linksCallback, + defaultStyle: defaultStyle, + ).convert(), ); } - static Text toTextView(String htmlContent, - {BrnHyperLinkCallback linksCallback, - TextStyle defaultStyle, - int maxLines, - TextAlign textAlign, - TextOverflow textOverflow}) { + static Text toTextView( + String htmlContent, { + BrnHyperLinkCallback? linksCallback, + TextStyle? defaultStyle, + int? maxLines, + TextAlign? textAlign, + TextOverflow? textOverflow, + }) { return Text.rich( - toTextSpan(htmlContent, - linksCallback: linksCallback, defaultStyle: defaultStyle), + toTextSpan( + htmlContent, + linksCallback: linksCallback, + defaultStyle: defaultStyle, + ), maxLines: maxLines, textAlign: textAlign, overflow: textOverflow ?? TextOverflow.clip, diff --git a/lib/src/utils/css/brn_util.dart b/lib/src/utils/css/brn_util.dart index bcbe5753..31f64996 100644 --- a/lib/src/utils/css/brn_util.dart +++ b/lib/src/utils/css/brn_util.dart @@ -1,50 +1,53 @@ -import 'dart:ui'; - import 'package:bruno/src/theme/brn_theme_configurator.dart'; +import 'package:flutter/painting.dart'; -//将标签属性 转为 相当的style +/// 将标签属性转为对应的 style class BrnConvertUtil { - //将标签color 转为 颜色 - static Color generateColorByString(String hexColor, - {String defColor: 'ffffffff'}) { - Color color = + const BrnConvertUtil._(); + + /// 将标签 color 转为 颜色 + static Color? generateColorByString( + String hexColor, { + Color defaultColor = const Color(0xffffffff), + }) { + Color? color = BrnThemeConfigurator.instance.getConfig().commonConfig.brandPrimary; - if (hexColor == null || hexColor.isEmpty) return color; - hexColor = hexColor.toUpperCase().replaceAll("#", ""); + if (hexColor.isEmpty) return color; + hexColor = hexColor.toUpperCase().replaceAll('#', ''); hexColor = hexColor.replaceAll('0X', ''); if (hexColor.length == 6) { - hexColor = "FF" + hexColor; + hexColor = 'FF' + hexColor; } try { color = Color(int.parse(hexColor, radix: 16)); - } catch (e) {} - return color; + } catch (_) {} + return color ?? defaultColor; } - //将标签字体 转为 合适的字体 + /// 将标签字体转为合适的字体 static FontWeight generateFontWidgetByString(String fontWeight) { FontWeight defaultWeight = FontWeight.normal; switch (fontWeight) { - case "Bold": + case 'Bold': defaultWeight = FontWeight.w600; break; - case "Medium": + case 'Medium': defaultWeight = FontWeight.w500; break; - case "Light": + case 'Light': defaultWeight = FontWeight.w300; break; } return defaultWeight; } - //将标签字体大小 转为 合适大小的字体 + /// 将标签字体大小转为合适大小的字体 static double generateFontSize(String size) { double defaultSize = 13; try { defaultSize = double.parse(size); - } catch (e) {} + } catch (_) {} return defaultSize; } } diff --git a/lib/src/utils/font/brn_font.dart b/lib/src/utils/font/brn_font.dart deleted file mode 100644 index 59de256b..00000000 --- a/lib/src/utils/font/brn_font.dart +++ /dev/null @@ -1,13 +0,0 @@ -class BrnFont { - static const double FONT_12 = 12; - - static const double FONT_14 = 14; - - static const double FONT_16 = 16; - - static const double FONT_18 = 18; - - static const double FONT_20 = 20; - - static const double FONT_22 = 22; -} diff --git a/lib/src/utils/i18n/brn_date_picker_i18n.dart b/lib/src/utils/i18n/brn_date_picker_i18n.dart index 2438c270..0d90a097 100755 --- a/lib/src/utils/i18n/brn_date_picker_i18n.dart +++ b/lib/src/utils/i18n/brn_date_picker_i18n.dart @@ -1,4 +1,4 @@ -import 'dart:math'; +import 'dart:math' as math; part 'brn_strings_zh_cn.dart'; @@ -63,65 +63,69 @@ enum DateTimePickerLocale { } /// Default value of date locale -const DateTimePickerLocale DATETIME_PICKER_LOCALE_DEFAULT = +const DateTimePickerLocale datetimePickerLocaleDefault = DateTimePickerLocale.zh_cn; const Map datePickerI18n = { - DateTimePickerLocale.zh_cn: const _StringsZhCn(), + DateTimePickerLocale.zh_cn: _StringsZhCn(), }; class DatePickerI18n { + const DatePickerI18n._(); + /// Get done button text static String getLocaleDone(DateTimePickerLocale locale) { - _StringsI18n i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; - return i18n.getDoneText() ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT].getDoneText(); + final _StringsI18n? i18n = datePickerI18n[locale] ?? + datePickerI18n[datetimePickerLocaleDefault]; + return i18n?.getDoneText() ?? + datePickerI18n[datetimePickerLocaleDefault]!.getDoneText(); } /// Get cancel button text static String getLocaleCancel(DateTimePickerLocale locale) { - _StringsI18n i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; - return i18n.getCancelText() ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT].getCancelText(); + final _StringsI18n? i18n = datePickerI18n[locale] ?? + datePickerI18n[datetimePickerLocaleDefault]; + return i18n?.getCancelText() ?? + datePickerI18n[datetimePickerLocaleDefault]!.getCancelText(); } /// Get locale month array static List getLocaleMonths(DateTimePickerLocale locale) { - _StringsI18n i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; - List months = i18n.getMonths(); + final _StringsI18n? i18n = datePickerI18n[locale] ?? + datePickerI18n[datetimePickerLocaleDefault]; + final List? months = i18n?.getMonths(); if (months != null && months.isNotEmpty) { return months; } - return datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT].getMonths(); + return datePickerI18n[datetimePickerLocaleDefault]!.getMonths(); } /// Get locale week array - static List getLocaleWeeks(DateTimePickerLocale locale, - [bool isFull = true]) { - _StringsI18n i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; + static List getLocaleWeeks( + DateTimePickerLocale locale, [ + bool isFull = true, + ]) { + final _StringsI18n? i18n = datePickerI18n[locale] ?? + datePickerI18n[datetimePickerLocaleDefault]; if (isFull) { - List weeks = i18n.getWeeksFull(); + final List? weeks = i18n?.getWeeksFull(); if (weeks != null && weeks.isNotEmpty) { return weeks; } - return datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT].getWeeksFull(); + return datePickerI18n[datetimePickerLocaleDefault]!.getWeeksFull(); } - List weeks = i18n.getWeeksShort(); + final List? weeks = i18n?.getWeeksShort(); if (weeks != null && weeks.isNotEmpty) { return weeks; } - List fullWeeks = i18n.getWeeksFull(); + final List? fullWeeks = i18n?.getWeeksFull(); if (fullWeeks != null && fullWeeks.isNotEmpty) { return fullWeeks - .map((item) => item.substring(0, min(3, item.length))) + .map((item) => item.substring(0, math.min(3, item.length))) .toList(); } - return datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT].getWeeksShort(); + return datePickerI18n[datetimePickerLocaleDefault]!.getWeeksShort(); } } diff --git a/lib/src/utils/i18n/brn_strings_zh_cn.dart b/lib/src/utils/i18n/brn_strings_zh_cn.dart index 9248bb43..7f9294c0 100755 --- a/lib/src/utils/i18n/brn_strings_zh_cn.dart +++ b/lib/src/utils/i18n/brn_strings_zh_cn.dart @@ -5,56 +5,52 @@ class _StringsZhCn extends _StringsI18n { const _StringsZhCn(); @override - String getCancelText() { - return '取消'; - } + String getCancelText() => '取消'; @override - String getDoneText() { - return '确定'; - } + String getDoneText() => '确定'; @override List getMonths() { - return [ - "01", - "02", - "03", - "04", - "05", - "06", - "07", - "08", - "09", - "10", - "11", - "12" + return [ + '01', + '02', + '03', + '04', + '05', + '06', + '07', + '08', + '09', + '10', + '11', + '12', ]; } @override List getWeeksFull() { - return [ - "星期一", - "星期二", - "星期三", - "星期四", - "星期五", - "星期六", - "星期日", + return [ + '星期一', + '星期二', + '星期三', + '星期四', + '星期五', + '星期六', + '星期日', ]; } @override List getWeeksShort() { - return [ - "周一", - "周二", - "周三", - "周四", - "周五", - "周六", - "周日", + return [ + '周一', + '周二', + '周三', + '周四', + '周五', + '周六', + '周日', ]; } } diff --git a/pubspec.yaml b/pubspec.yaml index 4dfcf223..f40c9439 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -4,7 +4,7 @@ version: 2.0.0 homepage: https://github.com/LianjiaTech/bruno environment: - sdk: ">=2.1.0 <3.0.0" + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: