diff --git a/example/.flutter-plugins-dependencies b/example/.flutter-plugins-dependencies index ebd1aa0..59b6db4 100644 --- a/example/.flutter-plugins-dependencies +++ b/example/.flutter-plugins-dependencies @@ -1 +1 @@ -{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"path_provider","path":"/Users/linyunhe/.pub-cache/hosted/pub.dartlang.org/path_provider-0.4.1/","dependencies":[]}],"android":[{"name":"path_provider","path":"/Users/linyunhe/.pub-cache/hosted/pub.dartlang.org/path_provider-0.4.1/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"path_provider","dependencies":[]}],"date_created":"2021-06-08 17:37:57.339650","version":"1.22.6-xianyu"} \ No newline at end of file +{"info":"This is a generated file; do not edit or check into version control.","plugins":{"ios":[{"name":"path_provider","path":"/Users/lingyan/Downloads/flutter/.pub-cache/hosted/pub.flutter-io.cn/path_provider-0.4.1/","dependencies":[]}],"android":[{"name":"path_provider","path":"/Users/lingyan/Downloads/flutter/.pub-cache/hosted/pub.flutter-io.cn/path_provider-0.4.1/","dependencies":[]}],"macos":[],"linux":[],"windows":[],"web":[]},"dependencyGraph":[{"name":"path_provider","dependencies":[]}],"date_created":"2021-07-01 11:18:54.633183","version":"2.2.2"} \ No newline at end of file diff --git a/example/lib/app.dart b/example/lib/app.dart index d6cbf4f..2f5d45a 100644 --- a/example/lib/app.dart +++ b/example/lib/app.dart @@ -28,10 +28,10 @@ Widget createApp() { /// 2. 参数2 当 AppStore.state 变化时, PageStore.state 该如何变化 page.connectExtraStore(GlobalStore.store, (Object pagestate, GlobalState appState) { - final GlobalBaseState p = pagestate; + final GlobalBaseState p = pagestate as dynamic; if (p.themeColor != appState.themeColor) { if (pagestate is Cloneable) { - final Object copy = pagestate.clone(); + final dynamic copy = pagestate.clone(); final GlobalBaseState newState = copy; newState.themeColor = appState.themeColor; return newState; @@ -77,7 +77,7 @@ Widget createApp() { home: routes.buildPage('todo_list', null), onGenerateRoute: (RouteSettings settings) { return MaterialPageRoute(builder: (BuildContext context) { - return routes.buildPage(settings.name, settings.arguments); + return routes.buildPage(settings.name!, settings.arguments); }); }, ); @@ -87,7 +87,7 @@ Widget createApp() { /// 只针对页面的生命周期进行打印 EffectMiddleware _pageAnalyticsMiddleware({String tag = 'redux'}) { return (AbstractLogic logic, Store store) { - return (Effect effect) { + return (Effect? effect) { return (Action action, Context ctx) { if (logic is Page && action.type is Lifecycle) { print('${logic.runtimeType} ${action.type.toString()} '); diff --git a/example/lib/global_store/reducer.dart b/example/lib/global_store/reducer.dart index 2596b0d..6a40766 100644 --- a/example/lib/global_store/reducer.dart +++ b/example/lib/global_store/reducer.dart @@ -11,18 +11,17 @@ Reducer buildReducer() { >{ GlobalAction.changeThemeColor: _onchangeThemeColor, }, - ); + )!; } -List _colors = [ - Colors.green, - Colors.red, - Colors.black, - Colors.blue -]; +List _colors = [Colors.green, Colors.red, Colors.black, Colors.blue]; GlobalState _onchangeThemeColor(GlobalState state, Action action) { - final Color next = - _colors[((_colors.indexOf(state.themeColor) + 1) % _colors.length)]; - return state.clone()..themeColor = next; + if (state.themeColor != null) { + final Color next = + /// todo(不确定) + _colors[((_colors.indexOf(state.themeColor!) + 1) % _colors.length)]; + return state.clone()..themeColor = next; + } + return state.clone(); } diff --git a/example/lib/global_store/state.dart b/example/lib/global_store/state.dart index ca8ef6a..c6931d0 100644 --- a/example/lib/global_store/state.dart +++ b/example/lib/global_store/state.dart @@ -3,13 +3,13 @@ import 'dart:ui'; import 'package:fish_redux/fish_redux.dart'; abstract class GlobalBaseState { - Color get themeColor; - set themeColor(Color color); + Color? get themeColor; + set themeColor(Color? color); } class GlobalState implements GlobalBaseState, Cloneable { @override - Color themeColor; + Color? themeColor; @override GlobalState clone() { diff --git a/example/lib/global_store/store.dart b/example/lib/global_store/store.dart index 7d386c0..98e41e3 100644 --- a/example/lib/global_store/store.dart +++ b/example/lib/global_store/store.dart @@ -5,7 +5,7 @@ import 'state.dart'; /// 建立一个AppStore /// 目前它的功能只有切换主题 class GlobalStore { - static Store _globalStore; + static Store? _globalStore; static Store get store => _globalStore ??= createStore(GlobalState(), buildReducer()); diff --git a/example/lib/todo_edit_page/effect.dart b/example/lib/todo_edit_page/effect.dart index 83f3e9f..0d4dd15 100644 --- a/example/lib/todo_edit_page/effect.dart +++ b/example/lib/todo_edit_page/effect.dart @@ -11,7 +11,7 @@ Effect buildEffect() { return combineEffects(>{ ToDoEditAction.onDone: _onDone, ToDoEditAction.onChangeTheme: _onChangeTheme, - }); + })!; } void _onDone(Action action, Context ctx) { diff --git a/example/lib/todo_edit_page/state.dart b/example/lib/todo_edit_page/state.dart index 6523d4a..4881cf7 100644 --- a/example/lib/todo_edit_page/state.dart +++ b/example/lib/todo_edit_page/state.dart @@ -5,16 +5,16 @@ import '../global_store/state.dart'; import '../todo_list_page/todo_component/component.dart'; class TodoEditState implements GlobalBaseState, Cloneable { - ToDoState toDo; + late ToDoState toDo; - TextEditingController nameEditController; - TextEditingController descEditController; + late TextEditingController nameEditController; + late TextEditingController descEditController; - FocusNode focusNodeName; - FocusNode focusNodeDesc; + late FocusNode focusNodeName; + late FocusNode focusNodeDesc; @override - Color themeColor; + Color? themeColor; @override TodoEditState clone() { @@ -28,7 +28,7 @@ class TodoEditState implements GlobalBaseState, Cloneable { } } -TodoEditState initState(ToDoState arg) { +TodoEditState initState(ToDoState? arg) { final TodoEditState state = TodoEditState(); state.toDo = arg?.clone() ?? ToDoState(); state.nameEditController = TextEditingController(text: arg?.title); diff --git a/example/lib/todo_list_page/effect.dart b/example/lib/todo_list_page/effect.dart index ce01fc3..eb35b3f 100644 --- a/example/lib/todo_list_page/effect.dart +++ b/example/lib/todo_list_page/effect.dart @@ -10,7 +10,7 @@ Effect buildEffect() { return combineEffects(>{ Lifecycle.initState: _init, PageAction.onAdd: _onAdd, - }); + })!; } void _init(Action action, Context ctx) { diff --git a/example/lib/todo_list_page/flow_adapter/adapter.dart b/example/lib/todo_list_page/flow_adapter/adapter.dart index 52209c4..ae1364c 100644 --- a/example/lib/todo_list_page/flow_adapter/adapter.dart +++ b/example/lib/todo_list_page/flow_adapter/adapter.dart @@ -5,13 +5,12 @@ import '../todo_component/component.dart'; import 'reducer.dart'; import 'connector.dart'; -FlowAdapter get adapter => - FlowAdapter( +FlowAdapter get adapter => FlowAdapter( reducer: buildReducer(), - view: (PageState state) => - DependentArray( - length: state.itemCount, - builder: (int index) { - return ToDoConnector(index: index) + ToDoComponent(); - }, - )); + view: (PageState state) => DependentArray( + length: state.itemCount, + builder: (int index) { + return ToDoConnector(index: index) + ToDoComponent(); + }, + ), + ); diff --git a/example/lib/todo_list_page/flow_adapter/connector.dart b/example/lib/todo_list_page/flow_adapter/connector.dart index 21c9415..5b0361f 100644 --- a/example/lib/todo_list_page/flow_adapter/connector.dart +++ b/example/lib/todo_list_page/flow_adapter/connector.dart @@ -6,20 +6,20 @@ import '../todo_component/component.dart'; class ToDoConnector extends ConnOp { - ToDoConnector({this.index}); + ToDoConnector({required this.index}); final int index; @override - ToDoState get(PageState state) { - if (index >= state.toDos.length) { + ToDoState? get(PageState? state) { + if (index >= state!.toDos!.length) { return null; } - return state.toDos[index]; + return state.toDos?[index]; } @override void set(PageState state, ToDoState subState) { - state.toDos[index] = subState; + state.toDos![index] = subState; } } \ No newline at end of file diff --git a/example/lib/todo_list_page/flow_adapter/reducer.dart b/example/lib/todo_list_page/flow_adapter/reducer.dart index 5432d3c..fc5674e 100644 --- a/example/lib/todo_list_page/flow_adapter/reducer.dart +++ b/example/lib/todo_list_page/flow_adapter/reducer.dart @@ -6,20 +6,19 @@ import '../todo_component/action.dart' as todo_action; import '../todo_component/component.dart'; Reducer buildReducer() { - return asReducer(>{ - ToDoListAction.add: _add, - todo_action.ToDoAction.remove: _remove - }); + return asReducer(>{ToDoListAction.add: _add, todo_action.ToDoAction.remove: _remove})!; } PageState _add(PageState state, Action action) { final ToDoState toDo = action.payload; - return state.clone()..toDos = (state.toDos.toList()..add(toDo)); + final List list = state.toDos?.toList() ?? []; + list.add(toDo); + return state.clone()..toDos = list; } PageState _remove(PageState state, Action action) { final String unique = action.payload; return state.clone() - ..toDos = (state.toDos.toList() + ..toDos = (state.toDos?.toList() ?? [] ..removeWhere((ToDoState state) => state.uniqueId == unique)); } diff --git a/example/lib/todo_list_page/list_adapter/reducer.dart b/example/lib/todo_list_page/list_adapter/reducer.dart index bca34da..b13cff9 100644 --- a/example/lib/todo_list_page/list_adapter/reducer.dart +++ b/example/lib/todo_list_page/list_adapter/reducer.dart @@ -9,17 +9,19 @@ Reducer buildReducer() { return asReducer(>{ ToDoListAction.add: _add, todo_action.ToDoAction.remove: _remove - }); + })!; } PageState _add(PageState state, Action action) { final ToDoState toDo = action.payload; - return state.clone()..toDos = (state.toDos.toList()..add(toDo)); + List list = state.toDos?.toList() ?? []; + list.add(toDo); + return state.clone()..toDos = list; } PageState _remove(PageState state, Action action) { final String unique = action.payload; return state.clone() - ..toDos = (state.toDos.toList() + ..toDos = (state.toDos?.toList() ?? [] ..removeWhere((ToDoState state) => state.uniqueId == unique)); } diff --git a/example/lib/todo_list_page/page.dart b/example/lib/todo_list_page/page.dart index 19f433b..ab11ad3 100644 --- a/example/lib/todo_list_page/page.dart +++ b/example/lib/todo_list_page/page.dart @@ -1,7 +1,6 @@ import 'package:fish_redux/fish_redux.dart'; import 'effect.dart'; -import 'list_adapter/adapter.dart'; import 'flow_adapter/adapter.dart'; import 'reducer.dart'; import 'report_component/component.dart'; diff --git a/example/lib/todo_list_page/reducer.dart b/example/lib/todo_list_page/reducer.dart index da26848..64e67e9 100644 --- a/example/lib/todo_list_page/reducer.dart +++ b/example/lib/todo_list_page/reducer.dart @@ -7,7 +7,7 @@ import 'todo_component/component.dart'; Reducer buildReducer() { return asReducer( >{PageAction.initToDos: _initToDosReducer}, - ); + )!; } PageState _initToDosReducer(PageState state, Action action) { diff --git a/example/lib/todo_list_page/state.dart b/example/lib/todo_list_page/state.dart index 4cf260a..8ffe030 100644 --- a/example/lib/todo_list_page/state.dart +++ b/example/lib/todo_list_page/state.dart @@ -7,10 +7,10 @@ import 'todo_component/component.dart'; class PageState extends ItemListLike implements GlobalBaseState, Cloneable { - List toDos; + List? toDos; @override - Color themeColor; + Color? themeColor; @override PageState clone() { @@ -20,7 +20,7 @@ class PageState extends ItemListLike } @override - Object getItemData(int index) => toDos[index]; + Object getItemData(int index) => toDos?.elementAt(index) as dynamic; @override String getItemType(int index) => 'toDo'; @@ -30,12 +30,12 @@ class PageState extends ItemListLike @override ItemListLike updateItemData(int index, Object data, bool isStateCopied) { - toDos[index] = data; + toDos?[index] = data as dynamic; return this; } } -PageState initState(Map args) { +PageState initState(Map? args) { //just demo, do nothing here... return PageState(); } @@ -45,15 +45,15 @@ class ReportConnector extends ConnOp @override ReportState computed(PageState state) { return ReportState() - ..done = state.toDos.where((ToDoState tds) => tds.isDone).length - ..total = state.toDos.length; + ..done = state.toDos?.where((ToDoState tds) => tds.isDone).length ?? 0 + ..total = state.toDos?.length ?? 0; } @override List factors(PageState state) { return [ - state.toDos.where((ToDoState tds) => tds.isDone).length, - state.toDos.length + state.toDos?.where((ToDoState tds) => tds.isDone).length ?? 0, + state.toDos?.length ?? 0 ]; } diff --git a/example/lib/todo_list_page/todo_component/effect.dart b/example/lib/todo_list_page/todo_component/effect.dart index 9d003df..f004540 100644 --- a/example/lib/todo_list_page/todo_component/effect.dart +++ b/example/lib/todo_list_page/todo_component/effect.dart @@ -8,7 +8,7 @@ Effect buildEffect() { return combineEffects(>{ ToDoAction.onEdit: _onEdit, ToDoAction.onRemove: _onRemove, - }); + })!; } void _onEdit(Action action, Context ctx) { @@ -27,7 +27,7 @@ void _onEdit(Action action, Context ctx) { } void _onRemove(Action action, Context ctx) async { - final String select = await showDialog( + final String? select = await showDialog( context: ctx.context, builder: (BuildContext buildContext) { return AlertDialog( @@ -49,6 +49,6 @@ void _onRemove(Action action, Context ctx) async { }); if (select == 'Yes') { - ctx.dispatch(ToDoActionCreator.removeAction(ctx.state.uniqueId)); + ctx.dispatch(ToDoActionCreator.removeAction(ctx.state.uniqueId!)); } } diff --git a/example/lib/todo_list_page/todo_component/reducer.dart b/example/lib/todo_list_page/todo_component/reducer.dart index 2e28e8b..4c932bd 100644 --- a/example/lib/todo_list_page/todo_component/reducer.dart +++ b/example/lib/todo_list_page/todo_component/reducer.dart @@ -7,7 +7,7 @@ Reducer buildReducer() { return asReducer(>{ ToDoAction.edit: _edit, ToDoAction.done: _markDone - }); + })!; } ToDoState _edit(ToDoState state, Action action) { diff --git a/example/lib/todo_list_page/todo_component/state.dart b/example/lib/todo_list_page/todo_component/state.dart index d8e4d64..ca0c8d3 100644 --- a/example/lib/todo_list_page/todo_component/state.dart +++ b/example/lib/todo_list_page/todo_component/state.dart @@ -2,9 +2,9 @@ import 'package:fish_redux/fish_redux.dart'; // import 'package:uuid/uuid.dart'; class ToDoState implements Cloneable { - String uniqueId; - String title; - String desc; + String? uniqueId; + String? title; + String? desc; bool isDone; static int _seed = 202103051044; diff --git a/example/lib/todo_list_page/todo_component/view.dart b/example/lib/todo_list_page/todo_component/view.dart index 32f9e4e..f9a964a 100644 --- a/example/lib/todo_list_page/todo_component/view.dart +++ b/example/lib/todo_list_page/todo_component/view.dart @@ -38,7 +38,7 @@ Widget buildView( : const Icon(Icons.check_box_outline_blank))(), ), onTap: () { - dispatch(ToDoActionCreator.doneAction(state.uniqueId)); + dispatch(ToDoActionCreator.doneAction(state.uniqueId!)); }, ) ], @@ -63,7 +63,7 @@ Widget buildView( child: const Icon(Icons.edit), ), onTap: () { - dispatch(ToDoActionCreator.onEditAction(state.uniqueId)); + dispatch(ToDoActionCreator.onEditAction(state.uniqueId!)); }, ) ], @@ -72,7 +72,7 @@ Widget buildView( ], ), onLongPress: () { - dispatch(ToDoActionCreator.onRemoveAction(state.uniqueId)); + dispatch(ToDoActionCreator.onRemoveAction(state.uniqueId!)); }, ), ); diff --git a/example/lib/todo_list_page/view.dart b/example/lib/todo_list_page/view.dart index e4a7b69..13cbc1c 100644 --- a/example/lib/todo_list_page/view.dart +++ b/example/lib/todo_list_page/view.dart @@ -5,7 +5,7 @@ import 'action.dart'; import 'state.dart'; Widget buildView(PageState state, Dispatch dispatch, ViewService viewService) { - final ListAdapter adapter = viewService.buildAdapter(); + final ListAdapter adapter = viewService.buildAdapter()!; return Scaffold( appBar: AppBar( backgroundColor: state.themeColor, @@ -17,7 +17,7 @@ Widget buildView(PageState state, Dispatch dispatch, ViewService viewService) { viewService.buildComponent('report'), Expanded( child: ListView.builder( - itemBuilder: adapter.itemBuilder, + itemBuilder: adapter.itemBuilder!, itemCount: adapter.itemCount)) ], ), diff --git a/example/pubspec.yaml b/example/pubspec.yaml index c635dbc..ab189b4 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -10,7 +10,7 @@ description: Demonstrates how to use the fish_redux. version: 1.0.0+1 environment: - sdk: '>=2.0.0-dev.68.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: fish_redux: @@ -20,12 +20,9 @@ dependencies: path_provider: ^0.4.1 dev_dependencies: - test: ^1.3.0 mockito: ^3.0.0 flutter_driver: sdk: flutter - flutter_test: - sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://www.dartlang.org/tools/pub/pubspec diff --git a/lib/src/extensions/adapter_extensions.dart b/lib/src/extensions/adapter_extensions.dart index 5b5f75d..7950086 100644 --- a/lib/src/extensions/adapter_extensions.dart +++ b/lib/src/extensions/adapter_extensions.dart @@ -9,11 +9,13 @@ import 'connector_extensions.dart'; class SimpleFlowAdapter extends FlowAdapter { SimpleFlowAdapter({ - @required FlowAdapterView view, - ReducerFilter filter, - Reducer reducer, - Effect effect, - @deprecated Object Function(T state) key, + required FlowAdapterView view, + + /// 父类可空 + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, + @deprecated Object Function(T state)? key, }) : super( view: view, filter: filter, @@ -23,11 +25,11 @@ class SimpleFlowAdapter extends FlowAdapter { ); SimpleFlowAdapter.static({ - @required List> children, - ReducerFilter filter, - Reducer reducer, - Effect effect, - @deprecated Object Function(T state) key, + required List> children, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, + @deprecated Object Function(T state)? key, }) : this( view: _buildByStatic(children), filter: filter, @@ -37,12 +39,12 @@ class SimpleFlowAdapter extends FlowAdapter { ); SimpleFlowAdapter.dynamic({ - @required Map> pool, - @required AbstractConnector> connector, - ReducerFilter filter, - Reducer reducer, - Effect effect, - @deprecated Object Function(T state) key, + required Map> pool, + required AbstractConnector> connector, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, + @deprecated required Object Function(T state) key, }) : this( view: _buildByDynamic(pool: pool, connector: connector), filter: filter, @@ -52,12 +54,12 @@ class SimpleFlowAdapter extends FlowAdapter { ); SimpleFlowAdapter.listLike({ - @required Map> pool, - @required AbstractConnector connector, - ReducerFilter filter, - Reducer reducer, - Effect effect, - @deprecated Object Function(T state) key, + required Map> pool, + required AbstractConnector connector, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, + @deprecated required Object Function(T state) key, }) : this( view: _buildByListLike(pool: pool, connector: connector), filter: filter, @@ -69,28 +71,28 @@ class SimpleFlowAdapter extends FlowAdapter { FlowAdapterView _buildByStatic(List> children) { return (T state) { - return DependentArray.fromList(children - .where((Dependent dep) => dep.subGetter(() => state).call() != null) - .toList()); + return DependentArray.fromList( + children.where((Dependent dep) => dep.subGetter(() => state).call() != null).toList()); }; } FlowAdapterView _buildByListLike({ - @required Map> pool, - @required AbstractConnector connector, + required Map> pool, + required AbstractConnector connector, }) { return (T state) { - final MutableItemListLike source = connector.get(state); + ///todo(不确定) + final MutableItemListLike source = connector.get(state)!; final DependentArray depList = DependentArray( length: source.itemCount, builder: (int index) { final String type = source.getItemType(index); - final Dependent dep = ConnHelper.join( + final Dependent? dep = ConnHelper.join( ConnHelper.to( connector, IndexedListLikeConn(index), ), - pool[type], + pool[type]!, ); return dep; }, @@ -100,11 +102,12 @@ FlowAdapterView _buildByListLike({ } FlowAdapterView _buildByDynamic({ - @required Map> pool, - @required AbstractConnector> connector, + required Map> pool, + required AbstractConnector> connector, }) { return (T state) { - final List list = connector.get(state); + ///todo(不确定) + final List list = connector.get(state)!; final DependentArray depList = DependentArray( length: list.length, builder: (int index) { @@ -117,7 +120,8 @@ FlowAdapterView _buildByDynamic({ connector, IndexedListConn(index), ), - pool[ib.type], + ///todo(不确定) + pool[ib.type]!, ); } return null; diff --git a/lib/src/extensions/component_extensions.dart b/lib/src/extensions/component_extensions.dart index f09ea36..7edbd49 100644 --- a/lib/src/extensions/component_extensions.dart +++ b/lib/src/extensions/component_extensions.dart @@ -4,11 +4,11 @@ import 'package:flutter/widgets.dart' hide Action; abstract class SimpleComponent extends Component { SimpleComponent({ - ReducerFilter filter, - Dependencies dependencies, - ShouldUpdate shouldUpdate, - WidgetWrapper wrapper, - @deprecated Key Function(T) key, + ReducerFilter? filter, + Dependencies? dependencies, + ShouldUpdate? shouldUpdate, + WidgetWrapper? wrapper, + @deprecated Key Function(T)? key, bool clearOnDependenciesChanged = false, }) : super( view: null, diff --git a/lib/src/extensions/connector_extensions.dart b/lib/src/extensions/connector_extensions.dart index 5ca32de..7684d3c 100644 --- a/lib/src/extensions/connector_extensions.dart +++ b/lib/src/extensions/connector_extensions.dart @@ -5,21 +5,22 @@ import '../redux_component/basic.dart'; import '../redux_connector/redux_connector.dart'; mixin IndexedConnMixin on AbstractConnector { - P _cached; + late P _cached; int get index; P getByIndex(T state, int index); @override - P get(T state) { - final P newState = getByIndex(state, index); - return checkNextState(newState); + P? get(T? state) { + ///todo(不确定) + final P newState = getByIndex(state!, index); + return checkNextState(newState as dynamic); } /// fix get 存在状态不同步 P checkNextState(Object newState) { - final Object lastState = _cached; + final Object lastState = _cached as Object; final Object nextState = ((newState is! P || newState.runtimeType != lastState.runtimeType) ? false @@ -27,7 +28,7 @@ mixin IndexedConnMixin on AbstractConnector { (lastState is StateKey ? lastState.key() : null)) ? newState : lastState; - return _cached = nextState; + return _cached = nextState as P; } } @@ -63,11 +64,11 @@ class IndexedListConn

extends MutableIndexedConn, P> @override P getByIndex(List

state, int index) { final P newState = state[index]; - return checkNextState(newState); + return checkNextState(newState as Object); } @override - void setByIndex(List

state, Object subState, int index) { + void setByIndex(List

state, P subState, int index) { state[index] = subState; } } diff --git a/lib/src/redux/apply_middleware.dart b/lib/src/redux/apply_middleware.dart index c185d64..6efefa7 100644 --- a/lib/src/redux/apply_middleware.dart +++ b/lib/src/redux/apply_middleware.dart @@ -2,7 +2,8 @@ import 'basic.dart'; /// Accumulate a list of Middleware that enhances Dispatch to the Store. /// The wrapped direction of the Store.dispatch is from inside to outside. -StoreEnhancer applyMiddleware(List> middleware) { +/// 可空 #7 +StoreEnhancer? applyMiddleware(List> middleware) { return middleware == null || middleware.isEmpty ? null : (StoreCreator creator) => (T initState, Reducer reducer) { diff --git a/lib/src/redux/basic.dart b/lib/src/redux/basic.dart index a372f3f..94fbe5a 100644 --- a/lib/src/redux/basic.dart +++ b/lib/src/redux/basic.dart @@ -28,7 +28,8 @@ class Action { /// Definition of the standard Reducer. /// If the Reducer needs to respond to the Action, it returns a new state, otherwise it returns the old state. -typedef Reducer = T Function(T state, Action action); +/// 可空 +typedef Reducer = T? Function(T state, Action action); /// Definition of the standard Dispatch. /// Send an "intention". @@ -58,12 +59,12 @@ typedef Middleware = Composable Function({ /// Definition of the standard Store. class Store { - Get getState; - Dispatch dispatch; - Subscribe subscribe; - Observable observable; - ReplaceReducer replaceReducer; - Future Function() teardown; + late Get getState; + late Dispatch dispatch; + late Subscribe subscribe; + late Observable observable; + late ReplaceReducer replaceReducer; + late Future Function() teardown; } /// Create a store definition @@ -85,7 +86,8 @@ typedef SubReducer = T Function(T state, Action action, bool isStateCopied); /// 2. How to synchronize changes of an instance of type P to an instance of type S. /// 3. How to clone a new S. abstract class AbstractConnector { - P get(S state); + /// 可空 【connector.dart#17】 [helper.dart#24] state? + P? get(S? state); /// For mutable state, there are three abilities needed to be met. /// 1. get: (S) => P @@ -97,5 +99,6 @@ abstract class AbstractConnector { /// 2. set: (S, P) => S /// /// See in [connector]. - SubReducer subReducer(Reducer

reducer); + /// 可空 【connector.dart#87】 [basic.dart#286] reducer? + SubReducer? subReducer(Reducer

? reducer); } diff --git a/lib/src/redux/combine_reducers.dart b/lib/src/redux/combine_reducers.dart index d3d0e86..c15cb1f 100644 --- a/lib/src/redux/combine_reducers.dart +++ b/lib/src/redux/combine_reducers.dart @@ -1,36 +1,38 @@ import 'basic.dart'; /// Combine an iterable of SubReducer into one Reducer -Reducer combineSubReducers(Iterable> subReducers) { - final List> notNullReducers = subReducers - ?.where((SubReducer e) => e != null) - ?.toList(growable: false); +/// 可空 +Reducer? combineSubReducers(Iterable?> subReducers) { + final List?>? notNullReducers = subReducers + .where((SubReducer? e) => e != null) + .toList(growable: false); if (notNullReducers == null || notNullReducers.isEmpty) { return null; } if (notNullReducers.length == 1) { - final SubReducer single = notNullReducers.single; - return (T state, Action action) => single(state, action, false); + final SubReducer? single = notNullReducers.single; + return (T state, Action action) => single?.call(state, action, false); } return (T state, Action action) { - T copy = state; + T? _copy; bool hasChanged = false; - for (SubReducer subReducer in notNullReducers) { - copy = subReducer(copy, action, hasChanged); - hasChanged = hasChanged || copy != state; + for (SubReducer? subReducer in notNullReducers) { + _copy = subReducer?.call(state, action, hasChanged); + hasChanged = hasChanged || _copy != state; } - assert(copy != null); - return copy; + assert(_copy != null); + return _copy; }; } /// Combine an iterable of Reducer into one Reducer -Reducer combineReducers(Iterable> reducers) { - final List> notNullReducers = - reducers?.where((Reducer r) => r != null)?.toList(growable: false); +/// 可空 +Reducer? combineReducers(Iterable?>? reducers) { + final List?>? notNullReducers = + reducers?.where((Reducer? r) => r != null).toList(growable: false); if (notNullReducers == null || notNullReducers.isEmpty) { return null; } @@ -41,8 +43,10 @@ Reducer combineReducers(Iterable> reducers) { return (T state, Action action) { T nextState = state; - for (Reducer reducer in notNullReducers) { - nextState = reducer(nextState, action); + for (Reducer? reducer in notNullReducers) { + /// 这里有问题,必须要重新赋值对象 + final T? _nextState = reducer?.call(nextState, action); + nextState = _nextState!; } assert(nextState != null); return nextState; @@ -50,11 +54,12 @@ Reducer combineReducers(Iterable> reducers) { } /// Convert a super Reducer to a sub Reducer -Reducer castReducer(Reducer sup) { +/// 可空 +Reducer? castReducer(Reducer? sup) { return sup == null ? null : (Sub state, Action action) { - final Sub result = sup(state, action); + final Sub result = sup(state, action) as dynamic; return result; }; } diff --git a/lib/src/redux/connector.dart b/lib/src/redux/connector.dart index 8e39009..cb23a16 100644 --- a/lib/src/redux/connector.dart +++ b/lib/src/redux/connector.dart @@ -19,16 +19,17 @@ abstract class ImmutableConn implements AbstractConnector { T set(T state, P subState); + /// 可空 reducer? @override - SubReducer subReducer(Reducer

reducer) { + SubReducer? subReducer(Reducer

? reducer) { return reducer == null ? null : (T state, Action action, bool isStateCopied) { - final P props = get(state); + final P? props = get(state); if (props == null) { return state; } - final P newProps = reducer(props, action); + final P newProps = reducer.call(props, action)!; final bool hasChanged = !identical(newProps, props); if (hasChanged) { final T result = set(state, newProps); @@ -82,16 +83,17 @@ abstract class MutableConn implements AbstractConnector { void set(T state, P subState); + /// 可空 @override - SubReducer subReducer(Reducer

reducer) { + SubReducer? subReducer(Reducer

? reducer) { return reducer == null ? null : (T state, Action action, bool isStateCopied) { - final P props = get(state); + final P? props = get(state); if (props == null) { return state; } - final P newProps = reducer(props, action); + final P newProps = reducer(props, action)!; final bool hasChanged = newProps != props; final T copy = (hasChanged && !isStateCopied) ? _clone(state) : state; diff --git a/lib/src/redux/create_store.dart b/lib/src/redux/create_store.dart index c2f1914..9301d91 100644 --- a/lib/src/redux/create_store.dart +++ b/lib/src/redux/create_store.dart @@ -6,13 +6,14 @@ Reducer _noop() => (T state, Action action) => state; typedef _VoidCallback = void Function(); -void _throwIfNot(bool condition, [String message]) { +void _throwIfNot(bool condition, [dynamic message]) { if (!condition) { throw ArgumentError(message); } } -Store _createStore(final T preloadedState, final Reducer reducer) { +/// 可空 reducer? +Store _createStore(final T preloadedState, final Reducer? reducer) { _throwIfNot( preloadedState != null, 'Expected the preloadedState to be non-null value.', @@ -41,7 +42,7 @@ Store _createStore(final T preloadedState, final Reducer reducer) { try { _isDispatching = true; - _state = _reducer(_state, action); + _state = _reducer(_state, action)!; } finally { _isDispatching = false; } @@ -55,8 +56,8 @@ Store _createStore(final T preloadedState, final Reducer reducer) { _notifyController.add(_state); } - ..replaceReducer = (Reducer replaceReducer) { - _reducer = replaceReducer ?? _noop; + ..replaceReducer = (Reducer? replaceReducer) { + _reducer = replaceReducer ?? _noop as T Function(T, Action); } ..subscribe = (_VoidCallback listener) { _throwIfNot( @@ -88,12 +89,14 @@ Store _createStore(final T preloadedState, final Reducer reducer) { /// create a store with enhancer Store createStore(T preloadedState, Reducer reducer, - [StoreEnhancer enhancer]) => + /// 可空 + [StoreEnhancer? enhancer]) => enhancer != null ? enhancer(_createStore)(preloadedState, reducer) : _createStore(preloadedState, reducer); -StoreEnhancer composeStoreEnhancer(List> enhancers) => +/// 可空 enhancers? +StoreEnhancer? composeStoreEnhancer(List>? enhancers) => enhancers == null || enhancers.isEmpty ? null : enhancers.reduce((StoreEnhancer previous, StoreEnhancer next) => diff --git a/lib/src/redux_adapter/adapter.dart b/lib/src/redux_adapter/adapter.dart index 095ead5..fffc391 100644 --- a/lib/src/redux_adapter/adapter.dart +++ b/lib/src/redux_adapter/adapter.dart @@ -7,15 +7,17 @@ import '../redux_component/redux_component.dart'; abstract class Adapter extends Logic implements AbstractAdapter { final AdapterBuilder _adapter; - AdapterBuilder get protectedAdapter => _adapter; + AdapterBuilder? get protectedAdapter => _adapter; Adapter({ - @required AdapterBuilder adapter, - Reducer reducer, - ReducerFilter filter, - Effect effect, - Dependencies dependencies, - @deprecated Object Function(T) key, + required AdapterBuilder adapter, + /// 可空 + Reducer? reducer, + /// 可空 + ReducerFilter? filter, + Effect? effect, + Dependencies? dependencies, + @deprecated Object Function(T)? key, }) : assert(adapter != null), assert(dependencies?.adapter == null, 'Unexpected dependencies.list for Adapter.'), @@ -30,7 +32,7 @@ abstract class Adapter extends Logic implements AbstractAdapter { ); @override - ListAdapter buildAdapter(ContextSys ctx) => + ListAdapter? buildAdapter(ContextSys ctx) => ctx.enhancer ?.adapterEnhance(protectedAdapter, this, ctx.store) ?.call(ctx.state, ctx.dispatch, ctx) ?? @@ -41,8 +43,8 @@ abstract class Adapter extends Logic implements AbstractAdapter { Store store, BuildContext buildContext, Get getState, { - @required Enhancer enhancer, - @required DispatchBus bus, + required Enhancer enhancer, + required DispatchBus bus, }) { assert(bus != null && enhancer != null); return AdapterContext( @@ -58,12 +60,12 @@ abstract class Adapter extends Logic implements AbstractAdapter { class AdapterContext extends LogicContext { AdapterContext({ - @required AbstractAdapter logic, - @required Store store, - @required BuildContext buildContext, - @required Get getState, - @required DispatchBus bus, - @required Enhancer enhancer, + required AbstractAdapter logic, + required Store store, + required BuildContext buildContext, + required Get getState, + required DispatchBus bus, + required Enhancer enhancer, }) : assert(bus != null && enhancer != null), super( logic: logic, @@ -75,8 +77,8 @@ class AdapterContext extends LogicContext { ); @override - ListAdapter buildAdapter() { - final AbstractAdapter curLogic = logic; + ListAdapter? buildAdapter() { + final AbstractAdapter curLogic = logic as dynamic; return curLogic.buildAdapter(this); } } diff --git a/lib/src/redux_adapter/dynamic_flow_adapter.dart b/lib/src/redux_adapter/dynamic_flow_adapter.dart index 8bc9fd6..638540c 100644 --- a/lib/src/redux_adapter/dynamic_flow_adapter.dart +++ b/lib/src/redux_adapter/dynamic_flow_adapter.dart @@ -15,18 +15,18 @@ class DynamicFlowAdapter extends Logic with RecycleContextMixin { final AbstractConnector> connector; DynamicFlowAdapter({ - @required this.pool, - @required this.connector, - ReducerFilter filter, - Reducer reducer, - Effect effect, + required this.pool, + required this.connector, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, /// implement [StateKey] in T instead of using key in Logic. /// class T implements StateKey { /// Object _key = UniqueKey(); /// Object key() => _key; /// } - @deprecated Object Function(T) key, + @deprecated Object Function(T)? key, }) : super( reducer: _dynamicReducer(reducer, pool, connector), effect: effect, @@ -36,12 +36,14 @@ class DynamicFlowAdapter extends Logic with RecycleContextMixin { key: key, ); + /// 可空 @override - ListAdapter buildAdapter(ContextSys ctx) { - final List list = connector.get(ctx.state); + ListAdapter? buildAdapter(ContextSys ctx) { + ///todo(不确定) + final List list = connector.get(ctx.state)!; assert(list != null); - final RecycleContext recycleCtx = ctx; + final RecycleContext recycleCtx = ctx as dynamic; final List adapters = []; recycleCtx.markAllUnused(); @@ -49,9 +51,8 @@ class DynamicFlowAdapter extends Logic with RecycleContextMixin { for (int index = 0; index < list.length; index++) { final ItemBean itemBean = list[index]; final String type = itemBean.type; - final AbstractLogic result = pool[type]; - assert( - result != null, 'Type of $type has not benn registered in the pool.'); + final AbstractLogic result = pool[type]!; + assert(result != null, 'Type of $type has not benn registered in the pool.'); if (result != null) { if (result is AbstractAdapter) { final ContextSys subCtx = recycleCtx.reuseOrCreate( @@ -62,19 +63,23 @@ class DynamicFlowAdapter extends Logic with RecycleContextMixin { () => result.createContext( recycleCtx.store, recycleCtx.context, - _subGetter(() => connector.get(recycleCtx.state), index), + + /// todo(不确定) + _subGetter(() => connector.get(recycleCtx.state)!, index), bus: recycleCtx.bus, enhancer: recycleCtx.enhancer, ), ); /// hack to reduce adapter's rebuilding - adapters.add(memoizeListAdapter(result, subCtx)); + adapters.add(memoizeListAdapter(result as AbstractAdapterBuilder, subCtx)); } else if (result is AbstractComponent) { adapters.add(ListAdapter((BuildContext buildContext, int _) { return result.buildComponent( recycleCtx.store, - _subGetter(() => connector.get(recycleCtx.state), index), + + /// todo(不确定) + _subGetter(() => connector.get(recycleCtx.state)!, index), bus: recycleCtx.bus, enhancer: recycleCtx.enhancer, ); @@ -89,17 +94,17 @@ class DynamicFlowAdapter extends Logic with RecycleContextMixin { } /// Generate reducer for List and combine them into one -Reducer _dynamicReducer( - Reducer reducer, +/// 可空 +Reducer? _dynamicReducer( + Reducer? reducer, Map> pool, AbstractConnector> connector, ) { - final Reducer> dyReducer = - (List state, Action action) { - List copy; + final Reducer> dyReducer = (List state, Action action) { + List? copy; for (int i = 0; i < state.length; i++) { final ItemBean itemBean = state[i]; - final AbstractLogic result = pool[itemBean.type]; + final AbstractLogic? result = pool[itemBean.type]; if (result != null) { final Object newData = result.onReducer(itemBean.data, action); if (newData != itemBean.data) { @@ -111,9 +116,9 @@ Reducer _dynamicReducer( return copy ?? state; }; - return combineReducers(>[ + return combineReducers(?>[ reducer, - combineSubReducers(>[connector.subReducer(dyReducer)]), + combineSubReducers(?>[connector.subReducer(dyReducer)]), ]); } @@ -128,7 +133,7 @@ Get _subGetter(Get> getter, int index) { ItemBean cacheItem = curState[index]; return () { - final List newState = getter(); + final List? newState = getter(); /// Either all sub-components use cache or not. if (newState != null && newState.length > index) { @@ -142,18 +147,18 @@ Get _subGetter(Get> getter, int index) { }; } -bool _couldReuse(ItemBean beanA, ItemBean beanB) { - if (beanA.type != beanB.type) { +bool _couldReuse(ItemBean? beanA, ItemBean? beanB) { + if (beanA?.type != beanB?.type) { return false; } - final Object dataA = beanA.data; - final Object dataB = beanB.data; + final Object? dataA = beanA?.data; + final Object? dataB = beanB?.data; if (dataA.runtimeType != dataB.runtimeType) { return false; } - final Object keyA = dataA is StateKey ? dataA.key() : null; - final Object keyB = dataB is StateKey ? dataB.key() : null; + final Object? keyA = dataA is StateKey ? dataA.key() : null; + final Object? keyB = dataB is StateKey ? dataB.key() : null; return keyA == keyB; } diff --git a/lib/src/redux_adapter/flow_adapter.dart b/lib/src/redux_adapter/flow_adapter.dart index 43df0f9..b11fcfc 100644 --- a/lib/src/redux_adapter/flow_adapter.dart +++ b/lib/src/redux_adapter/flow_adapter.dart @@ -9,11 +9,11 @@ class FlowAdapter extends Logic implements AbstractAdapter { final FlowDependencies _flowDependencies; FlowAdapter({ - @required FlowAdapterView view, - ReducerFilter filter, - Reducer reducer, - Effect effect, - @deprecated Object Function(T state) key, + required FlowAdapterView view, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, + @deprecated Object Function(T state)? key, }) : assert(view != null), _flowDependencies = FlowDependencies(_memoize>(view)), @@ -34,14 +34,14 @@ class FlowAdapter extends Logic final T state = ctx.state; final DependentArray depArray = _flowDependencies.build(state); - final RecycleContext recycleCtx = ctx; + final RecycleContext recycleCtx = ctx as dynamic; final List adapters = []; recycleCtx.markAllUnused(); final int count = depArray.length; for (int index = 0; index < count; index++) { - final Dependent dependent = depArray[index]; + final Dependent? dependent = depArray[index]; if (dependent == null) { continue; @@ -62,7 +62,7 @@ class FlowAdapter extends Logic }, ); - adapters.add(dependent.buildAdapter(subCtx)); + adapters.add(dependent.buildAdapter(subCtx)!); } else if (dependent.isComponent()) { adapters.add(ListAdapter((BuildContext buildContext, int index) { return dependent.buildComponent( @@ -81,19 +81,19 @@ class FlowAdapter extends Logic } ////////////////////////////////////////// -typedef IndexedDependentBuilder = Dependent Function(int); +typedef IndexedDependentBuilder = Dependent? Function(int); class DependentArray { final IndexedDependentBuilder builder; final int length; - DependentArray({@required this.builder, @required this.length}) + DependentArray({required this.builder, required this.length}) : assert(builder != null && length >= 0); DependentArray.fromList(List> list) : this(builder: (int index) => list[index], length: list.length); - Dependent operator [](int index) => builder(index); + Dependent? operator [](int index) => builder(index); } typedef FlowAdapterView = DependentArray Function(T); @@ -106,11 +106,11 @@ class FlowDependencies { Reducer createReducer() => (T state, Action action) { T copy = state; bool hasChanged = false; - final DependentArray list = build(state); + final DependentArray? list = build(state); if (list != null) { for (int i = 0; i < list.length; i++) { - final Dependent dep = list[i]; - final SubReducer subReducer = dep?.createSubReducer(); + final Dependent? dep = list[i]; + final SubReducer? subReducer = dep?.createSubReducer(); if (subReducer != null) { copy = subReducer(copy, action, hasChanged); hasChanged = hasChanged || copy != state; @@ -166,15 +166,16 @@ class ItemBean { const ItemBean(this.type, this.data); - ItemBean clone({String type, Object data}) => + /// 可空 + ItemBean clone({String? type, Object? data}) => ItemBean(type ?? this.type, data ?? this.data); } /// Optimize flow-adapter-view performance R Function(P) _memoize(R Function(P) functor) { bool hasInvoked = false; - P cahcedKey; - R cachedValue; + late P cahcedKey; + late R cachedValue; return (P param) { if (!hasInvoked) { hasInvoked = true; diff --git a/lib/src/redux_adapter/recycle_context.dart b/lib/src/redux_adapter/recycle_context.dart index 7421590..47aa11e 100644 --- a/lib/src/redux_adapter/recycle_context.dart +++ b/lib/src/redux_adapter/recycle_context.dart @@ -10,12 +10,12 @@ class RecycleContext extends AdapterContext { final Map _usedIndexMap = {}; RecycleContext({ - @required AbstractAdapter logic, - @required @required Store store, - @required BuildContext buildContext, - @required Get getState, - @required DispatchBus bus, - @required Enhancer enhancer, + required AbstractAdapter logic, + @required required Store store, + required BuildContext buildContext, + required Get getState, + required DispatchBus bus, + required Enhancer enhancer, }) : super( logic: logic, store: store, @@ -27,8 +27,8 @@ class RecycleContext extends AdapterContext { @override void onLifecycle(Action action) { - _cachedMap.forEach((Object key, List> list) { - for (ContextSys sub in list) { + _cachedMap.forEach((Object key, List> list) { + for (ContextSys sub in list) { sub.onLifecycle(action); } }); @@ -46,7 +46,7 @@ class RecycleContext extends AdapterContext { _cachedMap[key] ??= >[]; if (length > list.length) { - _cachedMap[key].add( + _cachedMap[key]?.add( create() ..setParent(this) ..onLifecycle(LifecycleCreator.initState()), @@ -76,9 +76,9 @@ mixin RecycleContextMixin implements AbstractAdapter { RecycleContext createContext( Store store, BuildContext buildContext, - Get getState, { - @required DispatchBus bus, - @required Enhancer enhancer, + Get getState, { + required DispatchBus bus, + required Enhancer enhancer, }) { assert(bus != null && enhancer != null); @@ -102,7 +102,8 @@ ListAdapter combineListAdapters(Iterable adapters) { /// The result is AbstractComponent return ListAdapter( (BuildContext buildContext, final int index) => - list[index].itemBuilder(buildContext, 0), + ///todo(不确定) + list[index].itemBuilder!(buildContext, 0), list.length, ); } else if (list.length == 1) { @@ -124,7 +125,8 @@ ListAdapter combineListAdapters(Iterable adapters) { xIndex++; } assert(xIndex < list.length); - return list[xIndex].itemBuilder(buildContext, yIndex); + ///todo(不确定) + return list[xIndex].itemBuilder!(buildContext, yIndex); }, maxItemCount, ); @@ -138,18 +140,20 @@ ListAdapter memoizeListAdapter( if (subCtx.extra['@last-state'] != newState) { subCtx.extra['@last-state'] = newState; subCtx.extra['@last-adapter'] = - _memoizeListAdapter(result.buildAdapter(subCtx)); + ///todo(不确定) + _memoizeListAdapter(result.buildAdapter(subCtx)!); } - return subCtx.extra['@last-adapter']; + return subCtx.extra['@last-adapter'] as ListAdapter; } ListAdapter _memoizeListAdapter(ListAdapter adapter) { if (adapter.itemCount > 0) { - final List memoized = - List.filled(adapter.itemCount, null, growable: false); + final List memoized = + List.filled(adapter.itemCount, null, growable: false); return ListAdapter((BuildContext context, int index) { - return (memoized[index] ??= adapter.itemBuilder(context, index)); + ///todo(不确定) + return (memoized[index] ??= adapter.itemBuilder!(context, index)); }, adapter.itemCount); } else { return adapter; diff --git a/lib/src/redux_adapter/source_flow_adapter.dart b/lib/src/redux_adapter/source_flow_adapter.dart index 0f2aeba..926b950 100644 --- a/lib/src/redux_adapter/source_flow_adapter.dart +++ b/lib/src/redux_adapter/source_flow_adapter.dart @@ -11,22 +11,21 @@ import 'recycle_context.dart'; /// see in example /// template is a map, driven by source @deprecated -class SourceFlowAdapter extends Logic - with RecycleContextMixin { +class SourceFlowAdapter extends Logic with RecycleContextMixin { final Map> pool; SourceFlowAdapter({ - @required this.pool, - ReducerFilter filter, - Reducer reducer, - Effect effect, + required this.pool, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, /// implement [StateKey] in T instead of using key in Logic. /// class T implements StateKey { /// Object _key = UniqueKey(); /// Object key() => _key; /// } - @deprecated Object Function(T) key, + @deprecated Object Function(T)? key, }) : super( reducer: _dynamicReducer(reducer, pool), effect: effect, @@ -41,14 +40,14 @@ class SourceFlowAdapter extends Logic final ItemListLike adapterSource = ctx.state; assert(adapterSource != null); - final RecycleContext recycleCtx = ctx; + final RecycleContext recycleCtx = ctx as RecycleContext; final List adapters = []; recycleCtx.markAllUnused(); for (int index = 0; index < adapterSource.itemCount; index++) { final String type = adapterSource.getItemType(index); - final AbstractLogic result = pool[type]; + final AbstractLogic? result = pool[type]; assert( result != null, 'Type of $type has not benn registered in the pool.'); @@ -89,14 +88,15 @@ class SourceFlowAdapter extends Logic } /// Generate reducer for List and combine them into one -Reducer _dynamicReducer( - Reducer reducer, +/// 可空 +Reducer? _dynamicReducer( + Reducer? reducer, Map> pool, ) { final Reducer dyReducer = (ItemListLike state, Action action) { - ItemListLike copy; + ItemListLike? copy; for (int i = 0; i < state.itemCount; i++) { - final AbstractLogic result = pool[state.getItemType(i)]; + final AbstractLogic? result = pool[state.getItemType(i)]; if (result != null) { final Object oldData = state.getItemData(i); final Object newData = result.onReducer(oldData, action); @@ -105,10 +105,13 @@ Reducer _dynamicReducer( } } } - return copy ?? state; + if (copy == null) { + return state is T ? state : null; + } + return copy is T ? copy : null; }; - return combineReducers(>[reducer, dyReducer]); + return combineReducers(?>[reducer, dyReducer]); } /// Define itemBean how to get state with connector @@ -145,11 +148,10 @@ Get _subGetter(Get getter, int index) { }; } -bool _couldReuse({String typeA, String typeB, Object dataA, Object dataB}) { +bool _couldReuse({String? typeA, String? typeB, Object? dataA, Object? dataB}) { return typeA != typeB ? false : dataA.runtimeType != dataB.runtimeType ? false - : (dataA is StateKey ? dataA.key() : null) == - (dataB is StateKey ? dataB.key() : null); + : (dataA is StateKey ? dataA.key() : null) == (dataB is StateKey ? dataB.key() : null); } diff --git a/lib/src/redux_adapter/static_flow_adapter.dart b/lib/src/redux_adapter/static_flow_adapter.dart index 9517993..93eada5 100644 --- a/lib/src/redux_adapter/static_flow_adapter.dart +++ b/lib/src/redux_adapter/static_flow_adapter.dart @@ -16,25 +16,25 @@ class StaticFlowAdapter extends Logic final List> _slots; StaticFlowAdapter({ - @required List> slots, - Reducer reducer, - Effect effect, - ReducerFilter filter, + required List> slots, + Reducer? reducer, + Effect? effect, + ReducerFilter? filter, /// implement [StateKey] in T instead of using key in Logic. /// class T implements StateKey { /// Object _key = UniqueKey(); /// Object key() => _key; /// } - @deprecated Object Function(T) key, + @deprecated Object Function(T)? key, }) : assert(slots != null), - _slots = Collections.compact(slots), + _slots = Collections.compact(slots)!, super( - reducer: combineReducers(>[ + reducer: combineReducers(?>[ reducer, combineSubReducers( slots.map( - (Dependent dependent) => dependent?.createSubReducer(), + (Dependent? dependent) => dependent?.createSubReducer(), ), ) ]), @@ -47,7 +47,7 @@ class StaticFlowAdapter extends Logic @override ListAdapter buildAdapter(ContextSys ctx) { - final RecycleContext recycleCtx = ctx; + final RecycleContext recycleCtx = ctx as RecycleContext; final List adapters = []; recycleCtx.markAllUnused(); diff --git a/lib/src/redux_aop/aop.dart b/lib/src/redux_aop/aop.dart index 27af42e..92c8618 100644 --- a/lib/src/redux_aop/aop.dart +++ b/lib/src/redux_aop/aop.dart @@ -8,7 +8,7 @@ typedef ApplyLikeEnhancer = ApplyLike Function(ApplyLike functor); ApplyLike _identity(ApplyLike f) => f; -ApplyLikeEnhancer _combine(ApplyLikeEnhancer e0, ApplyLikeEnhancer e1) => +ApplyLikeEnhancer _combine(ApplyLikeEnhancer? e0, ApplyLikeEnhancer? e1) => (ApplyLike f) => (e1 ?? _identity)((e0 ?? _identity)(f)); const ApplyLikeEnhancer ApplyLikeEnhancerIdentity = _identity; @@ -26,15 +26,15 @@ const ApplyLikeEnhancer ApplyLikeEnhancerIdentity = _identity; class AOP { final ApplyLikeEnhancer _enhancer; - AOP(List enhances) + AOP(List? enhances) : _enhancer = enhances?.isNotEmpty == true - ? enhances.reduce(_combine) + ? enhances!.reduce(_combine) : ApplyLikeEnhancerIdentity; - TypedApplyLike enhance(Function functor) { + TypedApplyLike? enhance(Function functor) { /// cast functor to ApplyLike final ApplyLike init = (List positionalArguments, - [Map namedArguments]) => + [Map? namedArguments]) => Function.apply(functor, positionalArguments, namedArguments); /// enhance ApplyLike @@ -47,54 +47,54 @@ class AOP { /// cast ApplyLike to TypedApplyLike return (List positionalArguments, - [Map namedArguments]) { + [Map? namedArguments]) { final R result = enhanced(positionalArguments); return result; }; } - R Function() withZero(R Function() f) { - final TypedApplyLike enhanced = enhance(f); + R? Function() withZero(R Function() f) { + final TypedApplyLike? enhanced = enhance(f); return enhanced != null ? () => enhanced([]) : f; } - R Function(P) withOne(R Function(P) f) { - final TypedApplyLike enhanced = enhance(f); + R? Function(P) withOne(R Function(P) f) { + final TypedApplyLike? enhanced = enhance(f); return enhanced != null ? (P p) => enhanced([p]) : f; } - R Function(P0, P1) withTwo(R Function(P0, P1) f) { - final R Function(List) enhanced = enhance(f); + R? Function(P0, P1) withTwo(R Function(P0, P1) f) { + final R? Function(List)? enhanced = enhance(f); return enhanced != null ? (P0 p0, P1 p1) => enhanced([p0, p1]) : f; } - R Function(P0, P1, P2) withThree(R Function(P0, P1, P2) f) { - final TypedApplyLike enhanced = enhance(f); + R? Function(P0, P1, P2) withThree(R Function(P0, P1, P2) f) { + final TypedApplyLike? enhanced = enhance(f); return enhanced != null ? (P0 p0, P1 p1, P2 p2) => enhanced([p0, p1, p2]) : f; } - R Function(P0, P1, P2, P3) withFour( + R? Function(P0, P1, P2, P3) withFour( R Function(P0, P1, P2, P3) f) { - final TypedApplyLike enhanced = enhance(f); + final TypedApplyLike? enhanced = enhance(f); return enhanced != null ? (P0 p0, P1 p1, P2 p2, P3 p3) => enhanced([p0, p1, p2, p3]) : f; } - R Function(P0, P1, P2, P3, P4) withFive( - R Function(P0, P1, P2, P3, P4) f) { - final TypedApplyLike enhanced = enhance(f); + R? Function(P0, P1, P2, P3, P4) withFive( + R? Function(P0, P1, P2, P3, P4) f) { + final TypedApplyLike? enhanced = enhance(f); return enhanced != null ? (P0 p0, P1 p1, P2 p2, P3 p3, P4 p4) => enhanced([p0, p1, p2, p3, p4]) : f; } - R Function(P0, P1, P2, P3, P4, P5) withSix( - R Function(P0, P1, P2, P3, P4, P5) f) { - final TypedApplyLike enhanced = enhance(f); + R? Function(P0, P1, P2, P3, P4, P5) withSix( + R Function(P0, P1, P2, P3, P4, P5?) f) { + final TypedApplyLike? enhanced = enhance(f); return enhanced != null ? (P0 p0, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) => enhanced([p0, p1, p2, p3, p4, p5]) diff --git a/lib/src/redux_aop/common_aop/debounce.dart b/lib/src/redux_aop/common_aop/debounce.dart index ce90c1c..21e94b3 100644 --- a/lib/src/redux_aop/common_aop/debounce.dart +++ b/lib/src/redux_aop/common_aop/debounce.dart @@ -8,7 +8,7 @@ ApplyLikeEnhancer debounce(int millis) { return (dynamic Function(List) functor) { int idGenerator = 0; return (List positionalArguments, - [Map namedArguments]) async { + [Map? namedArguments]) async { final int newId = ++idGenerator; await Future.delayed(Duration(milliseconds: millis)); if (newId == idGenerator) { diff --git a/lib/src/redux_aop/common_aop/delay.dart b/lib/src/redux_aop/common_aop/delay.dart index ea00ace..418a8e4 100644 --- a/lib/src/redux_aop/common_aop/delay.dart +++ b/lib/src/redux_aop/common_aop/delay.dart @@ -6,7 +6,7 @@ import '../aop.dart'; ApplyLikeEnhancer delay(int millis) { return (dynamic Function(List) functor) { return (List positionalArguments, - [Map namedArguments]) async { + [Map? namedArguments]) async { await Future.delayed(Duration(milliseconds: millis)); return functor(positionalArguments); }; diff --git a/lib/src/redux_aop/common_aop/log.dart b/lib/src/redux_aop/common_aop/log.dart index a5326f3..af0b622 100644 --- a/lib/src/redux_aop/common_aop/log.dart +++ b/lib/src/redux_aop/common_aop/log.dart @@ -8,14 +8,14 @@ ApplyLikeEnhancer logAOP(String tag) { return isDebug() ? (dynamic Function(List) functor) { return (List positionalArguments, - [Map namedArguments]) { + [Map? namedArguments]) { print('$tag input: $positionalArguments'); final Object result = functor(positionalArguments); if (result is Future) { - result.then((Object r) { + result.then((Object r) { print('$tag output : $r'); return r; - }); + } as FutureOr Function(dynamic)); } else { print('$tag output: $result'); } diff --git a/lib/src/redux_aop/common_aop/memoize.dart b/lib/src/redux_aop/common_aop/memoize.dart index 898df37..ee6a104 100644 --- a/lib/src/redux_aop/common_aop/memoize.dart +++ b/lib/src/redux_aop/common_aop/memoize.dart @@ -1,6 +1,6 @@ import '../aop.dart'; -bool _listEquals(List list1, List list2) { +bool _listEquals(List list1, List? list2) { if (identical(list1, list2)) { return true; } @@ -22,12 +22,12 @@ bool _listEquals(List list1, List list2) { /// memoize returns cached result of function call when inputs were not changed from previous invocation. ApplyLikeEnhancer memoize() { return (dynamic Function(List) functor) { - List memoizeArguments; + List? memoizeArguments; dynamic memoizeResult; bool hasBeenCalled = false; return (List positionalArguments, - [Map namedArguments]) { + [Map? namedArguments]) { if (!hasBeenCalled || !_listEquals(positionalArguments, memoizeArguments)) { memoizeResult = functor(positionalArguments); diff --git a/lib/src/redux_aop/common_aop/performance.dart b/lib/src/redux_aop/common_aop/performance.dart index 2dc2039..d87694e 100644 --- a/lib/src/redux_aop/common_aop/performance.dart +++ b/lib/src/redux_aop/common_aop/performance.dart @@ -10,15 +10,15 @@ ApplyLikeEnhancer performanceAOP(String tag) { return isDebug() ? (dynamic Function(List) functor) { return (List positionalArguments, - [Map namedArguments]) { + [Map? namedArguments]) { final int marked = DateTime.now().microsecondsSinceEpoch; final Object result = functor(positionalArguments); if (result is Future) { - result.then((Object r) { + result.then((Object r) { print( '$tag performance : ${_microSecsSinceEpoch() - marked}'); return r; - }); + } as FutureOr Function(dynamic)); } else { print('$tag performance: ${_microSecsSinceEpoch() - marked}'); } diff --git a/lib/src/redux_aop/common_aop/throttle.dart b/lib/src/redux_aop/common_aop/throttle.dart index 61b928b..8b0f81d 100644 --- a/lib/src/redux_aop/common_aop/throttle.dart +++ b/lib/src/redux_aop/common_aop/throttle.dart @@ -8,7 +8,7 @@ ApplyLikeEnhancer throttle(int millis) { return (dynamic Function(List) functor) { int last = 0; return (List positionalArguments, - [Map namedArguments]) { + [Map? namedArguments]) { final int now = _microSecsSinceEpoch(); final int elapsed = now - last; if (elapsed >= millis) { diff --git a/lib/src/redux_aop/common_aop/wait_until.dart b/lib/src/redux_aop/common_aop/wait_until.dart index 86b84a0..105ea10 100644 --- a/lib/src/redux_aop/common_aop/wait_until.dart +++ b/lib/src/redux_aop/common_aop/wait_until.dart @@ -6,11 +6,11 @@ ApplyLikeEnhancer waitUntil() { return (dynamic Function(List) functor) { bool isLocked = false; return (List positionalArguments, - [Map namedArguments]) { + [Map? namedArguments]) { if (isLocked) { return null; } else { - final Object result = functor(positionalArguments); + final Object? result = functor(positionalArguments); if (result is Future) { isLocked = true; return result.whenComplete(() { diff --git a/lib/src/redux_component/auto_dispose.dart b/lib/src/redux_component/auto_dispose.dart index 7e53fde..9383ad4 100644 --- a/lib/src/redux_component/auto_dispose.dart +++ b/lib/src/redux_component/auto_dispose.dart @@ -1,8 +1,11 @@ class _Fields { bool isDisposed = false; - Set children; - AutoDispose parent; - void Function() onDisposed; + /// 可空 + Set? children; + /// 可空 + AutoDispose? parent; + /// 可空 + void Function()? onDisposed; } /// Ultra-lightweight lifecycle management system @@ -22,7 +25,7 @@ class AutoDispose { void dispose() { /// dispose all children if (_fields.children != null) { - final List copy = _fields.children.toList(growable: false); + final List copy = _fields.children!.toList(growable: false); for (AutoDispose child in copy) { child.dispose(); } @@ -41,7 +44,8 @@ class AutoDispose { _fields.isDisposed = true; } - void onDisposed(void Function() onDisposed) { + /// 可空 onDisposed? + void onDisposed(void Function()? onDisposed) { assert(_fields.onDisposed == null); if (_fields.isDisposed) { onDisposed?.call(); @@ -50,10 +54,11 @@ class AutoDispose { } } - void setParent(AutoDispose newParent) { + /// 可空 newParent? + void setParent(AutoDispose? newParent) { assert(newParent != this); - final AutoDispose oldParent = _fields.parent; + final AutoDispose? oldParent = _fields.parent; if (oldParent == newParent || isDisposed) { return; } @@ -65,15 +70,15 @@ class AutoDispose { if (newParent != null) { newParent._fields.children ??= {}; - newParent._fields.children.add(this); + newParent._fields.children!.add(this); } if (oldParent != null) { - oldParent._fields.children.remove(this); + oldParent._fields.children!.remove(this); } _fields.parent = newParent; } - AutoDispose registerOnDisposed(void Function() onDisposed) => AutoDispose() + AutoDispose registerOnDisposed(void Function()? onDisposed) => AutoDispose() ..setParent(this) ..onDisposed(onDisposed); } diff --git a/lib/src/redux_component/basic.dart b/lib/src/redux_component/basic.dart index 2afee28..c8f1010 100644 --- a/lib/src/redux_component/basic.dart +++ b/lib/src/redux_component/basic.dart @@ -17,7 +17,8 @@ typedef ViewBuilder = Widget Function( /// Many small listAdapters could be merged to a bigger one. class ListAdapter { final int itemCount; - final IndexedWidgetBuilder itemBuilder; + /// 可空 + final IndexedWidgetBuilder? itemBuilder; const ListAdapter(this.itemBuilder, this.itemCount); } @@ -113,20 +114,23 @@ typedef EffectMiddleware = Composable> Function( /// AOP in page on store, view, adapter, effect... abstract class Enhancer { - ViewBuilder viewEnhance( - ViewBuilder view, + ViewBuilder? viewEnhance( + /// 可空 【component.dart#98】 + ViewBuilder? view, AbstractComponent component, Store store, ); - AdapterBuilder adapterEnhance( - AdapterBuilder adapterBuilder, + /// 可空 + AdapterBuilder? adapterEnhance( + AdapterBuilder? adapterBuilder, AbstractAdapter logic, Store store, ); - Effect effectEnhance( - Effect effect, + /// 可空 + Effect? effectEnhance( + Effect? effect, AbstractLogic logic, Store store, ); @@ -134,17 +138,17 @@ abstract class Enhancer { StoreCreator storeEnhance(StoreCreator creator); void unshift({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }); void append({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }); } @@ -158,7 +162,8 @@ abstract class ExtraData { /// Seen in view-part or adapter-part abstract class ViewService implements ExtraData { /// The way to build adapter which is configured in Dependencies.list - ListAdapter buildAdapter(); + /// 可空 + ListAdapter? buildAdapter(); /// The way to build slot component which is configured in Dependencies.slots Widget buildComponent(String name, {Widget defaultWidget}); @@ -201,7 +206,7 @@ abstract class Context extends AutoDispose implements ExtraData { /// final TickerProvider tickerProvider = context.stfState; /// AnimationController controller = AnimationController(vsync: tickerProvider); /// context.dispatch(ActionCreator.createController(controller)); - State get stfState; + State? get stfState; /// The way to build slot component which is configured in Dependencies.slots /// such as custom mask or dialog @@ -220,8 +225,8 @@ abstract class Context extends AutoDispose implements ExtraData { /// listen on the changes of some parts of . void Function() listen({ - bool Function(T, T) isChanged, - void Function() onChange, + bool Function(T?, T?)? isChanged, + void Function()? onChange, }); } @@ -234,34 +239,35 @@ abstract class ContextSys extends Context implements ViewService { Store get store; - Enhancer get enhancer; + Enhancer? get enhancer; - DispatchBus get bus; + DispatchBus? get bus; } abstract class AbstractAdapterBuilder { - ListAdapter buildAdapter(ContextSys ctx); + /// 可空, + ListAdapter? buildAdapter(ContextSys ctx); } /// Representation of each dependency abstract class Dependent implements AbstractAdapterBuilder { - Get subGetter(Get getter); + Get subGetter(Get getter); - SubReducer createSubReducer(); + SubReducer? createSubReducer(); Widget buildComponent( Store store, Get getter, { - @required DispatchBus bus, - @required Enhancer enhancer, + required DispatchBus bus, + required Enhancer enhancer, }); ContextSys createContext( Store store, BuildContext buildContext, Get getState, { - @required DispatchBus bus, - @required Enhancer enhancer, + required DispatchBus bus, + required Enhancer enhancer, }); bool isComponent(); @@ -275,7 +281,8 @@ abstract class Dependent implements AbstractAdapterBuilder { /// The logic is divided into two parts, Reducer & SideEffect. abstract class AbstractLogic { /// To create a reducer - Reducer createReducer(); + /// 可空 【helper.dart#62】 + Reducer? createReducer(); /// To solve Reducer is neither a subtype nor a supertype of Reducer issue. Object onReducer(Object state, Action action); @@ -289,7 +296,7 @@ abstract class AbstractLogic { /// To create each instance's dispatch /// Dispatch is the most important api for users which is provided by framework Dispatch createDispatch( - Dispatch effectDispatch, + Dispatch? effectDispatch, Dispatch nextDispatch, ContextSys ctx, ); @@ -299,18 +306,18 @@ abstract class AbstractLogic { Store store, BuildContext buildContext, Get getState, { - @required DispatchBus bus, - @required Enhancer enhancer, + required DispatchBus bus, + required Enhancer enhancer, }); /// To create each instance's key (for recycle) if needed - Object key(T state); + Object? key(T state); /// Find a dependent by name - Dependent slot(String name); + Dependent? slot(String name); /// Get a adapter-dependent - Dependent adapterDep(); + Dependent? adapterDep(); Type get propertyType; } @@ -320,13 +327,12 @@ abstract class AbstractComponent implements AbstractLogic { Widget buildComponent( Store store, Get getter, { - @required DispatchBus bus, - @required Enhancer enhancer, + required DispatchBus bus, + required Enhancer enhancer, }); } -abstract class AbstractAdapter - implements AbstractLogic, AbstractAdapterBuilder {} +abstract class AbstractAdapter implements AbstractLogic, AbstractAdapterBuilder {} /// Because a main reducer will be very complicated with multiple level's state. /// When a reducer is slow to handle an action, maybe we should use ReducerFilter to improve the performance. @@ -348,9 +354,11 @@ abstract class DispatchBus { void detach(); - void dispatch(Action action, {Dispatch excluded}); + /// 可空 【context.dart#122】 + void dispatch(Action action, {Dispatch? excluded}); void broadcast(Action action, {DispatchBus excluded}); - void Function() registerReceiver(Dispatch dispatch); + /// 可空 【dispatch_bus.dart#41】 + void Function()? registerReceiver(Dispatch dispatch); } diff --git a/lib/src/redux_component/batch_store.dart b/lib/src/redux_component/batch_store.dart index 4b9f5c2..eeb2648 100644 --- a/lib/src/redux_component/batch_store.dart +++ b/lib/src/redux_component/batch_store.dart @@ -10,7 +10,8 @@ mixin _BatchNotify on Store { final List _listeners = []; bool _isBatching = false; bool _isSetupBatch = false; - T _prevState; + /// 可空 【identical.dart#8】 + T? _prevState; void setupBatch() { if (!_isSetupBatch) { @@ -29,17 +30,17 @@ mixin _BatchNotify on Store { bool isInSuitablePhase() { return SchedulerBinding.instance != null && - SchedulerBinding.instance.schedulerPhase != + SchedulerBinding.instance?.schedulerPhase != SchedulerPhase.persistentCallbacks && - !(SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle && - WidgetsBinding.instance.renderViewElement == null); + !(SchedulerBinding.instance?.schedulerPhase == SchedulerPhase.idle && + WidgetsBinding.instance?.renderViewElement == null); } void _batch() { if (!isInSuitablePhase()) { if (!_isBatching) { _isBatching = true; - SchedulerBinding.instance.addPostFrameCallback((Duration duration) { + SchedulerBinding.instance?.addPostFrameCallback((Duration duration) { if (_isBatching) { _batch(); } @@ -78,8 +79,10 @@ class _BatchStore extends Store with _BatchNotify { Store createBatchStore( T preloadedState, - Reducer reducer, { - StoreEnhancer storeEnhancer, + /// 可空 + Reducer? reducer, { + /// 可空 + StoreEnhancer? storeEnhancer, }) => _BatchStore( createStore( @@ -94,7 +97,8 @@ Store createBatchStore( enum _UpdateState { Assign } // replace current state -Reducer _appendUpdateStateReducer(Reducer reducer) => +/// 可空 reducer? +Reducer _appendUpdateStateReducer(Reducer? reducer) => (T state, Action action) => action.type == _UpdateState.Assign ? action.payload : reducer == null ? state : reducer(state, action); @@ -112,7 +116,7 @@ Store connectStores( } }; - final void Function() unsubscribe = extraStore.subscribe(subscriber); + final void Function()? unsubscribe = extraStore.subscribe(subscriber); /// should triggle once subscriber(); diff --git a/lib/src/redux_component/component.dart b/lib/src/redux_component/component.dart index 368bf8e..744c132 100644 --- a/lib/src/redux_component/component.dart +++ b/lib/src/redux_component/component.dart @@ -13,31 +13,37 @@ typedef WidgetWrapper = Widget Function(Widget child); @immutable abstract class Component extends Logic implements AbstractComponent { - final ViewBuilder _view; + /// 可空 #47 + final ViewBuilder? _view; final ShouldUpdate _shouldUpdate; final WidgetWrapper _wrapper; final bool _clearOnDependenciesChanged; - ViewBuilder get protectedView => _view; + /// 可空 #16 + ViewBuilder? get protectedView => _view; ShouldUpdate get protectedShouldUpdate => _shouldUpdate; WidgetWrapper get protectedWrapper => _wrapper; bool get protectedClearOnDependenciesChanged => _clearOnDependenciesChanged; + /// 可空 【component_extensions.dart#14】 view? reducer? effect? Component({ - @required ViewBuilder view, - Reducer reducer, - ReducerFilter filter, - Effect effect, - Dependencies dependencies, - ShouldUpdate shouldUpdate, - WidgetWrapper wrapper, + /// 可空 + @required ViewBuilder? view, + /// 可空 + Reducer? reducer, + ReducerFilter? filter, + /// 可空 + Effect? effect, + Dependencies? dependencies, + ShouldUpdate? shouldUpdate, + WidgetWrapper? wrapper, /// implement [StateKey] in T instead of using key in Logic. /// class T implements StateKey { /// Object _key = UniqueKey(); /// Object key() => _key; /// } - @deprecated Key Function(T) key, + @deprecated Key Function(T)? key, bool clearOnDependenciesChanged = false, }) : _view = view, _wrapper = wrapper ?? _wrapperByDefault, @@ -55,9 +61,9 @@ abstract class Component extends Logic implements AbstractComponent { @override Widget buildComponent( Store store, - Get getter, { - @required DispatchBus bus, - @required Enhancer enhancer, + Get getter, { + required DispatchBus bus, + required Enhancer enhancer, }) { /// Check bus: DispatchBusDefault(); enhancer: EnhancerDefault(); assert(bus != null && enhancer != null); @@ -67,7 +73,7 @@ abstract class Component extends Logic implements AbstractComponent { component: this, getter: asGetter(getter), store: store, - key: key(getter()), + key: key(getter() as T) as Key, bus: bus, enhancer: enhancer, ), @@ -79,9 +85,9 @@ abstract class Component extends Logic implements AbstractComponent { Store store, BuildContext buildContext, Get getState, { - @required void Function() markNeedsBuild, - @required DispatchBus bus, - @required Enhancer enhancer, + void Function()? markNeedsBuild, + required DispatchBus bus, + required Enhancer enhancer, }) { assert(bus != null && enhancer != null); return ComponentContext( @@ -89,7 +95,7 @@ abstract class Component extends Logic implements AbstractComponent { store: store, buildContext: buildContext, getState: getState, - view: enhancer.viewEnhance(protectedView, this, store), + view: enhancer.viewEnhance(protectedView, this, store)!, shouldUpdate: protectedShouldUpdate, name: name, markNeedsBuild: markNeedsBuild, @@ -114,7 +120,7 @@ abstract class Component extends Logic implements AbstractComponent { static ShouldUpdate alwaysUpdate() => (K _, K __) => true; static ShouldUpdate updateByDefault() => - (K _, K __) => !identical(_, __); + (K a, K b) => !identical(a, b); static Widget _wrapperByDefault(Widget child) => child; } @@ -123,16 +129,20 @@ class ComponentWidget extends StatefulWidget { final Component component; final Store store; final Get getter; + /// 可空 final DispatchBus bus; + /// 可空 final Enhancer enhancer; const ComponentWidget({ - @required this.component, - @required this.store, - @required this.getter, - this.bus, - this.enhancer, - Key key, + required this.component, + required this.store, + required this.getter, + ///todo(不确定) + required this.bus, + ///todo(不确定) + required this.enhancer, + Key? key, }) : assert(component != null), assert(store != null), assert(getter != null), @@ -143,7 +153,7 @@ class ComponentWidget extends StatefulWidget { } class ComponentState extends State> { - ComponentContext _ctx; + late ComponentContext _ctx; ComponentContext get ctx => _ctx; diff --git a/lib/src/redux_component/context.dart b/lib/src/redux_component/context.dart index 37edb37..9c761a0 100644 --- a/lib/src/redux_component/context.dart +++ b/lib/src/redux_component/context.dart @@ -6,7 +6,8 @@ import 'basic.dart'; import 'lifecycle.dart'; mixin _ExtraMixin { - Map _extra; + Map? _extra; + Map get extra => _extra ??= {}; } @@ -23,21 +24,21 @@ abstract class LogicContext extends ContextSys with _ExtraMixin { final Get getState; - void Function() _forceUpdate; + void Function()? _forceUpdate; BuildContext _buildContext; - Dispatch _dispatch; - Dispatch _effectDispatch; + late Dispatch _dispatch; + late Dispatch _effectDispatch; LogicContext({ - @required this.logic, - @required this.store, - @required BuildContext buildContext, - @required this.getState, + required this.logic, + required this.store, + required BuildContext buildContext, + required this.getState, /// pageBus - @required this.bus, - @required this.enhancer, + required this.bus, + required this.enhancer, }) : assert(logic != null), assert(store != null), assert(buildContext != null), @@ -71,17 +72,16 @@ abstract class LogicContext extends ContextSys with _ExtraMixin { BuildContext get context => _buildContext; @override - T get state => getState(); + T get state => getState.call(); @override dynamic dispatch(Action action) => _dispatch(action); @override - Widget buildComponent(String name, {Widget defaultWidget}) { + Widget buildComponent(String name, {Widget? defaultWidget}) { assert(name != null, 'The name must be NotNull for buildComponent.'); - final Dependent dependent = logic.slot(name); - final Widget result = dependent?.buildComponent(store, getState, - bus: bus, enhancer: enhancer); + final Dependent? dependent = logic.slot(name); + final Widget? result = dependent?.buildComponent(store, getState, bus: bus, enhancer: enhancer); assert(result != null || defaultWidget != null, 'Could not found component by name "$name." You can set a default widget for buildComponent'); return result ?? (defaultWidget ?? Container()); @@ -96,30 +96,29 @@ abstract class LogicContext extends ContextSys with _ExtraMixin { @override void dispose() { super.dispose(); - _buildContext = null; _forceUpdate = null; } bool _throwIfDisposed() { if (isDisposed) { - throw Exception( - 'Ctx has been disposed which could not been used any more.'); + throw Exception('Ctx has been disposed which could not been used any more.'); } return true; } + /// 可空 @override - State get stfState { + State? get stfState { assert(_buildContext is StatefulElement); if (_buildContext is StatefulElement) { - final StatefulElement stfElement = _buildContext; + final StatefulElement stfElement = _buildContext as StatefulElement; return stfElement.state; } return null; } @override - void broadcastEffect(Action action, {bool excluded}) => + void broadcastEffect(Action action, {bool? excluded}) => bus.dispatch(action, excluded: excluded == true ? _effectDispatch : null); @override @@ -139,12 +138,13 @@ abstract class LogicContext extends ContextSys with _ExtraMixin { @override void Function() listen({ - bool Function(T, T) isChanged, - @required void Function() onChange, + /// 可空 #151 + bool Function(T?, T?)? isChanged, + void Function()? onChange, }) { assert(onChange != null); - T oldState; - final AutoDispose disposable = registerOnDisposed( + T? oldState; + final AutoDispose? disposable = registerOnDisposed( store.subscribe( () => () { final T newState = state; @@ -153,7 +153,7 @@ abstract class LogicContext extends ContextSys with _ExtraMixin { : isChanged(oldState, newState); oldState = newState; if (flag) { - onChange(); + onChange?.call(); } }, ), @@ -167,24 +167,24 @@ class ComponentContext extends LogicContext implements ViewUpdater { final ViewBuilder view; final ShouldUpdate shouldUpdate; final String name; - final Function() markNeedsBuild; - final ContextSys sidecarCtx; - - Widget _widgetCache; - T _latestState; + final Function()? markNeedsBuild; + final ContextSys? sidecarCtx; + /// 可空 + Widget? _widgetCache; + late T _latestState; ComponentContext({ - @required AbstractComponent logic, - @required Store store, - @required BuildContext buildContext, - @required Get getState, - @required this.view, - @required this.shouldUpdate, - @required this.name, - @required this.markNeedsBuild, - @required this.sidecarCtx, - @required DispatchBus bus, - @required Enhancer enhancer, + required AbstractComponent logic, + required Store store, + required BuildContext buildContext, + required Get getState, + required this.view, + required this.shouldUpdate, + required this.name, + this.markNeedsBuild, + required this.sidecarCtx, + required DispatchBus bus, + required Enhancer enhancer, }) : assert(bus != null && enhancer != null), super( logic: logic, @@ -208,13 +208,13 @@ class ComponentContext extends LogicContext implements ViewUpdater { @override ListAdapter buildAdapter() { assert(sidecarCtx != null); - return logic.adapterDep()?.buildAdapter(sidecarCtx) ?? + return logic.adapterDep()?.buildAdapter(sidecarCtx!) ?? const ListAdapter(null, 0); } @override Widget buildWidget() { - Widget result = _widgetCache; + Widget? result = _widgetCache; if (result == null) { result = _widgetCache = view(state, dispatch, this); @@ -238,7 +238,7 @@ class ComponentContext extends LogicContext implements ViewUpdater { if (shouldUpdate(_latestState, now)) { _widgetCache = null; - markNeedsBuild(); + markNeedsBuild?.call(); _latestState = now; } @@ -254,7 +254,7 @@ class ComponentContext extends LogicContext implements ViewUpdater { _widgetCache = null; try { - markNeedsBuild(); + markNeedsBuild?.call(); } catch (e) { /// TODO /// should try-catch in force mode which is called from outside @@ -274,14 +274,14 @@ class PureViewViewService implements ViewService { void broadcast(Action action) => bus.broadcast(action); @override - void broadcastEffect(Action action, {bool excluded}) => bus.dispatch(action); + void broadcastEffect(Action action, {bool? excluded}) => bus.dispatch(action); @override ListAdapter buildAdapter() => throw Exception( 'Unexpected call of "buildAdapter" in a PureViewComponent'); @override - Widget buildComponent(String name, {Widget defaultWidget}) => throw Exception( + Widget buildComponent(String name, {Widget? defaultWidget}) => throw Exception( 'Unexpected call of "buildComponent" in a PureViewComponent'); @override diff --git a/lib/src/redux_component/dependencies.dart b/lib/src/redux_component/dependencies.dart index ee0df46..f2f4dbc 100644 --- a/lib/src/redux_component/dependencies.dart +++ b/lib/src/redux_component/dependencies.dart @@ -2,8 +2,10 @@ import '../redux/redux.dart'; import 'basic.dart'; class Dependencies { - final Map> slots; - final Dependent adapter; + /// 可空 + final Map>? slots; + /// 可空 + final Dependent? adapter; /// Use [adapter: NoneConn() + Adapter()] instead of [adapter: Adapter()], /// Which is better reusability and consistency. @@ -13,24 +15,32 @@ class Dependencies { }) : assert(adapter == null || adapter.isAdapter(), 'The dependent must contains adapter.'); - Reducer createReducer() { - final List> subs = >[]; - if (slots != null && slots.isNotEmpty) { - subs.addAll(slots.entries.map>( + /// 可空 combine_reducers.dart#32 + Reducer? createReducer() { + final List?> subs = ?>[]; + if (slots != null && slots?.isNotEmpty == true) { + subs.addAll(slots!.entries.map?>( (MapEntry> entry) => entry.value.createSubReducer(), )); } if (adapter != null) { - subs.add(adapter.createSubReducer()); + subs.add(adapter?.createSubReducer()); } - return combineReducers(>[combineSubReducers(subs)]); + return combineReducers(?>[combineSubReducers(subs)]); } - Dependent slot(String type) => slots[type]; + /// 可空 + Dependent? slot(String type) { + if(slots != null && slots?.isNotEmpty == true){ + return slots![type]; + } + return null; + } - Dependencies trim() => + /// 可空 + Dependencies? trim() => adapter != null || slots?.isNotEmpty == true ? this : null; } diff --git a/lib/src/redux_component/dependent.dart b/lib/src/redux_component/dependent.dart index 7e8fd36..ad64cf8 100644 --- a/lib/src/redux_component/dependent.dart +++ b/lib/src/redux_component/dependent.dart @@ -7,64 +7,69 @@ import 'basic.dart'; class _Dependent implements Dependent { final AbstractConnector connector; final AbstractLogic

logic; - final SubReducer subReducer; + + /// 依据:[dependent.dart#21] + /// 可空 + final SubReducer? subReducer; _Dependent({ - @required this.logic, - @required this.connector, + required this.logic, + required this.connector, }) : assert(logic != null), assert(connector != null), - subReducer = logic.createReducer != null - ? connector.subReducer(logic.createReducer()) - : null; + subReducer = logic.createReducer != null ? connector.subReducer(logic.createReducer()) : null; @override - SubReducer createSubReducer() => subReducer; + SubReducer? createSubReducer() => subReducer; @override Widget buildComponent( Store store, Get getter, { - @required DispatchBus bus, - @required Enhancer enhancer, + required DispatchBus bus, + required Enhancer enhancer, }) { assert(bus != null && enhancer != null); assert(isComponent(), 'Unexpected type of ${logic.runtimeType}.'); - final AbstractComponent

component = logic; + final AbstractComponent

component = logic as AbstractComponent

; return component.buildComponent( store, - () => connector.get(getter()), + + /// todo(不确定) + () => connector.get(getter())!, bus: bus, enhancer: enhancer, ); } @override - ListAdapter buildAdapter(covariant ContextSys

ctx) { + ListAdapter? buildAdapter(ContextSys ctx) { assert(isAdapter(), 'Unexpected type of ${logic.runtimeType}.'); - final AbstractAdapter

adapter = logic; - return adapter.buildAdapter(ctx); + final AbstractAdapter

adapter = logic as dynamic; + return adapter.buildAdapter(ctx as dynamic); } @override - Get

subGetter(Get getter) => () => connector.get(getter()); + Get subGetter(Get getter) { + return () => connector.get(getter())!; + } @override - ContextSys

createContext( + ContextSys createContext( Store store, BuildContext buildContext, Get getState, { - @required DispatchBus bus, - @required Enhancer enhancer, + required DispatchBus bus, + required Enhancer enhancer, }) { assert(bus != null && enhancer != null); return logic.createContext( store, buildContext, - subGetter(getState), + subGetter(getState) as dynamic, bus: bus, enhancer: enhancer, - ); + ) as ContextSys; } @override @@ -78,11 +83,15 @@ class _Dependent implements Dependent { return Tuple3( logic.runtimeType, connector.runtimeType, - logic.key(connector.get(state)), + + ///todo(不确定) + logic.key(connector.get(state)!), ); } } -Dependent createDependent( - AbstractConnector connector, AbstractLogic logic) => - logic != null ? _Dependent(connector: connector, logic: logic) : null; +/// 可空 +Dependent? createDependent(AbstractConnector connector, AbstractLogic logic){ + return logic != null ? _Dependent(connector: connector, logic: logic) : null; +} + diff --git a/lib/src/redux_component/dispatch_bus.dart b/lib/src/redux_component/dispatch_bus.dart index b074a95..f12ef60 100644 --- a/lib/src/redux_component/dispatch_bus.dart +++ b/lib/src/redux_component/dispatch_bus.dart @@ -3,13 +3,13 @@ import 'basic.dart'; class DispatchBusDefault implements DispatchBus { final List _dispatchList = []; - DispatchBus parent; - void Function() unregister; + DispatchBus? parent; + void Function()? unregister; DispatchBusDefault(); @override - void attach(DispatchBus parent) { + void attach(DispatchBus? parent) { this.parent = parent; unregister?.call(); unregister = parent?.registerReceiver(dispatch); @@ -21,7 +21,7 @@ class DispatchBusDefault implements DispatchBus { } @override - void dispatch(Action action, {Dispatch excluded}) { + void dispatch(Action action, {Dispatch? excluded}) { final List list = _dispatchList .where((Dispatch dispatch) => dispatch != excluded) .toList(growable: false); @@ -32,12 +32,13 @@ class DispatchBusDefault implements DispatchBus { } @override - void broadcast(Action action, {DispatchBus excluded}) { + void broadcast(Action action, {DispatchBus? excluded}) { parent?.dispatch(action, excluded: excluded?.dispatch); } + /// 可空 @override - void Function() registerReceiver(Dispatch dispatch) { + void Function()? registerReceiver(Dispatch? dispatch) { assert(!_dispatchList.contains(dispatch), 'Do not register a dispatch which is already existed'); diff --git a/lib/src/redux_component/enhancer.dart b/lib/src/redux_component/enhancer.dart index 09920db..24255b0 100644 --- a/lib/src/redux_component/enhancer.dart +++ b/lib/src/redux_component/enhancer.dart @@ -4,10 +4,14 @@ import '../redux/redux.dart'; import 'basic.dart'; class EnhancerDefault implements Enhancer { - StoreEnhancer _storeEnhancer; - ViewMiddleware _viewEnhancer; - EffectMiddleware _effectEnhancer; - AdapterMiddleware _adapterEnhancer; + /// 可空 #44 + StoreEnhancer? _storeEnhancer; + /// 可空 #51 + ViewMiddleware? _viewEnhancer; + /// 可空 #51 + EffectMiddleware? _effectEnhancer; + /// 可空 #51 + AdapterMiddleware? _adapterEnhancer; final List> _middleware = >[]; final List> _viewMiddleware = >[]; @@ -16,10 +20,10 @@ class EnhancerDefault implements Enhancer { >[]; EnhancerDefault({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List> ?viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }) { append( middleware: middleware, @@ -31,10 +35,10 @@ class EnhancerDefault implements Enhancer { @override void unshift({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }) { if (middleware != null) { _middleware.insertAll(0, middleware); @@ -56,10 +60,10 @@ class EnhancerDefault implements Enhancer { @override void append({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }) { if (middleware != null) { _middleware.addAll(middleware); @@ -79,49 +83,75 @@ class EnhancerDefault implements Enhancer { } } + /// 可空 @override - ViewBuilder viewEnhance( - ViewBuilder view, + ViewBuilder? viewEnhance( + ViewBuilder? view, AbstractComponent component, Store store, - ) => - _viewEnhancer?.call(component, store)?.call(_inverterView(view)) ?? - view; + ) { + if(view == null){ + return null; + } + final ViewBuilder? viewBuilder = _inverterView(view); + if(viewBuilder == null){ + return view; + } + return _viewEnhancer?.call(component, store).call(viewBuilder) ?? view; + } + @override - AdapterBuilder adapterEnhance( - AdapterBuilder adapterBuilder, + AdapterBuilder? adapterEnhance( + AdapterBuilder? adapterBuilder, AbstractAdapter logic, Store store, - ) => - _adapterEnhancer - ?.call(logic, store) - ?.call(_inverterAdapter(adapterBuilder)) ?? - adapterBuilder; + ) { + if(adapterBuilder == null){ + return null; + } + final AdapterBuilder? viewBuilder = _inverterAdapter(adapterBuilder); + if(viewBuilder == null){ + return adapterBuilder; + } + return _adapterEnhancer?.call(logic, store).call(viewBuilder) ?? adapterBuilder; + } + + /// 可空 @override - Effect effectEnhance( - Effect effect, + Effect? effectEnhance( + Effect? effect, AbstractLogic logic, Store store, - ) => - _effectEnhancer?.call(logic, store)?.call(_inverterEffect(effect)) ?? - effect; + ) { + if(effect == null){ + return null; + } + final Effect? viewBuilder = _inverterEffect(effect); + if(viewBuilder == null){ + return effect; + } + return _effectEnhancer?.call(logic, store).call(viewBuilder) ?? effect; + } @override StoreCreator storeEnhance(StoreCreator creator) => _storeEnhancer?.call(creator) ?? creator; - Effect _inverterEffect(Effect effect) => effect == null + /// 可空 + Effect? _inverterEffect(Effect? effect) => effect == null ? null - : (Action action, Context ctx) => effect(action, ctx); + : (Action action, Context ctx) => effect(action, ctx as Context); - ViewBuilder _inverterView(ViewBuilder view) => view == null + /// 可空 + ViewBuilder? _inverterView(ViewBuilder? view) => view == null ? null : (dynamic state, Dispatch dispatch, ViewService viewService) => view(state, dispatch, viewService); - AdapterBuilder _inverterAdapter(AdapterBuilder adapter) => + /// 可空 + AdapterBuilder? _inverterAdapter(AdapterBuilder? adapter) => adapter == null ? null : (dynamic state, Dispatch dispatch, ViewService viewService) => diff --git a/lib/src/redux_component/helper.dart b/lib/src/redux_component/helper.dart index fa9a619..c24a314 100644 --- a/lib/src/redux_component/helper.dart +++ b/lib/src/redux_component/helper.dart @@ -1,5 +1,6 @@ import 'dart:async'; +import 'package:collection/collection.dart' show IterableExtension; import 'package:flutter/widgets.dart' hide Action, Page; import '../redux/basic.dart'; @@ -7,7 +8,7 @@ import '../utils/utils.dart'; import 'basic.dart'; import 'lifecycle.dart'; -Get asGetter(Get getter) { +Get asGetter(Get getter) { Get runtimeGetter; if (getter is Get) { runtimeGetter = getter; @@ -22,22 +23,21 @@ Get asGetter(Get getter) { AdapterBuilder asAdapter(ViewBuilder view) { return (T unstableState, Dispatch dispatch, ViewService service) { - final ContextSys ctx = service; + final ContextSys ctx = service as ContextSys; return ListAdapter( - (BuildContext buildContext, int index) => - view(ctx.state, dispatch, service), + (BuildContext buildContext, int index) => view(ctx.state, dispatch, service), 1, ); }; } -Reducer mergeReducers(Reducer sup, [Reducer sub]) { +Reducer mergeReducers(Reducer sup, [Reducer? sub]) { return (T state, Action action) { - return sub?.call(sup(state, action), action) ?? sup(state, action); + return sub?.call(sup(state, action) as T, action) ?? sup(state, action) as T; }; } -Effect mergeEffects(Effect sup, [Effect sub]) { +Effect mergeEffects(Effect sup, [Effect? sub]) { return (Action action, Context ctx) { return sub?.call(action, ctx) ?? sup.call(action, ctx); }; @@ -45,19 +45,28 @@ Effect mergeEffects(Effect sup, [Effect sub]) { /// combine & as /// for action.type which override it's == operator -Reducer asReducer(Map> map) => (map == null || - map.isEmpty) - ? null - : (T state, Action action) => - map.entries - .firstWhere( - (MapEntry> entry) => - action.type == entry.key, - orElse: () => null) - ?.value(state, action) ?? - state; - -Reducer filterReducer(Reducer reducer, ReducerFilter filter) { +Reducer? asReducer(Map>? map) { + return (map == null || map.isEmpty) + ? null + : (T state, Action action) { + MapEntry>? reducer; + for (MapEntry> element in map.entries) { + if (action.type == element.key) { + reducer = element; + break; + } + } + // map.entries + // .firstWhereOrNull((MapEntry> entry) => action.type == entry.key) + // ?.value(state, action) ?? + // state; + + return reducer?.value(state, action) ?? state; + }; +} + +/// 可空 【helper.dart#62】 +Reducer? filterReducer(Reducer? reducer, ReducerFilter? filter) { return (reducer == null || filter == null) ? reducer : (T state, Action action) { @@ -71,35 +80,32 @@ typedef SubEffect = FutureOr Function(Action action, Context ctx); /// for action.type which override it's == operator /// return [UserEffecr] -Effect combineEffects(Map> map) => - (map == null || map.isEmpty) - ? null - : (Action action, Context ctx) { - final SubEffect subEffect = map.entries - .firstWhere( - (MapEntry> entry) => - action.type == entry.key, - orElse: () => null, - ) - ?.value; - - if (subEffect != null) { - return subEffect.call(action, ctx) ?? _SUB_EFFECT_RETURN_NULL; - } - - //skip-lifecycle-actions - if (action.type is Lifecycle) { - return _SUB_EFFECT_RETURN_NULL; - } - - /// no subEffect - return null; - }; +Effect? combineEffects(Map> map) => (map == null || map.isEmpty) + ? null + : (Action action, Context ctx) { + final SubEffect? subEffect = map.entries + .firstWhereOrNull( + (MapEntry> entry) => action.type == entry.key, + ) + ?.value; + + if (subEffect != null) { + return subEffect.call(action, ctx) ?? _SUB_EFFECT_RETURN_NULL; + } + + //skip-lifecycle-actions + if (action.type is Lifecycle) { + return _SUB_EFFECT_RETURN_NULL; + } + + /// no subEffect + return null; + }; /// return [EffectDispatch] -Dispatch createEffectDispatch(Effect userEffect, Context ctx) { +Dispatch createEffectDispatch(Effect? userEffect, Context ctx) { return (Action action) { - final Object result = userEffect?.call(action, ctx); + final Object? result = userEffect?.call(action, ctx); //skip-lifecycle-actions if (action.type is Lifecycle && (result == null || result == false)) { @@ -117,9 +123,9 @@ Dispatch createNextDispatch(ContextSys ctx) => (Action action) { }; /// return [Dispatch] -Dispatch createDispatch(Dispatch onEffect, Dispatch next, Context ctx) => - (Action action) { - final Object result = onEffect?.call(action); +/// 可空 onEffect? +Dispatch createDispatch(Dispatch? onEffect, Dispatch next, Context ctx) => (Action action) { + final Object? result = onEffect?.call(action); if (result == null || result == false) { next(action); } @@ -127,9 +133,9 @@ Dispatch createDispatch(Dispatch onEffect, Dispatch next, Context ctx) => return result == _SUB_EFFECT_RETURN_NULL ? null : result; }; -ViewMiddleware mergeViewMiddleware(List> middleware) { - return Collections.reduce>(middleware, - (ViewMiddleware first, ViewMiddleware second) { +/// 可空 【collections.dart#7】 +ViewMiddleware? mergeViewMiddleware(List> middleware) { + return Collections.reduce>(middleware, (ViewMiddleware first, ViewMiddleware second) { return (AbstractComponent component, Store store) { final Composable> inner = first(component, store); final Composable> outer = second(component, store); @@ -140,14 +146,13 @@ ViewMiddleware mergeViewMiddleware(List> middleware) { }); } -AdapterMiddleware mergeAdapterMiddleware( - List> middleware) { +/// 可空 【collections.dart#7】 +AdapterMiddleware? mergeAdapterMiddleware(List> middleware) { return Collections.reduce>(middleware, (AdapterMiddleware first, AdapterMiddleware second) { return (AbstractAdapter component, Store store) { final Composable> inner = first(component, store); - final Composable> outer = - second(component, store); + final Composable> outer = second(component, store); return (AdapterBuilder view) { return outer(inner(view)); }; @@ -155,10 +160,9 @@ AdapterMiddleware mergeAdapterMiddleware( }); } -EffectMiddleware mergeEffectMiddleware( - List> middleware) { - return Collections.reduce>(middleware, - (EffectMiddleware first, EffectMiddleware second) { +/// 可空 【collections.dart#7】 +EffectMiddleware? mergeEffectMiddleware(List> middleware) { + return Collections.reduce>(middleware, (EffectMiddleware first, EffectMiddleware second) { return (AbstractLogic logic, Store store) { final Composable> inner = first(logic, store); final Composable> outer = second(logic, store); diff --git a/lib/src/redux_component/lifecycle.dart b/lib/src/redux_component/lifecycle.dart index 7e85b1e..eabe1de 100644 --- a/lib/src/redux_component/lifecycle.dart +++ b/lib/src/redux_component/lifecycle.dart @@ -34,7 +34,7 @@ enum Lifecycle { class LifecycleCreator { static Action initState() => const Action(Lifecycle.initState); - static Action build(String name) => Action(Lifecycle.build, payload: name); + static Action build(String? name) => Action(Lifecycle.build, payload: name); static Action reassemble() => const Action(Lifecycle.reassemble); @@ -49,9 +49,9 @@ class LifecycleCreator { static Action deactivate() => const Action(Lifecycle.deactivate); - static Action appear(int index) => Action(Lifecycle.appear, payload: index); + static Action appear(int? index) => Action(Lifecycle.appear, payload: index); - static Action disappear(int index) => + static Action disappear(int? index) => Action(Lifecycle.disappear, payload: index); static Action didChangeAppLifecycleState(AppLifecycleState state) => diff --git a/lib/src/redux_component/local.dart b/lib/src/redux_component/local.dart index f604d16..9160c6b 100644 --- a/lib/src/redux_component/local.dart +++ b/lib/src/redux_component/local.dart @@ -54,23 +54,23 @@ abstract class LocalProps> { @immutable class _LocalPropsProvider { final T Function(Context) construct; - final void Function(T, Context) destruct; + final void Function(T, Context)? destruct; - const _LocalPropsProvider({@required this.construct, this.destruct}) + const _LocalPropsProvider({required this.construct, this.destruct}) : assert(construct != null, 'Please provide a constructor to create instance.'); - T of(ExtraData context) { + T? of(ExtraData context) { assert(context is Context); - final Context ctx = context; + final Context ctx = context as Context; if (ctx.extra[_key] == null) { final T result = construct(ctx); - ctx.extra[_key] = result; + ctx.extra[_key] = result as Object; if (destruct != null) { - ctx.registerOnDisposed(() => destruct(result, ctx)); + ctx.registerOnDisposed(() => destruct!(result, ctx)); } } - return ctx.extra[_key]; + return ctx.extra[_key] as T?; } String get _key => '\$ ${T.toString()}'; diff --git a/lib/src/redux_component/logic.dart b/lib/src/redux_component/logic.dart index 006116e..e56c3e5 100644 --- a/lib/src/redux_component/logic.dart +++ b/lib/src/redux_component/logic.dart @@ -12,36 +12,47 @@ import 'helper.dart' as helper; /// 3. Dependencies /// 4. Key abstract class Logic implements AbstractLogic { - final Reducer _reducer; - final ReducerFilter _filter; - final Effect _effect; - final Dependencies _dependencies; - final Object Function(T state) _key; + /// 可空 【logic.dart#82】 + final Reducer? _reducer; + /// 可空 【logic.dart#82】 + final ReducerFilter? _filter; + /// 可空 + final Effect? _effect; + /// 可空 + final Dependencies? _dependencies; + final Object Function(T state)? _key; /// for extends - Reducer get protectedReducer => _reducer; - ReducerFilter get protectedFilter => _filter; - Effect get protectedEffect => _effect; - Dependencies get protectedDependencies => _dependencies; - Reducer get protectedDependenciesReducer => + /// 可空 [private_reducer_mixin.dart#12] + Reducer? get protectedReducer => _reducer; + /// 可空 【logic.dart#82】 + ReducerFilter? get protectedFilter => _filter; + /// 可空 + Effect? get protectedEffect => _effect; + /// 可空 【logic.dart#82】 + Dependencies? get protectedDependencies => _dependencies; + Reducer? get protectedDependenciesReducer => protectedDependencies?.createReducer(); - Object Function(T state) get protectedKey => _key; + /// 可空 + Object Function(T state)? get protectedKey => _key; /// Used as function cache to improve operational efficiency final Map _resultCache = {}; Logic({ - Reducer reducer, - Dependencies dependencies, - ReducerFilter filter, - Effect effect, + /// 可空 + Reducer? reducer, + Dependencies? dependencies, + ReducerFilter? filter, + /// 可空 + Effect? effect, /// implement [StateKey] in T instead of using key in Logic. /// class T implements StateKey { /// Object _key = UniqueKey(); /// Object key() => _key; /// } - @deprecated Object Function(T state) key, + @deprecated Object Function(T state)? key, }) : _reducer = reducer, _filter = filter, _effect = effect, @@ -68,19 +79,20 @@ abstract class Logic implements AbstractLogic { /// _resultCache['key'] = null; /// then /// _resultCache.containsKey('key') will be true; - R cache(String key, Get getter) => _resultCache.containsKey(key) - ? _resultCache[key] - : (_resultCache[key] = getter()); + R cache(String? key, Get getter) => _resultCache.containsKey(key) + ? _resultCache[key] as R + : (_resultCache[key!] = getter() as dynamic) as R; + /// 可空 【helper.dart#62】 protectedFilter? @override - Reducer createReducer() => helper.filterReducer( + Reducer? createReducer() => helper.filterReducer( combineReducers( - >[protectedReducer, protectedDependenciesReducer]), + ?>[protectedReducer, protectedDependenciesReducer]), protectedFilter); @override Object onReducer(Object state, Action action) => - cache>('onReducer', createReducer)?.call(state, action) ?? + cache?>('onReducer', createReducer)?.call(state as T, action) ?? state; @override @@ -91,7 +103,7 @@ abstract class Logic implements AbstractLogic { enhancer.effectEnhance( protectedEffect, this, - ctx.store, + ctx.store as Store, ), ctx); } @@ -100,9 +112,10 @@ abstract class Logic implements AbstractLogic { Dispatch createNextDispatch(ContextSys ctx, Enhancer enhancer) => helper.createNextDispatch(ctx); + /// 可空 effectDispatch? @override Dispatch createDispatch( - Dispatch effectDispatch, + Dispatch? effectDispatch, Dispatch nextDispatch, Context ctx, ) => @@ -112,8 +125,9 @@ abstract class Logic implements AbstractLogic { Object key(T state) => _key?.call(state) ?? ValueKey(runtimeType); @override - Dependent slot(String type) => protectedDependencies?.slot(type); + Dependent? slot(String type) => protectedDependencies?.slot(type); + ///可空 @override - Dependent adapterDep() => protectedDependencies?.adapter; + Dependent? adapterDep() => protectedDependencies?.adapter; } diff --git a/lib/src/redux_component/page.dart b/lib/src/redux_component/page.dart index 5c40c20..e1ee020 100644 --- a/lib/src/redux_component/page.dart +++ b/lib/src/redux_component/page.dart @@ -9,7 +9,8 @@ import 'dispatch_bus.dart'; import 'enhancer.dart'; /// init store's state by route-params -typedef InitState = T Function(P params); +/// 可空 params? +typedef InitState = T Function(P? params); typedef StoreUpdater = Store Function(Store store); @@ -28,25 +29,25 @@ abstract class Page extends Component { final List> _storeUpdaters = >[]; Page({ - @required InitState initState, - @required ViewBuilder view, - Reducer reducer, - ReducerFilter filter, - Effect effect, - Dependencies dependencies, - ShouldUpdate shouldUpdate, - WidgetWrapper wrapper, + required InitState initState, + required ViewBuilder view, + Reducer? reducer, + ReducerFilter? filter, + Effect? effect, + Dependencies? dependencies, + ShouldUpdate? shouldUpdate, + WidgetWrapper? wrapper, /// implement [StateKey] in T instead of using key in Logic. /// class T implements StateKey { /// Object _key = UniqueKey(); /// Object key() => _key; /// } - @deprecated Key Function(T) key, - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + @deprecated Key Function(T)? key, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }) : assert(initState != null), _initState = initState, enhancer = EnhancerDefault( @@ -67,12 +68,14 @@ abstract class Page extends Component { key: key, ); - Widget buildPage(P param) => protectedWrapper(_PageWidget( + /// 可空 param? + Widget buildPage(P? param) => protectedWrapper(_PageWidget( page: this, param: param, )); - Store createStore(P param) => updateStore(createBatchStore( + /// 可空 param? + Store createStore(P? param) => updateStore(createBatchStore( _initState(param), createReducer(), storeEnhancer: enhancer.storeEnhance, @@ -80,30 +83,30 @@ abstract class Page extends Component { Store updateStore(Store store) => _storeUpdaters.fold( store, - (Store previousValue, StoreUpdater element) => - element(previousValue), + (Store previousValue, StoreUpdater element) => element(previousValue), ); /// page-store connect with app-store void connectExtraStore( Store extraStore, + // Object pagestate, GlobalState appState /// To solve Reducer is neither a subtype nor a supertype of Reducer issue. Object Function(Object, K) update, ) => _storeUpdaters.add((Store store) => connectStores( - store, + store as Store, extraStore, update, - )); + ) as Store); DispatchBus createPageBus() => DispatchBusDefault(); void unshift({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }) { enhancer.unshift( middleware: middleware, @@ -114,10 +117,10 @@ abstract class Page extends Component { } void append({ - List> middleware, - List> viewMiddleware, - List> effectMiddleware, - List> adapterMiddleware, + List>? middleware, + List>? viewMiddleware, + List>? effectMiddleware, + List>? adapterMiddleware, }) { enhancer.append( middleware: middleware, @@ -130,12 +133,13 @@ abstract class Page extends Component { class _PageWidget extends StatefulWidget { final Page page; - final P param; + /// 可空 【app.dart#77】 + final P? param; const _PageWidget({ - Key key, - @required this.page, - @required this.param, + Key? key, + required this.page, + this.param, }) : super(key: key); @override @@ -143,8 +147,8 @@ class _PageWidget extends StatefulWidget { } class _PageState extends State<_PageWidget> { - Store _store; - DispatchBus _pageBus; + late Store _store; + late DispatchBus _pageBus; final Map extra = {}; @@ -172,10 +176,10 @@ class _PageState extends State<_PageWidget> { // ); return widget.page.buildComponent( - _store, + _store as Store, _store.getState, bus: _pageBus, - enhancer: widget.page.enhancer, + enhancer: widget.page.enhancer as Enhancer, ); } @@ -195,21 +199,20 @@ class PageProvider extends InheritedWidget { final Map extra; const PageProvider({ - @required this.store, - @required this.extra, - @required Widget child, - Key key, + required this.store, + required this.extra, + required Widget child, + Key? key, }) : assert(store != null), assert(child != null), super(child: child, key: key); - static PageProvider tryOf(BuildContext context) { - final PageProvider provider = - context.dependOnInheritedWidgetOfExactType(); + /// 可空 【framework.dart#2113】 + static PageProvider? tryOf(BuildContext context) { + final PageProvider? provider = context.dependOnInheritedWidgetOfExactType(); return provider; } @override - bool updateShouldNotify(PageProvider oldWidget) => - store != oldWidget.store && extra != oldWidget.extra; + bool updateShouldNotify(PageProvider oldWidget) => store != oldWidget.store && extra != oldWidget.extra; } diff --git a/lib/src/redux_component_mixin/private_reducer_mixin.dart b/lib/src/redux_component_mixin/private_reducer_mixin.dart index 6cdf9fc..bfde711 100644 --- a/lib/src/redux_component_mixin/private_reducer_mixin.dart +++ b/lib/src/redux_component_mixin/private_reducer_mixin.dart @@ -8,9 +8,10 @@ import '../redux_component/redux_component.dart'; /// ); /// } mixin PrivateReducerMixin on Logic { + /// 可空 @override - Reducer get protectedReducer { - final Reducer superReducer = super.protectedReducer; + Reducer? get protectedReducer { + final Reducer? superReducer = super.protectedReducer; return superReducer != null ? (T state, Action action) { if (action is PrivateAction && action.target == state) { @@ -22,14 +23,15 @@ mixin PrivateReducerMixin on Logic { } @override - Dispatch createDispatch(Dispatch effect, Dispatch next, Context ctx) { + Dispatch createDispatch(Dispatch? effect, Dispatch next, Context ctx) { final Dispatch superDispatch = super.createDispatch(effect, next, ctx); return (Action action) { if (action.type is! Lifecycle && action is! PrivateAction) { action = PrivateAction( action.type, payload: action.payload, - target: ctx.state, + ///todo(不确定) + target: ctx.state as Object, ); } return superDispatch(action); @@ -39,7 +41,7 @@ mixin PrivateReducerMixin on Logic { class PrivateAction extends Action { final Object target; - PrivateAction(Object type, {dynamic payload, this.target}) + PrivateAction(Object type, {dynamic payload, required this.target}) : super(type, payload: payload); Action asAction() => Action(type, payload: payload); diff --git a/lib/src/redux_component_mixin/visible_change_mixin.dart b/lib/src/redux_component_mixin/visible_change_mixin.dart index 400c92a..05843ff 100644 --- a/lib/src/redux_component_mixin/visible_change_mixin.dart +++ b/lib/src/redux_component_mixin/visible_change_mixin.dart @@ -13,36 +13,36 @@ import '../utils/utils.dart'; /// } mixin VisibleChangeMixin on AbstractAdapter { @override - ListAdapter buildAdapter(ContextSys ctx) { - return _wrapVisibleChange(super.buildAdapter(ctx), ctx); + ListAdapter? buildAdapter(ContextSys ctx) { + return _wrapVisibleChange(super.buildAdapter(ctx), ctx as dynamic); } } class _VisibleChangeState extends State<_VisibleChangeWidget> { @override Widget build(BuildContext context) => - widget.itemBuilder(context, widget.index); + widget.itemBuilder!(context, widget.index!); @override void initState() { super.initState(); - widget.dispatch(LifecycleCreator.appear(widget.index)); + widget.dispatch!(LifecycleCreator.appear(widget.index)); } @override void dispose() { - widget.dispatch(LifecycleCreator.disappear(widget.index)); + widget.dispatch!(LifecycleCreator.disappear(widget.index)); super.dispose(); } } class _VisibleChangeWidget extends StatefulWidget { - final IndexedWidgetBuilder itemBuilder; - final int index; - final Dispatch dispatch; + final IndexedWidgetBuilder? itemBuilder; + final int? index; + final Dispatch? dispatch; const _VisibleChangeWidget({ - Key key, + Key? key, this.itemBuilder, this.index, this.dispatch, @@ -52,12 +52,14 @@ class _VisibleChangeWidget extends StatefulWidget { State createState() => _VisibleChangeState(); } -ListAdapter _wrapVisibleChange( - ListAdapter listAdapter, - LogicContext ctx, +/// 可空 +ListAdapter? _wrapVisibleChange( + /// 可空 + ListAdapter? listAdapter, + LogicContext? ctx, ) { final _VisibleChangeDispatch onChange = - (ctx.extra['\$visible'] ??= _VisibleChangeDispatch(ctx.dispatch)); + (ctx?.extra['\$visible'] ??= _VisibleChangeDispatch(ctx.dispatch)) as _VisibleChangeDispatch; return listAdapter == null ? null diff --git a/lib/src/redux_component_mixin/widgets_binding_observer_mixin.dart b/lib/src/redux_component_mixin/widgets_binding_observer_mixin.dart index 0d78fe6..750c799 100644 --- a/lib/src/redux_component_mixin/widgets_binding_observer_mixin.dart +++ b/lib/src/redux_component_mixin/widgets_binding_observer_mixin.dart @@ -20,12 +20,12 @@ class _WidgetsBindingObserverStfState extends ComponentState @override void initState() { super.initState(); - WidgetsBinding.instance.addObserver(this); + WidgetsBinding.instance!.addObserver(this); } @override void dispose() { - WidgetsBinding.instance.removeObserver(this); + WidgetsBinding.instance!.removeObserver(this); super.dispose(); } diff --git a/lib/src/redux_connector/connector.dart b/lib/src/redux_connector/connector.dart index 6b81912..7095bbb 100644 --- a/lib/src/redux_connector/connector.dart +++ b/lib/src/redux_connector/connector.dart @@ -3,18 +3,19 @@ import '../redux/redux.dart'; import 'op_mixin.dart'; class ConnOp extends MutableConn with ConnOpMixin { - final P Function(T) _getter; - final void Function(T, P) _setter; + final P Function(T)? _getter; + final void Function(T, P)? _setter; const ConnOp({ - P Function(T) get, - void Function(T, P) set, + P Function(T)? get, + void Function(T, P)? set, }) : _getter = get, _setter = set; + /// 可空 @override - P get(T state) => _getter(state); + P? get(T? state) => state != null ? _getter?.call(state) : null; @override - void set(T state, P subState) => _setter(state, subState); + void set(T state, P subState) => _setter?.call(state, subState); } diff --git a/lib/src/redux_connector/helper.dart b/lib/src/redux_connector/helper.dart index 1cf7869..9875ff7 100644 --- a/lib/src/redux_connector/helper.dart +++ b/lib/src/redux_connector/helper.dart @@ -7,7 +7,8 @@ class ConnHelper { return _AbstractConnector(one, two); } - static Dependent join( + /// 可空 + static Dependent? join( AbstractConnector conn, AbstractLogic

logic) => createDependent(conn, logic); } @@ -18,15 +19,16 @@ class _AbstractConnector extends AbstractConnector { _AbstractConnector(this.one, this.two); + /// 可空 @override - K get(T state) { + K? get(T? state) { return two.get(one.get(state)); } @override - SubReducer subReducer(Reducer reducer) { + SubReducer? subReducer(Reducer? reducer) { return one.subReducer((P state, Action action) { - return two.subReducer(reducer)(state, action, false); + return two.subReducer(reducer)?.call(state, action, false); }); } } diff --git a/lib/src/redux_connector/map_like.dart b/lib/src/redux_connector/map_like.dart index 3c2c921..18c4a9e 100644 --- a/lib/src/redux_connector/map_like.dart +++ b/lib/src/redux_connector/map_like.dart @@ -6,40 +6,46 @@ abstract class MapLike { void clear() => _fieldsMap.clear(); - Object operator [](String key) => _fieldsMap[key]; + Object operator [](String key) => _fieldsMap[key]!; void operator []=(String key, Object value) => _fieldsMap[key] = value; bool containsKey(String key) => _fieldsMap.containsKey(key); - void copyFrom(MapLike from) => - _fieldsMap = {}..addAll(from._fieldsMap); + void copyFrom(MapLike from) => _fieldsMap = {}..addAll(from._fieldsMap); } ConnOp withMapLike(String key) => ConnOp( - get: (T state) => state[key], - set: (T state, P sub) => state[key] = sub, + get: (T state) => state[key] as P, + set: (T state, P sub) => state[key] = sub as Object, ); class AutoInitConnector extends ConnOp { static final String Function() _gen = generator(); final String _key; - final void Function(T state, P sub) _setHook; + final void Function(T state, P sub)? _setHook; final P Function(T state) init; - AutoInitConnector(this.init, {String key, void set(T state, P sub)}) + AutoInitConnector(this.init, {String? key, void set(T state, P sub)?}) : assert(init != null), _setHook = set, _key = key ?? _gen(); @override - P get(T state) => - state.containsKey(_key) ? state[_key] : (state[_key] = init(state)); + P? get(T? state) { + if (state != null) { + if (state.containsKey(_key)) { + return state[_key] as P?; + } + return (state[_key] = init(state) as Object) as P?; + } + return null; + } @override void set(T state, P subState) { - state[_key] = subState; + state[_key] = subState as Object; _setHook?.call(state, subState); } } diff --git a/lib/src/redux_connector/none.dart b/lib/src/redux_connector/none.dart index aed8554..65a305c 100644 --- a/lib/src/redux_connector/none.dart +++ b/lib/src/redux_connector/none.dart @@ -5,7 +5,7 @@ class NoneConn extends ImmutableConn with ConnOpMixin { const NoneConn(); @override - T get(T state) => state; + T? get(T? state) => state; @override T set(T state, T subState) => subState; diff --git a/lib/src/redux_connector/op_mixin.dart b/lib/src/redux_connector/op_mixin.dart index 4355841..7da123d 100644 --- a/lib/src/redux_connector/op_mixin.dart +++ b/lib/src/redux_connector/op_mixin.dart @@ -2,6 +2,7 @@ import '../redux/redux.dart'; import '../redux_component/redux_component.dart'; mixin ConnOpMixin on AbstractConnector { + /// 可空 【dependent.dart#89】 Dependent operator +(AbstractLogic

logic) => - createDependent(this, logic); + createDependent(this, logic)!; } diff --git a/lib/src/redux_connector/reselect.dart b/lib/src/redux_connector/reselect.dart index 9e66416..449815c 100644 --- a/lib/src/redux_connector/reselect.dart +++ b/lib/src/redux_connector/reselect.dart @@ -30,8 +30,8 @@ bool _listEquals(List list1, List list2) { abstract class _BasicReselect extends MutableConn with ConnOpMixin { - List _subsCache; - P _pCache; + late List _subsCache; + late P _pCache; bool _hasBeenCalled = false; List getSubs(T state); @@ -39,8 +39,9 @@ abstract class _BasicReselect extends MutableConn P reduceSubs(List list); @override - P get(T state) { - final List subs = getSubs(state); + P? get(T? state) { + ///todo(不确定) + final List subs = getSubs(state!); if (!_hasBeenCalled || !_listEquals(subs, _subsCache)) { _subsCache = subs; _pCache = reduceSubs(_subsCache); @@ -164,8 +165,8 @@ abstract class Reselect extends _BasicReselect { /// issue [https://github.com/alibaba/fish-redux/issues/482] mixin ReselectMixin on MutableConn { - List _cachedFactors; - P _cachedResult; + late List _cachedFactors; + late P _cachedResult; bool _hasBeenCalled = false; P computed(T state); @@ -174,8 +175,9 @@ mixin ReselectMixin on MutableConn { @mustCallSuper @override - P get(T state) { - final List newFactors = factors(state); + P? get(T? state) { + ///todo(不确定) + final List newFactors = factors(state!); if (!_hasBeenCalled || !_listEquals(newFactors, _cachedFactors)) { _cachedFactors = newFactors.toList(growable: false); _cachedResult = computed(state); diff --git a/lib/src/redux_middleware/adapter_middleware/safety_adapter.dart b/lib/src/redux_middleware/adapter_middleware/safety_adapter.dart index e4456ea..1b1858a 100644 --- a/lib/src/redux_middleware/adapter_middleware/safety_adapter.dart +++ b/lib/src/redux_middleware/adapter_middleware/safety_adapter.dart @@ -7,7 +7,7 @@ import '../../utils/utils.dart'; /// type = {0, 1} AdapterMiddleware safetyAdapter({ Widget Function(dynamic, StackTrace, - {AbstractAdapter adapter, Store store, int type}) + {AbstractAdapter adapter, Store store, int type})? onError, }) { return (AbstractAdapter adapter, Store store) { @@ -19,7 +19,8 @@ AdapterMiddleware safetyAdapter({ final ListAdapter result = next(state, dispatch, viewService); return ListAdapter((BuildContext buildContext, int index) { try { - return result.itemBuilder(buildContext, index); + ///todo(不确定) + return result.itemBuilder!(buildContext, index); } catch (e, stackTrace) { return onError?.call( e, @@ -32,7 +33,7 @@ AdapterMiddleware safetyAdapter({ } }, result.itemCount); } catch (e, stackTrace) { - final Widget errorWidget = onError?.call( + final Widget? errorWidget = onError?.call( e, stackTrace, adapter: adapter, diff --git a/lib/src/redux_middleware/middleware/log.dart b/lib/src/redux_middleware/middleware/log.dart index f6a02f1..649c70e 100644 --- a/lib/src/redux_middleware/middleware/log.dart +++ b/lib/src/redux_middleware/middleware/log.dart @@ -5,16 +5,17 @@ import '../../utils/utils.dart'; /// It works on debug mode. Middleware logMiddleware({ String tag = 'redux', - String Function(T) monitor, + /// 可空 + String Function(T)? monitor, }) { - return ({Dispatch dispatch, Get getState}) { + return ({ Dispatch? dispatch, Get? getState}) { return (Dispatch next) { return isDebug() ? (Action action) { print('---------- [$tag] ----------'); print('[$tag] ${action.type} ${action.payload}'); - final T prevState = getState(); + final T prevState = getState!(); if (monitor != null) { print('[$tag] prev-state: ${monitor(prevState)}'); } diff --git a/lib/src/redux_middleware/middleware/performance.dart b/lib/src/redux_middleware/middleware/performance.dart index 2566f41..1c6e49e 100644 --- a/lib/src/redux_middleware/middleware/performance.dart +++ b/lib/src/redux_middleware/middleware/performance.dart @@ -4,7 +4,7 @@ import '../../utils/utils.dart'; /// Middleware for print action dispatch performance by time consuming. /// It works on debug mode. Middleware performanceMiddleware({String tag = 'redux'}) { - return ({Dispatch dispatch, Get getState}) { + return ({Dispatch? dispatch, Get? getState}) { return (Dispatch next) { return isDebug() ? (Action action) { diff --git a/lib/src/redux_middleware/view_middleware/safety_view.dart b/lib/src/redux_middleware/view_middleware/safety_view.dart index 13563be..29507db 100644 --- a/lib/src/redux_middleware/view_middleware/safety_view.dart +++ b/lib/src/redux_middleware/view_middleware/safety_view.dart @@ -6,7 +6,7 @@ import '../../utils/utils.dart'; ViewMiddleware safetyView( {Widget Function(dynamic, StackTrace, - {AbstractComponent component, Store store}) + {AbstractComponent component, Store store})? onError}) { return (AbstractComponent component, Store store) { return (ViewBuilder next) { diff --git a/lib/src/redux_routes/page_routes.dart b/lib/src/redux_routes/page_routes.dart index ba8e396..84f7a50 100644 --- a/lib/src/redux_routes/page_routes.dart +++ b/lib/src/redux_routes/page_routes.dart @@ -13,10 +13,10 @@ class PageRoutes implements AbstractRoutes { final Map> pages; PageRoutes({ - @required this.pages, + required this.pages, /// For common enhance - void Function(String, Page) visitor, + void Function(String, Page)? visitor, }) : assert(pages != null, 'Expected the pages to be non-null value.') { if (visitor != null) { pages.forEach(visitor); @@ -25,5 +25,5 @@ class PageRoutes implements AbstractRoutes { @override Widget buildPage(String path, dynamic arguments) => - pages[path]?.buildPage(arguments); + pages[path]!.buildPage(arguments); } diff --git a/lib/src/utils/collections.dart b/lib/src/utils/collections.dart index ab05e9e..41dc349 100644 --- a/lib/src/utils/collections.dart +++ b/lib/src/utils/collections.dart @@ -3,10 +3,12 @@ import 'dart:core'; /// Util for collections. class Collections { /// Wrap List.reduce with a check list is null or empty. - static E reduce(List list, E combine(E e0, E e1)) => + /// 可空 + static E? reduce(List? list, E combine(E e0, E e1)) => (list == null || list.isEmpty) ? null : list.reduce(combine); /// Wrap List.fold with a check list is null or empty. + /// 可空 static T fold(T init, List list, T combine(T e0, E e1)) => (list == null || list.isEmpty) ? init : list.fold(init, combine); @@ -16,16 +18,17 @@ class Collections { /// List b = ['1', '2', '3']; /// List> list = [a, b] // [[a, b, c], [1, 2, 3]] /// List listFlatten = Collections.flatten(list) // [a, b, c, 1, 2, 3] - static List flatten(List> lists) => reduce(lists, merge); + /// 可空 + static List? flatten(List> lists) => reduce(lists, merge); /// Merge two Iterable /// List a = ['a', 'b', 'c']; /// List b = ['1', '2', '3']; /// List listMerge = Collections.merge(a, b) // [a, b, c, 1, 2, 3] - static List merge(Iterable a, Iterable b) => + static List merge(Iterable? a, Iterable? b) => []..addAll(a ?? [])..addAll(b ?? []); - static List clone(Iterable a) => + static List clone(Iterable? a) => (a == null || a.isEmpty) ? [] : ([]..addAll(a)); /// Cast map to list @@ -47,11 +50,12 @@ class Collections { /// List list = ['1', '2', null, '3', null]; /// print(list) // [1, 2, null, 3, null] /// print(Collections.compact(list)); // [1, 2, 3] - static List compact(Iterable list, {bool growable = true}) => - list?.where((T e) => e != null)?.toList(growable: growable); + /// 可空 list? + static List? compact(Iterable? list, {bool growable = true}) => + list?.where((T? e) => e != null)?.toList(growable: growable); /// Check if an Object is Empty. - static bool isEmpty(Object value) { + static bool isEmpty(Object? value) { if (value == null) { return true; } else { diff --git a/lib/src/utils/tuple.dart b/lib/src/utils/tuple.dart index bf791a4..82d3278 100644 --- a/lib/src/utils/tuple.dart +++ b/lib/src/utils/tuple.dart @@ -13,7 +13,7 @@ class Tuple0 { /// Represents a 1-tuple /// Mutable data types are easier to use. class Tuple1 { - T0 i0; + T0? i0; Tuple1([this.i0]); @@ -30,10 +30,10 @@ class Tuple1 { /// Represents a 2-tuple or pair. class Tuple2 { /// First item of the tuple - T0 i0; + T0? i0; /// Second item of the tuple - T1 i1; + T1? i1; /// Create a new tuple value with the specified items. Tuple2([this.i0, this.i1]); @@ -51,9 +51,9 @@ class Tuple2 { /// Represents a 3-tuple or pair. class Tuple3 { - T0 i0; - T1 i1; - T2 i2; + T0? i0; + T1? i1; + T2? i2; Tuple3([this.i0, this.i1, this.i2]); @@ -70,10 +70,10 @@ class Tuple3 { /// Represents a 4-tuple or pair. class Tuple4 { - T0 i0; - T1 i1; - T2 i2; - T3 i3; + T0? i0; + T1? i1; + T2? i2; + T3? i3; Tuple4([this.i0, this.i1, this.i2, this.i3]); @@ -95,11 +95,11 @@ class Tuple4 { /// Represents a 5-tuple or pair. class Tuple5 { - T0 i0; - T1 i1; - T2 i2; - T3 i3; - T4 i4; + T0? i0; + T1? i1; + T2? i2; + T3? i3; + T4? i4; Tuple5([this.i0, this.i1, this.i2, this.i3, this.i4]); @@ -122,12 +122,12 @@ class Tuple5 { /// Represents a 6-tuple or pair. class Tuple6 { - T0 i0; - T1 i1; - T2 i2; - T3 i3; - T4 i4; - T5 i5; + T0? i0; + T1? i1; + T2? i2; + T3? i3; + T4? i4; + T5? i5; Tuple6([this.i0, this.i1, this.i2, this.i3, this.i4, this.i5]); diff --git a/pubspec.yaml b/pubspec.yaml index 4ef550d..d3f9d2c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -5,10 +5,11 @@ author: Alibaba Xianyu Team homepage: https://github.com/alibaba/fish-redux environment: - sdk: ">=2.2.0 <3.0.0" + sdk: ">=2.12.0 <3.0.0" dependencies: flutter: sdk: flutter + collection: ^1.15.0-nullsafety.4 dev_dependencies: test: ^1.5.1 diff --git a/test/lib/redux_component/component_test.dart b/test/lib/redux_component/component_test.dart index d292869..6d9df17 100644 --- a/test/lib/redux_component/component_test.dart +++ b/test/lib/redux_component/component_test.dart @@ -147,7 +147,7 @@ void main() { expect(componentWidget, isNotNull); expect( - const TypeMatcher().check(componentWidget), isTrue); + const TypeMatcher(), componentWidget); }); testWidgets('build', (WidgetTester tester) async { diff --git a/test/lib/redux_component/lifecycle_test.dart b/test/lib/redux_component/lifecycle_test.dart index e120cbd..eccb294 100644 --- a/test/lib/redux_component/lifecycle_test.dart +++ b/test/lib/redux_component/lifecycle_test.dart @@ -109,7 +109,7 @@ void main() { expect(componentWidget, isNotNull); expect( - const TypeMatcher().check(componentWidget), isTrue); + const TypeMatcher(), componentWidget); }); testWidgets('cycleLife', (WidgetTester tester) async { diff --git a/test/lib/redux_component/page_test.dart b/test/lib/redux_component/page_test.dart index 10c2da6..0973d64 100644 --- a/test/lib/redux_component/page_test.dart +++ b/test/lib/redux_component/page_test.dart @@ -22,7 +22,7 @@ void main() { final Widget pageWidget = page.buildPage(pageInitParams); expect(pageWidget, isNotNull); - expect(const TypeMatcher().check(pageWidget), isTrue); + expect(const TypeMatcher(), pageWidget); //expect(pageWidget, TypeMatcher()); }); diff --git a/test/pubspec.yaml b/test/pubspec.yaml index 7337ffd..61a8212 100644 --- a/test/pubspec.yaml +++ b/test/pubspec.yaml @@ -5,7 +5,7 @@ author: homepage: environment: - sdk: '>=2.0.0-dev.68.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: diff --git a/test/test_widgets/lib/adapter/adapter.dart b/test/test_widgets/lib/adapter/adapter.dart index 8652f3c..790fc7c 100644 --- a/test/test_widgets/lib/adapter/adapter.dart +++ b/test/test_widgets/lib/adapter/adapter.dart @@ -25,7 +25,7 @@ Widget toDoView( height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -41,7 +41,7 @@ Widget toDoView( padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { @@ -87,7 +87,7 @@ bool toDoListEffect(Action action, Context ctx) { assert(action.payload is Todo); Todo toDo = ctx.state.list - .firstWhere((i) => i.id == action.payload.id, orElse: () => null) + .firstWhere((i) => i?.id == action.payload.id, orElse: () => null)! .clone(); toDo.desc = '${toDo.desc}-effect'; ctx.dispatch(Action(ToDoListAction.edit, payload: toDo)); @@ -123,12 +123,12 @@ ToDoList toDoListReducer(ToDoList state, Action action) { } else if (action.type == ToDoListAction.markDone) { return state.clone() ..list - .firstWhere((toDo) => toDo.id == item.id, orElse: () => null) + .firstWhere((toDo) => toDo?.id == item.id, orElse: () => null) ?.isDone = true; } else if (action.type == ToDoListAction.remove) { - return state.clone()..list.removeWhere((toDo) => toDo.id == item.id); + return state.clone()..list.removeWhere((toDo) => toDo?.id == item.id); } else if (action.type == ToDoListAction.edit) { - Todo toDo = state.list.firstWhere((toDo) => toDo.id == item.id); + Todo toDo = state.list.firstWhere((toDo) => toDo?.id == item.id)!; int index = state.list.indexOf(toDo); toDo = toDo.clone()..desc = item.desc; return state.clone()..list[index] = toDo; @@ -143,7 +143,7 @@ ListAdapter toDoListAdapter( ViewService viewService, ) { return ListAdapter((context, index) { - Todo toDo = state.list[index]; + Todo toDo = state.list[index]!; return toDoView(toDo, dispatch, viewService); }, state.list.length); diff --git a/test/test_widgets/lib/adapter/page.dart b/test/test_widgets/lib/adapter/page.dart index e2578e7..daace1f 100644 --- a/test/test_widgets/lib/adapter/page.dart +++ b/test/test_widgets/lib/adapter/page.dart @@ -11,9 +11,9 @@ Widget pageView( ViewService viewService, ) { print('build pageView'); - ListAdapter listAdapter = viewService.buildAdapter(); + ListAdapter listAdapter = viewService.buildAdapter()!; return ListView.builder( - itemBuilder: listAdapter.itemBuilder, itemCount: listAdapter.itemCount); + itemBuilder: listAdapter.itemBuilder!, itemCount: listAdapter.itemCount); } const Map pageInitParams = { @@ -45,7 +45,7 @@ const Map pageInitParams = { ] }; -ToDoList initState(Map map) => ToDoList.fromMap(map); +ToDoList initState(Map? map) => ToDoList.fromMap(map!); class PageWrapper extends StatelessWidget { final Widget child; diff --git a/test/test_widgets/lib/adapter/state.dart b/test/test_widgets/lib/adapter/state.dart index 5bf7107..a960081 100644 --- a/test/test_widgets/lib/adapter/state.dart +++ b/test/test_widgets/lib/adapter/state.dart @@ -1,9 +1,9 @@ import 'package:fish_redux/fish_redux.dart'; class Todo implements Cloneable { - String id; - String title; - String desc; + String? id; + String? title; + String? desc; bool isDone = false; Todo(); @@ -46,7 +46,7 @@ class Todo implements Cloneable { } class ToDoList implements Cloneable { - List list = []; + List list = []; ToDoList(); diff --git a/test/test_widgets/lib/component/component.dart b/test/test_widgets/lib/component/component.dart index 605323d..082a4a4 100644 --- a/test/test_widgets/lib/component/component.dart +++ b/test/test_widgets/lib/component/component.dart @@ -21,7 +21,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -38,7 +38,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { diff --git a/test/test_widgets/lib/component/page.dart b/test/test_widgets/lib/component/page.dart index 6fd8d29..b421398 100644 --- a/test/test_widgets/lib/component/page.dart +++ b/test/test_widgets/lib/component/page.dart @@ -31,7 +31,7 @@ Widget toDoListView( padding: const EdgeInsets.all(8.0), margin: const EdgeInsets.all(8.0), color: Colors.grey, - child: Text(toDo.desc), + child: Text(toDo.desc ?? ''), alignment: AlignmentDirectional.center, ); } @@ -130,7 +130,7 @@ const Map pageInitParams = { ] }; -ToDoList initState(Map map) => ToDoList.fromMap(map); +ToDoList initState(Map? map) => ToDoList.fromMap(map!); class ToDoComponent0 extends ToDoComponent {} diff --git a/test/test_widgets/lib/component/state.dart b/test/test_widgets/lib/component/state.dart index 5bf7107..5ac83ab 100644 --- a/test/test_widgets/lib/component/state.dart +++ b/test/test_widgets/lib/component/state.dart @@ -1,9 +1,9 @@ import 'package:fish_redux/fish_redux.dart'; class Todo implements Cloneable { - String id; - String title; - String desc; + String? id; + String? title; + String? desc; bool isDone = false; Todo(); diff --git a/test/test_widgets/lib/dynamic_flow_adapter/adapter.dart b/test/test_widgets/lib/dynamic_flow_adapter/adapter.dart index 2589d64..493210c 100644 --- a/test/test_widgets/lib/dynamic_flow_adapter/adapter.dart +++ b/test/test_widgets/lib/dynamic_flow_adapter/adapter.dart @@ -21,7 +21,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -38,7 +38,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { diff --git a/test/test_widgets/lib/dynamic_flow_adapter/component.dart b/test/test_widgets/lib/dynamic_flow_adapter/component.dart index a6518a7..ce6ca02 100644 --- a/test/test_widgets/lib/dynamic_flow_adapter/component.dart +++ b/test/test_widgets/lib/dynamic_flow_adapter/component.dart @@ -21,7 +21,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -38,7 +38,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { diff --git a/test/test_widgets/lib/dynamic_flow_adapter/dynamic_flow_adapter.dart b/test/test_widgets/lib/dynamic_flow_adapter/dynamic_flow_adapter.dart index 4fbf94a..8908b47 100644 --- a/test/test_widgets/lib/dynamic_flow_adapter/dynamic_flow_adapter.dart +++ b/test/test_widgets/lib/dynamic_flow_adapter/dynamic_flow_adapter.dart @@ -39,7 +39,7 @@ final TestDynamicFlowAdapter testAdapter = set: (ToDoList toDoList, List beans) { toDoList.list.clear(); toDoList.list.addAll( - beans.map((ItemBean bean) => bean.data).toList()); + beans.map((ItemBean bean) => bean.data as dynamic).toList()); }), reducer: toDoListReducer, effect: toDoListEffect); diff --git a/test/test_widgets/lib/dynamic_flow_adapter/page.dart b/test/test_widgets/lib/dynamic_flow_adapter/page.dart index 463fbc2..5eb444e 100644 --- a/test/test_widgets/lib/dynamic_flow_adapter/page.dart +++ b/test/test_widgets/lib/dynamic_flow_adapter/page.dart @@ -12,12 +12,12 @@ Widget pageView( ViewService viewService, ) { print('build pageView'); - final ListAdapter listAdapter = viewService.buildAdapter(); + final ListAdapter listAdapter = viewService.buildAdapter()!; return Column( children: [ Expanded( child: ListView.builder( - itemBuilder: listAdapter.itemBuilder, + itemBuilder: listAdapter.itemBuilder!, itemCount: listAdapter.itemCount)), Row( children: [ @@ -84,7 +84,7 @@ bool pageEffect(Action action, Context ctx) { return false; } -ToDoList initState(Map map) => ToDoList.fromMap(map); +ToDoList initState(Map? map) => ToDoList.fromMap(map!); Widget createDynamicAdapterWidget(BuildContext context) { return TestPage( diff --git a/test/test_widgets/lib/dynamic_flow_adapter/state.dart b/test/test_widgets/lib/dynamic_flow_adapter/state.dart index 5bf7107..5ac83ab 100644 --- a/test/test_widgets/lib/dynamic_flow_adapter/state.dart +++ b/test/test_widgets/lib/dynamic_flow_adapter/state.dart @@ -1,9 +1,9 @@ import 'package:fish_redux/fish_redux.dart'; class Todo implements Cloneable { - String id; - String title; - String desc; + String? id; + String? title; + String? desc; bool isDone = false; Todo(); diff --git a/test/test_widgets/lib/page/page.dart b/test/test_widgets/lib/page/page.dart index 4b1fc0f..ad14c81 100644 --- a/test/test_widgets/lib/page/page.dart +++ b/test/test_widgets/lib/page/page.dart @@ -23,7 +23,7 @@ Widget toDoView(Todo toDo, BuildContext context, Dispatch dispatch) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -39,7 +39,7 @@ Widget toDoView(Todo toDo, BuildContext context, Dispatch dispatch) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { @@ -87,7 +87,7 @@ Widget toDoListView( Expanded( child: ListView.builder( itemBuilder: (context, index) { - Todo toDo = state.list[index]; + Todo toDo = state.list[index]!; return toDoView(toDo, context, dispatch); }, itemCount: state.list.length, @@ -142,7 +142,7 @@ bool toDoListEffect(Action action, Context ctx) { assert(action.payload is Todo); Todo toDo = ctx.state.list - .firstWhere((i) => i.id == action.payload.id, orElse: () => null); + .firstWhere((Todo? i) => i?.id == action.payload.id, orElse: () => null)!; assert(toDo != null); @@ -183,14 +183,14 @@ ToDoList toDoListReducer(ToDoList state, Action action) { } else if (action.type == ToDoListAction.markDone) { return state.clone() ..list - .firstWhere((toDo) => toDo.id == item.id, orElse: () => null) + .firstWhere((toDo) => toDo?.id == item.id, orElse: () => null) ?.isDone = true; } else if (action.type == ToDoListAction.remove) { - return state.clone()..list.removeWhere((toDo) => toDo.id == item.id); + return state.clone()..list.removeWhere((toDo) => toDo?.id == item.id); } else if (action.type == ToDoListAction.edit) { return state.clone() ..list - .firstWhere((toDo) => toDo.id == item.id, orElse: () => null) + .firstWhere((toDo) => toDo?.id == item.id, orElse: () => null) ?.desc = item.desc; } else { return state; @@ -211,16 +211,16 @@ bool toDoListErrorHandler(Exception exception, Context ctx) { } Composable toDoListMiddleware({ - Dispatch dispatch, - Get getState, + required Dispatch dispatch, + required Get getState, }) => (Dispatch next) => (Action action) { if (action.type == ToDoListAction.middlewareEdit) { assert(action.payload is Todo); Todo toDo = getState().list.firstWhere( - (i) => i.id == action.payload.id, - orElse: () => null); + (i) => i?.id == action.payload.id, + orElse: () => null)!; assert(toDo != null); @@ -262,7 +262,7 @@ const Map pageInitParams = { ] }; -ToDoList initState(Map map) => ToDoList.fromMap(map); +ToDoList initState(Map? map) => ToDoList.fromMap(map!); class PageWrapper extends StatelessWidget { final Widget child; @@ -283,5 +283,5 @@ Widget createPageWidget(BuildContext context) { effect: toDoListEffectAsync, // shouldUpdate: forbidRefreshWhenAddOrRemove, // onError: toDoListErrorHandler, - middleware: [toDoListMiddleware]).buildPage(pageInitParams); + middleware: [toDoListMiddleware as dynamic]).buildPage(pageInitParams); } diff --git a/test/test_widgets/lib/page/state.dart b/test/test_widgets/lib/page/state.dart index 5bf7107..a960081 100644 --- a/test/test_widgets/lib/page/state.dart +++ b/test/test_widgets/lib/page/state.dart @@ -1,9 +1,9 @@ import 'package:fish_redux/fish_redux.dart'; class Todo implements Cloneable { - String id; - String title; - String desc; + String? id; + String? title; + String? desc; bool isDone = false; Todo(); @@ -46,7 +46,7 @@ class Todo implements Cloneable { } class ToDoList implements Cloneable { - List list = []; + List list = []; ToDoList(); diff --git a/test/test_widgets/lib/source_flow_adapter/adapter.dart b/test/test_widgets/lib/source_flow_adapter/adapter.dart index 2589d64..493210c 100644 --- a/test/test_widgets/lib/source_flow_adapter/adapter.dart +++ b/test/test_widgets/lib/source_flow_adapter/adapter.dart @@ -21,7 +21,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -38,7 +38,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { diff --git a/test/test_widgets/lib/source_flow_adapter/component.dart b/test/test_widgets/lib/source_flow_adapter/component.dart index a6518a7..ce6ca02 100644 --- a/test/test_widgets/lib/source_flow_adapter/component.dart +++ b/test/test_widgets/lib/source_flow_adapter/component.dart @@ -21,7 +21,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -38,7 +38,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { diff --git a/test/test_widgets/lib/source_flow_adapter/page.dart b/test/test_widgets/lib/source_flow_adapter/page.dart index 6152bda..c4d2f0a 100644 --- a/test/test_widgets/lib/source_flow_adapter/page.dart +++ b/test/test_widgets/lib/source_flow_adapter/page.dart @@ -12,12 +12,12 @@ Widget pageView( ViewService viewService, ) { print('build pageView'); - final ListAdapter listAdapter = viewService.buildAdapter(); + final ListAdapter listAdapter = viewService.buildAdapter()!; return Column( children: [ Expanded( child: ListView.builder( - itemBuilder: listAdapter.itemBuilder, + itemBuilder: listAdapter.itemBuilder!, itemCount: listAdapter.itemCount)), Row( children: [ @@ -84,7 +84,7 @@ bool pageEffect(Action action, Context ctx) { return false; } -ToDoList initState(Map map) => ToDoList.fromMap(map); +ToDoList initState(Map? map) => ToDoList.fromMap(map!); Widget createDynamicAdapterWidget(BuildContext context) { return TestPage( diff --git a/test/test_widgets/lib/source_flow_adapter/state.dart b/test/test_widgets/lib/source_flow_adapter/state.dart index 4a73afe..240d546 100644 --- a/test/test_widgets/lib/source_flow_adapter/state.dart +++ b/test/test_widgets/lib/source_flow_adapter/state.dart @@ -1,9 +1,9 @@ import 'package:fish_redux/fish_redux.dart'; class Todo implements Cloneable { - String id; - String title; - String desc; + String? id; + String? title; + String? desc; bool isDone = false; Todo(); @@ -88,7 +88,7 @@ class ToDoList extends ItemListLike implements Cloneable { @override ItemListLike updateItemData(int index, Object data, bool isStateCopied) { - list[index] = data; + list[index] = data as dynamic; return this; } } diff --git a/test/test_widgets/lib/static_flow_adapter/component.dart b/test/test_widgets/lib/static_flow_adapter/component.dart index 1a34451..0a4c57c 100644 --- a/test/test_widgets/lib/static_flow_adapter/component.dart +++ b/test/test_widgets/lib/static_flow_adapter/component.dart @@ -21,7 +21,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { height: 28.0, color: Colors.yellow, child: Text( - toDo.title, + toDo.title ?? '', style: TextStyle(fontSize: 16.0), ), alignment: AlignmentDirectional.centerStart, @@ -38,7 +38,7 @@ Widget toDoView(Todo toDo, Dispatch dispatch, ViewService viewService) { padding: const EdgeInsets.all(8.0), height: 60.0, color: Colors.grey, - child: Text(toDo.desc, style: TextStyle(fontSize: 14.0)), + child: Text(toDo.desc ?? '', style: TextStyle(fontSize: 14.0)), alignment: AlignmentDirectional.centerStart, ), onTap: () { diff --git a/test/test_widgets/lib/static_flow_adapter/page.dart b/test/test_widgets/lib/static_flow_adapter/page.dart index 64d37ad..745842a 100644 --- a/test/test_widgets/lib/static_flow_adapter/page.dart +++ b/test/test_widgets/lib/static_flow_adapter/page.dart @@ -11,9 +11,9 @@ Widget pageView( ViewService viewService, ) { print('build pageView'); - ListAdapter listAdapter = viewService.buildAdapter(); + ListAdapter listAdapter = viewService.buildAdapter()!; return ListView.builder( - itemBuilder: listAdapter.itemBuilder, itemCount: listAdapter.itemCount); + itemBuilder: listAdapter.itemBuilder!, itemCount: listAdapter.itemCount); } const Map pageInitParams = { @@ -45,7 +45,7 @@ const Map pageInitParams = { ] }; -ToDoList initState(Map map) => ToDoList.fromMap(map); +ToDoList initState(Map? map) => ToDoList.fromMap(map!); Widget createStaticAdapterWidget(BuildContext context) { return TestPage( diff --git a/test/test_widgets/lib/static_flow_adapter/state.dart b/test/test_widgets/lib/static_flow_adapter/state.dart index 5bf7107..a960081 100644 --- a/test/test_widgets/lib/static_flow_adapter/state.dart +++ b/test/test_widgets/lib/static_flow_adapter/state.dart @@ -1,9 +1,9 @@ import 'package:fish_redux/fish_redux.dart'; class Todo implements Cloneable { - String id; - String title; - String desc; + String? id; + String? title; + String? desc; bool isDone = false; Todo(); @@ -46,7 +46,7 @@ class Todo implements Cloneable { } class ToDoList implements Cloneable { - List list = []; + List list = []; ToDoList(); diff --git a/test/test_widgets/lib/static_flow_adapter/static_flow_adapter.dart b/test/test_widgets/lib/static_flow_adapter/static_flow_adapter.dart index a9b826d..e0a7a2e 100644 --- a/test/test_widgets/lib/static_flow_adapter/static_flow_adapter.dart +++ b/test/test_widgets/lib/static_flow_adapter/static_flow_adapter.dart @@ -34,7 +34,7 @@ ToDoList toDoListReducer(ToDoList state, Action action) { if (action.type == ToDoListAction.add) { return state.clone()..list.add(action.payload); } else if (action.type == ToDoListAction.remove) { - Todo toDo = state.list.firstWhere((toDo) => toDo?.id == action.payload.id); + Todo? toDo = state.list.firstWhere((Todo? toDo) => toDo?.id == action.payload.id); int index = state.list.indexOf(toDo); return state.clone()..list[index] = null; } else { @@ -52,19 +52,19 @@ class ToDoComponent3 extends ToDoComponent {} final testAdapter = TestStaticFlowAdapter(slots: [ ConnOp( - get: (toDoList) => toDoList.list[0], + get: (ToDoList toDoList) => toDoList.list[0]!, set: (toDoList, toDo) => toDoList.list[0] = toDo) + ToDoComponent0(), ConnOp( - get: (toDoList) => toDoList.list[1], + get: (toDoList) => toDoList.list[1]!, set: (toDoList, toDo) => toDoList.list[1] = toDo) + ToDoComponent1(), ConnOp( - get: (toDoList) => toDoList.list[2], + get: (toDoList) => toDoList.list[2]!, set: (toDoList, toDo) => toDoList.list[2] = toDo) + ToDoComponent2(), ConnOp( - get: (toDoList) => toDoList.list[3], + get: (toDoList) => toDoList.list[3]!, set: (toDoList, toDo) => toDoList.list[3] = toDo) + ToDoComponent3() ], reducer: toDoListReducer, effect: toDoListEffect); diff --git a/test/test_widgets/lib/test_base.dart b/test/test_widgets/lib/test_base.dart index e5dca5f..1233e99 100644 --- a/test/test_widgets/lib/test_base.dart +++ b/test/test_widgets/lib/test_base.dart @@ -25,16 +25,16 @@ class _StubState extends State { class TestPage, P> extends Page { TestPage({ - @required InitState initState, - List> middleware, - @required ViewBuilder view, - Reducer reducer, - ReducerFilter filter, - Effect effect, - Dependencies dependencies, - ShouldUpdate shouldUpdate, - WidgetWrapper wrapper, - Key Function(T) key, + required InitState initState, + List>? middleware, + required ViewBuilder view, + Reducer? reducer, + ReducerFilter? filter, + Effect? effect, + Dependencies? dependencies, + ShouldUpdate? shouldUpdate, + WidgetWrapper? wrapper, + Key Function(T)? key, }) : super( initState: initState, middleware: middleware, @@ -51,14 +51,14 @@ class TestPage, P> extends Page { class TestComponent> extends Component { TestComponent({ - @required ViewBuilder view, - Reducer reducer, - ReducerFilter filter, - Effect effect, - Dependencies dependencies, - ShouldUpdate shouldUpdate, - WidgetWrapper wrapper, - Key Function(T) key, + required ViewBuilder view, + Reducer? reducer, + ReducerFilter? filter, + Effect? effect, + Dependencies? dependencies, + ShouldUpdate? shouldUpdate, + WidgetWrapper? wrapper, + Key Function(T)? key, }) : super( view: view, reducer: reducer, @@ -72,11 +72,11 @@ class TestComponent> extends Component { class TestAdapter> extends Adapter { TestAdapter({ - AdapterBuilder adapter, - Reducer reducer, - Effect effect, - ReducerFilter filter, - Dependencies dependencies, + required AdapterBuilder adapter, + Reducer? reducer, + Effect? effect, + ReducerFilter? filter, + Dependencies? dependencies, }) : super( adapter: adapter, reducer: reducer, @@ -88,21 +88,21 @@ class TestAdapter> extends Adapter { class TestStaticFlowAdapter> extends StaticFlowAdapter { TestStaticFlowAdapter({ - @required List> slots, - Reducer reducer, - Effect effect, - ReducerFilter filter, + required List> slots, + Reducer? reducer, + Effect? effect, + ReducerFilter? filter, }) : super(slots: slots, reducer: reducer, effect: effect, filter: filter); } class TestDynamicFlowAdapter> extends DynamicFlowAdapter { TestDynamicFlowAdapter({ - @required Map> pool, - @required ConnOp> connector, - ReducerFilter filter, - Reducer reducer, - Effect effect, + required Map> pool, + required ConnOp> connector, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, }) : super( pool: pool, connector: connector, @@ -111,13 +111,13 @@ class TestDynamicFlowAdapter> filter: filter); } -class TestSourceFlowAdapter +class TestSourceFlowAdapter extends SourceFlowAdapter { TestSourceFlowAdapter({ - @required Map> pool, - ReducerFilter filter, - Reducer reducer, - Effect effect, + required Map> pool, + ReducerFilter? filter, + Reducer? reducer, + Effect? effect, }) : super( pool: pool, reducer: reducer, diff --git a/test/test_widgets/pubspec.yaml b/test/test_widgets/pubspec.yaml index cde8798..30129b6 100644 --- a/test/test_widgets/pubspec.yaml +++ b/test/test_widgets/pubspec.yaml @@ -2,7 +2,7 @@ name: test_widgets description: widgets for redux test... environment: - sdk: '>=2.0.0-dev.28.0 <3.0.0' + sdk: '>=2.12.0 <3.0.0' dependencies: flutter: