From a4c1a74228a162641fd4e73964dd52137ab40ae7 Mon Sep 17 00:00:00 2001 From: Sandy <15143015732@163.com> Date: Wed, 26 Jan 2022 12:11:52 +0800 Subject: [PATCH] migrate picker to null safety (#91) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --- .../components/line/dashed_line_example.dart | 4 +- .../picker/date_picker_example.dart | 2 +- .../components/picker/picker_entry_page.dart | 12 +- lib/src/components/line/brn_dashed_line.dart | 98 ++++++------ .../components/picker/base/brn_picker.dart | 73 +++++---- .../picker/base/brn_picker_constants.dart | 14 +- .../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 | 46 +++--- .../picker/brn_mulit_select_tags_picker.dart | 77 +++++----- .../components/picker/brn_multi_picker.dart | 103 ++++++------- .../picker/brn_picker_cliprrect.dart | 9 +- .../brn_select_tags_with_input_picker.dart | 139 +++++++++-------- .../picker/brn_tags_common_picker.dart | 33 ++-- .../picker/brn_tags_picker_config.dart | 24 +-- .../bean/brn_multi_column_picker_entity.dart | 104 ++++++------- .../brn_multi_column_converter.dart | 35 +++-- .../brn_multi_column_list.dart | 98 ++++++------ .../brn_multi_column_picker.dart | 142 ++++++++---------- .../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 | 18 +-- .../time_picker/brn_date_time_formatter.dart | 12 +- .../date_picker/brn_date_picker.dart | 91 ++++++----- .../date_picker/brn_date_widget.dart | 94 ++++++------ .../date_picker/brn_datetime_widget.dart | 142 +++++++++--------- .../date_picker/brn_time_widget.dart | 104 ++++++------- .../brn_date_range_picker.dart | 93 ++++++------ .../brn_date_range_side_widget.dart | 99 ++++++------ .../brn_date_range_widget.dart | 88 +++++------ .../brn_time_range_side_widget.dart | 137 ++++++++--------- .../brn_time_range_widget.dart | 108 +++++++------ .../bean/brn_selection_common_entity.dart | 4 +- .../brn_selection_more_item_widget.dart | 2 +- .../theme/base/brn_default_config_utils.dart | 8 +- lib/src/utils/i18n/brn_date_picker_i18n.dart | 20 +-- 39 files changed, 1099 insertions(+), 1140 deletions(-) diff --git a/example/lib/sample/components/line/dashed_line_example.dart b/example/lib/sample/components/line/dashed_line_example.dart index f3d738c7..f5021e53 100644 --- a/example/lib/sample/components/line/dashed_line_example.dart +++ b/example/lib/sample/components/line/dashed_line_example.dart @@ -35,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: @@ -56,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, diff --git a/example/lib/sample/components/picker/date_picker_example.dart b/example/lib/sample/components/picker/date_picker_example.dart index d2c9b332..8fffca2a 100644 --- a/example/lib/sample/components/picker/date_picker_example.dart +++ b/example/lib/sample/components/picker/date_picker_example.dart @@ -156,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/picker_entry_page.dart b/example/lib/sample/components/picker/picker_entry_page.dart index c5484461..5bde9125 100644 --- a/example/lib/sample/components/picker/picker_entry_page.dart +++ b/example/lib/sample/components/picker/picker_entry_page.dart @@ -82,7 +82,7 @@ class PickerEntryPage extends StatelessWidget { describe: "底部级联选择框", onPressed: () { rootBundle.loadString('assets/list_picker.json').then((data) { - List _selectionData = List() + List _selectionData = [] ..addAll((JsonDecoder().convert(data)["data"]['list'] as List ?? []) .map((o) => BrnPickerEntity.fromMap(o))); if (_selectionData != null && _selectionData.length > 0) { @@ -100,7 +100,7 @@ class PickerEntryPage extends StatelessWidget { describe: "底部级联选择框(Title 动态改变)", onPressed: () { rootBundle.loadString('assets/list_picker.json').then((data) { - List _selectionData = List() + List _selectionData = [] ..addAll((JsonDecoder().convert(data)["data"]['list'] as List ?? []) .map((o) => BrnPickerEntity.fromMap(o))); if (_selectionData != null && _selectionData.length > 0) { @@ -131,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)); @@ -353,7 +353,7 @@ class PickerEntryPage extends StatelessWidget { List items = List(); 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); } @@ -371,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/lib/src/components/line/brn_dashed_line.dart b/lib/src/components/line/brn_dashed_line.dart index 427f122e..c7a2abe4 100644 --- a/lib/src/components/line/brn_dashed_line.dart +++ b/lib/src/components/line/brn_dashed_line.dart @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; @@ -13,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; @@ -54,7 +48,7 @@ class BrnDashedLine extends StatelessWidget { final double dashedSpacing; /// 颜色,默认值[_normalColor] - final Color color; + final Color? color; /// 虚线的Widget final Widget contentWidget; @@ -66,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, ); } @@ -107,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 @@ -130,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获取到宽度 @@ -139,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) { @@ -161,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/picker/base/brn_picker.dart b/lib/src/components/picker/base/brn_picker.dart index 21f6b401..2f4a01e9 100644 --- a/lib/src/components/picker/base/brn_picker.dart +++ b/lib/src/components/picker/base/brn_picker.dart @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @dart=2.9 + import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; @@ -12,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; @@ -61,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, @@ -70,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), @@ -106,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, @@ -115,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, @@ -153,7 +153,7 @@ class BrnPicker extends StatefulWidget { final Color backgroundColor; ///分割线颜色 - final Color lineColor; + final Color? lineColor; /// {@macro flutter.rendering.wheelList.offAxisFraction} final double offAxisFraction; @@ -167,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. /// @@ -197,8 +197,8 @@ class BrnPicker extends StatefulWidget { } class _CupertinoPickerState extends State { - int _lastHapticIndex; - FixedExtentScrollController _controller; + int? _lastHapticIndex; + FixedExtentScrollController? _controller; @override void initState() { @@ -249,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( @@ -288,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()); @@ -326,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()); @@ -361,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(), @@ -406,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; @@ -433,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; } @@ -458,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(); } @@ -485,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; @@ -494,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 977539ea..9ed44cc5 100755 --- a/lib/src/components/picker/base/brn_picker_constants.dart +++ b/lib/src/components/picker/base/brn_picker_constants.dart @@ -1,28 +1,28 @@ import 'package:flutter/material.dart'; /// Default value of DatePicker's item [TextStyle]. -const TextStyle DATETIME_PICKER_ITEM_TEXT_STYLE = TextStyle( +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 = TextStyle( +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 1f62b309..7079cbbf 100755 --- a/lib/src/components/picker/base/brn_picker_title.dart +++ b/lib/src/components/picker/base/brn_picker_title.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + 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'; @@ -11,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); } @@ -33,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), ), ), ), @@ -51,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, @@ -64,7 +64,7 @@ class BrnPickerTitle extends StatelessWidget { ), Text( pickerTitleConfig.titleContent, - style: themeData.titleTextStyle.generateTextStyle(), + style: themeData!.titleTextStyle.generateTextStyle(), ), GestureDetector( child: _renderConfirmWidget(context), @@ -76,7 +76,7 @@ class BrnPickerTitle extends StatelessWidget { ), ), Divider( - color: themeData.dividerColor, + color: themeData!.dividerColor, indent: 0.0, height: 0.5, ), @@ -87,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, @@ -101,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 f84677a7..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,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker_constants.dart'; import 'package:flutter/material.dart'; @@ -17,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 2668896b..91a531c9 100644 --- a/lib/src/components/picker/brn_bottom_picker.dart +++ b/lib/src/components/picker/brn_bottom_picker.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; @@ -26,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, }) { @@ -50,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, @@ -75,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, @@ -99,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() { @@ -117,7 +117,7 @@ class BrnBottomPickerWidgetState extends State Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { - _controller?.reverse(); + _controller.reverse(); return true; }, child: Scaffold( @@ -136,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 @@ -177,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( @@ -194,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) { @@ -206,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) { @@ -231,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 83cb45d8..553e810f 100644 --- a/lib/src/components/picker/brn_bottom_write_picker.dart +++ b/lib/src/components/picker/brn_bottom_write_picker.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_bottom_picker.dart'; @@ -7,11 +7,11 @@ import 'package:flutter/material.dart'; ///取消输入事件回调 typedef BrnBottomWritePickerClickCallback = Future Function( - String content); + String? content); ///确认输入事件回调 typedef BrnBottomWritePickerConfirmClickCallback = Future Function( - BuildContext dialogContext, String content); + BuildContext dialogContext, String? content); class BrnBottomWritePicker extends StatefulWidget { /// 弹窗左边自定义文案,默认 '取消' @@ -30,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, @@ -71,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, @@ -105,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(); } @@ -173,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 30218dc0..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,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_tags_common_picker.dart'; @@ -25,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, @@ -40,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, @@ -56,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; @@ -84,8 +85,8 @@ class BrnMultiSelectTagsPicker extends CommonTagsPicker { final double itemHeight; /// 操作类型属性 - List _selectedTags; - List _sourceTags; + late List _selectedTags; + late List _sourceTags; @override void show() { @@ -99,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( @@ -112,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 { @@ -127,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; //计算宽高比 @@ -143,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() @@ -177,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( @@ -201,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(), @@ -215,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 ?? @@ -223,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() @@ -247,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( @@ -268,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(), @@ -281,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); } } @@ -308,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 d1834051..e6ad7cc4 100644 --- a/lib/src/components/picker/brn_multi_picker.dart +++ b/lib/src/components/picker/brn_multi_picker.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; @@ -7,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] 是否被选中 @@ -36,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); @@ -52,7 +51,7 @@ class BrnMultiDataPicker extends StatefulWidget { final String title; ///多级数据选择标题文案样式 - final TextStyle titleTextStyle; + final TextStyle? titleTextStyle; /// 多级数据选择弹窗所要覆盖页面的context final BuildContext context; @@ -61,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, @@ -119,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), @@ -132,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); } @@ -155,7 +153,7 @@ class BrnMultiDataPicker extends StatefulWidget { } class _BrnMultiDataPickerState extends State { - List _selectedIndexList = List(); + List _selectedIndexList = []; @override void initState() { @@ -168,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( @@ -176,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(), ), @@ -200,7 +198,8 @@ class _BrnMultiDataPickerState extends State { }, onConfirm: () { Navigator.of(context).pop(_selectedIndexList); - widget?.confirmClick(_selectedIndexList); + if (widget.confirmClick != null) + widget.confirmClick!(_selectedIndexList); }, ); } @@ -218,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 = @@ -236,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), @@ -252,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 = @@ -268,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++) { @@ -294,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(), ), )); } @@ -303,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; @@ -311,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++) { @@ -334,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() { @@ -371,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(), @@ -383,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 c3313044..ca5ac7e3 100644 --- a/lib/src/components/picker/brn_picker_cliprrect.dart +++ b/lib/src/components/picker/brn_picker_cliprrect.dart @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'package:flutter/foundation.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; @@ -8,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 7c21e2f0..97280e81 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 @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; import 'package:bruno/src/constants/brn_asset_constants.dart'; import 'package:bruno/src/theme/brn_theme_configurator.dart'; @@ -13,7 +11,7 @@ typedef SelectTagWithInputValueGetter = String Function(V data); ///提交按钮事件回调 typedef BrnTagInputConfirmClickCallback = Future Function( BuildContext dialogContext, - List selectedTags, + List? selectedTags, String content); ///关闭 picker回调 @@ -31,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; @@ -68,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) { @@ -91,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, @@ -128,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() { @@ -142,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)))); } @@ -171,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), ), @@ -218,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) { @@ -246,7 +247,7 @@ class _BrnSelectTagsWithInputPickerWidgetState mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( - widget.title, + widget.title ?? '', style: TextStyle( color: BrnThemeConfigurator.instance .getConfig() @@ -259,7 +260,7 @@ class _BrnSelectTagsWithInputPickerWidgetState InkWell( onTap: () { if (widget.cancelCallBack != null) { - widget.cancelCallBack(context); + widget.cancelCallBack!(context); } Navigator.of(context).pop(); }, @@ -283,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) / @@ -295,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 @@ -320,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)), @@ -333,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( @@ -423,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( @@ -453,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() { @@ -463,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; } @@ -484,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, }); } @@ -506,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 aac2b73c..d6cb4a5e 100644 --- a/lib/src/components/picker/brn_tags_common_picker.dart +++ b/lib/src/components/picker/brn_tags_common_picker.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; @@ -13,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, @@ -36,7 +37,7 @@ class CommonTagsPicker extends StatefulWidget { : super(key: key) { this.themeData ??= BrnPickerConfig(); this.themeData = this - .themeData + .themeData! .merge(BrnThemeConfigurator.instance.getConfig().pickerConfig); } @@ -49,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!(); } } }); @@ -61,7 +62,7 @@ class CommonTagsPicker extends StatefulWidget { /// 子类重写实现builder @protected - Widget createBuilder(BuildContext context, VoidCallback onUpdate) { + Widget? createBuilder(BuildContext context, VoidCallback? onUpdate) { return null; } @@ -80,7 +81,7 @@ class CommonTagsPicker extends StatefulWidget { } class _CommonPickerState extends State { - VoidCallback _onUpdate; + VoidCallback? _onUpdate; @override void initState() { @@ -135,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); } @@ -150,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 7fc4477b..1303df3c 100644 --- a/lib/src/components/picker/brn_tags_picker_config.dart +++ b/lib/src/components/picker/brn_tags_picker_config.dart @@ -1,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/theme/brn_theme_configurator.dart'; import 'package:flutter/material.dart'; @@ -26,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 { @@ -58,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; @@ -84,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 81b95621..4ee900f6 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 @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'package:bruno/src/constants/brn_constants.dart'; import 'package:bruno/src/utils/brn_tools.dart'; @@ -17,41 +15,37 @@ enum PickerWindowType { } 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.maxSelectCount; } - 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'] ?? ""; @@ -63,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.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; } @@ -81,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(); } @@ -95,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(); @@ -112,7 +107,7 @@ class BrnPickerEntity { return PickerWindowType.List; } - PickerFilterType parserFilterTypeWithType(String type) { + PickerFilterType parserFilterTypeWithType(String? type) { if (type == "unlimit") { return PickerFilterType.UnLimit; } else if (type == "radio") { @@ -124,7 +119,7 @@ class BrnPickerEntity { } 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(); @@ -133,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) { @@ -152,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); } } @@ -168,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; @@ -196,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); @@ -223,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; @@ -237,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; } } @@ -255,13 +241,13 @@ class BrnPickerEntity { } 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 06ffd420..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,4 +1,4 @@ -// @dart=2.9 + 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'; @@ -15,7 +15,7 @@ class BrnMultiRangeSelConverter { } Map> getSelectionParams( - List selectedResults, + List? selectedResults, {bool includeUnlimitSelection = false}) { Map> params = Map(); if (selectedResults == null) return params; @@ -28,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, @@ -52,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; @@ -69,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 be9667eb..5a10b95f 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,4 +1,4 @@ -// @dart=2.9 + 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'; @@ -12,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 = []; } } @@ -61,7 +61,7 @@ class BrnMultiColumnListWidget extends StatefulWidget { _BrnMultiColumnListWidgetState createState() => _BrnMultiColumnListWidgetState(); - List getSelectedItems() { + List? getSelectedItems() { return _selectedItems; } } @@ -72,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, @@ -80,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); @@ -99,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); + } }, ); }, @@ -124,7 +126,7 @@ class _BrnMultiColumnListWidgetState extends State { } /// Item 点击之后的数据处理 - void _processFilterData(BrnPickerEntity selectedEntity) { + void _processFilterData(BrnPickerEntity? selectedEntity) { if (null == selectedEntity) { return; } @@ -139,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(); } /// 设置选中数据。 @@ -157,21 +159,23 @@ 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); } } } @@ -180,12 +184,12 @@ class _BrnMultiColumnListWidgetState extends State { void _configFirstList(BrnPickerEntity selectedEntity) { if (PickerFilterType.Radio == selectedEntity.filterType) { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else if (PickerFilterType.Checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 @@ -193,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()) { @@ -205,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(); + selectedEntity.parent!.clearChildSelection(); } } else { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 if (PickerFilterType.Radio == selectedEntity.filterType) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else if (PickerFilterType.Checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 @@ -226,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()) { @@ -239,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(); + selectedEntity.parent!.clearChildSelection(); } } else { /// 单选,清除同一级别选中的状态,则其他的设置为未选中。 if (PickerFilterType.Radio == selectedEntity.filterType) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else if (PickerFilterType.Checkbox == selectedEntity.filterType) { /// 选中【不限】清除同一级别其他的状态 if (selectedEntity.isUnLimit()) { - selectedEntity.parent.clearChildSelection(); + selectedEntity.parent!.clearChildSelection(); selectedEntity.isSelected = true; } else { ///清除【不限】类型。 @@ -260,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 59c9ac33..80667415 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,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/picker/base/brn_picker_title.dart'; import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; @@ -25,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); /// 从屏幕下方弹起的多级筛选选择器 /// 可设置筛项的层级、多选、单选等筛选相关功能 @@ -35,7 +35,7 @@ class BrnMultiColumnPicker extends StatefulWidget { final BrnPickerEntity entity; /// 初始化时的选中选项 - final List defaultFocusedIndexes; + final List? defaultFocusedIndexes; /// Picker展示最大高度,默认 280 final double maxHeight; @@ -48,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, @@ -77,7 +77,7 @@ class BrnMultiColumnPicker extends StatefulWidget { : super(key: key) { this.themeData ??= BrnPickerConfig(); this.themeData = this - .themeData + .themeData! .merge(BrnThemeConfigurator.instance.getConfig().pickerConfig); } @@ -88,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() { @@ -123,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(), @@ -135,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, @@ -159,7 +159,7 @@ class _BrnSelectionGroupViewState extends State { } Widget _listWidget() { - List widgets = List(); + List widgets = []; if (!BrunoTools.isEmpty(_firstList) && BrunoTools.isEmpty(_secondList) && @@ -184,7 +184,7 @@ class _BrnSelectionGroupViewState extends State { _confirmButtonClickEvent(); } if (widget.onEntityTap != null) { - widget.onEntityTap(0, index, entity); + widget.onEntityTap!(0, index, entity); } })); } else if (!BrunoTools.isEmpty(_firstList) && @@ -204,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); } })); @@ -221,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) && @@ -241,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); } })); @@ -258,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( @@ -279,7 +279,7 @@ class _BrnSelectionGroupViewState extends State { } setState(() {}); if (widget.onEntityTap != null) { - widget.onEntityTap(2, index, entity); + widget.onEntityTap!(2, index, entity); } })); } @@ -304,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); } } @@ -343,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; } @@ -358,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); } @@ -413,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); } @@ -425,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); } } @@ -437,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(() { @@ -453,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; @@ -488,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 cb9e9959..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,29 +1,25 @@ -// @dart=2.9 + 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; } @@ -35,7 +31,7 @@ class BrnMultiColumnPickerUtil { } /// 确定当前 Item 在第几层级 - static int getCurrentColumnIndex(BrnPickerEntity currentItem) { + static int getCurrentColumnIndex(BrnPickerEntity? currentItem) { int listIndex = -1; if (currentItem != null) { listIndex = 0; @@ -52,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 b7342d71..e745625b 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,4 +1,4 @@ -// @dart=2.9 + 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'; @@ -12,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, @@ -37,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), @@ -57,7 +57,7 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { return GestureDetector( onTap: () { if (itemSelectFunction != null) { - itemSelectFunction(item); + itemSelectFunction!(item); } }, child: Container( @@ -90,8 +90,8 @@ class BrnMultiRangePickerCommonItem extends StatelessWidget { ); } - Color _getItemBGColor() { - if (isCurrentFocused) { + Color? _getItemBGColor() { + if (isCurrentFocused!) { return this.selectedBackgroundColor; } else { return this.backgroundColor; @@ -99,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; } @@ -123,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) { @@ -135,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 9ac9a4ba..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,4 +1,4 @@ -// @dart=2.9 + 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 9d6bf570..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,4 +1,4 @@ -// @dart=2.9 + import 'package:bruno/src/components/line/brn_line.dart'; import 'package:bruno/src/components/picker/base/brn_picker_constants.dart'; @@ -24,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, }) { @@ -57,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, @@ -100,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); } } }, @@ -120,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)), ], ), ], @@ -135,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: () { @@ -145,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( @@ -180,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 4b4fbe68..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,6 +1,6 @@ /// Selected value of DatePicker. -// @dart=2.9 + typedef DateValueCallback(DateTime dateTime, List selectedIndex); @@ -14,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 210eb24c..bed44c7f 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 @@ -34,11 +34,11 @@ class DateTimeFormatter { } 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 ''; } @@ -50,9 +50,9 @@ class DateTimeFormatter { } 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 ''; } @@ -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 6b82f1cf..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 @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; import 'package:bruno/src/components/picker/time_picker/brn_date_picker_constants.dart'; @@ -46,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 @@ -131,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); @@ -170,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( @@ -200,7 +198,7 @@ class _DatePickerRoute extends PopupRoute { ); if (theme != null) { - bottomSheet = Theme(data: theme, child: bottomSheet); + bottomSheet = Theme(data: theme!, child: bottomSheet); } return bottomSheet; } @@ -211,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( @@ -265,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, ), @@ -287,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 5347991b..b7f6622a 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,4 +1,4 @@ -// @dart=2.9 + import 'dart:math'; @@ -21,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( @@ -60,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; @@ -79,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(); @@ -141,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); } @@ -150,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); } @@ -159,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; @@ -175,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; @@ -187,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), @@ -214,21 +214,21 @@ 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( @@ -245,15 +245,15 @@ class _BrnDateWidgetState extends State { Widget _renderDatePickerItemComponent( ColumnType columnType, int index, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); + 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(); + 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), @@ -325,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 b34e316c..010a35dd 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,4 +1,4 @@ -// @dart=2.9 + import 'dart:math'; @@ -17,12 +17,12 @@ enum ColumnType { Year, Month, Day, Hour, Minute, Second } // 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, @@ -30,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( @@ -58,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) { @@ -134,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(); @@ -151,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); @@ -202,7 +202,7 @@ class _BrnDateTimeWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -216,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); } @@ -252,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; @@ -268,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; @@ -280,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), @@ -316,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); @@ -353,17 +353,17 @@ 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; } else if (format.contains('M')) { @@ -465,8 +465,8 @@ 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(); + 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]) || @@ -476,11 +476,11 @@ class _BrnDateTimeWidgetState extends State { index == _calcSelectIndexList()[4]) || (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), @@ -510,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(); @@ -576,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!); } } @@ -600,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, @@ -689,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; } @@ -717,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; @@ -731,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 e5a8aaec..314b6312 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,4 +1,4 @@ -// @dart=2.9 + import 'dart:math'; @@ -18,12 +18,12 @@ 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, @@ -31,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, @@ -59,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 @@ -155,7 +155,7 @@ class _BrnTimeWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -166,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); } @@ -177,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; @@ -193,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; @@ -205,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), @@ -232,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; @@ -267,7 +267,7 @@ class _BrnTimeWidgetState extends State { } // ignore: missing_return - ColumnType getColumnType(String format) { + ColumnType? getColumnType(String format) { if (format.contains('H')) { return ColumnType.Hour; } else if (format.contains('m')) { @@ -278,27 +278,27 @@ class _BrnTimeWidgetState extends State { 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(); + 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 && 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 9d975051..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 @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'package:bruno/src/components/picker/base/brn_picker_title_config.dart'; import 'package:bruno/src/components/picker/brn_picker_cliprrect.dart'; import 'package:bruno/src/components/picker/time_picker/brn_date_picker_constants.dart'; @@ -39,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 @@ -93,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, @@ -123,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, @@ -133,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); } @@ -149,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( @@ -182,7 +180,7 @@ class _DatePickerRoute extends PopupRoute { ); if (theme != null) { - bottomSheet = Theme(data: theme, child: bottomSheet); + bottomSheet = Theme(data: theme!, child: bottomSheet); } return bottomSheet; } @@ -192,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( @@ -234,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, ), @@ -256,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 c3113d61..97a46047 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 @@ -1,5 +1,3 @@ -// @dart=2.9 - import 'dart:math'; import 'package:bruno/src/components/picker/base/brn_picker.dart'; @@ -18,43 +16,43 @@ enum ColumnType { Year, Month, Day } // 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); } @@ -68,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(); @@ -132,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()), ); } @@ -141,7 +144,7 @@ class _DatePickerWidgetState extends State { void _onInitSelectedChange() { if (_onInitSelectChange != null) { DateTime dateTime = DateTime(_currYear, _currMonth, _currDay); - _onInitSelectChange(dateTime, _calcSelectIndexList()); + _onInitSelectChange!(dateTime, _calcSelectIndexList()); } } @@ -149,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; @@ -165,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; @@ -177,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), @@ -204,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")) { @@ -217,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; @@ -246,15 +249,15 @@ class _DatePickerWidgetState extends State { Widget _renderDatePickerItemComponent( ColumnType columnType, int index, int value, String format) { - TextStyle textStyle = widget.themeData.itemTextStyle.generateTextStyle(); + 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(); + 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 5a7294e8..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,4 +1,4 @@ -// @dart=2.9 + import 'dart:math'; @@ -18,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); } @@ -81,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(); @@ -115,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 = @@ -174,7 +174,7 @@ class _DatePickerWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -182,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); @@ -203,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, @@ -232,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, @@ -264,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 ca8e4ad0..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,4 +1,4 @@ -// @dart=2.9 + import 'dart:math'; @@ -14,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 @@ -68,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; @@ -115,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( @@ -148,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)), ); } @@ -164,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()); } } @@ -174,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; @@ -190,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; @@ -202,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), @@ -227,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")) { @@ -241,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; @@ -257,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; @@ -272,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 536932ab..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,4 +1,4 @@ -// @dart=2.9 + import 'dart:math'; @@ -16,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; @@ -50,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, @@ -71,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); } @@ -93,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, @@ -139,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; @@ -200,7 +196,7 @@ class _TimePickerWidgetState extends State { /// pressed cancel widget void _onPressedCancel() { if (widget.onCancel != null) { - widget.onCancel(); + widget.onCancel!(); } Navigator.pop(context); } @@ -208,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); @@ -229,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, @@ -260,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, @@ -336,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/selection/bean/brn_selection_common_entity.dart b/lib/src/components/selection/bean/brn_selection_common_entity.dart index 603093c5..14f96b7a 100644 --- a/lib/src/components/selection/bean/brn_selection_common_entity.dart +++ b/lib/src/components/selection/bean/brn_selection_common_entity.dart @@ -535,8 +535,8 @@ class BrnSelectionEntity { 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); + 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 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 bb29f3af..3d8ce56c 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 @@ -495,7 +495,7 @@ class __MoreRangeWidgetState extends State<_MoreRangeWidget> { item: widget.rangeEntity, isNeedTitle: false, showTextSize: 14, - dateFormat: DATETIME_PICKER_DATE_FORMAT, + dateFormat: datetimePickerDateFormat, minTextEditingController: minController, maxTextEditingController: maxController, themeData: widget.themeData, diff --git a/lib/src/theme/base/brn_default_config_utils.dart b/lib/src/theme/base/brn_default_config_utils.dart index 03c565fc..cbc06626 100644 --- a/lib/src/theme/base/brn_default_config_utils.dart +++ b/lib/src/theme/base/brn_default_config_utils.dart @@ -531,7 +531,7 @@ class BrnDefaultConfigUtils { ); static BrnPickerConfig defaultPickerConfig = BrnPickerConfig( - backgroundColor: PICKER_BACKGROUND_COLOR, + backgroundColor: pickerBackgroundColor, cancelTextStyle: BrnTextStyle( color: defaultCommonConfig.colorTextBase, fontSize: defaultCommonConfig.fontSizeSubHead, @@ -546,9 +546,9 @@ class BrnDefaultConfigUtils { fontWeight: FontWeight.w600, decoration: TextDecoration.none, ), - pickerHeight: PICKER_HEIGHT, - titleHeight: PICKER_TITLE_HEIGHT, - itemHeight: PICKER_ITEM_HEIGHT, + pickerHeight: pickerHeight, + titleHeight: pickerTitleHeight, + itemHeight: pickerItemHeight, dividerColor: Color(0xFFF0F0F0), itemTextStyle: BrnTextStyle( color: defaultCommonConfig.colorTextBase, diff --git a/lib/src/utils/i18n/brn_date_picker_i18n.dart b/lib/src/utils/i18n/brn_date_picker_i18n.dart index b8180a0a..0d90a097 100755 --- a/lib/src/utils/i18n/brn_date_picker_i18n.dart +++ b/lib/src/utils/i18n/brn_date_picker_i18n.dart @@ -63,7 +63,7 @@ enum DateTimePickerLocale { } /// Default value of date locale -const DateTimePickerLocale DATETIME_PICKER_LOCALE_DEFAULT = +const DateTimePickerLocale datetimePickerLocaleDefault = DateTimePickerLocale.zh_cn; const Map datePickerI18n = { @@ -76,28 +76,28 @@ class DatePickerI18n { /// Get done button text static String getLocaleDone(DateTimePickerLocale locale) { final _StringsI18n? i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; + datePickerI18n[datetimePickerLocaleDefault]; return i18n?.getDoneText() ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]!.getDoneText(); + datePickerI18n[datetimePickerLocaleDefault]!.getDoneText(); } /// Get cancel button text static String getLocaleCancel(DateTimePickerLocale locale) { final _StringsI18n? i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; + datePickerI18n[datetimePickerLocaleDefault]; return i18n?.getCancelText() ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]!.getCancelText(); + datePickerI18n[datetimePickerLocaleDefault]!.getCancelText(); } /// Get locale month array static List getLocaleMonths(DateTimePickerLocale locale) { final _StringsI18n? i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; + 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 @@ -106,13 +106,13 @@ class DatePickerI18n { bool isFull = true, ]) { final _StringsI18n? i18n = datePickerI18n[locale] ?? - datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]; + datePickerI18n[datetimePickerLocaleDefault]; if (isFull) { final List? weeks = i18n?.getWeeksFull(); if (weeks != null && weeks.isNotEmpty) { return weeks; } - return datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]!.getWeeksFull(); + return datePickerI18n[datetimePickerLocaleDefault]!.getWeeksFull(); } final List? weeks = i18n?.getWeeksShort(); @@ -126,6 +126,6 @@ class DatePickerI18n { .map((item) => item.substring(0, math.min(3, item.length))) .toList(); } - return datePickerI18n[DATETIME_PICKER_LOCALE_DEFAULT]!.getWeeksShort(); + return datePickerI18n[datetimePickerLocaleDefault]!.getWeeksShort(); } }