repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_logger.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import '../logger/thrio_logger.dart';
bool navigatorLogging = false;
void verbose(dynamic message) {
assert(() {
if (navigatorLogging) {
ThrioLogger.v(message);
}
return true;
}());
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_observer.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import 'thrio_navigator.dart';
/// An interface for observing the page lifecycle of a [ThrioNavigator].
///
mixin NavigatorPageObserver {
/// The `route` to be observed,default to null.
///
RouteSettings? get settings => null;
/// The `route` is about to be activated.
///
void willAppear(RouteSettings routeSettings) {}
/// The `route` has been appeared.
///
void didAppear(RouteSettings routeSettings) {}
/// The `route` is about to disappear.
///
void willDisappear(RouteSettings routeSettings) {}
/// The `route` has been disappeared.
///
void didDisappear(RouteSettings routeSettings) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_route.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
import 'thrio_navigator_implement.dart';
enum NavigatorRouteType { push, pop, popTo, remove, replace }
/// A route managed by the `ThrioNavigatorImplement`.
///
mixin NavigatorRoute on PageRoute<bool> {
NavigatorRouteType? routeType;
@override
RouteSettings get settings;
NavigatorParamsCallback? poppedResult;
final _popDisableds = <String, bool>{};
final _popDisabledFutures = <String, Future<dynamic>>{};
@protected
void setPopDisabled({bool disabled = false}) {
if (_popDisableds[settings.name!] == disabled) {
return;
}
_popDisableds[settings.name!] = disabled;
// 延迟300ms执行,避免因为WillPopScope依赖变更导致发送过多的Channel消息
_popDisabledFutures[settings.name!] ??=
Future.delayed(const Duration(milliseconds: 300), () {
_popDisabledFutures.remove(settings.name); // ignore: unawaited_futures
final disabled = _popDisableds.remove(settings.name);
if (disabled != null) {
ThrioNavigatorImplement.shared().setPopDisabled(
url: settings.url,
index: settings.index,
disabled: disabled,
);
}
});
}
@protected
void clearPopDisabledFutures() {
_popDisabledFutures.clear();
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_route.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import '../module/thrio_module.dart';
import 'navigator_route.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
/// A route managed by the `ThrioNavigatorImplement`.
///
class NavigatorPageRoute extends MaterialPageRoute<bool> with NavigatorRoute {
NavigatorPageRoute({
required NavigatorPageBuilder pageBuilder,
required RouteSettings settings,
super.maintainState,
super.fullscreenDialog,
}) : super(builder: (_) => pageBuilder(settings), settings: settings);
@override
void addScopedWillPopCallback(WillPopCallback callback) {
setPopDisabled(disabled: true);
super.addScopedWillPopCallback(callback);
}
@override
void removeScopedWillPopCallback(WillPopCallback callback) {
setPopDisabled();
super.removeScopedWillPopCallback(callback);
}
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (settings.isNested) {
if (!settings.animated) {
return child;
}
final builder =
ThrioModule.get<RouteTransitionsBuilder>(url: settings.url);
if (builder != null) {
return builder(context, animation, secondaryAnimation, child);
}
return super.buildTransitions(
context,
animation,
secondaryAnimation,
child,
);
}
return child;
}
@override
void dispose() {
clearPopDisabledFutures();
super.dispose();
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_url_template.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import '../exception/thrio_exception.dart';
@immutable
class NavigatorUrlTemplate {
NavigatorUrlTemplate({required this.template}) {
var tem = template;
final paramsStr = RegExp(r'\{(.*?)\}').stringMatch(tem);
if (paramsStr != null) {
tem = tem.replaceAll(paramsStr, '');
}
final parts = tem.split('://');
if (parts.length > 2) {
throw ThrioException('inivalid template: $template');
} else if (parts.length == 2) {
scheme = parts[0].toLowerCase();
host = parts[1].split('/')[0];
path = parts[1].replaceFirst(host, '');
} else {
scheme = '';
host = '';
path = tem;
}
if (paramsStr != null) {
final paramsKeys = paramsStr
.replaceAll(' ', '')
.replaceAll('{', '')
.replaceAll('}', '')
.split(',');
requiredParamKeys.addAll(paramsKeys
.where((it) => it.isNotEmpty && !it.endsWith('?'))
.map((it) => it.replaceAll('?', '')));
}
}
final String template;
late final String scheme;
late final String host;
late final String path;
final List<String> requiredParamKeys = <String>[];
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is NavigatorUrlTemplate && template == other.template;
}
bool match(Uri uri) {
// url 允许通过传入模板来表明使用者已经正常传入参数
var uriPath = Uri.decodeFull(uri.path);
var uriParamsKeys = uri.queryParametersAll.keys;
if (uriPath.contains('{')) {
uriParamsKeys = uriPath
.split('{')[1]
.replaceAll('}', '')
.replaceAll('=', '?')
.split(',');
uriPath = uriPath.split('{')[0];
}
if (scheme == uri.scheme &&
((host.contains('*') &&
RegExp(host.replaceFirst('*', '.*')).hasMatch(uri.host)) ||
host == uri.host) &&
(path.isEmpty || path == uriPath)) {
if (requiredParamKeys.isEmpty) {
return true;
}
if (!requiredParamKeys.any((k) => !uriParamsKeys.contains(k))) {
return true;
}
}
return false;
}
@override
int get hashCode => template.hashCode;
@override
String toString() => template;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/thrio_navigator_implement.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../async/async_task_queue.dart';
import '../channel/thrio_channel.dart';
import '../exception/thrio_exception.dart';
import '../extension/thrio_iterable.dart';
import '../extension/thrio_uri_string.dart';
import '../module/module_anchor.dart';
import '../module/module_types.dart';
import '../module/thrio_module.dart';
import '../registry/registry_set.dart';
import 'navigator_dialog_route.dart';
import 'navigator_material_app.dart';
import 'navigator_observer_manager.dart';
import 'navigator_page_observer_channel.dart';
import 'navigator_route.dart';
import 'navigator_route_observer_channel.dart';
import 'navigator_route_receive_channel.dart';
import 'navigator_route_send_channel.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
import 'navigator_widget.dart';
class ThrioNavigatorImplement {
factory ThrioNavigatorImplement.shared() => _default;
ThrioNavigatorImplement._();
static final ThrioNavigatorImplement _default = ThrioNavigatorImplement._();
Future<void> init(ModuleContext moduleContext) async {
_moduleContext = moduleContext;
_channel =
ThrioChannel(channel: '__thrio_app__${moduleContext.entrypoint}');
ThrioChannel(channel: '__thrio_module_context__${moduleContext.entrypoint}')
.registryMethodCall('set', ([final arguments]) async {
if (arguments == null || arguments.isEmpty) {
return;
}
for (final key in arguments.keys) {
final value = arguments[key];
if (value == null) {
anchor.remove<dynamic>(key);
} else {
anchor.set(key, _deserializeParams(value));
}
}
});
_sendChannel = NavigatorRouteSendChannel(_channel);
_receiveChannel = NavigatorRouteReceiveChannel(_channel);
routeChannel = NavigatorRouteObserverChannel(moduleContext.entrypoint);
pageChannel = NavigatorPageObserverChannel(moduleContext.entrypoint);
}
TransitionBuilder get builder => (context, child) {
Navigator? navigator;
if (child is Navigator) {
navigator = child;
}
if (navigator == null && child is FocusScope) {
final c = child.child;
if (c is Navigator) {
navigator = c;
}
}
if (navigator != null) {
if (!navigator.observers.contains(observerManager)) {
navigator.observers.add(observerManager);
}
return NavigatorWidget(
key: _stateKey,
moduleContext: _moduleContext,
observerManager: observerManager,
child: navigator,
);
}
return const SizedBox(
width: 200,
height: 100,
child: Text('child for builder must be Navigator'),
);
};
late final ModuleContext _moduleContext;
late final _stateKey = GlobalKey<NavigatorWidgetState>();
NavigatorWidgetState? get navigatorState => _stateKey.currentState;
final _pushBeginHandlers = RegistrySet();
final poppedResults = <String, NavigatorParamsCallback>{};
List<NavigatorRoute> get currentPopRoutes => observerManager.currentPopRoutes;
late final ThrioChannel _channel;
late final NavigatorRouteSendChannel _sendChannel;
late final NavigatorRouteReceiveChannel _receiveChannel;
late final NavigatorRouteObserverChannel routeChannel;
late final NavigatorPageObserverChannel pageChannel;
late final observerManager = NavigatorObserverManager();
final _taskQueue = AsyncTaskQueue();
void ready() {
// 需要将 WidgetsAppState 中的 `didPopRoute` 去掉,否则后续所有的 `didPopRoute` 都不生效了
final appState = NavigatorMaterialApp.appKey.currentState;
if (appState != null) {
final state = GlobalObjectKey(appState).currentState;
if (state is WidgetsBindingObserver) {
WidgetsBinding.instance.removeObserver(state as WidgetsBindingObserver);
}
}
_channel.invokeMethod<bool>('ready');
}
VoidCallback registerPushBeginHandle(NavigatorPushBeginHandle handle) =>
_pushBeginHandlers.registry(handle);
Future<TPopParams?> push<TParams, TPopParams>({
required String url,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams?>();
final handled = await _pushToHandler(
url,
params,
animated,
completer,
result,
);
if (!handled) {
Future<void> pushFuture() {
final resultCompleter = Completer();
_pushToNative<TParams, TPopParams>(
url,
params,
animated,
completer,
).then((index) {
resultCompleter.complete();
result?.call(index);
});
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<void> _onPushBeginHandle<TParams>({
required String url,
TParams? params,
}) async {
for (final handle in _pushBeginHandlers) {
await handle(url, params);
}
}
Future<TPopParams?> _onRouteCustomHandle<TParams, TPopParams>({
required NavigatorRouteCustomHandler handler,
required Uri uri,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
final queryParametersAll = handler.queryParamsDecoded
? uri.queryParametersAll
: uri.query.rawQueryParametersAll;
return handler<TParams, TPopParams>(
uri.toString(),
queryParametersAll,
params: params,
animated: animated,
result: result,
);
}
Future<TPopParams?> pushSingle<TParams, TPopParams>({
required String url,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams?>();
final handled =
await _pushToHandler(url, params, animated, completer, (index) async {
result?.call(index);
if (index > 0) {
await removeAll(url: url, excludeIndex: index);
}
});
if (!handled) {
Future<void> pushFuture() {
final resultCompleter = Completer();
_pushToNative<TParams, TPopParams>(url, params, animated, completer)
.then<void>((index) async {
resultCompleter.complete();
result?.call(index);
if (index > 0) {
await removeAll(url: url, excludeIndex: index);
}
});
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<TPopParams?> pushReplace<TParams, TPopParams>({
required String url,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams>();
final lastSetting = await lastRoute();
if (lastSetting == null) {
throw ThrioException('no route to replace');
}
final handled =
await _pushToHandler(url, params, animated, completer, (index) async {
if (index > 0) {
await remove(url: lastSetting.url, index: lastSetting.index);
}
result?.call(index);
});
if (!handled) {
Future<void> pushFuture() async {
final resultCompleter = Completer();
final lastSetting = await lastRoute();
if (lastSetting == null) {
throw ThrioException('no route to replace');
}
unawaited(
_pushToNative<TParams, TPopParams>(url, params, animated, completer)
.then((index) async {
resultCompleter.complete();
if (index > 0) {
await remove(url: lastSetting.url, index: lastSetting.index);
}
result?.call(index);
}));
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<TPopParams?> pushAndRemoveTo<TParams, TPopParams>({
required String url,
required String toUrl,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams>();
final routes = await allRoutes();
final route = routes.lastWhereOrNull((it) => it.url == toUrl);
if (route == null) {
result?.call(0);
}
final handled =
await _pushToHandler(url, params, animated, completer, (index) async {
if (index > 0) {
await removeBelowUntil(predicate: (url) => url == toUrl);
}
result?.call(index);
});
if (!handled) {
Future<void> pushFuture() async {
final resultCompleter = Completer();
final routes = await allRoutes();
final route = routes.lastWhereOrNull((it) => it.url == toUrl);
if (route == null) {
result?.call(0);
resultCompleter.complete();
}
unawaited(
_pushToNative<TParams, TPopParams>(url, params, animated, completer)
.then((index) async {
resultCompleter.complete();
if (index > 0) {
await removeBelowUntil(predicate: (url) => url == toUrl);
}
result?.call(index);
}));
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<TPopParams?> pushAndRemoveToFirst<TParams, TPopParams>({
required String url,
required String toUrl,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams>();
final routes = await allRoutes();
final route = routes.firstWhereOrNull((it) => it.url == toUrl);
if (route == null) {
result?.call(0);
}
final handled =
await _pushToHandler(url, params, animated, completer, (index) async {
if (index > 0) {
await removeBelowUntilFirst(predicate: (url) => url == toUrl);
}
result?.call(index);
});
if (!handled) {
Future<void> pushFuture() async {
final resultCompleter = Completer();
final routes = await allRoutes();
final route = routes.firstWhereOrNull((it) => it.url == toUrl);
if (route == null) {
result?.call(0);
resultCompleter.complete();
}
unawaited(
_pushToNative<TParams, TPopParams>(url, params, animated, completer)
.then((index) async {
resultCompleter.complete();
if (index > 0) {
await removeBelowUntilFirst(predicate: (url) => url == toUrl);
}
result?.call(index);
}));
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<TPopParams?> pushAndRemoveUntil<TParams, TPopParams>({
required String url,
required bool Function(String url) predicate,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams>();
final routes = await allRoutes();
final route =
routes.lastWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
result?.call(0);
}
final handled =
await _pushToHandler(url, params, animated, completer, (index) async {
if (index > 0) {
await removeBelowUntil(predicate: predicate);
}
result?.call(index);
});
if (!handled) {
Future<void> pushFuture() async {
final resultCompleter = Completer();
final routes = await allRoutes();
final route = routes
.lastWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
resultCompleter.complete();
result?.call(0);
}
unawaited(
_pushToNative<TParams, TPopParams>(url, params, animated, completer)
.then((index) async {
resultCompleter.complete();
if (index > 0) {
await removeBelowUntil(predicate: predicate);
}
result?.call(index);
}));
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<TPopParams?> pushAndRemoveUntilFirst<TParams, TPopParams>({
required String url,
required bool Function(String url) predicate,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) async {
await _onPushBeginHandle(url: url, params: params);
final completer = Completer<TPopParams>();
final routes = await allRoutes();
final route =
routes.firstWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
result?.call(0);
}
final handled =
await _pushToHandler(url, params, animated, completer, (index) async {
if (index > 0) {
await removeBelowUntilFirst(predicate: predicate);
}
result?.call(index);
});
if (!handled) {
Future<void> pushFuture() async {
final resultCompleter = Completer();
final routes = await allRoutes();
final route = routes
.firstWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
resultCompleter.complete();
result?.call(0);
}
unawaited(
_pushToNative<TParams, TPopParams>(url, params, animated, completer)
.then((index) async {
resultCompleter.complete();
if (index > 0) {
await removeBelowUntilFirst(predicate: predicate);
}
result?.call(index);
}));
return resultCompleter.future;
}
unawaited(_taskQueue.add(pushFuture));
}
return completer.future;
}
Future<bool> _pushToHandler<TParams, TPopParams>(
String url,
TParams? params,
bool animated,
Completer<TPopParams?> completer,
NavigatorIntCallback? result,
) async {
var handled = false;
final uri = Uri.parse(url);
var handler =
anchor.routeCustomHandlers.lastWhereOrNull((it) => it.match(uri));
if (handler != null) {
for (var i = anchor.routeCustomHandlers.length - 1; i >= 0; i--) {
final entry = anchor.routeCustomHandlers.elementAt(i);
if (!entry.key.match(uri)) {
continue;
}
handler = entry.value;
var index = 0;
final pr = await _onRouteCustomHandle<TParams, TPopParams>(
handler: handler,
uri: uri,
params: params,
animated: animated,
result: (idx) {
index = idx;
result?.call(index);
},
);
if (index != navigatorResultTypeNotHandled) {
handled = true;
poppedResult(completer, pr);
break;
}
}
}
return handled;
}
Future<int> _pushToNative<TParams, TPopParams>(
String url,
TParams? params,
bool animated,
Completer<TPopParams?> completer,
) {
final qidx = url.indexOf('?');
final ps = params ?? <String, dynamic>{};
var noQueryUrl = url;
if (qidx != -1) {
if (ps is Map) {
final query = url.substring(qidx);
final qps = query.rawQueryParameters;
ps.addAll(qps);
}
noQueryUrl = url.substring(0, qidx);
}
return _sendChannel
.push(url: noQueryUrl, params: ps, animated: animated)
.then((index) {
if (index > 0) {
final routeName = '$index $noQueryUrl';
final routeHistory =
ThrioNavigatorImplement.shared().navigatorState?.history;
final route = routeHistory
?.lastWhereOrNull((it) => it.settings.name == routeName);
if (route != null && route is NavigatorRoute) {
route.poppedResult =
(params) => poppedResult<TPopParams>(completer, params);
} else {
// 不在当前页面栈上,则通过name来缓存
poppedResults[routeName] =
(params) => poppedResult<TPopParams>(completer, params);
}
}
return index;
});
}
void poppedResult<TPopParams>(
Completer<TPopParams?> completer,
dynamic params,
) {
if (completer.isCompleted) {
return;
}
if (params == null) {
completer.complete(null);
} else if (params is TPopParams) {
completer.complete(params);
} else {
completer
.completeError(ArgumentError('invalid params: $params', 'params'));
}
}
Future<bool> notifyAll<TParams>({
required String name,
TParams? params,
}) async {
final all = await allRoutes();
if (all.isEmpty) {
return false;
}
for (final route in all) {
if (route.url.isEmpty) {
continue;
}
await _sendChannel.notify<TParams>(
name: name,
url: route.url,
index: route.index,
params: params,
);
}
return true;
}
Future<bool> notifyFirstWhere<TParams>({
required bool Function(String url) predicate,
required String name,
TParams? params,
}) async {
final routes = await allRoutes();
final route =
routes.firstWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
return false;
}
await _sendChannel.notify<TParams>(
name: name,
url: route.url,
index: route.index,
params: params,
);
return true;
}
Future<bool> notifyWhere<TParams>({
required bool Function(String url) predicate,
required String name,
TParams? params,
}) async {
final routes = await allRoutes();
final all = routes.where((it) => it.url.isNotEmpty && predicate(it.url));
if (all.isEmpty) {
return false;
}
for (final route in all) {
await _sendChannel.notify<TParams>(
name: name,
url: route.url,
index: route.index,
params: params,
);
}
return true;
}
Future<bool> notifyLastWhere<TParams>({
required bool Function(String url) predicate,
required String name,
TParams? params,
}) async {
final routes = await allRoutes();
final route =
routes.lastWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
return false;
}
await _sendChannel.notify<TParams>(
name: name,
url: route.url,
index: route.index,
params: params,
);
return true;
}
Future<bool> notifyFirst<TParams>({
required String url,
required String name,
TParams? params,
}) async {
final route = await firstRoute(url: url);
if (route == null || route.url.isEmpty) {
return false;
}
return _sendChannel.notify<TParams>(
name: name,
url: route.url,
index: route.index,
params: params,
);
}
Future<bool> notifyLast<TParams>({
required String url,
required String name,
TParams? params,
}) async {
final route = await lastRoute(url: url);
if (route == null || route.url.isEmpty) {
return false;
}
return _sendChannel.notify<TParams>(
name: name,
url: route.url,
index: route.index,
params: params,
);
}
Future<TResult?> act<TParams, TResult>({
required String url,
required String action,
TParams? params,
}) async {
final routeAction = anchor.get<NavigatorRouteAction>(url: url, key: action);
if (routeAction == null) {
return null;
}
final actionUri = Uri.parse(action);
return routeAction<TParams, TResult>(
url,
actionUri.path,
actionUri.queryParametersAll,
params: params,
);
}
Future<bool> maybePop<TParams>({
TParams? params,
bool animated = true,
}) =>
_sendChannel.maybePop<TParams>(params: params, animated: animated);
Future<bool> pop<TParams>({
TParams? params,
bool animated = true,
}) {
Future<bool> popFuture() =>
_sendChannel.pop<TParams>(params: params, animated: animated);
return _taskQueue.add<bool>(popFuture).then((value) => value ?? false);
}
Future<bool> popFlutter<TParams>({
TParams? params,
bool animated = true,
}) {
Future<bool> popFuture() =>
_sendChannel.popFlutter<TParams>(params: params, animated: animated);
return _taskQueue.add<bool>(popFuture).then((value) => value ?? false);
}
Future<bool> popToRoot({
bool animated = true,
}) {
Future<bool> popToFuture() async {
final rootRoute = await firstRoute();
if (rootRoute == null) {
return false;
}
return _sendChannel.popTo(
url: rootRoute.url, index: rootRoute.index, animated: animated);
}
return _taskQueue.add<bool>(popToFuture).then((value) => value ?? false);
}
Future<bool> popTo({
required String url,
bool animated = true,
}) {
Future<bool> popToFuture() =>
_sendChannel.popTo(url: url, animated: animated);
return _taskQueue.add<bool>(popToFuture).then((value) => value ?? false);
}
Future<bool> popToFirst({
required String url,
bool animated = true,
}) {
Future<bool> popToFuture() async {
final route = await firstRoute(url: url);
if (route == null) {
return false;
}
return _sendChannel.popTo(
url: route.url, index: route.index, animated: animated);
}
return _taskQueue.add<bool>(popToFuture).then((value) => value ?? false);
}
Future<bool> popUntil({
required bool Function(String url) predicate,
bool animated = true,
}) {
Future<bool> popFuture() async {
final routes = await allRoutes();
final route = routes
.lastWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
return false;
}
return _sendChannel.popTo(
url: route.url, index: route.index, animated: animated);
}
return _taskQueue.add<bool>(popFuture).then((value) => value ?? false);
}
Future<bool> popUntilFirst({
required bool Function(String url) predicate,
bool animated = true,
}) {
Future<bool> popFuture() async {
final routes = await allRoutes();
final route = routes
.firstWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
return false;
}
return _sendChannel.popTo(
url: route.url, index: route.index, animated: animated);
}
return _taskQueue.add<bool>(popFuture).then((value) => value ?? false);
}
Future<int> removeAll({
required String url,
int excludeIndex = 0,
}) async {
Future<int> removeFuture() async {
if (url.isEmpty) {
return 0;
}
var total = 0;
var isMatch = false;
final all =
(await allRoutes(url: url)).where((it) => it.index != excludeIndex);
for (final r in all) {
isMatch = await _sendChannel.remove(url: r.url, index: r.index);
if (isMatch) {
total += 1;
}
}
return total;
}
return _taskQueue.add<int>(removeFuture).then((value) => value ?? 0);
}
Future<bool> remove({
required String url,
int index = 0,
bool animated = true,
}) {
Future<bool> removeFuture() => _sendChannel.remove(
url: url,
index: index,
animated: animated,
);
return _taskQueue.add<bool>(removeFuture).then((value) => value ?? false);
}
Future<bool> removeFirst({
required String url,
bool animated = true,
}) {
Future<bool> removeFuture() async {
final route = await firstRoute(url: url);
if (route == null) {
return false;
}
return _sendChannel.remove(
url: route.url,
index: route.index,
animated: animated,
);
}
return _taskQueue.add<bool>(removeFuture).then((value) => value ?? false);
}
Future<bool> removeBelowUntil({
required bool Function(String url) predicate,
bool animated = true,
}) {
Future<bool> removeFuture() async {
final routes = await allRoutes();
final route = routes
.sublist(0, routes.length - 1)
.lastWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
return false;
}
final index = routes.indexOf(route);
final all = routes.getRange(index + 1, routes.length - 1);
for (final r in all) {
await _sendChannel.remove(url: r.url, index: r.index);
}
return true;
}
return _taskQueue.add<bool>(removeFuture).then((value) => value ?? false);
}
Future<bool> removeBelowUntilFirst({
required bool Function(String url) predicate,
bool animated = true,
}) {
Future<bool> removeFuture() async {
final routes = await allRoutes();
final route = routes
.sublist(0, routes.length - 1)
.firstWhereOrNull((it) => it.url.isNotEmpty && predicate(it.url));
if (route == null) {
return false;
}
final index = routes.indexOf(route);
final all = routes.getRange(index + 1, routes.length - 1);
for (final r in all) {
await _sendChannel.remove(url: r.url, index: r.index);
}
return true;
}
return _taskQueue.add<bool>(removeFuture).then((value) => value ?? false);
}
Future<int> replace({
required String url,
required String newUrl,
}) {
Future<int> replaceFuture() =>
_sendChannel.replace(url: url, newUrl: newUrl);
return _taskQueue.add<int>(replaceFuture).then((value) => value ?? 0);
}
Future<int> replaceFirst({
required String url,
required String newUrl,
}) {
Future<int> replaceFuture() async {
final route = await firstRoute(url: url);
if (route == null) {
return 0;
}
return _sendChannel.replace(
url: route.url,
index: route.index,
newUrl: newUrl,
);
}
return _taskQueue.add<int>(replaceFuture).then((value) => value ?? 0);
}
Future<bool> canPop() => _sendChannel.canPop();
Widget? build<TParams>({
required String url,
int? index,
TParams? params,
}) {
final settings = NavigatorRouteSettings.settingsWith(
url: url,
index: index,
params: params,
);
return buildWithSettings(settings: settings);
}
Widget? buildWithSettings<TParams>({required RouteSettings settings}) {
final pageBuilder =
ThrioModule.get<NavigatorPageBuilder>(url: settings.url);
if (pageBuilder == null) {
return null;
}
settings.isBuilt = true;
return pageBuilder(settings);
}
Future<bool> isInitialRoute({required String url, int index = 0}) =>
_sendChannel.isInitialRoute(url: url, index: index);
Future<RouteSettings?> firstRoute({String? url}) async {
final all = await allRoutes(url: url);
return all.firstOrNull;
}
Future<RouteSettings?> lastRoute({String? url}) =>
_sendChannel.lastRoute(url: url);
Future<List<RouteSettings>> allRoutes({String? url}) =>
_sendChannel.allRoutes(url: url);
NavigatorRoute? lastFlutterRoute({String? url, int? index}) {
final ns = navigatorState;
if (ns == null) {
return null;
}
var route = ns.history.lastOrNull;
if (url?.isNotEmpty == true) {
route = ns.history.lastWhereOrNull((it) =>
it is NavigatorRoute &&
it.settings.url == url &&
(index == null || it.settings.index == index));
}
return route is NavigatorRoute ? route : null;
}
List<NavigatorRoute> allFlutterRoutes({String? url, int? index}) {
final ns = navigatorState;
if (ns == null) {
return <NavigatorRoute>[];
}
if (url?.isNotEmpty == true) {
return ns.history
.whereType<NavigatorRoute>()
.where((it) =>
it.settings.url == url &&
(index == null || it.settings.index == index))
.toList();
}
return ns.history.whereType<NavigatorRoute>().toList();
}
bool isDialogAbove({String? url, int? index}) {
final ns = navigatorState;
if (ns == null) {
return false;
}
if (url?.isNotEmpty == true) {
final routes = ns.history;
final idx = routes.lastIndexWhere((it) =>
it is NavigatorRoute &&
it.settings.url == url &&
(index == null || it.settings.index == index));
if (idx < 0 || routes.length <= idx + 1) {
return false;
}
return routes[idx + 1] is NavigatorDialogRoute;
}
return ns.history.last is NavigatorDialogRoute;
}
Future<bool> setPopDisabled({
required String url,
int index = 0,
bool disabled = true,
}) =>
_sendChannel.setPopDisabled(url: url, index: index, disabled: disabled);
Stream<dynamic> onPageNotify({
required String name,
String? url,
int index = 0,
}) =>
_receiveChannel.onPageNotify(name: name, url: url, index: index);
void hotRestart() {
_channel.invokeMethod<bool>('hotRestart');
}
dynamic _deserializeParams(dynamic params) {
if (params == null) {
return null;
}
if (params is Map && params.containsKey('__thrio_TParams__')) {
// ignore: avoid_as
final typeString = params['__thrio_TParams__'] as String;
if (typeString.isNotEmpty) {
final paramsObj =
ThrioModule.get<JsonDeserializer<dynamic>>(key: typeString)
?.call(params.cast<String, dynamic>());
if (paramsObj != null) {
return paramsObj;
}
}
}
return params;
}
Future<void> syncPagePoppedResults({NavigatorRoute? route}) async {
route?.poppedResult?.call(null);
if (poppedResults.isEmpty) {
return;
}
final routes = await allRoutes();
if (routes.isEmpty) {
poppedResults.clear();
} else {
poppedResults.removeWhere((name, poppedResult) {
if (!routes.any((it) => it.name == name)) {
Future(() => poppedResult.call(null));
return true;
}
return false;
});
}
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_route_observer_channel.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import '../channel/thrio_channel.dart';
import '../module/thrio_module.dart';
import 'navigator_logger.dart';
import 'navigator_route_observer.dart';
import 'navigator_route_settings.dart';
import 'thrio_navigator_implement.dart';
typedef NavigatorRouteObserverCallback = void Function(
NavigatorRouteObserver observer,
RouteSettings settings,
);
class NavigatorRouteObserverChannel with NavigatorRouteObserver {
NavigatorRouteObserverChannel(String entrypoint)
: _channel = ThrioChannel(channel: '__thrio_route_channel__$entrypoint') {
_on('didPush',
(observer, routeSettings) => observer.didPush(routeSettings));
_on('didPop', (observer, routeSettings) => observer.didPop(routeSettings));
_on('didPopTo',
(observer, routeSettings) => observer.didPopTo(routeSettings));
_on('didRemove',
(observer, routeSettings) => observer.didRemove(routeSettings));
_onDidReplace();
}
final ThrioChannel _channel;
@override
void didPush(RouteSettings routeSettings) => _channel.invokeMethod<bool>(
'didPush', routeSettings.toArguments()..remove('params'));
@override
void didPop(RouteSettings routeSettings) {
verbose('didPop: ${routeSettings.name}');
_channel.invokeMethod<bool>(
'didPop', routeSettings.toArguments()..remove('params'));
}
@override
void didPopTo(RouteSettings routeSettings) => _channel.invokeMethod<bool>(
'didPopTo', routeSettings.toArguments()..remove('params'));
@override
void didRemove(RouteSettings routeSettings) => _channel.invokeMethod<bool>(
'didRemove', routeSettings.toArguments()..remove('params'));
@override
void didReplace(
RouteSettings newRouteSettings,
RouteSettings oldRouteSettings,
) {
final oldArgs = oldRouteSettings.toArguments()..remove('params');
final newArgs = newRouteSettings.toArguments()..remove('params');
_channel.invokeMethod<bool>('didReplace', {
'oldRouteSettings': oldArgs,
'newRouteSettings': newArgs,
});
}
void _on(
String method,
NavigatorRouteObserverCallback callback,
) =>
_channel.registryMethodCall(method, ([final arguments]) {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings != null) {
final observers =
ThrioModule.gets<NavigatorRouteObserver>(url: routeSettings.url);
for (final observer in observers) {
callback(observer, routeSettings);
}
if (method == 'didPop') {
final currentPopRoutes =
ThrioNavigatorImplement.shared().currentPopRoutes;
if (currentPopRoutes.isNotEmpty &&
currentPopRoutes.last.settings.name == routeSettings.name) {
currentPopRoutes.first.poppedResult?.call(null);
}
ThrioNavigatorImplement.shared().currentPopRoutes.clear();
}
}
return Future.value();
});
void _onDidReplace() =>
_channel.registryMethodCall('didReplace', ([final arguments]) {
final newRouteSettings = NavigatorRouteSettings.fromArguments(
(arguments?['newRouteSettings'] as Map<Object?, Object?>)
.cast<String, dynamic>());
final oldRouteSettings = NavigatorRouteSettings.fromArguments(
(arguments?['oldRouteSettings'] as Map<Object?, Object?>)
.cast<String, dynamic>());
if (newRouteSettings != null && oldRouteSettings != null) {
final observers = <NavigatorRouteObserver>[
...ThrioModule.gets<NavigatorRouteObserver>(
url: newRouteSettings.url),
...ThrioModule.gets<NavigatorRouteObserver>(
url: oldRouteSettings.url),
];
for (final observer in observers) {
observer.didReplace(newRouteSettings, oldRouteSettings);
}
}
return Future.value();
});
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_stateful_page.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import '../module/thrio_module.dart';
import 'navigator_page.dart';
abstract class NavigatorStatefulPage extends StatefulWidget with NavigatorPage {
const NavigatorStatefulPage({
super.key,
required this.moduleContext,
required this.settings,
});
@override
final ModuleContext moduleContext;
@override
final RouteSettings settings;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_route_observer.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import 'thrio_navigator.dart';
/// An interface for observing the navigation behavior of a [ThrioNavigator].
///
mixin NavigatorRouteObserver {
/// The [ThrioNavigator] pushed `route`.
///
void didPush(RouteSettings routeSettings) {}
/// The [ThrioNavigator] popped `route`.
///
void didPop(RouteSettings routeSettings) {}
/// The [ThrioNavigator] popped to `route`.
///
void didPopTo(RouteSettings routeSettings) {}
/// The [ThrioNavigator] removed `route`.
///
void didRemove(RouteSettings routeSettings) {}
/// The [ThrioNavigator] replace `route` .
///
void didReplace(
RouteSettings newRouteSettings,
RouteSettings oldRouteSettings,
) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_observer_channel.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import '../channel/thrio_channel.dart';
import '../module/thrio_module.dart';
import 'navigator_page_observer.dart';
import 'navigator_route.dart';
import 'navigator_route_settings.dart';
typedef NavigatorPageObserverCallback = void Function(
NavigatorPageObserver observer, RouteSettings settings);
class NavigatorPageObserverChannel {
NavigatorPageObserverChannel(String entrypoint)
: _channel = ThrioChannel(channel: '__thrio_page_channel__$entrypoint') {
_on('willAppear',
(observer, routeSettings) => observer.willAppear(routeSettings));
_on('didAppear', (observer, routeSettings) {
observer.didAppear(routeSettings);
});
_on('willDisappear',
(observer, routeSettings) => observer.willDisappear(routeSettings));
_on('didDisappear',
(observer, routeSettings) => observer.didDisappear(routeSettings));
}
final ThrioChannel _channel;
void willAppear(RouteSettings routeSettings, NavigatorRouteType routeType) {
final arguments = routeSettings.toArguments()..remove('params');
arguments['routeType'] = routeType.toString().split('.').last;
_channel.invokeMethod<dynamic>('willAppear', arguments);
}
void didAppear(RouteSettings routeSettings, NavigatorRouteType routeType) {
final arguments = routeSettings.toArguments()..remove('params');
arguments['routeType'] = routeType.toString().split('.').last;
_channel.invokeMethod<dynamic>('didAppear', arguments);
}
void willDisappear(
RouteSettings routeSettings,
NavigatorRouteType routeType,
) {
final arguments = routeSettings.toArguments()..remove('params');
arguments['routeType'] = routeType.toString().split('.').last;
_channel.invokeMethod<dynamic>('willDisappear', arguments);
}
void didDisappear(RouteSettings routeSettings, NavigatorRouteType routeType) {
final arguments = routeSettings.toArguments()..remove('params');
arguments['routeType'] = routeType.toString().split('.').last;
_channel.invokeMethod<dynamic>('didDisappear', arguments);
}
void _on(String method, NavigatorPageObserverCallback callback) =>
_channel.registryMethodCall(method, ([final arguments]) {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings != null) {
final observers =
ThrioModule.gets<NavigatorPageObserver>(url: routeSettings.url);
for (final observer in observers) {
if (observer.settings == null ||
observer.settings?.name == routeSettings.name) {
callback(observer, routeSettings);
}
}
}
return Future.value();
});
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_material_app.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsoter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import '../module/module_anchor.dart';
import '../module/thrio_module.dart';
import 'navigator_home.dart';
import 'navigator_page_route.dart';
import 'thrio_navigator_implement.dart';
class NavigatorMaterialApp extends MaterialApp {
NavigatorMaterialApp({
super.navigatorKey,
List<NavigatorObserver> navigatorObservers = const <NavigatorObserver>[],
TransitionBuilder? builder,
super.title,
super.onGenerateTitle,
this.transitionPage,
super.color,
super.theme,
super.darkTheme,
super.themeMode,
super.locale,
super.localizationsDelegates,
super.localeListResolutionCallback,
super.localeResolutionCallback,
super.supportedLocales,
super.debugShowMaterialGrid,
super.showPerformanceOverlay,
super.checkerboardRasterCacheImages,
super.checkerboardOffscreenLayers,
super.showSemanticsDebugger,
super.debugShowCheckedModeBanner,
super.shortcuts,
super.actions,
super.restorationScopeId,
}) : super(
key: appKey,
builder: (context, child) => builder == null
? ThrioNavigatorImplement.shared().builder(context, child)
: builder(context,
ThrioNavigatorImplement.shared().builder(context, child)),
navigatorObservers: [...navigatorObservers],
initialRoute: '1 /',
onGenerateRoute: (settings) => settings.name == '1 /'
? NavigatorPageRoute(
pageBuilder: (_) => transitionPage ?? const NavigatorHome(),
settings: const RouteSettings(name: '1 /', arguments: {
'animated': false,
}))
: null);
static final appKey = GlobalKey(debugLabel: 'app');
/// Transition page
///
final Widget? transitionPage;
/// Get moduleContext of root module.
///
ModuleContext get moduleContext => anchor.rootModuleContext;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_stateless_page.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import '../module/thrio_module.dart';
import 'navigator_page.dart';
abstract class NavigatorStatelessPage extends StatelessWidget
with NavigatorPage {
const NavigatorStatelessPage({
super.key,
required this.moduleContext,
required this.settings,
});
@override
final ModuleContext moduleContext;
@override
final RouteSettings settings;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/thrio_navigator.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: avoid_classes_with_only_static_members
import 'dart:async';
import 'package:flutter/material.dart';
import 'navigator_route.dart';
import 'navigator_types.dart';
import 'thrio_navigator_implement.dart';
abstract class ThrioNavigator {
/// Register a handle called before the push call.
///
static VoidCallback registerPushBeginHandle(
NavigatorPushBeginHandle handle) =>
ThrioNavigatorImplement.shared().registerPushBeginHandle(handle);
/// Push the page onto the navigation stack.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> push<TParams, TPopParams>({
required String url,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared().push<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
/// Push the page onto the navigation stack, and remove all old page.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> pushSingle<TParams, TPopParams>({
required String url,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared().pushSingle<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
/// Push the page onto the navigation stack, and remove the top page.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> pushReplace<TParams, TPopParams>({
required String url,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared().pushReplace<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
/// Push the page onto the navigation stack, and remove until the last page with `toUrl`.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> pushAndRemoveTo<TParams, TPopParams>({
required String url,
required String toUrl,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared().pushAndRemoveTo<TParams, TPopParams>(
url: url,
toUrl: toUrl,
params: params,
animated: animated,
result: result,
);
/// Push the page onto the navigation stack, and remove until the first page with `toUrl`.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> pushAndRemoveToFirst<TParams, TPopParams>({
required String url,
required String toUrl,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared()
.pushAndRemoveToFirst<TParams, TPopParams>(
url: url,
toUrl: toUrl,
params: params,
animated: animated,
result: result,
);
/// Push the page onto the navigation stack, and remove until the last page with `toUrl` satisfies the `predicate`.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> pushAndRemoveUntil<TParams, TPopParams>({
required String url,
required bool Function(String url) predicate,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared().pushAndRemoveUntil<TParams, TPopParams>(
url: url,
predicate: predicate,
params: params,
animated: animated,
result: result,
);
/// Push the page onto the navigation stack, and remove until the first page with `toUrl` satisfies the `predicate`.
///
/// If a native page builder exists for the `url`, open the native page,
/// otherwise open the flutter page.
///
static Future<TPopParams?> pushAndRemoveUntilFirst<TParams, TPopParams>({
required String url,
required bool Function(String url) predicate,
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigatorImplement.shared()
.pushAndRemoveUntilFirst<TParams, TPopParams>(
url: url,
predicate: predicate,
params: params,
animated: animated,
result: result,
);
/// Send a notification to all page.
///
/// Notifications will be triggered when the page enters the foreground.
/// Notifications with the same `name` will be overwritten.
///
static Future<bool> notifyAll<TParams>({
required String name,
TParams? params,
}) =>
ThrioNavigatorImplement.shared()
.notifyAll<TParams>(name: name, params: params);
/// Send a notification to the last page with `url`.
///
/// Notifications will be triggered when the page enters the foreground.
/// Notifications with the same `name` will be overwritten.
///
static Future<bool> notify<TParams>({
required String url,
required String name,
TParams? params,
}) =>
ThrioNavigatorImplement.shared().notifyLast<TParams>(
url: url,
name: name,
params: params,
);
/// Send a notification to the first page with `url`.
///
/// Notifications will be triggered when the page enters the foreground.
/// Notifications with the same `name` will be overwritten.
///
static Future<bool> notifyFrist<TParams>({
required String url,
required String name,
TParams? params,
}) =>
ThrioNavigatorImplement.shared().notifyFirst<TParams>(
url: url,
name: name,
params: params,
);
/// Send a notification to the first page with `url` satisfies the `predicate`.
///
/// Notifications will be triggered when the page enters the foreground.
/// Notifications with the same `name` will be overwritten.
///
static Future<bool> notifyFirstWhere<TParams>({
required bool Function(String url) predicate,
required String name,
TParams? params,
}) =>
ThrioNavigatorImplement.shared().notifyFirstWhere<TParams>(
predicate: predicate,
name: name,
params: params,
);
/// Send a notification to all pages with `url` satisfies the `predicate`.
///
/// Notifications will be triggered when the page enters the foreground.
/// Notifications with the same `name` will be overwritten.
///
static Future<bool> notifyWhere<TParams>({
required bool Function(String url) predicate,
required String name,
TParams? params,
}) =>
ThrioNavigatorImplement.shared().notifyWhere<TParams>(
predicate: predicate,
name: name,
params: params,
);
/// Send a notification to the last page with `url` satisfies the `predicate`.
///
/// Notifications will be triggered when the page enters the foreground.
/// Notifications with the same `name` will be overwritten.
///
static Future<bool> notifyLastWhere<TParams>({
required bool Function(String url) predicate,
required String name,
TParams? params,
}) =>
ThrioNavigatorImplement.shared().notifyLastWhere<TParams>(
predicate: predicate,
name: name,
params: params,
);
static Future<TResult?> act<TParams, TResult>({
required String url,
required String action,
TParams? params,
}) =>
ThrioNavigatorImplement.shared()
.act<TParams, TResult>(url: url, action: action, params: params);
/// Maybe pop a page from the navigation stack.
///
static Future<bool> maybePop<TParams>({
TParams? params,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().maybePop<TParams>(
params: params,
animated: animated,
);
/// Pop a page from the navigation stack.
///
static Future<bool> pop<TParams>({
TParams? params,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().pop<TParams>(
params: params,
animated: animated,
);
/// Pop the top Flutter page.
///
static Future<bool> popFlutter<TParams>({
TParams? params,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().popFlutter<TParams>(
params: params,
animated: animated,
);
/// Pop the page in the navigation stack until the first page.
///
static Future<bool> popToRoot({bool animated = true}) =>
ThrioNavigatorImplement.shared().popToRoot(animated: animated);
/// Pop the page in the navigation stack until the last page with `url`.
///
static Future<bool> popTo({
required String url,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().popTo(
url: url,
animated: animated,
);
/// Pop the page in the navigation stack until the first page with `url`.
///
static Future<bool> popToFirst({
required String url,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().popToFirst(
url: url,
animated: animated,
);
/// Pop the page in the navigation stack until the last page with `url` satisfies the `predicate`.
///
static Future<bool> popUntil({
required bool Function(String url) predicate,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared()
.popUntil(predicate: predicate, animated: animated);
/// Pop the page in the navigation stack until the first page with `url` satisfies the `predicate`.
///
static Future<bool> popUntilFirst({
required bool Function(String url) predicate,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared()
.popUntilFirst(predicate: predicate, animated: animated);
/// Remove the last page with `url` in the navigation stack.
///
static Future<bool> remove({
required String url,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().remove(
url: url,
animated: animated,
);
/// Remove the first page with `url` in the navigation stack.
///
static Future<bool> removeFirst({
required String url,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().removeFirst(
url: url,
animated: animated,
);
/// Remove pages below the last page in the navigation stack.
/// Until the last page with `url` satisfies the `predicate`.
///
static Future<bool> removeBelowUntil({
required bool Function(String url) predicate,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().removeBelowUntil(
predicate: predicate,
animated: animated,
);
/// Remove pages below the last page in the navigation stack.
/// Until the first page with `url` satisfies the `predicate`.
///
static Future<bool> removeBelowUntilFirst({
required bool Function(String url) predicate,
bool animated = true,
}) =>
ThrioNavigatorImplement.shared().removeBelowUntilFirst(
predicate: predicate,
animated: animated,
);
/// Remove all pages with `url` in the navigation stack, except the one with index equals to `excludeIndex`.
///
static Future<int> removeAll({required String url, int excludeIndex = 0}) =>
ThrioNavigatorImplement.shared()
.removeAll(url: url, excludeIndex: excludeIndex);
/// Replace the last flutter page with `newUrl` in the navigation stack.
///
/// Both `url` and `newUrl` must be flutter page.
///
static Future<int> replace({
required String url,
required String newUrl,
}) =>
ThrioNavigatorImplement.shared().replace(
url: url,
newUrl: newUrl,
);
/// Replace the first flutter page with `newUrl` in the navigation stack.
///
/// Both `url` and `newUrl` must be flutter page.
///
static Future<int> replaceFirst({
required String url,
required String newUrl,
}) =>
ThrioNavigatorImplement.shared().replaceFirst(
url: url,
newUrl: newUrl,
);
/// Whether the navigator can be popped.
///
static Future<bool> canPop() => ThrioNavigatorImplement.shared().canPop();
/// Build widget with `url` and `params`.
///
static Widget? build<TParams>({
required String url,
int? index,
TParams? params,
}) =>
ThrioNavigatorImplement.shared().build(
url: url,
index: index,
params: params,
);
/// Returns the route of the page that was last pushed to the navigation
/// stack.
///
static Future<RouteSettings?> lastRoute({String? url}) =>
ThrioNavigatorImplement.shared().lastRoute(url: url);
/// Returns all route of the page with `url` in the navigation stack.
///
static Future<List<RouteSettings>> allRoutes({String? url}) =>
ThrioNavigatorImplement.shared().allRoutes(url: url);
/// Returns the flutter route of the page that was last pushed to the
/// navigation stack matching `url` and `index`.
///
static NavigatorRoute? lastFlutterRoute({String? url, int? index}) =>
ThrioNavigatorImplement.shared().lastFlutterRoute(url: url, index: index);
/// Returns all flutter route of the page with `url` and `index` in the navigation stack.
///
static List<NavigatorRoute> allFlutterRoutes({String? url, int? index}) =>
ThrioNavigatorImplement.shared().allFlutterRoutes(url: url, index: index);
/// Returns true if there is a dialog route on the last matching `url` and `index`.
static bool isDialogAbove({String? url, int? index}) =>
ThrioNavigatorImplement.shared().isDialogAbove(url: url, index: index);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_view.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../module/thrio_module.dart';
import 'navigator_page_observer.dart';
import 'navigator_route_settings.dart';
import 'thrio_navigator_implement.dart';
// ignore: must_be_immutable
class NavigatorPageView extends StatefulWidget {
NavigatorPageView({
super.key,
this.scrollDirection = Axis.horizontal,
this.reverse = false,
this.controller,
this.physics,
this.pageSnapping = true,
this.onPageChanged,
this.routeSettings = const <RouteSettings>[],
this.keepIndex = false,
this.childBuilder,
this.dragStartBehavior = DragStartBehavior.start,
this.allowImplicitScrolling = false,
this.restorationId,
this.clipBehavior = Clip.hardEdge,
this.scrollBehavior,
this.padEnds = true,
});
final Axis scrollDirection;
final bool reverse;
final PageController? controller;
late final PageController _realController = controller ?? PageController();
final ScrollPhysics? physics;
final bool pageSnapping;
final void Function(int, RouteSettings)? onPageChanged;
final List<RouteSettings> routeSettings;
final bool keepIndex;
final Widget Function(
BuildContext context,
RouteSettings settings,
Widget child,
)? childBuilder;
final DragStartBehavior dragStartBehavior;
final bool allowImplicitScrolling;
final String? restorationId;
final Clip clipBehavior;
final ScrollBehavior? scrollBehavior;
final bool padEnds;
late List<Widget> _children;
List<Widget> get children => _children;
@override
State<NavigatorPageView> createState() => _NavigatorPageViewState();
}
class _NavigatorPageViewState extends State<NavigatorPageView> {
final _nameSettings = <String, RouteSettings>{};
List<String> _currentNames = <String>[];
List<RouteSettings> get routeSettings =>
_currentNames.map((it) => _nameSettings[it]!).toList();
late RouteSettings current =
routeSettings[widget._realController.initialPage];
late int currentIndex = widget._realController.initialPage;
@override
void initState() {
super.initState();
if (mounted) {
if (widget.routeSettings.isEmpty) {
return;
}
_checkRouteSettings(widget.routeSettings);
_mapRouteSettings(widget.routeSettings);
_initSelectedState();
}
}
void _checkRouteSettings(List<RouteSettings> settings) {
final names = settings.map((it) => it.name).toList();
final nameSet = names.toSet();
if (nameSet.length != names.length) {
nameSet.forEach(names.remove);
throw ArgumentError.value(
settings,
'duplicate RouteSettings',
names.join(','),
);
}
}
void _mapRouteSettings(List<RouteSettings> settings) {
final newNames = settings.map<String>((it) => it.name!).toList();
_currentNames = newNames;
for (final it in settings) {
if (!_nameSettings.containsKey(it.name)) {
final tem = NavigatorRouteSettings.settingsWith(
url: it.url,
index: widget.keepIndex ? it.index : null,
params: it.params,
);
_nameSettings[it.name!] = tem;
} else {
final old = _nameSettings[it.name!]!;
_nameSettings[it.name!] = NavigatorRouteSettings.settingsWith(
url: old.url,
index: old.index,
params: it.params,
);
}
}
}
void _initSelectedState() {
current.isSelected = true;
final sts = routeSettings;
for (final it in sts) {
if (it.name != current.name) {
it.isSelected = false;
}
}
}
@override
void dispose() {
if (widget.controller == null) {
widget._realController.dispose();
}
super.dispose();
}
@override
void didUpdateWidget(NavigatorPageView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.routeSettings.isNotEmpty) {
_checkRouteSettings(widget.routeSettings);
_mapRouteSettings(widget.routeSettings);
// 重置索引
currentIndex = widget._realController.initialPage;
if (widget._realController.positions.isNotEmpty) {
final idx = widget._realController.page?.round();
if (idx != null) {
currentIndex = idx;
}
}
current = routeSettings[currentIndex];
_initSelectedState();
}
if (oldWidget.controller == null) {
oldWidget._realController.dispose();
}
}
@override
Widget build(BuildContext context) {
final pv = PageView(
key: widget.key,
scrollDirection: widget.scrollDirection,
reverse: widget.reverse,
controller: widget._realController,
physics: widget.physics,
pageSnapping: widget.pageSnapping,
onPageChanged: onPageChanged,
dragStartBehavior: widget.dragStartBehavior,
allowImplicitScrolling: widget.allowImplicitScrolling,
restorationId: widget.restorationId,
clipBehavior: widget.clipBehavior,
scrollBehavior: widget.scrollBehavior,
padEnds: widget.padEnds,
children: routeSettings.map((it) {
var w = ThrioNavigatorImplement.shared().buildWithSettings(
settings: it,
);
if (w == null) {
throw ArgumentError.value(
it,
'routeSettings',
'invalid routeSettings',
);
}
if (widget.childBuilder != null) {
w = widget.childBuilder!(context, it, w);
}
return w;
}).toList(),
);
widget._children =
(pv.childrenDelegate as SliverChildListDelegate).children;
return pv;
}
void onPageChanged(int idx) {
currentIndex = idx;
final sts = routeSettings[currentIndex];
if (sts.name != current.name) {
final oldRouteSettings = current;
current = sts;
widget.onPageChanged?.call(currentIndex, sts);
_changedToDisappear(oldRouteSettings);
oldRouteSettings.isSelected = false;
current.isSelected = true;
_changedToAppear(current);
}
}
void _changedToAppear(RouteSettings routeSettings) {
final obs = ThrioModule.gets<NavigatorPageObserver>(url: routeSettings.url);
for (final ob in obs) {
if (ob.settings == null || ob.settings?.name == routeSettings.name) {
ob.didAppear(routeSettings);
}
}
}
void _changedToDisappear(RouteSettings routeSettings) {
final obs = ThrioModule.gets<NavigatorPageObserver>(url: routeSettings.url);
for (final ob in obs) {
if (ob.settings == null || ob.settings?.name == routeSettings.name) {
ob.didDisappear(routeSettings);
}
}
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_widget.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../extension/thrio_iterable.dart';
import '../extension/thrio_stateful_widget.dart';
import '../module/module_anchor.dart';
import '../module/module_types.dart';
import '../module/thrio_module.dart';
import 'navigator_logger.dart';
import 'navigator_observer_manager.dart';
import 'navigator_page_route.dart';
import 'navigator_route.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
import 'thrio_navigator_implement.dart';
/// A widget that manages a set of child widgets with a stack discipline.
///
class NavigatorWidget extends StatefulWidget {
const NavigatorWidget({
super.key,
required this.moduleContext,
required NavigatorObserverManager observerManager,
required this.child,
}) : _observerManager = observerManager;
final Navigator child;
final ModuleContext moduleContext;
final NavigatorObserverManager _observerManager;
@override
State<StatefulWidget> createState() => NavigatorWidgetState();
}
class NavigatorWidgetState extends State<NavigatorWidget> {
final _style = const SystemUiOverlayStyle();
List<Route<dynamic>> get history => widget._observerManager.pageRoutes;
/// 还无法实现animated=false
Future<bool> push(
RouteSettings settings, {
bool animated = true,
}) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null) {
return false;
}
final pageBuilder =
ThrioModule.get<NavigatorPageBuilder>(url: settings.url);
if (pageBuilder == null) {
return false;
}
// 加载模块
// await anchor.loading(settings.url);
NavigatorRoute route;
final routeBuilder =
ThrioModule.get<NavigatorRouteBuilder>(url: settings.url);
if (routeBuilder == null) {
route = NavigatorPageRoute(pageBuilder: pageBuilder, settings: settings);
} else {
route = routeBuilder(pageBuilder, settings);
}
ThrioNavigatorImplement.shared()
.pageChannel
.willAppear(route.settings, NavigatorRouteType.push);
verbose(
'push: url->${route.settings.url} '
'index->${route.settings.index} '
'params->${route.settings.params}',
);
// 设置一个空值,避免页面打开后不生效
SystemChrome.setSystemUIOverlayStyle(_style);
// ignore: unawaited_futures
navigatorState.push(route);
route.settings.isPushed = true;
return true;
}
Future<bool> canPop(
RouteSettings settings, {
bool inRoot = false,
}) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null) {
return false;
}
// 在原生端处于容器的根部,且当前 Flutter 页面栈上不超过 3,则不能再 pop
if (inRoot && history.whereType<NavigatorRoute>().length < 3) {
return false;
}
return true;
}
Future<int> maybePop(
RouteSettings settings, {
bool animated = true,
bool inRoot = false,
}) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null) {
return 0;
}
// 关闭非体系内的顶部 route,同时 return false,避免原生端清栈
if (history.last is! NavigatorRoute) {
final result = await navigatorState.maybePop(settings.params);
// 返回 -1 表示关闭非体系内的顶部 route
return result ? -1 : 0;
}
if (settings.name != history.last.settings.name) {
return 0;
}
// 在原生端处于容器的根部,且当前 Flutter 页面栈上不超过 2,则不能再 pop
if (inRoot && history.whereType<NavigatorRoute>().length < 2) {
return 0;
}
final notPop = await history.last.willPop() == RoutePopDisposition.doNotPop;
return notPop ? 0 : 1;
}
Future<bool> pop(
RouteSettings settings, {
bool animated = true,
bool inRoot = false,
}) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null || history.isEmpty) {
return false;
}
// 关闭非体系内的顶部 route,同时 return false,避免原生端清栈
if (history.last is! NavigatorRoute) {
navigatorState.pop(settings.params);
return false;
}
if (settings.name != history.last.settings.name) {
final poppedResults = ThrioNavigatorImplement.shared().poppedResults;
if (poppedResults.containsKey(settings.name)) {
// 不匹配的时候表示这里是非当前引擎触发的,调用 poppedResult 回调
final poppedResult = poppedResults.remove(settings.name);
_poppedResultCallback(poppedResult, settings.url, settings.params);
}
// 在原生端不处于容器的根部,或者当前 Flutter 页面栈上超过 2,则 pop
// 解决目前单引擎下偶现的无法 pop 的问题
if (!inRoot && history.whereType<NavigatorRoute>().length > 2) {
navigatorState.pop();
}
// return false,避免原生端清栈,如果仅仅是为了触发 poppedResult 回调原生端也不会清栈
return false;
}
// 在原生端处于容器的根部,且当前 Flutter 页面栈上不超过 3,则不能再 pop
if (inRoot && history.whereType<NavigatorRoute>().length < 3) {
return false;
}
verbose(
'pop: url->${history.last.settings.url} '
'index->${history.last.settings.index}',
);
// ignore: avoid_as
final route = history.last as NavigatorRoute;
ThrioNavigatorImplement.shared()
.pageChannel
.willDisappear(route.settings, NavigatorRouteType.pop);
route.routeType = NavigatorRouteType.pop;
if (animated) {
navigatorState.pop();
} else {
navigatorState.removeRoute(route);
}
return Future.value(true).then((value) {
_poppedResultCallback(
route.poppedResult,
route.settings.url,
settings.params,
);
route.poppedResult = null;
return value;
});
}
Future<bool> popTo(
RouteSettings settings, {
bool animated = true,
}) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null) {
return false;
}
var index = history.indexWhere((it) => it.settings.name == settings.name);
if (index == -1) {
index = history.indexWhere((it) => it.settings.url == settings.url);
if (index == -1) {
return false;
}
}
// 已经是最顶部的页面了,直接返回 true
if (index == history.length - 1) {
return true;
}
final route = history[index];
verbose(
'popTo: url->${route.settings.url} '
'index->${route.settings.index}',
);
ThrioNavigatorImplement.shared().pageChannel.willAppear(
route.settings,
NavigatorRouteType.popTo,
);
// ignore: avoid_as
(route as NavigatorRoute).routeType = NavigatorRouteType.popTo;
if (history.last != route) {
for (var i = history.length - 2; i > index; i--) {
if (history[i].settings.name == route.settings.name) {
break;
}
navigatorState.removeRoute(history[i]);
}
if (animated) {
navigatorState.pop();
} else {
navigatorState.removeRoute(history.last);
}
}
return true;
}
Future<bool> remove(
RouteSettings settings, {
bool animated = false,
bool inRoot = false,
}) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null) {
return false;
}
final route =
history.firstWhereOrNull((it) => it.settings.name == settings.name);
if (route == null) {
return false;
}
// 在原生端处于容器的根部,且当前 Flutter 页面栈上不超过 3,则不能再 pop
if (inRoot && history.whereType<NavigatorRoute>().length < 3) {
return false;
}
verbose(
'remove: url->${route.settings.url} '
'index->${route.settings.index}',
);
// ignore: avoid_as
(route as NavigatorRoute).routeType = NavigatorRouteType.remove;
if (settings.name == history.last.settings.name) {
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed) {
ThrioNavigatorImplement.shared()
.pageChannel
.willDisappear(route.settings, NavigatorRouteType.remove);
}
navigatorState.pop();
return true;
}
navigatorState.removeRoute(route);
return true;
}
Future<bool> replace(
RouteSettings settings,
RouteSettings newSettings,
) async {
final navigatorState = widget.child.tryStateOf<NavigatorState>();
if (navigatorState == null) {
return false;
}
final route =
history.lastWhereOrNull((it) => it.settings.name == settings.name);
if (route == null) {
return false;
}
final pageBuilder =
ThrioModule.get<NavigatorPageBuilder>(url: newSettings.url);
if (pageBuilder == null) {
return false;
}
// 加载模块
// await anchor.loading(newSettings.url);
NavigatorRoute newRoute;
final routeBuilder =
ThrioModule.get<NavigatorRouteBuilder>(url: newSettings.url);
if (routeBuilder == null) {
newRoute =
NavigatorPageRoute(pageBuilder: pageBuilder, settings: newSettings);
} else {
newRoute = routeBuilder(pageBuilder, newSettings);
}
verbose(
'replace: url->${route.settings.url} index->${route.settings.index}\n'
'nweUrl->${newSettings.url} newIndex->${newSettings.index}',
);
// ignore: avoid_as
(route as NavigatorRoute).routeType = NavigatorRouteType.replace;
if (settings.name == history.last.settings.name) {
if (WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed) {
ThrioNavigatorImplement.shared()
.pageChannel
.willDisappear(route.settings, NavigatorRouteType.replace);
ThrioNavigatorImplement.shared()
.pageChannel
.willAppear(newRoute.settings, NavigatorRouteType.replace);
}
navigatorState.replace(oldRoute: route, newRoute: newRoute);
} else {
final anchorRoute = history[history.indexOf(route) + 1];
navigatorState.replaceRouteBelow(
anchorRoute: anchorRoute, newRoute: newRoute);
}
return true;
}
@override
void initState() {
super.initState();
if (mounted) {
ThrioNavigatorImplement.shared().ready();
}
}
@override
Widget build(BuildContext context) => widget.child;
void _poppedResultCallback(
NavigatorParamsCallback? poppedResultCallback,
String? url,
dynamic params,
) {
if (poppedResultCallback == null) {
return;
}
if (url?.isEmpty ?? true && params == null) {
poppedResultCallback(null);
} else {
if (params is Map) {
if (params.containsKey('__thrio_Params_HashCode__')) {
// ignore: avoid_as
final paramsObjs = anchor
.removeParam<dynamic>(params['__thrio_Params_HashCode__'] as int);
poppedResultCallback(paramsObjs);
return;
}
if (params.containsKey('__thrio_TParams__')) {
// ignore: avoid_as
final typeString = params['__thrio_TParams__'] as String;
final paramsObjs = ThrioModule.get<JsonDeserializer<dynamic>>(
url: url, key: typeString)
?.call(params.cast<String, dynamic>());
poppedResultCallback(paramsObjs);
return;
}
}
poppedResultCallback(params);
}
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_route_push_mixin.dart | // The MIT License (MIT)
//
// Copyright (c) 2023 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import '../module/module_anchor.dart';
import 'navigator_page_lifecycle_mixin.dart';
import 'navigator_types.dart';
mixin NavigatorRoutePushMixin<T extends StatefulWidget>
on State<T>, NavigatorPageLifecycleMixin<T> {
/// 拦截路由的 handle,return prevention 表示该路由会被拦截
///
NavigatorRoutePushHandle get onPush;
/// 表示是否总是拦截
///
/// 默认为 false,表示在页面 disappear 后将不会生效
///
bool get alwaysTakeEffect => false;
VoidCallback? _registry;
@override
void initState() {
super.initState();
if (mounted) {
_init();
}
}
@override
void didUpdateWidget(covariant T oldWidget) {
super.didUpdateWidget(oldWidget);
_init();
}
void _init() {
_registry?.call();
_registry = anchor.pushHandlers.registry(onPush);
}
@override
void dispose() {
_registry?.call();
super.dispose();
}
@override
void didAppear(RouteSettings settings) {
if (alwaysTakeEffect) {
return;
}
_init();
}
@override
void didDisappear(RouteSettings settings) {
if (alwaysTakeEffect) {
return;
}
_registry?.call();
_registry = null;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_lifecycle_mixin.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import 'package:async/async.dart';
import 'package:flutter/widgets.dart';
import '../module/module_anchor.dart';
import 'navigator_logger.dart';
import 'navigator_page.dart';
import 'navigator_page_observer.dart';
import 'navigator_route_settings.dart';
import 'thrio_navigator_implement.dart';
mixin NavigatorPageLifecycleMixin<T extends StatefulWidget> on State<T> {
late RouteSettings _current;
late final _currentObserver = _CurrentLifecycleObserver(this);
VoidCallback? _currentObserverCallback;
late List<RouteSettings> _anchors;
final _anchorsObserverCallbacks = <VoidCallback>[];
final _initAppear = AsyncMemoizer<void>();
late final _observer = _NavigatorMountedObserver(this);
bool _unmounted = false;
@override
void initState() {
super.initState();
if (mounted) {
ThrioNavigatorImplement.shared().observerManager.observers.add(_observer);
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_init();
_initAppear.runOnce(() {
if (!_current.isBuilt || _current.isSelected != false) {
Future(() => didAppear(_current));
}
});
}
@override
void didUpdateWidget(T oldWidget) {
super.didUpdateWidget(oldWidget);
_init();
}
void didAppear(RouteSettings settings) {
verbose(
'NavigatorPageLifecycleMixin didAppear: ${settings.name}, $runtimeType, hash: ${settings.hashCode}');
}
void didDisappear(RouteSettings settings) {
verbose(
'NavigatorPageLifecycleMixin didDisappear: ${settings.name}, $runtimeType, hash: ${settings.hashCode}');
}
@override
void dispose() {
_currentObserverCallback?.call();
for (final callback in _anchorsObserverCallbacks) {
callback();
}
_doDispose();
super.dispose();
}
void _init() {
_current = NavigatorPage.routeSettingsOf(context);
_currentObserverCallback?.call();
_currentObserverCallback =
anchor.pageLifecycleObservers.registry(_current.url, _currentObserver);
_anchors = NavigatorPage.routeSettingsListOf(context);
// 链路上重复的 settings 要去掉
_anchors.removeWhere((it) => it.name == _current.name);
for (final callback in _anchorsObserverCallbacks) {
callback();
}
_anchorsObserverCallbacks.clear();
for (final it in _anchors) {
_anchorsObserverCallbacks.add(anchor.pageLifecycleObservers.registry(
it.url,
_AnchorLifecycleObserver(this, it),
));
}
}
void _doDispose() {
Future(() => ThrioNavigatorImplement.shared()
.observerManager
.observers
.remove(_observer));
_unmounted = true;
}
}
// ignore: prefer_mixin
class _CurrentLifecycleObserver with NavigatorPageObserver {
_CurrentLifecycleObserver(this._delegate);
final NavigatorPageLifecycleMixin _delegate;
@override
RouteSettings? get settings => _delegate._current;
@override
void didAppear(RouteSettings routeSettings) {
// state not mounted, not trigger didAppear
if (_delegate._unmounted) {
return;
}
if (_delegate._current.name == routeSettings.name &&
routeSettings.isSelected != false) {
_delegate.didAppear(routeSettings);
}
}
@override
void didDisappear(RouteSettings routeSettings) {
// state not disposed and not mounted, not trigger didDisappear
if (_delegate._current.name == routeSettings.name &&
routeSettings.isSelected != false) {
_delegate.didDisappear(routeSettings);
}
}
}
class _AnchorLifecycleObserver with NavigatorPageObserver {
_AnchorLifecycleObserver(this._delegate, this._anchor);
final NavigatorPageLifecycleMixin _delegate;
final RouteSettings _anchor;
@override
RouteSettings? get settings => _anchor;
@override
void didAppear(RouteSettings routeSettings) {
final callback = _delegate._currentObserver.didAppear;
_lifecycleCallback(callback, routeSettings);
}
@override
void didDisappear(RouteSettings routeSettings) {
final callback = _delegate._currentObserver.didDisappear;
_lifecycleCallback(callback, routeSettings);
}
void _lifecycleCallback(
void Function(RouteSettings) callback,
RouteSettings routeSettings,
) {
if (_anchor.name != routeSettings.name ||
_delegate._current.isSelected == false) {
return;
}
final idx =
_delegate._anchors.indexWhere((it) => it.name == routeSettings.name);
final ins = _delegate._anchors.sublist(0, idx);
if (ins.every((it) => it.isSelected == true)) {
callback(_delegate._current);
}
}
}
// ignore: prefer_mixin
class _NavigatorMountedObserver extends NavigatorObserver {
_NavigatorMountedObserver(this._delegate);
final NavigatorPageLifecycleMixin _delegate;
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (_delegate._currentObserverCallback == null) {
return;
}
if (route.settings.name == _delegate._current.name) {
_delegate._doDispose();
}
}
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (_delegate._currentObserverCallback == null) {
return;
}
if (route.settings.name == _delegate._current.name) {
_delegate._doDispose();
}
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
if (_delegate._currentObserverCallback == null) {
return;
}
if (oldRoute?.settings.name == _delegate._current.name) {
_delegate._doDispose();
}
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_dialog_route.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import '../module/thrio_module.dart';
import 'navigator_route.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
/// A route managed by the `ThrioNavigatorImplement`.
///
class NavigatorDialogRoute extends PageRouteBuilder<bool> with NavigatorRoute {
NavigatorDialogRoute({
required NavigatorPageBuilder pageBuilder,
required RouteSettings settings,
super.transitionDuration,
super.reverseTransitionDuration,
super.opaque,
super.barrierDismissible = false,
super.barrierColor,
super.barrierLabel,
super.maintainState,
super.fullscreenDialog,
}) : super(
pageBuilder: (_, __, ___) => pageBuilder(settings),
settings: settings,
);
@override
void addScopedWillPopCallback(WillPopCallback callback) {
setPopDisabled(disabled: true);
super.addScopedWillPopCallback(callback);
}
@override
void removeScopedWillPopCallback(WillPopCallback callback) {
setPopDisabled();
super.removeScopedWillPopCallback(callback);
}
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (settings.isNested) {
final builder =
ThrioModule.get<RouteTransitionsBuilder>(url: settings.url);
if (builder != null) {
return builder(context, animation, secondaryAnimation, child);
}
return super
.buildTransitions(context, animation, secondaryAnimation, child);
}
return child;
}
@override
void dispose() {
clearPopDisabledFutures();
super.dispose();
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_will_pop_mixin.dart | // The MIT License (MIT)
//
// Copyright (c) 2023 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: prefer_mixin
import 'package:flutter/widgets.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
/// Handle a callback to veto attempts by the user to dismiss the enclosing
/// [ModalRoute].
///
mixin NavigatorWillPopMixin<T extends StatefulWidget> on State<T> {
GlobalKey<NavigatorState> get internalNavigatorKey;
/// Called to veto attempts by the user to dismiss the enclosing [ModalRoute].
///
Future<bool> onWillPop() => Future.value(true);
ModalRoute<dynamic>? _route;
bool _added = false;
VoidCallback? _callback;
static final _observerMaps = <GlobalKey<NavigatorState>, NavigatorObserver>{};
static NavigatorObserver navigatorObserverFor(
GlobalKey<NavigatorState> navigatorStateKey,
) =>
_observerMaps[navigatorStateKey] ??
(_observerMaps[navigatorStateKey] = _InternalNavigatorObserver());
@override
void initState() {
super.initState();
if (mounted) {
_init();
}
}
@override
void didUpdateWidget(covariant T oldWidget) {
super.didUpdateWidget(oldWidget);
_init();
}
void _init() {
_callback?.call();
final observer = navigatorObserverFor(internalNavigatorKey);
if (observer is _InternalNavigatorObserver) {
_callback = observer.delegates.registry(this);
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_added = false;
_route?.removeScopedWillPopCallback(onWillPop);
_route = ModalRoute.of(context);
_checkWillPop();
}
void _checkWillPop() {
if (internalNavigatorKey.currentState?.canPop() == true) {
if (!_added) {
_added = true;
_route?.addScopedWillPopCallback(onWillPop);
}
} else {
if (_added) {
_added = false;
_route?.removeScopedWillPopCallback(onWillPop);
}
}
}
@override
void dispose() {
_added = false;
_route?.removeScopedWillPopCallback(onWillPop);
_callback?.call();
super.dispose();
}
}
class _InternalNavigatorObserver extends NavigatorObserver {
final delegates = RegistrySet<NavigatorWillPopMixin>();
@override
void didPush(
Route<dynamic> route,
Route<dynamic>? previousRoute,
) {
for (final it in delegates) {
it._checkWillPop();
}
}
@override
void didPop(
Route<dynamic> route,
Route<dynamic>? previousRoute,
) {
for (final it in delegates) {
it._checkWillPop();
}
}
@override
void didRemove(
Route<dynamic> route,
Route<dynamic>? previousRoute,
) {
for (final it in delegates) {
it._checkWillPop();
}
}
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
for (final it in delegates) {
it._checkWillPop();
}
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_route_receive_channel.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import '../channel/thrio_channel.dart';
import '../module/module_anchor.dart';
import '../module/module_types.dart';
import '../module/thrio_module.dart';
import 'navigator_logger.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
import 'thrio_navigator_implement.dart';
class NavigatorRouteReceiveChannel {
NavigatorRouteReceiveChannel(ThrioChannel channel) : _channel = channel {
_onPush();
_onMaybePop();
_onPop();
_onPopTo();
_onRemove();
_onReplace();
_onCanPop();
}
final ThrioChannel _channel;
void _onPush() =>
_channel.registryMethodCall('push', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return false;
}
verbose(
'push: url->${routeSettings.url} '
'index->${routeSettings.index}',
);
routeSettings.params =
_deserializeParams(routeSettings.url, routeSettings.params);
final animated = arguments?['animated'] == true;
final handlers = anchor.pushHandlers;
for (final handler in handlers) {
final result = await handler(routeSettings, animated: animated);
if (result == NavigatorRoutePushHandleType.prevention) {
return false;
}
}
return await ThrioNavigatorImplement.shared()
.navigatorState
?.push(routeSettings, animated: animated)
.then((value) {
ThrioNavigatorImplement.shared().syncPagePoppedResults();
return value;
}) ??
false;
});
void _onMaybePop() =>
_channel.registryMethodCall('maybePop', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return 0;
}
final animated = arguments?['animated'] == true;
final inRoot = arguments?['inRoot'] == true;
return await ThrioNavigatorImplement.shared()
.navigatorState
?.maybePop(routeSettings, animated: animated, inRoot: inRoot)
.then((value) {
ThrioNavigatorImplement.shared().syncPagePoppedResults();
return value;
}) ??
0;
});
void _onPop() =>
_channel.registryMethodCall('pop', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return false;
}
final animated = arguments?['animated'] == true;
final inRootValue = arguments != null ? arguments['inRoot'] : null;
final inRoot =
(inRootValue != null && inRootValue is bool) && inRootValue;
return await ThrioNavigatorImplement.shared()
.navigatorState
?.pop(routeSettings, animated: animated, inRoot: inRoot)
.then((value) {
ThrioNavigatorImplement.shared().syncPagePoppedResults();
return value;
}) ??
false;
});
void _onCanPop() =>
_channel.registryMethodCall('canPop', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return false;
}
final inRoot = arguments?['inRoot'] == true;
return await ThrioNavigatorImplement.shared()
.navigatorState
?.canPop(routeSettings, inRoot: inRoot) ??
false;
});
void _onPopTo() =>
_channel.registryMethodCall('popTo', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return false;
}
final animated = arguments?['animated'] == true;
return await ThrioNavigatorImplement.shared()
.navigatorState
?.popTo(routeSettings, animated: animated)
.then((value) {
ThrioNavigatorImplement.shared().syncPagePoppedResults();
return value;
}) ??
false;
});
void _onRemove() =>
_channel.registryMethodCall('remove', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return false;
}
final animated = arguments?['animated'] == true;
return await ThrioNavigatorImplement.shared()
.navigatorState
?.remove(routeSettings, animated: animated)
.then((value) {
ThrioNavigatorImplement.shared().syncPagePoppedResults();
return value;
}) ??
false;
});
void _onReplace() =>
_channel.registryMethodCall('replace', ([final arguments]) async {
final routeSettings = NavigatorRouteSettings.fromArguments(arguments);
if (routeSettings == null) {
return false;
}
final newRouteSettings =
NavigatorRouteSettings.fromNewUrlArguments(arguments);
if (newRouteSettings == null) {
return false;
}
return await ThrioNavigatorImplement.shared()
.navigatorState
?.replace(routeSettings, newRouteSettings)
.then((value) {
ThrioNavigatorImplement.shared().syncPagePoppedResults();
return value;
}) ??
false;
});
Stream<dynamic> onPageNotify({
required String name,
String? url,
int index = 0,
}) =>
_channel
.onEventStream('__onNotify__')
.where((arguments) =>
arguments.containsValue(name) &&
(url == null || url.isEmpty || arguments.containsValue(url)) &&
(index == 0 || arguments.containsValue(index)))
.map((arguments) => arguments['params']);
dynamic _deserializeParams(String url, dynamic params) {
if (params == null) {
return null;
}
if (params is Map) {
if (params.containsKey('__thrio_Params_HashCode__')) {
// ignore: avoid_as
return anchor
.removeParam<dynamic>(params['__thrio_Params_HashCode__'] as int);
}
if (params.containsKey('__thrio_TParams__')) {
// ignore: avoid_as
final typeString = params['__thrio_TParams__'] as String;
if (typeString.isNotEmpty) {
final paramsObj = ThrioModule.get<JsonDeserializer<dynamic>>(
url: url, key: typeString)
?.call(params.cast<String, dynamic>());
if (paramsObj != null) {
return paramsObj;
}
}
}
}
return params;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_route_push.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import 'navigator_page_lifecycle_mixin.dart';
import 'navigator_route_push_mixin.dart';
import 'navigator_types.dart';
class NavigatorRoutePush extends StatefulWidget {
const NavigatorRoutePush({
super.key,
required this.onPush,
this.alwaysTakeEffect = false,
required this.child,
});
/// 拦截路由的 handle,return prevention 表示该路由会被拦截
///
final NavigatorRoutePushHandle onPush;
/// 表示是否总是拦截
///
/// 默认为 false,表示在页面 disappear 后将不会生效
///
final bool alwaysTakeEffect;
final Widget child;
@override
_NavigatorRoutePushState createState() => _NavigatorRoutePushState();
}
class _NavigatorRoutePushState extends State<NavigatorRoutePush>
with NavigatorPageLifecycleMixin, NavigatorRoutePushMixin {
@override
bool get alwaysTakeEffect => widget.alwaysTakeEffect;
@override
NavigatorRoutePushHandle get onPush => widget.onPush;
@override
Widget build(BuildContext context) => widget.child;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_types.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: avoid_positional_boolean_parameters
import 'package:flutter/widgets.dart';
import 'navigator_route.dart';
/// Signature of page builder with RouteSettings.
///
typedef NavigatorPageBuilder = Widget Function(RouteSettings settings);
/// Signature of route builder with NavigatorPageBuilder and RouteSettings.
///
typedef NavigatorRouteBuilder = NavigatorRoute Function(
NavigatorPageBuilder pageBuilder,
RouteSettings settings,
);
/// Signature of callbacks with bool parameter.
///
typedef NavigatorBoolCallback = void Function(bool result);
/// Signature of callbacks with int parameter.
///
typedef NavigatorIntCallback = void Function(int index);
/// Signature of callbacks with dynamic parameter.
///
typedef NavigatorParamsCallback = void Function(dynamic params);
/// Signature of page observer callbacks with RouteSettings.
///
typedef NavigatorPageObserverCallback = void Function(RouteSettings settings);
enum NavigatorRoutePushHandleType {
none, // Do not prevent routing actions from continuing
prevention, // Prevent routing behavior from continuing
}
/// Signature of route push handler with RouteSettings.
///
typedef NavigatorRoutePushHandle = Future<NavigatorRoutePushHandleType>
Function(
RouteSettings settings, {
bool animated,
});
/// Signature of push begin handler with url.
typedef NavigatorPushBeginHandle = Future<void> Function<TParams>(
String url,
TParams? params,
);
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_lifecycle.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import 'navigator_page_lifecycle_mixin.dart';
import 'navigator_types.dart';
class NavigatorPageLifecycle extends StatefulWidget {
const NavigatorPageLifecycle({
super.key,
this.didAppear,
this.didDisappear,
required this.child,
});
final NavigatorPageObserverCallback? didAppear;
final NavigatorPageObserverCallback? didDisappear;
final Widget child;
@override
_NavigatorPageLifecycleState createState() => _NavigatorPageLifecycleState();
}
class _NavigatorPageLifecycleState extends State<NavigatorPageLifecycle>
with NavigatorPageLifecycleMixin {
@override
Widget build(BuildContext context) => widget.child;
@override
void didAppear(RouteSettings settings) {
super.didAppear(settings);
widget.didAppear?.call(settings);
}
@override
void didDisappear(RouteSettings settings) {
super.didDisappear(settings);
widget.didDisappear?.call(settings);
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_will_pop.dart | // The MIT License (MIT)
//
// Copyright (c) 2023 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import 'navigator_will_pop_mixin.dart';
class NavigatorWillPop extends StatefulWidget {
const NavigatorWillPop({
super.key,
required this.onWillPop,
required this.internalNavigatorKey,
required this.child,
});
final Future<bool> Function() onWillPop;
final GlobalKey<NavigatorState> internalNavigatorKey;
final Widget child;
static NavigatorObserver navigatorObserverFor(
GlobalKey<NavigatorState> navigatorStateKey,
) =>
NavigatorWillPopMixin.navigatorObserverFor(navigatorStateKey);
@override
_NavigatorWillPopState createState() => _NavigatorWillPopState();
}
class _NavigatorWillPopState extends State<NavigatorWillPop>
with NavigatorWillPopMixin {
@override
Widget build(BuildContext context) => widget.child;
@override
Future<bool> onWillPop() => widget.onWillPop();
@override
GlobalKey<NavigatorState> get internalNavigatorKey =>
widget.internalNavigatorKey;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_home.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'navigator_hot_restart_button.dart';
class NavigatorHome extends StatefulWidget {
const NavigatorHome({super.key, this.showRestartButton = false});
final bool showRestartButton;
@override
_NavigatorHomeState createState() => _NavigatorHomeState();
}
class _NavigatorHomeState extends State<NavigatorHome> {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: const Text('...', style: TextStyle(color: Colors.blue)),
systemOverlayStyle: SystemUiOverlayStyle.dark,
),
body: Center(
child: SingleChildScrollView(
child: Column(children: <Widget>[
const SizedBox(
width: 60, height: 60, child: CircularProgressIndicator()),
const SizedBox(width: 60, height: 60),
if (widget.showRestartButton)
const SizedBox(
width: 200, height: 48, child: NavigatorHotRestartButton()),
]))),
);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/navigator/navigator_page_notify.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import 'package:flutter/widgets.dart';
import '../module/module_anchor.dart';
import '../module/module_types.dart';
import '../module/thrio_module.dart';
import 'navigator_page.dart';
import 'navigator_route_settings.dart';
import 'navigator_types.dart';
import 'thrio_navigator_implement.dart';
class NavigatorPageNotify extends StatefulWidget {
const NavigatorPageNotify({
super.key,
required this.name,
required this.onPageNotify,
this.initialParams,
required this.child,
});
final String name;
final NavigatorParamsCallback onPageNotify;
final dynamic initialParams;
final Widget child;
@override
_NavigatorPageNotifyState createState() => _NavigatorPageNotifyState();
}
class _NavigatorPageNotifyState extends State<NavigatorPageNotify> {
RouteSettings? _settings;
StreamSubscription<dynamic>? _notifySubscription;
@override
void initState() {
super.initState();
if (mounted) {
if (widget.initialParams != null) {
widget.onPageNotify(widget.initialParams);
}
}
}
@override
void didChangeDependencies() {
final settings = NavigatorPage.routeSettingsOf(context);
if (settings.name != _settings?.name) {
_settings = settings;
_notifySubscription?.cancel();
_notifySubscription = ThrioNavigatorImplement.shared()
.onPageNotify(
url: _settings!.url,
index: _settings!.index,
name: widget.name,
)
.listen(_listen);
}
super.didChangeDependencies();
}
@override
void didUpdateWidget(covariant NavigatorPageNotify oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialParams != null &&
widget.initialParams != oldWidget.initialParams) {
widget.onPageNotify(widget.initialParams);
}
if (widget.name != oldWidget.name) {
_notifySubscription?.cancel();
_notifySubscription = ThrioNavigatorImplement.shared()
.onPageNotify(
url: _settings!.url,
index: _settings!.index,
name: widget.name,
)
.listen(_listen);
}
}
void _listen(dynamic params) {
if (params != null) {
if (params is Map) {
if (params.containsKey('__thrio_Params_HashCode__')) {
// ignore: avoid_as
final paramsObjs = anchor
.removeParam<dynamic>(params['__thrio_Params_HashCode__'] as int);
widget.onPageNotify(paramsObjs);
return;
}
if (params.containsKey('__thrio_TParams__')) {
// ignore: avoid_as
final typeString = params['__thrio_TParams__'] as String;
final paramsObj =
ThrioModule.get<JsonDeserializer<dynamic>>(key: typeString)
?.call(params.cast<String, dynamic>());
if (paramsObj != null) {
widget.onPageNotify(paramsObj);
return;
}
}
}
widget.onPageNotify(params);
} else {
widget.onPageNotify(null);
}
}
@override
void dispose() {
_notifySubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/registry/registry_set_map.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
class RegistrySetMap<K, V> {
final Map<K, Set<V>> _maps = {};
VoidCallback registry(K key, V value) {
assert(key != null, 'key must not be null.');
assert(value != null, 'value must not be null.');
_maps[key] ??= <V>{};
_maps[key]?.add(value);
return () {
_maps[key]?.remove(value);
if (_maps[key]?.isEmpty ?? true) {
_maps.remove(key);
}
};
}
VoidCallback registryAll(Map<K, V> values) {
assert(values.isNotEmpty, 'values must not be null or empty.');
for (final key in values.keys) {
_maps[key] ??= <V>{};
final value = values[key];
if (value != null) {
_maps[key]?.add(value);
}
}
return () {
for (final key in values.keys) {
_maps[key]?.remove(values[key]);
if (_maps[key]?.isEmpty ?? true) {
_maps.remove(key);
}
}
};
}
Iterable<K> get keys => _maps.keys;
Iterable<Set<V>> get values => _maps.values;
void clear() => _maps.clear();
Set<V> operator [](K key) => _maps[key] ?? <V>{};
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/registry/registry_map.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
class RegistryMap<K, V> {
final Map<K, V> _maps = {};
VoidCallback registry(K key, V value) {
assert(key != null, 'key must not be null.');
assert(value != null, 'value must not be null.');
_maps[key] = value;
return () {
_maps.remove(key);
};
}
VoidCallback registryAll(Map<K, V> values) {
assert(values.isNotEmpty, 'values must not be null or empty.');
_maps.addAll(values);
return () {
_maps.removeWhere((k, _) => _maps.containsKey(k));
};
}
Iterable<K> get keys => _maps.keys;
Iterable<V> get values => _maps.values;
void clear() => _maps.clear();
V? operator [](K key) => _maps[key];
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/registry/registry_order_map.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../extension/thrio_iterable.dart';
class RegistryOrderMap<K, V> {
final _list = <MapEntry<K, V>>[];
VoidCallback registry(K key, V value) {
assert(key != null, 'key must not be null.');
assert(value != null, 'value must not be null.');
final item = MapEntry(key, value);
_list.add(item);
return () {
_list.remove(item);
};
}
int get length => _list.length;
MapEntry<K, V> elementAt(int index) => _list.elementAt(index);
Iterable<K> get keys => _list.map((it) => it.key);
Iterable<V> get values => _list.map((it) => it.value);
V first([final K? key]) => key == null
? _list.first.value
: _list.firstWhere((it) => it.key == key).value;
V? firstOrNull([final K? key]) => key == null
? _list.firstOrNull?.value
: _list.firstWhereOrNull((it) => it.key == key)?.value;
V firstWhere(bool Function(K k) predicate) =>
_list.firstWhere((it) => predicate(it.key)).value;
V? firstWhereOrNull(bool Function(K k) predicate) =>
_list.firstWhereOrNull((it) => predicate(it.key))?.value;
Iterable<V> where(bool Function(K k) predicate) =>
_list.where((it) => predicate(it.key)).map((it) => it.value);
V last([final K? key]) => key == null
? _list.last.value
: _list.lastWhere((it) => it.key == key).value;
V? lastOrNull([final K? key]) => key == null
? _list.lastOrNull?.value
: _list.lastWhereOrNull((it) => it.key == key)?.value;
V lastWhere(bool Function(K k) predicate) =>
_list.lastWhere((it) => predicate(it.key)).value;
V? lastWhereOrNull(bool Function(K k) predicate) =>
_list.lastWhereOrNull((it) => predicate(it.key))?.value;
void clear() => _list.clear();
Iterable<V> operator [](K key) =>
_list.where((it) => it.key == key).map((it) => it.value);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/registry/registry_set.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:collection';
import 'package:flutter/foundation.dart';
// ignore: prefer_mixin
class RegistrySet<T> with IterableMixin<T> {
final Set<T> _sets = {};
VoidCallback registry(T value) {
assert(value != null, 'value must not be null.');
_sets.add(value);
return () {
_sets.remove(value);
};
}
VoidCallback registryAll(Set<T> values) {
assert(values.isNotEmpty, 'values must not be null or empty');
_sets.addAll(values);
return () {
_sets.removeAll(values);
};
}
void clear() => _sets.clear();
@override
Iterator<T> get iterator => _sets.iterator;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_dynamic.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
/// Get value from params, throw ArgumentError when`key`'s value not found .
///
T getValue<T>(dynamic params, String key) {
final val = getValueOrNull<T>(params, key);
if (val != null) {
return val;
}
throw ArgumentError.notNull(key);
}
/// Get value from params, return `defaultValue` when`key`'s value not found .
///
T getValueOrDefault<T>(dynamic params, String key, T defaultValue) {
final val = getValueOrNull<T>(params, key);
if (val != null) {
return val;
}
return defaultValue;
}
/// Get value from params.
///
T? getValueOrNull<T>(dynamic params, String key) {
if (params is Map) {
final val = params[key];
if (val is T) {
return val;
}
}
return null;
}
List<E> getListValue<E>(dynamic params, String key) {
if (params is Map) {
final col = params[key];
if (col is List) {
return List<E>.from(col);
}
}
return <E>[];
}
Map<K, V> getMapValue<K, V>(dynamic params, String key) {
if (params is Map) {
final col = params[key];
if (col is Map) {
return Map<K, V>.from(col);
}
}
return <K, V>{};
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_build_context.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: avoid_positional_boolean_parameters
import 'package:flutter/widgets.dart';
import '../navigator/navigator_route.dart';
import '../navigator/navigator_route_settings.dart';
import '../navigator/navigator_widget.dart';
import '../navigator/thrio_navigator_implement.dart';
extension ThrioBuildContext on BuildContext {
/// Get widget state by ancestorStateOfType method.
///
/// Throw `Exception` if the `state.runtimeType` is not a T.
///
T stateOf<T extends State<StatefulWidget>>() {
final state = findAncestorStateOfType<T>();
if (state != null) {
return state;
}
throw Exception('${state.runtimeType} is not a $T');
}
/// Get widget state by ancestorStateOfType method.
///
T? tryStateOf<T extends State<StatefulWidget>>() {
final state = findAncestorStateOfType<T>();
if (state != null) {
return state;
}
return null;
}
/// Use `shouldCanPop` to determine whether to display the back arrow.
///
/// ```dart
/// AppBar(
/// brightness: Brightness.light,
/// backgroundColor: Colors.blue,
/// title: const Text(
/// 'thrio_example',
/// style: TextStyle(color: Colors.black)),
/// leading: context.shouldCanPop(const IconButton(
/// color: Colors.black,
/// tooltip: 'back',
/// icon: Icon(Icons.arrow_back_ios),
/// onPressed: ThrioNavigator.pop,
/// )),
/// ))
/// ```
///
Widget showPopAwareWidget(
Widget trueWidget, {
Widget falseWidget = const SizedBox(),
void Function(bool)? canPopResult,
}) =>
FutureBuilder<bool>(
future: _isInitialRoute(),
builder: (context, snapshot) {
canPopResult?.call(snapshot.data != true);
if (snapshot.data == true) {
return falseWidget;
} else {
return trueWidget;
}
});
Future<bool> _isInitialRoute() {
final state = stateOf<NavigatorWidgetState>();
final route = state.history.last;
return route is NavigatorRoute
? ThrioNavigatorImplement.shared().isInitialRoute(
url: route.settings.url,
index: route.settings.index,
)
: Future<bool>.value(false);
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_stateful_widget.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
extension ThrioStatefulWidget on StatefulWidget {
/// Get widget state from the global key.
///
T? tryStateOf<T extends State<StatefulWidget>>() {
if (this.key == null) {
return null;
}
final key = this.key;
if (key is GlobalKey<T>) {
return key.currentState;
}
return null;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_map.dart | // The MIT License (MIT)
//
// Copyright (c) 2023 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'thrio_object.dart';
extension ThrioMap<K, V> on Map<K, V> {
/// Filter the key/value of the current map, keeping only simple types.
///
Map<K, V> toSimpleMap() {
final map = <K, V>{};
final ts = this;
for (final k in ts.keys) {
final v = ts[k];
if (v?.isSimpleType == true) {
map[k] = v as V;
}
}
return map;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_iterable.dart | // The MIT License (MIT)
//
// Copyright (c) 2021 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
extension ThrioIterable<E> on Iterable<E> {
/// Returns the first element.
///
/// Return `null` if `this` is empty.
/// Otherwise returns the first element in the iteration order,
///
E? get firstOrNull => isEmpty ? null : first;
/// Returns the last element.
///
/// Return `null` if `this` is empty.
/// Otherwise may iterate through the elements and returns the last one
/// seen.
E? get lastOrNull => isEmpty ? null : last;
/// Returns the first element that satisfies the given [predicate].
///
/// If no element satisfies [test], return `null`.
///
E? firstWhereOrNull(bool Function(E it) predicate) {
for (final it in this) {
if (predicate(it)) {
return it;
}
}
return null;
}
/// Returns the last element that satisfies the given [predicate].
///
/// If no element satisfies [test], return `null`.
///
E? lastWhereOrNull(bool Function(E it) predicate) {
final reversed = toList().reversed;
for (final it in reversed) {
if (predicate(it)) {
return it;
}
}
return null;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_list.dart | // The MIT License (MIT)
//
// Copyright (c) 2023 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'thrio_object.dart';
extension ThrioList<E> on List<E> {
/// Filter the elements of the current map, keeping only simple types.
///
List<E> toSimpleList() {
final list = <E>[];
final ts = this;
for (final e in ts) {
if (e?.isSimpleType == true) {
list.add(e);
}
}
return list;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_object.dart | // The MIT License (MIT)
//
// Copyright (c) 2021 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
extension ThrioObject on Object {
/// Determine whether the current instance is a bool.
///
/// Can be called in the following ways,
/// `true.isDouble`
/// `false.runtimeType.isDouble`
///
bool get isBool {
if (this is Type) {
return this == bool;
} else {
return this is bool;
}
}
/// Determine whether the current instance is an int.
///
/// Can be called in the following ways,
/// `2.isInt`
/// `2.runtimeType.isInt`
///
bool get isInt {
if (this is Type) {
return this == int;
} else {
return this is int;
}
}
/// Determine whether the current instance is a double.
///
/// Can be called in the following ways,
/// `2.0.isDouble`
/// `2.0.runtimeType.isDouble`
///
bool get isDouble {
if (this is Type) {
return this == double;
} else {
return this is double;
}
}
/// Determine whether the current instance is an int or double.
///
/// Can be called in the following ways,
/// `2.isNumber`
/// `2.0.runtimeType.isNumber`
///
bool get isNumber {
if (this is Type) {
return this == double || this == int;
} else {
return this is num;
}
}
/// Determine whether the current instance is a String.
///
/// Can be called in the following ways,
/// `'2'.isString`
/// `'2'.runtimeType.isString`
///
bool get isString {
if (this is Type) {
return this == String;
} else {
return this is String;
}
}
/// Determine whether the current instance is a List.
///
/// Can be called in the following ways,
/// `[ 'k', '2' ].isString`
/// `[ 'k', '2' ].runtimeType.isString`
///
bool get isList {
if (this is Type) {
return toString().contains('List');
} else {
return this is List;
}
}
/// Determine whether the current instance is a simple List.
///
/// Can be called in the following ways,
/// `[ 'k', '2' ].isString`
///
bool get isSimpleList {
final ts = this;
if (ts is! List) {
return false;
}
for (final it in ts) {
if (it is Object && it.isSimpleType == false) {
return false;
}
}
return true;
}
/// Determine whether the current instance is a Map.
///
/// Can be called in the following ways,
/// `{ 'k': 2 }.isMap`
/// `{ 'k': 2 }.runtimeType.isMap`
///
bool get isMap {
if (this is Type) {
return toString().contains('Map');
} else {
return this is Map;
}
}
/// Determine whether the current instance is a simple Map.
///
/// Can be called in the following ways,
/// `{ 'k': 2 }.isMap`
///
bool get isSimpleMap {
final ts = this;
if (ts is! Map) {
return false;
}
for (final it in ts.values) {
if (it is Object && it.isSimpleType == false) {
return false;
}
}
return true;
}
/// Determine whether the current instance is a primitive type,
/// including bool, int, double, String.
///
/// Can be called in the following ways,
/// `2.isPrimitiveType`
/// `2.runtimeType.isPrimitiveType`
///
bool get isPrimitiveType {
if (this is Type) {
return this == bool || this == int || this == double || this == String;
} else {
return this is bool || this is num || this is String;
}
}
/// Determine whether the current instance is a simple type,
/// including bool, int, double, String, Map, List.
///
/// Can be called in the following ways,
/// `2.isSimpleType`
///
bool get isSimpleType => isPrimitiveType || isSimpleList || isSimpleMap;
/// Determine whether the current instance is a complex type,
/// not bool, int, double, String, Map, List.
///
/// Can be called in the following ways,
/// `2.isComplexType`
///
bool get isComplexType => !isSimpleType;
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/extension/thrio_uri_string.dart | // The MIT License (MIT)
//
// Copyright (c) 2023 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
const int _ampersand = 0x26;
const int _equals = 0x3d;
extension ThrioUri on String {
static List<String> _createList() => <String>[];
Map<String, List<String>> get rawQueryParametersAll {
if (isEmpty) {
return const <String, List<String>>{};
}
final result = <String, List<String>>{};
var i = 0;
var start = 0;
var equalsIndex = -1;
void parsePair(int start, int equalsIndex, int end) {
String key;
String value;
if (start == end) {
return;
}
if (equalsIndex < 0) {
key = substring(start, end);
value = '';
} else {
key = substring(start, equalsIndex);
value = substring(equalsIndex + 1, end);
}
result.putIfAbsent(key, _createList).add(value);
}
while (i < length) {
final char = codeUnitAt(i);
if (char == _equals) {
if (equalsIndex < 0) {
equalsIndex = i;
}
} else if (char == _ampersand) {
parsePair(start, equalsIndex, i);
start = i + 1;
equalsIndex = -1;
}
i++;
}
parsePair(start, equalsIndex, i);
return Map<String, List<String>>.unmodifiable(result);
}
Map<String, String> get rawQueryParameters => split('&').fold({}, (map, it) {
final index = it.indexOf('=');
if (index == -1) {
if (it != '') {
map[it] = '';
}
} else if (index != 0) {
final key = it.substring(0, index);
final value = it.substring(index + 1);
map[key] = value;
}
return map;
});
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_route_transitions_builder.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import 'thrio_module.dart';
mixin ModuleRouteTransitionsBuilder on ThrioModule {
@protected
RouteTransitionsBuilder? routeTransitionsBuilder;
@protected
bool get routeTransitionsDisabled => routeTransitionsBuilder == null;
/// A function for setting a `RouteTransitionsBuilder` .
///
@protected
void onRouteTransitionsBuilderSetting(ModuleContext moduleContext) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_expando.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'thrio_module.dart';
/// Associate module to `ModuleContext`.
///
/// Get module of `ModuleContext` by `moduleOf[this]`.
///
final moduleOf = Expando<ThrioModule>();
/// Associate parent module to current module.
///
/// Get parent module of `module` by `parentOf[module]`.
///
final parentOf = Expando<ThrioModule>();
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_page_builder.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../navigator/navigator_types.dart';
import 'module_anchor.dart';
import 'thrio_module.dart';
mixin ModulePageBuilder on ThrioModule {
NavigatorPageBuilder? _pageBuilder;
NavigatorPageBuilder? get pageBuilder => _pageBuilder;
/// If there is a ModulePageBuilder in a module, there can be no submodules.
///
set pageBuilder(NavigatorPageBuilder? builder) {
_pageBuilder = builder;
final urlComponents = <String>['/$key'];
var parentModule = parent;
while (parentModule != null && parentModule.key.isNotEmpty) {
urlComponents.insert(0, '/${parentModule.key}');
parentModule = parentModule.parent;
}
final url = (StringBuffer()..writeAll(urlComponents)).toString();
if (builder == null) {
anchor.allUrls.remove(url);
} else {
anchor.allUrls.add(url);
}
}
/// A function for setting a `NavigatorPageBuilder`.
///
@protected
void onPageBuilderSetting(ModuleContext moduleContext) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_param_scheme.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../exception/thrio_exception.dart';
import '../registry/registry_map.dart';
import 'module_anchor.dart';
import 'thrio_module.dart';
mixin ModuleParamScheme on ThrioModule {
/// Param schemes registered in the current Module
///
final _paramSchemes = RegistryMap<Comparable<dynamic>, Type>();
@protected
bool hasParamScheme<T>(Comparable<dynamic> key) {
if (_paramSchemes.keys.contains(key)) {
if (T == dynamic || T == Object) {
return true;
}
return _paramSchemes[key] == T;
}
return false;
}
@protected
final paramStreamCtrls =
<Comparable<dynamic>, Set<StreamController<dynamic>>>{};
/// Subscribe to a series of param by `key`.
///
@protected
Stream<T?>? onParam<T>(Comparable<dynamic> key, {T? initialValue}) {
paramStreamCtrls[key] ??= <StreamController<dynamic>>{};
final sc = StreamController<T?>();
sc
..onListen = () {
paramStreamCtrls[key]?.add(sc);
// sink lastest value.
final value = getParam<T>(key);
if (value != null) {
sc.add(value);
} else if (initialValue != null) {
sc.add(initialValue);
}
}
..onCancel = () {
paramStreamCtrls[key]?.remove(sc);
};
return sc.stream;
}
final _params = <Comparable<dynamic>, dynamic>{};
/// Gets param by `key` & `T`.
///
/// Throw `ThrioException` if `T` is not matched param scheme.
///
@protected
T? getParam<T>(Comparable<dynamic> key) {
// Anchor module does not need to get param scheme.
if (this == anchor) {
return _params[key] as T?;
}
if (!_paramSchemes.keys.contains(key)) {
return null;
}
final value = _params[key];
if (value == null) {
return null;
}
if (T != dynamic && T != Object && value is! T) {
throw ThrioException(
'$T does not match the param scheme type: ${value.runtimeType}');
}
return value as T?;
}
/// Sets param with `key` & `value`.
///
/// Return `false` if param scheme is not registered.
///
@protected
bool setParam<T>(Comparable<dynamic> key, T value) {
// Anchor module does not need to set param scheme.
if (this == anchor) {
final oldValue = _params[key];
if (oldValue != null && oldValue.runtimeType != value.runtimeType) {
return false;
}
_setParam(key, value);
return true;
}
if (!_paramSchemes.keys.contains(key)) {
return false;
}
final schemeType = _paramSchemes[key];
if (schemeType == dynamic || schemeType == Object) {
final oldValue = _params[key];
if (oldValue != null && oldValue.runtimeType != value.runtimeType) {
return false;
}
} else {
if (schemeType.toString() != value.runtimeType.toString()) {
return false;
}
}
_setParam(key, value);
return true;
}
void _setParam(Comparable<dynamic> key, dynamic value) {
if (_params[key] != value) {
_params[key] = value;
final scs = paramStreamCtrls[key];
if (scs == null || scs.isEmpty) {
return;
}
for (final sc in scs) {
if (sc.hasListener && !sc.isPaused && !sc.isClosed) {
sc.add(value);
}
}
}
}
/// Remove param by `key` & `T`, if exists, return the `value`.
///
/// Throw `ThrioException` if `T` is not matched param scheme.
///
T? removeParam<T>(Comparable<dynamic> key) {
// Anchor module does not need to get param scheme.
if (this == anchor) {
return _params.remove(key) as T?;
}
if (T != dynamic &&
T != Object &&
_paramSchemes.keys.contains(key) &&
_paramSchemes[key] != T) {
throw ThrioException(
'$T does not match the param scheme type: ${_paramSchemes[key]}');
}
final param = _params.remove(key) as T?;
if (param != null) {
_setParam(key, param);
}
return param;
}
/// A function for register a param scheme.
///
@protected
void onParamSchemeRegister(ModuleContext moduleContext) {}
/// Register a param scheme for the module.
///
/// `T` can be optional.
///
/// Unregistry by calling the return value `VoidCallback`.
///
@protected
VoidCallback registerParamScheme<T>(Comparable<dynamic> key) {
if (_paramSchemes.keys.contains(key)) {
throw ThrioException(
'$T is already registered for key ${_paramSchemes[key]}');
}
final callback = _paramSchemes.registry(key, T);
return () {
callback();
final scs = paramStreamCtrls.remove(key);
if (scs != null && scs.isNotEmpty) {
for (final sc in scs) {
sc.close();
}
}
};
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_route_builder.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/widgets.dart';
import '../navigator/navigator_types.dart';
import 'thrio_module.dart';
mixin ModuleRouteBuilder on ThrioModule {
@protected
NavigatorRouteBuilder? routeBuilder;
/// A function for setting a `NavigatorRouteBuilder` .
///
@protected
void onRouteBuilderSetting(ModuleContext moduleContext) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_context.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: invalid_use_of_protected_member, avoid_as
part of 'thrio_module.dart';
class ModuleContext {
ModuleContext({this.entrypoint = 'main'});
/// Entrypoint of current app.
///
final String entrypoint;
/// Module of module context.
///
ThrioModule get module => moduleOf[this]!;
/// Get param `value` of `key`.
///
/// If not exist, get from parent module's `ModuleContext`.
///
T? get<T>(String key) {
if (module is ModuleParamScheme) {
final value = (module as ModuleParamScheme).getParam<T>(key);
if (value != null) {
return value;
}
}
return module.parent?._moduleContext.get<T>(key);
}
/// Set param `value` with `key`.
///
/// Return `false` if param scheme is not registered.
///
bool set<T>(String key, T value) {
if (module is ModuleParamScheme) {
if ((module as ModuleParamScheme).setParam<T>(key, value)) {
return true;
}
}
// Anchor module caches the data of the framework
return module.parent != anchor &&
module.parent != null &&
(module.parent?._moduleContext.set<T>(key, value) ?? false);
}
/// Remove param with `key`.
///
/// Return `value` if param not exists.
///
T? remove<T>(String key) {
if (module is ModuleParamScheme) {
final value = (module as ModuleParamScheme).removeParam<T>(key);
if (value != null) {
return value;
}
}
// Anchor module caches the data of the framework
return module.parent == anchor
? null
: module.parent?._moduleContext.remove<T>(key);
}
/// Subscribe to a series of param by `key`.
///
/// sink `null` when `key` removed.
///
Stream<T?>? onWithNull<T>(String key, {T? initialValue}) {
if (module == anchor) {
return anchor.onParam<T>(key, initialValue: initialValue);
}
if (module is ModuleParamScheme) {
final paramModule = module as ModuleParamScheme;
if (paramModule.hasParamScheme<T>(key)) {
return paramModule.onParam<T>(key, initialValue: initialValue);
}
}
return module.parent?._moduleContext
.onWithNull<T>(key, initialValue: initialValue);
}
/// Subscribe to a series of param by `key`.
///
Stream<T>? on<T>(String key, {T? initialValue}) =>
onWithNull<T>(key, initialValue: initialValue)
?.transform<T>(StreamTransformer.fromHandlers(
handleData: (data, sink) {
if (data != null) {
sink.add(data);
}
},
));
@override
String toString() => 'Context of module ${module.key}';
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_page_observer.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../navigator/navigator_page_observer.dart';
import '../registry/registry_set.dart';
import 'thrio_module.dart';
mixin ModulePageObserver on ThrioModule {
@protected
final pageObservers = RegistrySet<NavigatorPageObserver>();
/// A function for register a page observer.
///
@protected
void onPageObserverRegister(ModuleContext moduleContext) {}
/// Register observers for the life cycle of all pages under
/// the current module and submodules.
///
/// Unregistry by calling the return value `VoidCallback`.
///
/// Do not override this method.
///
@protected
VoidCallback registerPageObserver(NavigatorPageObserver pageObserver) =>
pageObservers.registry(pageObserver);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/thrio_module.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: invalid_use_of_protected_member
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../exception/thrio_exception.dart';
import '../navigator/navigator_logger.dart';
import '../navigator/navigator_types.dart';
import 'module_anchor.dart';
import 'module_expando.dart';
import 'module_json_deserializer.dart';
import 'module_json_serializer.dart';
import 'module_jsonable.dart';
import 'module_page_builder.dart';
import 'module_page_observer.dart';
import 'module_param_scheme.dart';
import 'module_route_action.dart';
import 'module_route_builder.dart';
import 'module_route_custom_handler.dart';
import 'module_route_observer.dart';
import 'module_route_transitions_builder.dart';
part 'module_context.dart';
mixin ThrioModule {
/// Modular initialization function, needs to be called once during App initialization.
///
static Future<void> init(
ThrioModule rootModule, {
String? entrypoint,
void Function(String)? onModuleInitStart,
void Function(String)? onModuleInitEnd,
}) async {
if (anchor.modules.length == 1) {
throw ThrioException('init method can only be called once.');
}
ThrioModule._onModuleInitStart = onModuleInitStart;
ThrioModule._onModuleInitEnd = onModuleInitEnd;
final moduleContext = entrypoint == null
? ModuleContext()
: ModuleContext(entrypoint: entrypoint);
moduleOf[moduleContext] = anchor;
anchor
.._moduleContext = moduleContext
..registerModule(rootModule, moduleContext);
await anchor.onModuleInit(moduleContext);
await anchor.initModule();
}
/// Get instance by `T`, `url` and `key`.
///
/// `T` can be `ThrioModule`, `NavigatorPageBuilder`, `JsonSerializer`,
/// `JsonDeserializer`, `ProtobufSerializer`, `ProtobufDeserializer`,
/// `RouteTransitionsBuilder`, default is `ThrioModule`.
///
/// If `T` is `ThrioModule`, returns the last module matched by the `url`.
///
/// If `T` is `ThrioModule`, `RouteTransitionsBuilder` or
/// `NavigatorPageBuilder`, then `url` must not be null or empty.
///
/// If `T` is not `ThrioModule`, `RouteTransitionsBuilder` or
/// `NavigatorPageBuilder`, and `url` is null or empty, find instance of `T`
/// in all modules.
///
static T? get<T>({String? url, String? key}) =>
anchor.get<T>(url: url, key: key);
/// Returns true if the `url` has been registered.
///
static bool contains(String url) =>
anchor.get<NavigatorPageBuilder>(url: url) != null;
/// Get instances by `T` and `url`.
///
/// `T` can not be optional. Can be `NavigatorPageObserver`,
/// `NavigatorRouteObserver`.
///
/// If `T` is `NavigatorPageObserver`, returns all page observers
/// matched by `url`.
///
/// If `T` is `NavigatorRouteObserver`, returns all route observers
/// matched by `url`.
///
static Iterable<T> gets<T>({required String url}) => anchor.gets<T>(url);
@protected
final modules = <String, ThrioModule>{};
/// A [Key] is an identifier for a module.
///
@protected
String get key => '';
/// Get parent module.
///
@protected
ThrioModule? get parent => parentOf[this];
String? _url;
/// Get route url by join all route node's name.
///
String get url {
_initUrl(this);
return _url!;
}
/// `ModuleContext` of current module.
///
@protected
ModuleContext get moduleContext => _moduleContext;
late ModuleContext _moduleContext;
/// Call at module init start.
///
static void Function(String)? get onModuleInitStart => _onModuleInitStart;
static void Function(String)? _onModuleInitStart;
/// Call at module init end.
static void Function(String)? get onModuleInitEnd => _onModuleInitEnd;
static void Function(String)? _onModuleInitEnd;
/// A function for registering a module, which will call
/// the `onModuleRegister` function of the `module`.
///
@protected
void registerModule(
ThrioModule module,
ModuleContext moduleContext,
) {
if (modules.containsKey(module.key)) {
throw ThrioException(
'A module with the same key ${module.key} already exists');
} else {
final submoduleContext =
ModuleContext(entrypoint: moduleContext.entrypoint);
moduleOf[submoduleContext] = module;
modules[module.key] = module;
parentOf[module] = this;
module
.._moduleContext = submoduleContext
..onModuleRegister(submoduleContext);
}
}
/// A function for module initialization that will call the
/// `onModuleInit`, `onPageBuilderRegister`,
/// `onRouteTransitionsBuilderRegister`, `onPageObserverRegister`
/// `onRouteObserverRegister`, `onJsonSerializerRegister`,
/// `onJsonDeserializerRegister`, `onProtobufSerializerRegister`,
/// `onProtobufDeserializerRegister` and `onModuleAsyncInit`
/// methods of all modules.
///
@protected
Future<void> initModule() async {
final values = modules.values;
for (final module in values) {
if (module is ModuleParamScheme) {
module.onParamSchemeRegister(module._moduleContext);
}
}
for (final module in values) {
if (module is ModuleRouteAction) {
module.onRouteActionRegister(module._moduleContext);
}
if (module is ModuleRouteCustomHandler) {
module.onRouteCustomHandlerRegister(module._moduleContext);
}
}
for (final module in values) {
if (module is ModulePageBuilder) {
module.onPageBuilderSetting(module._moduleContext);
}
if (module is ModuleRouteBuilder) {
module.onRouteBuilderSetting(module._moduleContext);
}
if (module is ModuleRouteTransitionsBuilder) {
module.onRouteTransitionsBuilderSetting(module._moduleContext);
}
}
for (final module in values) {
if (module is ModulePageObserver) {
module.onPageObserverRegister(module._moduleContext);
}
if (module is ModuleRouteObserver) {
module.onRouteObserverRegister(module._moduleContext);
}
}
for (final module in values) {
if (module is ModuleJsonSerializer) {
module.onJsonSerializerRegister(module._moduleContext);
}
if (module is ModuleJsonDeserializer) {
module.onJsonDeserializerRegister(module._moduleContext);
}
}
for (final module in values) {
if (module is ModuleJsonable) {
module.onJsonableRegister(module._moduleContext);
}
}
for (final module in values) {
onModuleInitStart?.call(module.url);
if (kDebugMode) {
final sw = Stopwatch()..start();
await module.onModuleInit(module._moduleContext);
verbose('init: ${module.key} = ${sw.elapsedMicroseconds} µs');
sw.stop();
} else {
await module.onModuleInit(module._moduleContext);
}
onModuleInitEnd?.call(module.url);
await module.initModule();
}
for (final module in values) {
unawaited(module.onModuleAsyncInit(module._moduleContext));
}
}
/// A function for registering submodules.
///
@protected
void onModuleRegister(ModuleContext moduleContext) {}
/// A function for module initialization.
///
@protected
Future<void> onModuleInit(ModuleContext moduleContext) async {}
/// Returns whether the module is loaded.
///
@protected
bool isLoaded = false;
/// Called when the first page in the module is about to be pushed.
///
@protected
Future<void> onModuleLoading(ModuleContext moduleContext) async =>
verbose('onModuleLoading: $key');
/// Called when the last page in the module is closed.
///
@protected
Future<void> onModuleUnloading(ModuleContext moduleContext) async =>
verbose('onModuleUnloading: $key');
/// A function for module asynchronous initialization.
///
@protected
Future<void> onModuleAsyncInit(ModuleContext moduleContext) async {}
@protected
bool get navigatorLogEnabled => navigatorLogging;
@protected
set navigatorLogEnabled(bool enabled) => navigatorLogging = enabled;
@override
String toString() => '$key: ${modules.keys.toString()}';
void _initUrl(ThrioModule module) {
if (module._url == null) {
var parentUrl = '';
final parentModule = module.parent;
if (parentModule != null &&
parentModule != anchor &&
parentModule.key.isNotEmpty) {
parentUrl = parentModule.url;
}
module._url = '$parentUrl/${module.key}';
}
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_json_serializer.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../registry/registry_map.dart';
import 'module_types.dart';
import 'thrio_module.dart';
mixin ModuleJsonSerializer on ThrioModule {
/// Json serializer registered in the current Module
///
final _jsonSerializers = RegistryMap<Type, JsonSerializer>();
/// Get json serializer by type string.
///
@protected
JsonSerializer? getJsonSerializer(String typeString) {
final type = _jsonSerializers.keys.lastWhere(
(it) =>
it.toString() == typeString || typeString.endsWith(it.toString()),
orElse: () => Null);
return _jsonSerializers[type];
}
/// A function for register a json serializer.
///
@protected
void onJsonSerializerRegister(ModuleContext moduleContext) {}
/// Register a json serializer for the module.
///
/// Unregistry by calling the return value `VoidCallback`.
///
@protected
VoidCallback registerJsonSerializer<T>(JsonSerializer serializer) =>
_jsonSerializers.registry(T, serializer);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_anchor.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: avoid_as
import 'package:flutter/widgets.dart';
import '../navigator/navigator_page_observer.dart';
import '../navigator/navigator_route.dart';
import '../navigator/navigator_route_observer.dart';
import '../navigator/navigator_route_settings.dart';
import '../navigator/navigator_types.dart';
import '../navigator/navigator_url_template.dart';
import '../navigator/thrio_navigator_implement.dart';
import '../registry/registry_order_map.dart';
import '../registry/registry_set.dart';
import '../registry/registry_set_map.dart';
import 'module_json_deserializer.dart';
import 'module_json_serializer.dart';
import 'module_page_builder.dart';
import 'module_page_observer.dart';
import 'module_param_scheme.dart';
import 'module_route_action.dart';
import 'module_route_builder.dart';
import 'module_route_observer.dart';
import 'module_route_transitions_builder.dart';
import 'module_types.dart';
import 'thrio_module.dart';
final anchor = ModuleAnchor();
class ModuleAnchor
with
ThrioModule,
ModuleJsonSerializer,
ModuleJsonDeserializer,
ModulePageObserver,
ModuleParamScheme,
ModuleRouteBuilder,
ModuleRouteObserver,
ModuleRouteTransitionsBuilder {
/// Holds PageObserver registered by `NavigatorPageLifecycle`.
///
final pageLifecycleObservers =
RegistrySetMap<String, NavigatorPageObserver>();
/// Holds PushHandler registered by `NavigatorRoutePush` .
///
final pushHandlers = RegistrySet<NavigatorRoutePushHandle>();
/// A collection of route handlers for matching the key's pattern.
///
final routeCustomHandlers =
RegistryOrderMap<NavigatorUrlTemplate, NavigatorRouteCustomHandler>();
/// All registered urls.
///
final allUrls = <String>[];
ModuleContext get rootModuleContext => modules.values.first.moduleContext;
@override
Future<void> onModuleInit(ModuleContext moduleContext) =>
ThrioNavigatorImplement.shared().init(moduleContext);
Future<dynamic> loading(String url) async {
final modules = _getModules(url: url);
for (final module in modules) {
if (!module.isLoaded) {
module.isLoaded = true;
await module.onModuleLoading(module.moduleContext);
}
}
}
Future<dynamic> unloading(Iterable<NavigatorRoute> allRoutes) async {
final urls = allRoutes.map<String>((it) => it.settings.url).toSet();
final notPushedUrls = allUrls.where((it) => !urls.contains(it)).toList();
final modules = <ThrioModule>{};
for (final url in notPushedUrls) {
modules.addAll(_getModules(url: url));
}
final notPushedModules = modules
.where((it) => it is ModulePageBuilder && it.pageBuilder != null)
.toSet();
for (final module in notPushedModules) {
// 页 Module onModuleUnloading
if (module.isLoaded) {
module.isLoaded = false;
await module.onModuleUnloading(module.moduleContext);
if (module is ModuleParamScheme) {
module.paramStreamCtrls.clear();
}
}
// 页 Module 的 父 Module onModuleUnloading
var parentModule = module.parent;
while (parentModule != null) {
final leafModules = _getAllLeafModules(parentModule);
if (notPushedModules.containsAll(leafModules)) {
if (parentModule.isLoaded) {
parentModule.isLoaded = false;
await parentModule.onModuleUnloading(parentModule.moduleContext);
if (parentModule is ModuleParamScheme) {
parentModule.paramStreamCtrls.clear();
}
}
}
parentModule = parentModule.parent;
}
}
}
T? get<T>({String? url, String? key}) {
var modules = <ThrioModule>[];
if (url != null && url.isNotEmpty) {
final typeString = T.toString();
modules = _getModules(url: url);
if (T == ThrioModule || T == dynamic || T == Object) {
return modules.isEmpty ? null : modules.last as T;
} else if (typeString == (NavigatorPageBuilder).toString()) {
if (modules.isEmpty) {
return null;
}
final lastModule = modules.last;
if (lastModule is ModulePageBuilder) {
final builder = lastModule.pageBuilder;
if (builder is NavigatorPageBuilder) {
return builder as T;
}
}
} else if (typeString == (NavigatorRouteBuilder).toString()) {
if (modules.isEmpty) {
return null;
}
for (final it in modules.reversed) {
if (it is ModuleRouteBuilder) {
if (it.routeBuilder != null) {
return it.routeBuilder as T;
}
}
}
return null;
} else if (typeString == (RouteTransitionsBuilder).toString()) {
if (modules.isEmpty) {
return null;
}
for (final it in modules.reversed) {
if (it is ModuleRouteTransitionsBuilder) {
if (it.routeTransitionsDisabled) {
return null;
}
if (!it.routeTransitionsDisabled &&
it.routeTransitionsBuilder != null) {
return it.routeTransitionsBuilder as T;
}
}
}
return null;
} else if (typeString == (NavigatorRouteAction).toString()) {
if (modules.isEmpty || key == null) {
return null;
}
for (final it in modules.reversed) {
if (it is ModuleRouteAction) {
final routeAction = it.getRouteAction(key);
if (routeAction != null) {
return routeAction as T;
}
}
}
return null;
}
}
if (modules.isEmpty &&
(url == null || url.isEmpty || !ThrioModule.contains(url))) {
modules = _getModules();
}
if (key == null || key.isEmpty) {
return null;
}
return _get<T>(modules, key);
}
Iterable<T> gets<T>(String url) {
final modules = _getModules(url: url);
if (modules.isEmpty) {
return <T>[];
}
final typeString = T.toString();
if (typeString == (NavigatorPageObserver).toString()) {
final observers = <NavigatorPageObserver>{};
for (final module in modules) {
if (module is ModulePageObserver) {
observers.addAll(module.pageObservers);
}
}
observers.addAll(pageLifecycleObservers[url]);
return observers.toList().cast<T>();
} else if (typeString == (NavigatorRouteObserver).toString()) {
final observers = <NavigatorRouteObserver>{};
for (final module in modules) {
if (module is ModuleRouteObserver) {
observers.addAll(module.routeObservers);
}
}
return observers.toList().cast<T>();
}
return <T>[];
}
void set<T>(Comparable<dynamic> key, T value) => setParam(key, value);
T? remove<T>(Comparable<dynamic> key) => removeParam(key);
List<ThrioModule> _getModules({String? url}) {
if (modules.isEmpty) {
return <ThrioModule>[];
}
final firstModule = modules.values.first;
final allModules = [firstModule];
if (url == null || url.isEmpty) {
// 子节点所有的 module
return allModules..addAll(_getAllModules(firstModule));
}
final components =
url.isEmpty ? <String>[] : url.replaceAll('/', ' ').trim().split(' ');
final length = components.length;
ThrioModule? module = firstModule;
// 确定根节点,根部允许连续的空节点
if (components.isNotEmpty) {
final key = components.removeAt(0);
var m = module.modules[key];
if (m == null) {
m = module.modules[''];
while (m != null) {
allModules.add(m);
final m0 = m.modules[key];
if (m0 == null) {
m = m.modules[''];
} else {
m = m0;
break;
}
}
}
if (m == null) {
return allModules;
}
module = m;
allModules.add(module);
}
// 寻找剩余的节点
while (components.isNotEmpty) {
final key = components.removeAt(0);
module = module?.modules[key];
if (module != null) {
allModules.add(module);
}
}
// url 不能完全匹配到 module,可能是原生的 url 或者不存在的 url
if (allModules.where((it) => it.key.isNotEmpty).length != length) {
return <ThrioModule>[];
}
return allModules;
}
Iterable<ThrioModule> _getAllModules(ThrioModule module) {
final subModules = module.modules.values;
final allModules = [...subModules];
for (final it in subModules) {
allModules.addAll(_getAllModules(it));
}
return allModules;
}
Iterable<ThrioModule> _getAllLeafModules(ThrioModule module) {
final subModules = module.modules.values;
final allLeafModules = <ThrioModule>[];
for (final module in subModules) {
if (module is ModulePageBuilder) {
if (module.pageBuilder != null) {
allLeafModules.add(module);
}
} else {
allLeafModules.addAll(_getAllLeafModules(module));
}
}
return allLeafModules;
}
T? _get<T>(List<ThrioModule> modules, String key) {
final typeString = T.toString();
if (typeString == (JsonSerializer).toString()) {
for (final it in modules.reversed) {
if (it is ModuleJsonSerializer) {
final jsonSerializer = it.getJsonSerializer(key);
if (jsonSerializer != null) {
return jsonSerializer as T;
}
}
}
} else if (typeString == (JsonDeserializer).toString()) {
for (final it in modules.reversed) {
if (it is ModuleJsonDeserializer) {
final jsonDeserializer = it.getJsonDeserializer(key);
if (jsonDeserializer != null) {
return jsonDeserializer as T;
}
}
}
}
return null;
}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_jsonable.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import 'package:flutter_jsonable/flutter_jsonable.dart';
import 'thrio_module.dart';
mixin ModuleJsonable on ThrioModule {
/// Get jsonable by type string.
///
@protected
Jsonable<dynamic>? getJsonable(String typeString) =>
jsonableRegistry.getByTypeName(typeString);
/// A function for register a jsonable.
///
@protected
void onJsonableRegister(ModuleContext moduleContext) {}
/// Register a jsonable.
///
/// Unregistry by calling the return value `VoidCallback`.
///
@protected
VoidCallback registerJsonable<T>(Jsonable<dynamic> jsonable) =>
jsonableRegistry.registerJsonable(jsonable);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_types.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import '../navigator/navigator_types.dart';
/// Signature of callbacks for json serializer.
///
typedef JsonSerializer = Map<String, dynamic> Function(T Function<T>() factory);
/// Signature of callbacks for json deserializer.
///
typedef JsonDeserializer<T> = T? Function(Map<String, dynamic> params);
/// Signature of route custom handler.
///
/// Can be used to handle deeplink or route redirection.
///
typedef NavigatorRouteCustomHandler = FutureOr<TPopParams?>
Function<TParams, TPopParams>(
String url,
Map<String, List<String>> queryParams, {
TParams? params,
bool animated,
NavigatorIntCallback? result,
});
final _queryParamsDecodedOf = Expando<bool>();
extension NavigatorRouteCustomHandlerX on NavigatorRouteCustomHandler {
bool get queryParamsDecoded => _queryParamsDecodedOf[this] ?? true;
set queryParamsDecoded(bool value) => _queryParamsDecodedOf[this] = value;
}
typedef RegisterRouteCustomHandlerFunc = void Function(
String,
NavigatorRouteCustomHandler, {
bool queryParamsDecoded,
});
const navigatorResultTypeHandled = 0;
const navigatorResultTypeNotHandled = -1;
/// Signature of route action.
///
/// Can be used to handle route action.
///
typedef NavigatorRouteAction = FutureOr<TResult?> Function<TParams, TResult>(
String url,
String action,
Map<String, List<String>> queryParams, {
TParams? params,
});
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_json_deserializer.dart | // The MIT License (MIT)
//
// Copyright (c) 2020 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../registry/registry_map.dart';
import 'module_types.dart';
import 'thrio_module.dart';
mixin ModuleJsonDeserializer on ThrioModule {
/// Json deserializer registered in the current Module
///
final _jsonDeserializers = RegistryMap<Type, JsonDeserializer<dynamic>>();
/// Get json deserializer by type string.
///
@protected
JsonDeserializer<dynamic>? getJsonDeserializer(String typeString) {
final type = _jsonDeserializers.keys.lastWhere(
(it) =>
it.toString() == typeString || typeString.endsWith(it.toString()),
orElse: () => Null);
return _jsonDeserializers[type];
}
/// A function for register a json deserializer.
///
@protected
void onJsonDeserializerRegister(ModuleContext moduleContext) {}
/// Register a json deserializer for the module.
///
/// Unregistry by calling the return value `VoidCallback`.
///
@protected
VoidCallback registerJsonDeserializer<T>(JsonDeserializer<T> deserializer) =>
_jsonDeserializers.registry(T, deserializer);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_route_custom_handler.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../navigator/navigator_url_template.dart';
import 'module_anchor.dart';
import 'module_types.dart';
import 'thrio_module.dart';
mixin ModuleRouteCustomHandler on ThrioModule {
/// Register a route custom handler.
///
/// format of `template` is 'scheme://foxsofter.com/login{userName?,password}'
///
/// Unregistry by calling the return value `VoidCallback`.
///
@protected
VoidCallback registerRouteCustomHandler(
String template,
NavigatorRouteCustomHandler handler, {
bool queryParamsDecoded = false,
}) {
final key = NavigatorUrlTemplate(template: template);
handler.queryParamsDecoded = queryParamsDecoded;
return anchor.routeCustomHandlers.registry(key, handler);
}
/// A function for register a `NavigatorRouteCustomHandler` .
///
@protected
void onRouteCustomHandlerRegister(ModuleContext moduleContext) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_route_observer.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../navigator/navigator_route_observer.dart';
import '../registry/registry_set.dart';
import 'thrio_module.dart';
mixin ModuleRouteObserver on ThrioModule {
@protected
final routeObservers = RegistrySet<NavigatorRouteObserver>();
/// A function for register a route observer.
///
@protected
void onRouteObserverRegister(ModuleContext moduleContext) {}
/// Register observers for routing actions. Only the pages under the current module and
/// sub-module take effect.
///
/// Unregistry by calling the return value `VoidCallback`.
///
/// Do not override this method.
///
@protected
VoidCallback registerRouteObserver(NavigatorRouteObserver routeObserver) =>
routeObservers.registry(routeObserver);
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/module/module_route_action.dart | // The MIT License (MIT)
//
// Copyright (c) 2022 foxsofter
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'package:flutter/foundation.dart';
import '../exception/thrio_exception.dart';
import '../navigator/navigator_url_template.dart';
import '../registry/registry_order_map.dart';
import 'module_types.dart';
import 'thrio_module.dart';
mixin ModuleRouteAction on ThrioModule {
/// A collection of route action.
///
final _routeActionHandlers =
RegistryOrderMap<NavigatorUrlTemplate, NavigatorRouteAction>();
NavigatorRouteAction? getRouteAction(String action) {
final a = action.replaceAll('?', '='); // ? 通过 Uri 解析会引起截断,先替换成 =
return _routeActionHandlers.lastWhereOrNull((k) => k.match(Uri.parse(a)));
}
/// Register a route action.
///
/// format of `template` is 'login{userName?,password}'
///
/// Unregistry by calling the return value `VoidCallback`.
///
@protected
VoidCallback registerRouteAction(
String template,
NavigatorRouteAction action,
) {
final key = NavigatorUrlTemplate(template: template);
if (key.scheme.isNotEmpty) {
throw ThrioException(
'action url template should not contains scheme: $template',
);
}
if (_routeActionHandlers.keys.contains(key)) {
throw ThrioException('duplicate action url template: $template');
}
return _routeActionHandlers.registry(key, action);
}
/// A function for register a `NavigatorRouteAction` .
///
@protected
void onRouteActionRegister(ModuleContext moduleContext) {}
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/logger/thrio_logger.dart | // The MIT License (MIT)
//
// Copyright (c) 2019 Hellobike Group
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ignore_for_file: avoid_classes_with_only_static_members
import 'package:flutter/material.dart';
abstract class ThrioLogger {
/// Log a message at level verbose.
///
static void v(dynamic message) => _print('V', message);
/// Log a message at level debug.
///
static void d(dynamic message) => _print('D', message);
/// Log a message at level info.
///
static void i(dynamic message) => _print('I', message);
/// Log a message at level warning.
///
static void w(dynamic message) => _print('W', message);
/// Log a message at level error.
///
static void e(dynamic message) => _print('E', message);
static void _print(String level, dynamic message) =>
debugPrint('[$level] $message');
}
| 0 |
mirrored_repositories/flutter_thrio/lib/src | mirrored_repositories/flutter_thrio/lib/src/async/async_task_queue.dart | // The MIT License (MIT)
//
// Copyright (c) 2021 foxsofter.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
import 'dart:async';
import '../extension/thrio_iterable.dart';
class AsyncTaskQueue {
final _queue = <Completer<dynamic>>[];
Future<T?> add<T>(Future<T> Function() task, {Duration? timeLimit}) {
final completer = Completer<T?>();
void complete(T? value) {
if (!completer.isCompleted) {
_queue.remove(completer);
completer.complete(value);
}
}
final last = _queue.lastOrNull;
_queue.insert(_queue.length, completer);
if (last == null) {
final f = task().then(complete).catchError((_) => complete(null));
if (timeLimit != null) {
f.timeout(timeLimit, onTimeout: () => complete(null));
}
} else {
last.future.whenComplete(() {
final f = task().then(complete).catchError((_) => complete(null));
if (timeLimit != null) {
f.timeout(timeLimit, onTimeout: () => complete(null));
}
});
}
return completer.future;
}
}
| 0 |
mirrored_repositories/flutter_thrio | mirrored_repositories/flutter_thrio/test/flutter_thrio_test.dart | import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
void main() {
test(' async task queue', () async {
final queue = AsyncTaskQueue();
var idx = 0;
Future<int> f() {
idx += 1;
// print('begin with $idx');
return Future.delayed(const Duration(microseconds: 10), () {
// print('executing with $idx');
if (idx == 3) {
throw ArgumentError.value(idx);
}
if (idx == 4) {
// var r = queue.add(f, debugLabel: '6');
// r.then<void>((value) => queue.add(f, debugLabel: '7'));
}
return idx;
});
}
// var r = queue.add(f, debugLabel: '1');
// var s = r.then<void>((value) => print('end with $value'));
// r = queue.add(f, debugLabel: '2');
// s = r.then<void>((value) => print('end with $value'));
// r = queue.add(f, debugLabel: '3');
// s = r.then<void>((value) => print('end with $value'));
// r = queue.add(f, debugLabel: '4');
// s = r.then<void>((value) => print('end with $value'));
// r = queue.add(f, debugLabel: '5');
// s = r.then<void>((value) => print('end with $value'));
// await r;
});
test('getPlatformVersion', () async {});
}
| 0 |
mirrored_repositories/flutter_thrio/example | mirrored_repositories/flutter_thrio/example/lib/main.dart | import 'dart:async';
import 'package:flutter_thrio/flutter_thrio.dart';
import 'src/app.dart' as app;
Future<void> main() async {
ThrioLogger.v('main');
runZonedGuarded(app.main, (error, stack) {
Zone.current.handleUncaughtError(error, stack);
});
}
@pragma('vm:entry-point')
Future<void> biz1() async {
runZonedGuarded(app.biz1, (error, stack) {
Zone.current.handleUncaughtError(error, stack);
});
}
@pragma('vm:entry-point')
Future<void> biz2() async {
runZonedGuarded(app.biz2, (error, stack) {
Zone.current.handleUncaughtError(error, stack);
});
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib | mirrored_repositories/flutter_thrio/example/lib/src/app.dart | import 'package:flutter/material.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
import 'module.dart';
void main() => runApp(const MainApp());
void biz1() => runApp(const MainApp(entrypoint: 'biz1'));
void biz2() => runApp(const MainApp(entrypoint: 'biz2'));
class MainApp extends StatefulWidget {
const MainApp({super.key, String entrypoint = 'main'})
: _entrypoint = entrypoint;
final String _entrypoint;
@override
_MainAppState createState() => _MainAppState();
}
class _MainAppState extends State<MainApp> {
@override
void initState() {
super.initState();
ThrioModule.init(Module(), entrypoint: widget._entrypoint,
onModuleInitStart: (url) {
ThrioLogger.i('module start init: $url');
});
}
@override
Widget build(BuildContext context) => NavigatorMaterialApp(
transitionPage: const NavigatorHome(showRestartButton: true),
builder: (context, child) => Container(
child: child,
),
theme: ThemeData(
pageTransitionsTheme: const PageTransitionsTheme(builders: {
TargetPlatform.iOS: CupertinoPageTransitionsBuilder(),
TargetPlatform.android: CupertinoPageTransitionsBuilder(),
}),
),
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib | mirrored_repositories/flutter_thrio/example/lib/src/module.dart | // Copyright (c) 2022 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'biz/module.dart' as biz;
class Module
with
ThrioModule,
ModuleJsonDeserializer,
ModuleJsonSerializer,
ModuleParamScheme {
@override
void onModuleRegister(ModuleContext moduleContext) {
navigatorLogEnabled = true;
registerModule(biz.Module(), moduleContext);
}
@override
void onParamSchemeRegister(ModuleContext moduleContext) {}
@override
void onJsonSerializerRegister(ModuleContext moduleContext) {}
@override
void onJsonDeserializerRegister(ModuleContext moduleContext) {}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src | mirrored_repositories/flutter_thrio/example/lib/src/biz/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_jsonable/flutter_jsonable.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
import 'biz1/module.dart' as biz1;
import 'biz2/module.dart' as biz2;
import 'types/house.dart';
import 'types/people.dart';
import 'types/user_profile.dart';
class Module
with
ThrioModule,
ModuleJsonDeserializer,
ModuleJsonSerializer,
ModuleJsonable,
ModuleParamScheme {
@override
String get key => 'biz';
@override
void onModuleRegister(ModuleContext moduleContext) {
registerModule(biz1.Module(), moduleContext);
registerModule(biz2.Module(), moduleContext);
}
@override
void onParamSchemeRegister(ModuleContext moduleContext) {
registerParamScheme('intKeyRootModule');
registerParamScheme('people');
}
@override
void onJsonableRegister(ModuleContext moduleContext) {
registerJsonable<People>(JsonableBuilder<People>(
(obj) => obj.toJson(),
People.fromJson,
));
registerJsonable<House>(JsonableBuilder<House>(
(obj) => obj.toJson(),
House.fromJson,
));
registerJsonable<UserProfile>(JsonableBuilder<UserProfile>(
(obj) => obj.toJson(),
UserProfile.fromJson,
));
}
@override
void onJsonSerializerRegister(ModuleContext moduleContext) {
registerJsonSerializer<People>((i) => i<People>().toJson());
registerJsonSerializer<House>((i) => i<House>().toJson());
registerJsonSerializer<UserProfile>((i) => i<UserProfile>().toJson());
}
@override
void onJsonDeserializerRegister(ModuleContext moduleContext) {
registerJsonDeserializer(People.fromJson);
registerJsonDeserializer(House.fromJson);
registerJsonDeserializer(UserProfile.fromJson);
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src | mirrored_repositories/flutter_thrio/example/lib/src/biz/context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
extension Context on ModuleContext {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src | mirrored_repositories/flutter_thrio/example/lib/src/biz/route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'biz1/biz1.route.dart';
import 'biz2/biz2.route.dart';
final biz = AppRoute();
class AppRoute extends NavigatorRouteNode {
factory AppRoute() => _instance ??= AppRoute._();
AppRoute._() : super.home();
static AppRoute? _instance;
late final biz1 = Biz1Route(this);
late final biz2 = Biz2Route(this);
@override
String get name => 'biz';
/// 当登录成功后调用
///
/// `userName` user name of login user.
///
Future<bool> login({
int? uid,
required String userName,
String userToken = 'good token',
}) =>
ThrioNavigator.notify(
url: url,
name: 'login',
params: {
'uid': uid,
'userName': userName,
'userToken': userToken,
},
);
Future<bool> logout() => ThrioNavigator.notify(
url: url,
name: 'logout',
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/types/house.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:example/src/biz/types/people.dart';
import 'package:flutter_jsonable/flutter_jsonable.dart';
/// a struct description a house.
///
class House {
House({
this.address = '',
this.owner,
});
factory House.fromJson(Map<String, dynamic> json) => House(
address: getValueFromJsonOrNull<String>(json, 'address') ?? '',
owner: getValueFromJsonOrNull<People>(json, 'owner'),
);
factory House.copyWith(
House other, {
String? address,
People? owner,
}) {
final otherJson = other.toJson();
otherJson['address'] = address ?? otherJson['address'];
otherJson['owner'] = getJsonFromValue<People>(owner) ?? otherJson['owner'];
return House.fromJson(otherJson);
}
final String address;
final People? owner;
Map<String, dynamic> toJson() => <String, dynamic>{
'address': address,
'owner': getJsonFromValue<People>(owner),
};
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/types/user_profile.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_jsonable/flutter_jsonable.dart';
/// 结构体的注释
///
class UserProfile {
UserProfile({
this.uid = 2,
this.userName = '',
this.emailVerified = false,
this.mobileVerified = false,
this.userToken = '',
});
factory UserProfile.fromJson(Map<String, dynamic> json) => UserProfile(
userName: getValueFromJsonOrNull<String>(json, 'userName') ?? '',
emailVerified:
getValueFromJsonOrNull<bool>(json, 'emailVerified') ?? false,
mobileVerified:
getValueFromJsonOrNull<bool>(json, 'mobileVerified') ?? false,
userToken: getValueFromJsonOrNull<String>(json, 'userToken') ?? '',
);
factory UserProfile.copyWith(
UserProfile other, {
int? uid,
String? userName,
bool? emailVerified,
bool? mobileVerified,
String? userToken,
}) {
final otherJson = other.toJson();
otherJson['userName'] = userName ?? otherJson['userName'];
otherJson['emailVerified'] = emailVerified ?? otherJson['emailVerified'];
otherJson['mobileVerified'] = mobileVerified ?? otherJson['mobileVerified'];
otherJson['userToken'] = userToken ?? otherJson['userToken'];
return UserProfile.fromJson(otherJson)..uid = uid ?? other.uid;
}
int uid;
final String userName;
final bool emailVerified;
final bool mobileVerified;
final String userToken;
Map<String, dynamic> toJson() => <String, dynamic>{
'userName': userName,
'emailVerified': emailVerified,
'mobileVerified': mobileVerified,
'userToken': userToken,
};
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/types/people.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_jsonable/flutter_jsonable.dart';
/// a struct description a people
///
class People {
People({
this.name = '',
this.age = 10,
this.sex = '',
this.balance = 0.0,
this.wife,
this.aliases = const <String>[],
this.children = const <People>[],
this.parents = const <String, People>{},
});
factory People.fromJson(Map<String, dynamic> json) => People(
name: getValueFromJsonOrNull<String>(json, 'name') ?? '',
age: getValueFromJsonOrNull<int>(json, 'age') ?? 10,
sex: getValueFromJsonOrNull<String>(json, 'sex') ?? '',
wife: getValueFromJsonOrNull<People>(json, 'wife'),
children:
getListFromJsonOrNull<People>(json, 'children') ?? const <People>[],
parents: getMapFromJsonOrNull<People>(json, 'parents') ??
const <String, People>{},
);
factory People.copyWith(
People other, {
String? name,
int? age,
String? sex,
double? balance,
People? wife,
List<String>? aliases,
List<People>? children,
Map<String, People>? parents,
}) {
final otherJson = other.toJson();
otherJson['name'] = name ?? otherJson['name'];
otherJson['age'] = age ?? otherJson['age'];
otherJson['sex'] = sex ?? otherJson['sex'];
otherJson['wife'] = getJsonFromValue<People>(wife) ?? otherJson['wife'];
otherJson['children'] = getJsonFromList(children) ?? otherJson['children'];
otherJson['parents'] = getJsonFromMap(parents) ?? otherJson['parents'];
return People.fromJson(otherJson)
..balance = balance ?? other.balance
..aliases = aliases ?? other.aliases;
}
final String name;
final int age;
final String sex;
double balance;
final People? wife;
List<String> aliases;
final List<People> children;
final Map<String, People> parents;
Map<String, dynamic> toJson() => <String, dynamic>{
'name': name,
'age': age,
'sex': sex,
'wife': getJsonFromValue<People>(wife),
'children': getJsonFromList(children),
'parents': getJsonFromMap(parents),
};
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/notifies/logout_notify.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
// ignore_for_file: avoid_as
import 'package:flutter_thrio/flutter_thrio.dart';
typedef LogoutNotifyCallback = void Function();
class LogoutNotify extends NavigatorPageNotify {
LogoutNotify({
super.key,
required LogoutNotifyCallback onNotify,
required super.child,
}) : super(
name: 'logout',
onPageNotify: (_) => onNotify(),
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/notifies/login_notify.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
// ignore_for_file: avoid_as
import 'package:flutter_thrio/flutter_thrio.dart';
typedef LoginNotifyCallback = void Function({
int? uid,
String userName,
String userToken,
});
class LoginNotify extends NavigatorPageNotify {
LoginNotify({
super.key,
required LoginNotifyCallback onNotify,
int? uid,
String? userName,
String? userToken,
required super.child,
}) : super(
name: 'login',
onPageNotify: (params) => onNotify(
uid: params['uid'] as int?,
userName: params['userName'] as String,
userToken: params['userToken'] as String),
initialParams: uid == null && userName == null && userToken == null
? null
: {'uid': uid, 'userName': userName, 'userToken': userToken});
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/biz1.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
extension Biz1Context on ModuleContext {
/// get an int value.
///
int get intValue =>
get<int>('intValue') ?? (throw ArgumentError('intValue not exists'));
bool setIntValue(int value) => set<int>('intValue', value);
/// remove an int value.remove an int value.remove an int value.
///
int? removeIntValue() => remove<int>('intValue');
Stream<int> get onIntValue =>
on<int>('intValue') ??
(throw ArgumentError('intValue stream not exists'));
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter1/module.dart' as flutter1;
import 'flutter11/module.dart' as flutter11;
import 'flutter3/module.dart' as flutter3;
import 'flutter5/module.dart' as flutter5;
import 'flutter7/module.dart' as flutter7;
import 'flutter9/module.dart' as flutter9;
class Module with ThrioModule, ModuleParamScheme {
@override
String get key => 'biz1';
@override
void onModuleRegister(ModuleContext moduleContext) {
registerModule(flutter1.Module(), moduleContext);
registerModule(flutter3.Module(), moduleContext);
registerModule(flutter5.Module(), moduleContext);
registerModule(flutter7.Module(), moduleContext);
registerModule(flutter9.Module(), moduleContext);
registerModule(flutter11.Module(), moduleContext);
}
@override
void onParamSchemeRegister(ModuleContext moduleContext) {
registerParamScheme<int>('intValue');
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/biz1.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter1/flutter1.route.dart';
import 'flutter11/flutter11.route.dart';
import 'flutter3/flutter3.route.dart';
import 'flutter5/flutter5.route.dart';
import 'flutter7/flutter7.route.dart';
import 'flutter9/flutter9.route.dart';
class Biz1Route extends NavigatorRouteNode {
factory Biz1Route(NavigatorRouteNode parent) =>
_instance ??= Biz1Route._(parent);
Biz1Route._(super.parent);
static Biz1Route? _instance;
late final flutter1 = Flutter1Route(this);
late final flutter3 = Flutter3Route(this);
late final flutter5 = Flutter5Route(this);
late final flutter7 = Flutter7Route(this);
late final flutter9 = Flutter9Route(this);
late final flutter11 = Flutter11Route(this);
@override
String get name => 'biz1';
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter11/flutter11.page.dart | // Copyright (c) 2023 foxsofter.
//
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
import 'package:permission_handler/permission_handler.dart';
part 'flutter11.context.dart';
part 'flutter11.state.dart';
class Flutter11Page extends NavigatorStatefulPage {
const Flutter11Page({
super.key,
required super.moduleContext,
required super.settings,
});
@override
_Flutter11PageState createState() => _Flutter11PageState();
}
class _Flutter11PageState extends State<Flutter11Page> {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: const Text('thrio_deeplink_example',
style: TextStyle(color: Colors.black)),
leading: context.showPopAwareWidget(const IconButton(
color: Colors.black,
tooltip: 'back',
icon: Icon(Icons.arrow_back_ios),
onPressed: ThrioNavigator.pop,
)),
systemOverlayStyle: SystemUiOverlayStyle.dark,
),
body: const PermissionHandlerWidget());
}
class PermissionHandlerWidget extends StatefulWidget {
const PermissionHandlerWidget({super.key});
@override
_PermissionHandlerWidgetState createState() =>
_PermissionHandlerWidgetState();
}
class _PermissionHandlerWidgetState extends State<PermissionHandlerWidget> {
@override
Widget build(BuildContext context) => Center(
child: ListView(
children: Permission.values
.where((permission) {
if (Platform.isIOS) {
return permission != Permission.unknown &&
permission != Permission.phone &&
permission != Permission.sms &&
permission != Permission.ignoreBatteryOptimizations &&
permission != Permission.accessMediaLocation &&
permission != Permission.activityRecognition &&
permission != Permission.manageExternalStorage &&
permission != Permission.systemAlertWindow &&
permission != Permission.requestInstallPackages &&
permission != Permission.accessNotificationPolicy &&
permission != Permission.bluetoothScan &&
permission != Permission.bluetoothAdvertise &&
permission != Permission.bluetoothConnect &&
permission != Permission.nearbyWifiDevices &&
permission != Permission.videos &&
permission != Permission.audio &&
permission != Permission.scheduleExactAlarm &&
permission != Permission.sensorsAlways;
} else {
return permission != Permission.unknown &&
permission != Permission.mediaLibrary &&
permission != Permission.photosAddOnly &&
permission != Permission.reminders &&
permission != Permission.bluetooth &&
permission != Permission.appTrackingTransparency &&
permission != Permission.criticalAlerts;
}
})
.map(PermissionWidget.new)
.toList()),
);
}
/// Permission widget containing information about the passed [Permission]
class PermissionWidget extends StatefulWidget {
/// Constructs a [PermissionWidget] for the supplied [Permission]
const PermissionWidget(this._permission, {super.key});
final Permission _permission;
@override
_PermissionState createState() => _PermissionState();
}
class _PermissionState extends State<PermissionWidget> {
_PermissionState();
Permission get _permission => widget._permission;
PermissionStatus _permissionStatus = PermissionStatus.denied;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
}
Future<void> _listenForPermissionStatus() async {
final status = await _permission.status;
setState(() => _permissionStatus = status);
}
Color getPermissionColor() {
switch (_permissionStatus) {
case PermissionStatus.denied:
return Colors.red;
case PermissionStatus.granted:
return Colors.green;
case PermissionStatus.limited:
return Colors.orange;
default:
return Colors.grey;
}
}
@override
Widget build(BuildContext context) => ListTile(
title: Text(
_permission.toString(),
style: Theme.of(context).textTheme.bodyLarge,
),
subtitle: Text(
_permissionStatus.toString(),
style: TextStyle(color: getPermissionColor()),
),
trailing: (_permission is PermissionWithService)
? IconButton(
icon: const Icon(
Icons.info,
color: Colors.white,
),
onPressed: () {
checkServiceStatus(
context, _permission as PermissionWithService);
})
: null,
onTap: () {
requestPermission(_permission);
},
);
Future<void> checkServiceStatus(
BuildContext context, PermissionWithService permission) async {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text((await permission.serviceStatus).toString()),
));
}
Future<void> requestPermission(Permission permission) async {
final status = await permission.request();
setState(() {
debugPrint(status.toString());
_permissionStatus = status;
debugPrint(_permissionStatus.toString());
});
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter11/flutter11.state.dart | // Copyright (c) 2023 foxsofter.
//
// ignore_for_file: avoid_as
part of 'flutter11.page.dart';
extension Flutter11 on State<Flutter11Page> {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter11/flutter11.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
class Flutter11Route extends NavigatorRouteLeaf {
factory Flutter11Route(NavigatorRouteNode parent) =>
_instance ??= Flutter11Route._(parent);
Flutter11Route._(super.parent);
static Flutter11Route? _instance;
@override
String get name => 'flutter11';
Future<TPopParams?> push<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.push<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
Future<TPopParams?> pushSingle<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.pushSingle<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter11/flutter11.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
part of 'flutter11.page.dart';
extension Flutter11Context on ModuleContext {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter11/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter11.page.dart';
class Module with ThrioModule, ModulePageBuilder {
@override
String get key => 'flutter11';
@override
void onPageBuilderSetting(ModuleContext moduleContext) =>
pageBuilder = (settings) => Flutter11Page(
moduleContext: moduleContext,
settings: settings,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter9/flutter9.state.dart | // Copyright (c) 2023 foxsofter.
//
// ignore_for_file: avoid_as
part of 'flutter9.page.dart';
extension Flutter9 on State<Flutter9Page> {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter9/flutter9.page.dart | // Copyright (c) 2023 foxsofter.
//
import 'package:flutter/widgets.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
part 'flutter9.context.dart';
part 'flutter9.state.dart';
class Flutter9Page extends NavigatorStatefulPage {
const Flutter9Page({
super.key,
required super.moduleContext,
required super.settings,
});
@override
_Flutter9PageState createState() => _Flutter9PageState();
}
class _Flutter9PageState extends State<Flutter9Page>
with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
Widget get child => widget.getParam<Widget>('child');
@override
Widget build(BuildContext context) {
super.build(context);
return NavigatorPageLifecycle(
didAppear: (settings) {
ThrioLogger.v('flutter9 didAppear: ${settings.name}');
},
didDisappear: (settings) {
ThrioLogger.v('flutter9 didDisappear: ${settings.name}');
},
child: child);
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter9/flutter9.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
part of 'flutter9.page.dart';
extension Flutter9Context on ModuleContext {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter9/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter9.page.dart';
class Module with ThrioModule, ModulePageBuilder {
@override
String get key => 'flutter9';
@override
void onPageBuilderSetting(ModuleContext moduleContext) =>
pageBuilder = (settings) => Flutter9Page(
moduleContext: moduleContext,
settings: settings,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter9/flutter9.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
class Flutter9Route extends NavigatorRouteLeaf {
factory Flutter9Route(NavigatorRouteNode parent) =>
_instance ??= Flutter9Route._(parent);
Flutter9Route._(super.parent);
static Flutter9Route? _instance;
@override
String get name => 'flutter9';
Future<TPopParams?> push<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.push<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
Future<TPopParams?> pushSingle<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.pushSingle<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter5/flutter5.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
class Flutter5Route extends NavigatorRouteLeaf {
factory Flutter5Route(NavigatorRouteNode parent) =>
_instance ??= Flutter5Route._(parent);
Flutter5Route._(super.parent);
static Flutter5Route? _instance;
@override
String get name => 'flutter5';
Future<TPopParams?> push<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.push<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
Future<TPopParams?> pushSingle<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.pushSingle<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter5/flutter5.state.dart | // Copyright (c) 2023 foxsofter.
//
// ignore_for_file: avoid_as
part of 'flutter5.page.dart';
extension Flutter5 on State<Flutter5Page> {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter5/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter5.page.dart';
class Module with ThrioModule, ModulePageBuilder {
@override
String get key => 'flutter5';
@override
void onPageBuilderSetting(ModuleContext moduleContext) =>
pageBuilder = (settings) => Flutter5Page(
moduleContext: moduleContext,
settings: settings,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter5/flutter5.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
part of 'flutter5.page.dart';
extension Flutter5Context on ModuleContext {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter5/flutter5.page.dart | // Copyright (c) 2022 foxsofter.
//
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
import '../../route.dart';
part 'flutter5.context.dart';
part 'flutter5.state.dart';
class Flutter5Page extends NavigatorStatefulPage {
const Flutter5Page({
super.key,
required super.moduleContext,
required super.settings,
});
@override
_Flutter5PageState createState() => _Flutter5PageState();
}
class _Flutter5PageState extends State<Flutter5Page>
with NavigatorPageLifecycleMixin, AutomaticKeepAliveClientMixin {
@override
void dispose() {
ThrioLogger.d('page5 dispose: ${widget.settings.index}');
super.dispose();
}
@override
bool get wantKeepAlive => true;
@override
void didAppear(RouteSettings routeSettings) {
super.didAppear(routeSettings);
}
@override
void didDisappear(RouteSettings routeSettings) {
super.didDisappear(routeSettings);
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: const Text('page view example',
style: TextStyle(color: Colors.black)),
leading: context.showPopAwareWidget(const IconButton(
color: Colors.black,
tooltip: 'back',
icon: Icon(Icons.arrow_back_ios),
onPressed: ThrioNavigator.pop,
)),
systemOverlayStyle: SystemUiOverlayStyle.dark,
),
body: NavigatorPageLifecycle(
didAppear: (settings) {
ThrioLogger.v('page5 didAppear -> $settings');
},
didDisappear: (settings) {
ThrioLogger.v('page5 didDisappear -> $settings');
},
child: NavigatorPageView(
routeSettings: <RouteSettings>[
NavigatorRouteSettings.settingsWith(
url: biz.biz1.flutter1.home.url),
NavigatorRouteSettings.settingsWith(
url: biz.biz1.flutter3.url, index: 1),
NavigatorRouteSettings.settingsWith(
url: biz.biz1.flutter3.url, index: 2),
NavigatorRouteSettings.settingsWith(url: biz.biz1.flutter5.url),
],
)));
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter1.route_action.dart';
import 'home/module.dart' as home;
class Module with ThrioModule, ModuleRouteAction {
@override
void onRouteActionRegister(ModuleContext moduleContext) {
registerRouteAction('getPeople{intValue?}', <TParams, TResult>(
url,
action,
queryParams, {
params,
}) {
final result = onGetPeople(
moduleContext,
url,
action,
queryParams,
intValue: getValueOrNull<int>(params, 'intValue'),
);
if (result is Future<TResult?>) {
return result as Future<TResult?>;
} else if (result is TResult) {
return result as TResult;
}
return null;
});
registerRouteAction('getString{boolValue}', <TParams, TResult>(
url,
action,
queryParams, {
params,
}) {
final result = onGetString(
moduleContext,
url,
action,
queryParams,
boolValue: getValue<bool>(params, 'boolValue'),
);
if (result is Future<TResult?>) {
return result as Future<TResult?>;
} else if (result is TResult) {
return result as TResult;
}
return null;
});
}
@override
String get key => 'flutter1';
@override
void onModuleRegister(ModuleContext moduleContext) {
registerModule(home.Module(), moduleContext);
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/flutter1.route_action.dart | // Copyright (c) 2022 foxsofter.
//
import 'dart:async';
import 'package:example/src/biz/types/people.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
/// get people
///
FutureOr<People?> onGetPeople(
final ModuleContext moduleContext,
final String url,
final String action,
final Map<String, List<String>> queryParams, {
final int? intValue,
}) =>
Future.value(People(name: 'name', age: intValue ?? 1, sex: 'sex'));
/// get string
///
FutureOr<String?> onGetString(
final ModuleContext moduleContext,
final String url,
final String action,
final Map<String, List<String>> queryParams, {
final bool boolValue = false,
}) =>
'goodman';
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/flutter1.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
extension Flutter1Context on ModuleContext {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/flutter1.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:example/src/biz/types/people.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
import 'home/home.route.dart';
class Flutter1Route extends NavigatorRouteNode {
factory Flutter1Route(NavigatorRouteNode parent) =>
_instance ??= Flutter1Route._(parent);
Flutter1Route._(super.parent);
static Flutter1Route? _instance;
late final home = HomeRoute(this);
@override
String get name => 'flutter1';
/// 通知 flutter1
///
Future<bool> flutter1({required int intValue}) => ThrioNavigator.notify(
url: url,
name: 'flutter1',
params: intValue,
);
/// get people
///
Future<People?> getPeople({int? intValue}) =>
ThrioNavigator.act<Map<String, dynamic>, People>(
url: url,
action: 'getPeople{intValue?}',
params: {
'intValue': intValue,
},
);
/// get string
///
Future<String?> getString({required bool boolValue}) =>
ThrioNavigator.act<Map<String, dynamic>, String>(
url: url,
action: 'getString{boolValue}',
params: {
'boolValue': boolValue,
},
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/notifies/flutter1_notify.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
// ignore_for_file: avoid_as
import 'package:flutter_thrio/flutter_thrio.dart';
typedef Flutter1NotifyCallback = void Function({int intValue});
class Flutter1Notify extends NavigatorPageNotify {
Flutter1Notify({
super.key,
required Flutter1NotifyCallback onNotify,
int? intValue,
required super.child,
}) : super(
name: 'flutter1',
onPageNotify: (params) =>
onNotify(intValue: params['intValue'] as int),
initialParams: intValue == null ? null : {'intValue': intValue});
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/home/home.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
class HomeRoute extends NavigatorRouteLeaf {
factory HomeRoute(NavigatorRouteNode parent) =>
_instance ??= HomeRoute._(parent);
HomeRoute._(super.parent);
static HomeRoute? _instance;
@override
String get name => 'home';
/// `strList` hello, this is a list.
///
/// `goodMap` hello, this is a map.
///
/// 测试 集合 传参
///
Future<TPopParams?> push<TPopParams>({
List<String> strList = const <String>[],
Map<String, dynamic> goodMap = const <String, dynamic>{},
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.push<Map<String, dynamic>, TPopParams>(
url: url,
params: <String, dynamic>{
'strList': strList,
'goodMap': goodMap,
},
animated: animated,
result: result,
);
/// `strList` hello, this is a list.
///
/// `goodMap` hello, this is a map.
///
/// 测试 集合 传参
///
Future<TPopParams?> pushSingle<TPopParams>({
List<String> strList = const <String>[],
Map<String, dynamic> goodMap = const <String, dynamic>{},
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.pushSingle<Map<String, dynamic>, TPopParams>(
url: url,
params: <String, dynamic>{
'strList': strList,
'goodMap': goodMap,
},
animated: animated,
result: result,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/home/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'home.page.dart';
class Module with ThrioModule, ModuleParamScheme, ModulePageBuilder {
@override
String get key => 'home';
@override
void onPageBuilderSetting(ModuleContext moduleContext) =>
pageBuilder = (settings) => HomePage(
moduleContext: moduleContext,
settings: settings,
);
@override
void onParamSchemeRegister(ModuleContext moduleContext) {
registerParamScheme('stringKeyBiz1');
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/home/home.state.dart | // Copyright (c) 2023 foxsofter.
//
// ignore_for_file: avoid_as
part of 'home.page.dart';
extension Home on State<HomePage> {
/// hello, this is a list.
///
List<String> get strList => widget.getListParam<String>('strList');
/// hello, this is a map.
///
Map<String, dynamic> get goodMap =>
widget.getMapParam<String, dynamic>('goodMap');
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/home/home.page.dart | // Copyright (c) 2022 foxsofter.
//
// ignore_for_file: prefer_mixin
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_thrio/flutter_thrio.dart';
import 'package:image_picker/image_picker.dart';
import '../../../route.dart';
import '../../../types/people.dart';
import '../notifies/flutter1_notify.dart';
part 'home.state.dart';
part 'home.context.dart';
class HomePage extends NavigatorStatefulPage {
const HomePage({
super.key,
required super.moduleContext,
required super.settings,
});
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with
NavigatorPageLifecycleMixin,
AutomaticKeepAliveClientMixin,
WidgetsBindingObserver {
late final TextEditingController _inputController = TextEditingController();
@override
void initState() {
super.initState();
if (mounted) {
WidgetsBinding.instance.addObserver(this);
widget.moduleContext.onStringKeyBiz1.listen((i) {
ThrioLogger.v('onIntKeyRootModule value is $i');
});
}
}
@override
void dispose() {
ThrioLogger.d('page1 dispose: ${widget.settings.index}');
_inputController.dispose();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
Future<bool> didPopRoute() async {
ThrioLogger.v('didPopRoute: flutter 1');
return false;
}
@override
bool get wantKeepAlive => true;
@override
void didAppear(RouteSettings routeSettings) {
super.didAppear(routeSettings);
}
@override
void didDisappear(RouteSettings routeSettings) {
super.didDisappear(routeSettings);
}
@override
Widget build(BuildContext context) {
super.build(context);
return NavigatorRoutePush(
onPush: (settings, {animated = true}) async {
// root.biz1.flutter1.home.replace(newUrl: root.biz2.flutter2.url);
if (settings.url == biz.biz2.flutter2.url) {
ThrioLogger.d('page2 onPush');
}
return NavigatorRoutePushHandleType.none;
},
child: NavigatorPageNotify(
name: 'all_page_notify',
onPageNotify: (params) =>
ThrioLogger.v('flutter1 receive all page notify:$params'),
child: Flutter1Notify(
onNotify: ({intValue = 0}) =>
ThrioLogger.v('flutter1 receive notify:$intValue'),
child: Scaffold(
appBar: PreferredSize(
preferredSize: Platform.isIOS
? const Size.fromHeight(44)
: const Size.fromHeight(56),
child: AppBar(
backgroundColor: Colors.blue,
title: const Text('thrio_example',
style: TextStyle(color: Colors.black)),
leading: context.showPopAwareWidget(const IconButton(
color: Colors.black,
tooltip: 'back',
icon: Icon(Icons.arrow_back_ios),
onPressed: ThrioNavigator.pop,
)),
systemOverlayStyle: SystemUiOverlayStyle.dark,
)),
body: SingleChildScrollView(
child: Container(
margin: const EdgeInsets.all(24),
child: Column(children: <Widget>[
Container(
margin: const EdgeInsets.only(top: 10, bottom: 20),
alignment: AlignmentDirectional.center,
child: Text(
'flutter1: index is ${widget.settings.index}',
style: const TextStyle(
fontSize: 28, color: Colors.blue),
),
),
SizedBox(
height: 25,
width: 100,
child: TextField(
controller: _inputController,
textInputAction: TextInputAction.done,
// onSubmitted: onSubmitted,
decoration: const InputDecoration(
hintText: 'hintText',
contentPadding: EdgeInsets.only(bottom: 12),
border: InputBorder.none,
),
onChanged: print)),
InkWell(
onTap: () {
final mtx = NavigatorPage.moduleContextOf(context);
ThrioLogger.v('$mtx');
final murl = NavigatorPage.urlOf(context);
ThrioLogger.v(murl);
final rmtx = NavigatorPage.moduleContextOf(context,
pageModuleContext: true);
ThrioLogger.v('$rmtx');
final rmurl = NavigatorPage.urlOf(context,
pageModuleContext: true);
ThrioLogger.v(rmurl);
if (widget.moduleContext
.setStringKeyBiz1(_inputController.text)) {
final value = widget.moduleContext.stringKeyBiz1;
ThrioLogger.v('stringKeyBiz1 value is $value');
}
if (widget.moduleContext
.setIntKeyRootModule(10000)) {
final value =
widget.moduleContext.intKeyRootModule;
ThrioLogger.v('intKeyRootModule value is $value');
}
widget.moduleContext.setStringKeyBiz1('value');
final value =
widget.moduleContext.get('people_from_native');
ThrioLogger.v('people_from_native value is $value');
},
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.yellow,
child: const Text(
'set module context',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () async {
final params = await biz.biz1.flutter1.home.push(
strList: <String>['foxsofter', 'sex', '男性'],
goodMap: <String, dynamic>{'good': 'man'});
ThrioLogger.v('/biz1/flutter1 strList:$strList');
ThrioLogger.v('/biz1/flutter1 goodMap:$goodMap');
ThrioLogger.v('/biz1/flutter1 popped:$params');
},
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.yellow,
child: const Text(
'push flutter1',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: biz.biz1.flutter1.home.remove,
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.yellow,
child: const Text(
'remove flutter1',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () async {
// Future.delayed(const Duration(seconds: 10), () {
// ThrioNavigator.pop(params: 'fsfwfwfw');
// });
// unawaited(ThrioNavigator.pop());
final params = await ThrioNavigator.push(
url:
'${biz.biz2.flutter2.url}?fewfew=2131&fwe=1&&',
params: People(name: '大宝剑', age: 0, sex: 'x'),
animated: false,
result: (index) {
ThrioLogger.v('test_async_queue: push $index');
},
);
ThrioLogger.v(
'${biz.biz2.flutter2.url} poppedResult call popped:$params');
},
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.yellow,
child: const Text(
'push flutter2',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () => ThrioNavigator.pop(
params: People(name: '大宝剑', age: 0, sex: 'x')),
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.yellow,
child: const Text(
'pop',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () async {
final params = await ThrioNavigator.push(
url: '/biz1/native1',
params: People(name: '大宝剑', sex: 'x'),
);
ThrioLogger.v(
'/biz1/native1 poppedResult call params:$params');
},
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.grey,
child: const Text(
'push native1',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () => ThrioNavigator.notify(
url: '/biz1/native1',
name: 'aaa',
params: {
'1': {'2': '3'}
},
),
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.grey,
child: const Text(
'notify native1',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () =>
ThrioNavigator.remove(url: '/biz1/native1'),
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.grey,
child: const Text(
'remove native1',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () => ThrioNavigator.replace(
url: biz.biz1.flutter1.home.url,
newUrl: biz.biz2.flutter2.url,
),
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.grey,
child: const Text(
'replace flutter2',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () async {
final canPop = await ThrioNavigator.canPop();
debugPrint('canPop: $canPop');
},
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.grey,
child: const Text(
'canPop',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
InkWell(
onTap: () async {
final picker = ImagePicker();
final images = await picker.pickMultiImage();
if (images.isEmpty) {}
debugPrint('images: ${images.length}');
},
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
color: Colors.grey,
child: const Text(
'pick image',
style: TextStyle(
fontSize: 22, color: Colors.black),
)),
),
]),
),
)))),
);
}
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter1/home/home.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
part of 'home.page.dart';
extension HomeContext on ModuleContext {
String get stringKeyBiz1 =>
get<String>('stringKeyBiz1') ??
(throw ArgumentError('stringKeyBiz1 not exists'));
String? get stringKeyBiz1OrNull => get<String>('stringKeyBiz1');
String get stringKeyBiz1OrDefault => get<String>('stringKeyBiz1') ?? 'weewr';
bool setStringKeyBiz1(String value) => set<String>('stringKeyBiz1', value);
String? removeStringKeyBiz1() => remove<String>('stringKeyBiz1');
Stream<String> get onStringKeyBiz1 =>
on<String>('stringKeyBiz1') ??
(throw ArgumentError('stringKeyBiz1 stream not exists'));
Stream<String?> get onStringKeyBiz1WithNull =>
onWithNull<String>('stringKeyBiz1') ??
(throw ArgumentError('stringKeyBiz1 stream not exists'));
Stream<String> get onStringKeyBiz1WithInitial =>
on<String>('stringKeyBiz1', initialValue: 'weewr') ??
(throw ArgumentError('stringKeyBiz1 stream not exists'));
int get intKeyRootModule =>
get<int>('intKeyRootModule') ??
(throw ArgumentError('intKeyRootModule not exists'));
bool setIntKeyRootModule(int value) => set<int>('intKeyRootModule', value);
Stream<int> get onIntKeyRootModule =>
on<int>('intKeyRootModule') ??
(throw ArgumentError('intKeyRootModule stream not exists'));
Stream<int?> get onIntKeyRootModuleWithNull =>
onWithNull<int>('intKeyRootModule') ??
(throw ArgumentError('intKeyRootModule stream not exists'));
Stream<int> onIntKeyRootModuleWithInitial({required int initialValue}) =>
on<int>('intKeyRootModule', initialValue: initialValue) ??
(throw ArgumentError('intKeyRootModule stream not exists'));
People get people =>
get<People>('people') ?? (throw ArgumentError('people not exists'));
People? get peopleOrNull => get<People>('people');
People getPeopleOrDefault({required People defaultValue}) =>
get<People>('people') ?? defaultValue;
bool setPeople(People value) => set<People>('people', value);
People? removePeople() => remove<People>('people');
Stream<People> get onPeople =>
on<People>('people') ?? (throw ArgumentError('people stream not exists'));
Stream<People?> get onPeopleWithNull =>
onWithNull<People>('people') ??
(throw ArgumentError('people stream not exists'));
Stream<People> onPeopleWithInitial({required People initialValue}) =>
on<People>('people', initialValue: initialValue) ??
(throw ArgumentError('people stream not exists'));
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter7/flutter7.context.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
part of 'flutter7.page.dart';
extension Flutter7Context on ModuleContext {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter7/flutter7.route.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
class Flutter7Route extends NavigatorRouteLeaf {
factory Flutter7Route(NavigatorRouteNode parent) =>
_instance ??= Flutter7Route._(parent);
Flutter7Route._(super.parent);
static Flutter7Route? _instance;
@override
String get name => 'flutter7';
Future<TPopParams?> push<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.push<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
Future<TPopParams?> pushSingle<TParams, TPopParams>({
TParams? params,
bool animated = true,
NavigatorIntCallback? result,
}) =>
ThrioNavigator.pushSingle<TParams, TPopParams>(
url: url,
params: params,
animated: animated,
result: result,
);
}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter7/flutter7.state.dart | // Copyright (c) 2023 foxsofter.
//
// ignore_for_file: avoid_as
part of 'flutter7.page.dart';
extension Flutter7 on State<Flutter7Page> {}
| 0 |
mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1 | mirrored_repositories/flutter_thrio/example/lib/src/biz/biz1/flutter7/module.dart | // Copyright (c) 2023 foxsofter.
//
// Do not edit this file.
//
import 'package:flutter_thrio/flutter_thrio.dart';
import 'flutter7.page.dart';
class Module with ThrioModule, ModulePageBuilder {
@override
String get key => 'flutter7';
@override
void onPageBuilderSetting(ModuleContext moduleContext) =>
pageBuilder = (settings) => Flutter7Page(
moduleContext: moduleContext,
settings: settings,
);
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.