Commit db7ca34a authored by justin's avatar justin Committed by GitHub

Merge pull request #663 from AlexVincent525/master

Update format according for flutter's analysis option
parents cdc08394 d9ee0cfe
......@@ -20,6 +20,7 @@
analyzer:
strong-mode:
implicit-casts: false
implicit-dynamic: false
errors:
# treat missing required parameters as a warning (not a hint)
......@@ -38,9 +39,7 @@ analyzer:
# see https://github.com/dart-lang/sdk/issues/28463
- "lib/i18n/messages_*.dart"
- "lib/src/http/**"
- "example/**"
- "example_swift/**"
- "test/**"
linter:
rules:
# these rules are documented on and in the same order as
......@@ -60,6 +59,7 @@ linter:
- avoid_classes_with_only_static_members
# - avoid_double_and_int_checks # only useful when targeting JS runtime
- avoid_empty_else
- avoid_equals_and_hash_code_on_mutable_classes
- avoid_field_initializers_in_const_classes
- avoid_function_literals_in_foreach_calls
# - avoid_implementing_value_types # not yet tested
......@@ -67,7 +67,9 @@ linter:
# - avoid_js_rounded_ints # only useful when targeting JS runtime
- avoid_null_checks_in_equality_operators
# - avoid_positional_boolean_parameters # not yet tested
# - avoid_print # not yet tested
# - avoid_private_typedef_functions # we prefer having typedef (discussion in https://github.com/flutter/flutter/pull/16356)
# - avoid_redundant_argument_values # not yet tested
- avoid_relative_lib_imports
- avoid_renaming_method_parameters
- avoid_return_types_on_setters
......@@ -77,13 +79,16 @@ linter:
# - avoid_returning_this # there are plenty of valid reasons to return this
# - avoid_setters_without_getters # not yet tested
# - avoid_shadowing_type_parameters # not yet tested
# - avoid_single_cascade_in_expression_statements # not yet tested
- avoid_single_cascade_in_expression_statements
- avoid_slow_async_io
- avoid_types_as_parameter_names
# - avoid_types_on_closure_parameters # conflicts with always_specify_types
# - avoid_unnecessary_containers # not yet tested
- avoid_unused_constructor_parameters
- avoid_void_async
# - avoid_web_libraries_in_flutter # not yet tested
- await_only_futures
- camel_case_extensions
- camel_case_types
- cancel_subscriptions
# - cascade_invocations # not yet tested
......@@ -109,8 +114,11 @@ linter:
# - lines_longer_than_80_chars # not yet tested
- list_remove_unrelated_type
# - literal_only_boolean_expressions # too many false positives: https://github.com/dart-lang/sdk/issues/34181
# - missing_whitespace_between_adjacent_strings # not yet tested
- no_adjacent_strings_in_list
- no_duplicate_case_values
# - no_logic_in_create_state # not yet tested
# - no_runtimeType_toString # not yet tested
- non_constant_identifier_names
# - null_closures # not yet tested
# - omit_local_variable_types # opposite of always_specify_types
......@@ -136,9 +144,9 @@ linter:
- prefer_equal_for_default_values
# - prefer_expression_function_bodies # conflicts with https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#consider-using--for-short-functions-and-methods
- prefer_final_fields
# - prefer_final_in_for_each # not yet tested
- prefer_final_in_for_each
- prefer_final_locals
# - prefer_for_elements_to_map_fromIterable # not yet tested
- prefer_for_elements_to_map_fromIterable
- prefer_foreach
# - prefer_function_declarations_over_variables # not yet tested
- prefer_generic_function_type_aliases
......@@ -150,9 +158,11 @@ linter:
# - prefer_interpolation_to_compose_strings # not yet tested
- prefer_is_empty
- prefer_is_not_empty
- prefer_is_not_operator
- prefer_iterable_whereType
# - prefer_mixin # https://github.com/dart-lang/language/issues/32
# - prefer_null_aware_operators # disable until NNBD, see https://github.com/flutter/flutter/pull/32711#issuecomment-492930932
# - prefer_relative_imports # not yet tested
- prefer_single_quotes
- prefer_spread_collections
- prefer_typing_uninitialized_variables
......@@ -173,6 +183,7 @@ linter:
# - unnecessary_await_in_return # not yet tested
- unnecessary_brace_in_string_interps
- unnecessary_const
# - unnecessary_final # conflicts with prefer_final_locals
- unnecessary_getters_setters
# - unnecessary_lambdas # has false positives: https://github.com/dart-lang/linter/issues/498
- unnecessary_new
......@@ -181,14 +192,16 @@ linter:
- unnecessary_overrides
- unnecessary_parenthesis
- unnecessary_statements
# - unnecessary_string_interpolations
- unnecessary_this
- unrelated_type_equality_checks
# - unsafe_html # not yet tested
- use_full_hex_values_for_flutter_colors
# - use_function_type_syntax_for_parameters # not yet tested
# - use_key_in_widget_constructors # not yet tested
- use_rethrow_when_possible
# - use_setters_to_change_properties # not yet tested
# - use_string_buffers # has false positives: https://github.com/dart-lang/sdk/issues/34182
# - use_to_and_as_if_applicable # has false positives, so we prefer to catch this by code-review
- valid_regexps
# - void_checks # not yet tested
- void_checks
\ No newline at end of file
......@@ -16,20 +16,26 @@ class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
FlutterBoost.singleton.registerPageBuilders({
'embeded': (pageName, params, _)=>EmbededFirstRouteWidget(),
'first': (pageName, params, _) => FirstRouteWidget(),
'firstFirst': (pageName, params, _) => FirstFirstRouteWidget(),
'second': (pageName, params, _) => SecondRouteWidget(),
'secondStateful': (pageName, params, _) => SecondStatefulRouteWidget(),
'tab': (pageName, params, _) => TabRouteWidget(),
'platformView': (pageName, params, _) => PlatformRouteWidget(),
'flutterFragment': (pageName, params, _) => FragmentRouteWidget(params),
FlutterBoost.singleton.registerPageBuilders(<String, PageBuilder>{
'embeded': (String pageName, Map<String, dynamic> params, String _) =>
EmbeddedFirstRouteWidget(),
'first': (String pageName, Map<String, dynamic> params, String _) => FirstRouteWidget(),
'firstFirst': (String pageName, Map<String, dynamic> params, String _) =>
FirstFirstRouteWidget(),
'second': (String pageName, Map<String, dynamic> params, String _) => SecondRouteWidget(),
'secondStateful': (String pageName, Map<String, dynamic> params, String _) =>
SecondStatefulRouteWidget(),
'tab': (String pageName, Map<String, dynamic> params, String _) => TabRouteWidget(),
'platformView': (String pageName, Map<String, dynamic> params, String _) =>
PlatformRouteWidget(),
'flutterFragment': (String pageName, Map<String, dynamic> params, String _) =>
FragmentRouteWidget(params),
///可以在native层通过 getContainerParams 来传递参数
'flutterPage': (pageName, params, _) {
print("flutterPage params:$params");
'flutterPage': (String pageName, Map<String, dynamic> params, String _) {
print('flutterPage params:$params');
return FlutterRouteWidget(params:params);
return FlutterRouteWidget(params: params);
},
});
FlutterBoost.singleton.addBoostNavigatorObserver(TestBoostNavigatorObserver());
......@@ -40,31 +46,36 @@ class _MyAppState extends State<MyApp> {
return MaterialApp(
title: 'Flutter Boost example',
builder: FlutterBoost.init(postPush: _onRoutePushed),
home: Container(
color:Colors.white
));
home: Container(color: Colors.white));
}
void _onRoutePushed(
String pageName, String uniqueId, Map params, Route route, Future _) {
}
String pageName,
String uniqueId,
Map<String, dynamic> params,
Route<dynamic> route,
Future<dynamic> _,
) {}
}
class TestBoostNavigatorObserver extends NavigatorObserver{
void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
print("flutterboost#didPush");
class TestBoostNavigatorObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
print('flutterboost#didPush');
}
@override
void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
print("flutterboost#didPop");
print('flutterboost#didPop');
}
@override
void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
print("flutterboost#didRemove");
print('flutterboost#didRemove');
}
@override
void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
print("flutterboost#didReplace");
print('flutterboost#didReplace');
}
}
......@@ -3,7 +3,7 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
typedef void TextViewCreatedCallback(TextViewController controller);
typedef TextViewCreatedCallback = void Function(TextViewController controller);
class TextView extends StatefulWidget {
const TextView({
......@@ -34,13 +34,13 @@ class _TextViewState extends State<TextView> {
if (widget.onTextViewCreated == null) {
return;
}
widget.onTextViewCreated(new TextViewController._(id));
widget.onTextViewCreated(TextViewController._(id));
}
}
class TextViewController {
TextViewController._(int id)
: _channel = new MethodChannel('plugins.felix.angelov/textview_$id');
: _channel = MethodChannel('plugins.felix.angelov/textview_$id');
final MethodChannel _channel;
......@@ -48,4 +48,4 @@ class TextViewController {
assert(text != null);
return _channel.invokeMethod('setText', text);
}
}
\ No newline at end of file
}
This diff is collapsed.
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
TestPage({Key key, this.title = "Input Test"}) : super(key: key);
const TestPage({
Key key,
this.title = 'Input Test',
}) : super(key: key);
final String title;
......@@ -18,95 +21,82 @@ class _TestPageState extends State<TestPage> {
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
appBar: AppBar(title: Text(widget.title)),
body: SafeArea(
bottom: false,
child: ListView(
children: <Widget>[
Container(
child: Text(
'You have pushed the button this many times:',
bottom: false,
child: ListView(
children: <Widget>[
Container(
child: const Text(
'You have pushed the button this many times:',
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
Container(
child: Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
Container(
child: Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
Container(
child: TextField(
minLines: 2,
maxLines: 10,
Container(
child: const TextField(minLines: 2, maxLines: 10),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
TestTextField(),
Container(
child: Container(
color: Colors.red,
width: double.infinity,
height: 128.0,
TestTextField(),
Container(
child: Container(
color: Colors.red,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.orange,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.orange,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.green,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.green,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.blue,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.blue,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.yellow,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.yellow,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: TextField(
minLines: 2,
maxLines: 10,
Container(
child: const TextField(minLines: 2, maxLines: 10),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
TestTextField(),
],
)),
TestTextField(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
......@@ -123,22 +113,22 @@ class TestTextField extends StatefulWidget {
class _TestTextFieldState extends State<TestTextField> {
FocusNode _node;
PersistentBottomSheetController _controller;
PersistentBottomSheetController<dynamic> _controller;
@override
void initState() {
// TODO: implement initState
super.initState();
_node = FocusNode();
_node.addListener(() {
if (_node.hasFocus) {
print('showBottomSheet');
_controller = Scaffold.of(context)
.showBottomSheet<dynamic>((BuildContext ctx) => Container(
width: double.infinity,
height: 36.0,
color: Colors.deepPurple,
));
_controller = Scaffold.of(context).showBottomSheet<dynamic>(
(BuildContext ctx) => Container(
width: double.infinity,
height: 36.0,
color: Colors.deepPurple,
),
);
} else {
if (_controller != null) {
//Navigator.of(context).pop();
......
......@@ -6,13 +6,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../lib/main.dart';
import 'package:flutter_boost_example/main.dart';
void main() {
testWidgets('Verify Platform version', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(new MyApp());
await tester.pumpWidget(MyApp());
// Verify that platform version is retrieved.
expect(
......
......@@ -16,17 +16,22 @@ class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
FlutterBoost.singleton.registerPageBuilders({
'first': (pageName, params, _) => FirstRouteWidget(),
'second': (pageName, params, _) => SecondRouteWidget(),
'tab': (pageName, params, _) => TabRouteWidget(),
'flutterFragment': (pageName, params, _) => FragmentRouteWidget(params),
FlutterBoost.singleton.registerPageBuilders(<String, PageBuilder>{
'first': (String pageName, Map<String, dynamic> params, String _) =>
FirstRouteWidget(),
'second': (String pageName, Map<String, dynamic> params, String _) =>
SecondRouteWidget(),
'tab': (String pageName, Map<String, dynamic> params, String _) =>
TabRouteWidget(),
'flutterFragment':
(String pageName, Map<String, dynamic> params, String _) =>
FragmentRouteWidget(params),
///可以在native层通过 getContainerParams 来传递参数
'flutterPage': (pageName, params, _) {
print("flutterPage params:$params");
'flutterPage': (String pageName, Map<String, dynamic> params, String _) {
print('flutterPage params:$params');
return FlutterRouteWidget();
return const FlutterRouteWidget();
},
});
}
......@@ -34,12 +39,17 @@ class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Boost example',
builder: FlutterBoost.init(postPush: _onRoutePushed),
home: Container());
title: 'Flutter Boost example',
builder: FlutterBoost.init(postPush: _onRoutePushed),
home: Container(),
);
}
void _onRoutePushed(
String pageName, String uniqueId, Map params, Route route, Future _) {
}
String pageName,
String uniqueId,
Map<String, dynamic> params,
Route<dynamic> route,
Future<dynamic> _,
) {}
}
This diff is collapsed.
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
TestPage({Key key, this.title = "Input Test"}) : super(key: key);
const TestPage({
Key key,
this.title = 'Input Test',
}) : super(key: key);
final String title;
......@@ -18,100 +21,87 @@ class _TestPageState extends State<TestPage> {
});
}
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
appBar: AppBar(title: Text(widget.title)),
body: SafeArea(
bottom: false,
child: ListView(
children: <Widget>[
Container(
child: Text(
'You have pushed the button this many times:',
bottom: false,
child: ListView(
children: <Widget>[
Container(
child: const Text(
'You have pushed the button this many times:',
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
Container(
child: Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
Container(
child: Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
margin: const EdgeInsets.all(8.0),
alignment: Alignment.center,
),
Container(
child: TextField(
minLines: 2,
maxLines: 10,
Container(
child: const TextField(minLines: 2, maxLines: 10),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
TestTextField(),
Container(
child: Container(
color: Colors.red,
width: double.infinity,
height: 128.0,
TestTextField(),
Container(
child: Container(
color: Colors.red,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.orange,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.orange,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.green,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.green,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.blue,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.blue,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: Container(
color: Colors.yellow,
width: double.infinity,
height: 128.0,
Container(
child: Container(
color: Colors.yellow,
width: double.infinity,
height: 128.0,
),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
Container(
child: TextField(
minLines: 2,
maxLines: 10,
Container(
child: const TextField(minLines: 2, maxLines: 10),
padding: const EdgeInsets.all(8.0),
),
padding: const EdgeInsets.all(8.0),
),
TestTextField(),
],
)),
TestTextField(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
),
);
}
}
......@@ -123,25 +113,24 @@ class TestTextField extends StatefulWidget {
class _TestTextFieldState extends State<TestTextField> {
FocusNode _node;
PersistentBottomSheetController _controller;
PersistentBottomSheetController<dynamic> _controller;
@override
void initState() {
// TODO: implement initState
super.initState();
_node = FocusNode();
_node.addListener(() {
if (_node.hasFocus) {
print('showBottomSheet');
_controller = Scaffold.of(context)
.showBottomSheet<dynamic>((BuildContext ctx) => Container(
width: double.infinity,
height: 36.0,
color: Colors.deepPurple,
));
_controller = Scaffold.of(context).showBottomSheet<dynamic>(
(BuildContext ctx) => Container(
width: double.infinity,
height: 36.0,
color: Colors.deepPurple,
),
);
} else {
if (_controller != null) {
//Navigator.of(context).pop();
print('closeBottomSheet');
_controller.close();
}
......
......@@ -24,30 +24,30 @@
import 'dart:async';
import 'dart:ui';
import 'package:flutter/services.dart';
typedef Future<dynamic> EventListener(String name, Map arguments);
typedef Future<dynamic> MethodHandler(MethodCall call);
import 'package:flutter/services.dart';
class BoostChannel {
final MethodChannel _methodChannel = MethodChannel("flutter_boost");
typedef EventListener = Future<dynamic> Function(
String name, Map<String, dynamic> arguments);
final Map<String, List<EventListener>> _eventListeners = Map();
final Set<MethodHandler> _methodHandlers = Set();
typedef MethodHandler = Future<dynamic> Function(MethodCall call);
class BoostChannel {
BoostChannel() {
_methodChannel.setMethodCallHandler((MethodCall call) {
if (call.method == "__event__") {
String name = call.arguments["name"];
Map arg = call.arguments["arguments"];
List<EventListener> list = _eventListeners[name];
if (call.method == '__event__') {
final String name = call.arguments['name'] as String;
final Map<String, dynamic> arg =
(call.arguments['arguments'] as Map<dynamic, dynamic>)
?.cast<String, dynamic>();
final List<EventListener> list = _eventListeners[name];
if (list != null) {
for (EventListener l in list) {
for (final EventListener l in list) {
l(name, arg);
}
}
} else {
for (MethodHandler handler in _methodHandlers) {
for (final MethodHandler handler in _methodHandlers) {
handler(call);
}
}
......@@ -56,37 +56,41 @@ class BoostChannel {
});
}
void sendEvent(String name, Map arguments) {
final MethodChannel _methodChannel = const MethodChannel('flutter_boost');
final Map<String, List<EventListener>> _eventListeners =
<String, List<EventListener>>{};
final Set<MethodHandler> _methodHandlers = <MethodHandler>{};
void sendEvent(String name, Map<String, dynamic> arguments) {
if (name == null) {
return;
}
if (arguments == null) {
arguments = Map<dynamic, dynamic>();
}
arguments ??= <String, dynamic>{};
Map msg = Map<dynamic, dynamic>();
msg["name"] = name;
msg["arguments"] = arguments;
_methodChannel.invokeMethod<dynamic>("__event__", msg);
final Map<String, dynamic> msg = <String, dynamic>{};
msg['name'] = name;
msg['arguments'] = arguments;
_methodChannel.invokeMethod<dynamic>('__event__', msg);
}
Future<T> invokeMethod<T>(String method, [dynamic arguments]) async {
assert(method != "__event__");
assert(method != '__event__');
return _methodChannel.invokeMethod<T>(method, arguments);
}
Future<List<T>> invokeListMethod<T>(String method,
[dynamic arguments]) async {
assert(method != "__event__");
assert(method != '__event__');
return _methodChannel.invokeListMethod<T>(method, arguments);
}
Future<Map<K, V>> invokeMapMethod<K, V>(String method,
[dynamic arguments]) async {
assert(method != "__event__");
assert(method != '__event__');
return _methodChannel.invokeMapMethod<K, V>(method, arguments);
}
......@@ -94,9 +98,11 @@ class BoostChannel {
VoidCallback addEventListener(String name, EventListener listener) {
assert(name != null && listener != null);
List<EventListener> list = _eventListeners[name];
List<EventListener> list;
list = _eventListeners[name];
if (list == null) {
list = List();
list = <EventListener>[];
_eventListeners[name] = list;
}
......
......@@ -22,10 +22,11 @@
* THE SOFTWARE.
*/
import 'package:flutter/material.dart';
import 'container_manager.dart';
import '../flutter_boost.dart';
import 'boost_page_route.dart';
import '../support/logger.dart';
import 'boost_page_route.dart';
import 'container_manager.dart';
enum ContainerLifeCycle {
Init,
......@@ -37,28 +38,31 @@ enum ContainerLifeCycle {
Foreground
}
typedef void BoostContainerLifeCycleObserver(
ContainerLifeCycle state, BoostContainerSettings settings);
typedef BoostContainerLifeCycleObserver = void Function(
ContainerLifeCycle state,
BoostContainerSettings settings,
);
class BoostContainer extends Navigator {
final BoostContainerSettings settings;
const BoostContainer(
{GlobalKey<BoostContainerState> key,
this.settings = const BoostContainerSettings(),
String initialRoute,
RouteFactory onGenerateRoute,
RouteFactory onUnknownRoute,
List<NavigatorObserver> observers})
: super(
key: key,
initialRoute: initialRoute,
onGenerateRoute: onGenerateRoute,
onUnknownRoute: onUnknownRoute,
observers: observers);
factory BoostContainer.copy(Navigator navigator,
[BoostContainerSettings settings = const BoostContainerSettings()]) =>
const BoostContainer({
GlobalKey<BoostContainerState> key,
this.settings = const BoostContainerSettings(),
String initialRoute,
RouteFactory onGenerateRoute,
RouteFactory onUnknownRoute,
List<NavigatorObserver> observers,
}) : super(
key: key,
initialRoute: initialRoute,
onGenerateRoute: onGenerateRoute,
onUnknownRoute: onUnknownRoute,
observers: observers,
);
factory BoostContainer.copy(
Navigator navigator, [
BoostContainerSettings settings = const BoostContainerSettings(),
]) =>
BoostContainer(
key: GlobalKey<BoostContainerState>(),
settings: settings,
......@@ -69,28 +73,34 @@ class BoostContainer extends Navigator {
);
factory BoostContainer.obtain(
Navigator navigator, BoostContainerSettings settings) =>
Navigator navigator,
BoostContainerSettings settings,
) =>
BoostContainer(
key: GlobalKey<BoostContainerState>(),
settings: settings,
onGenerateRoute: (RouteSettings routeSettings) {
if (routeSettings.name == '/') {
return BoostPageRoute<dynamic>(
pageName: settings.name,
params: settings.params,
uniqueId: settings.uniqueId,
animated: false,
settings: routeSettings,
builder: settings.builder);
} else {
return navigator.onGenerateRoute(routeSettings);
}
},
observers: <NavigatorObserver>[
ContainerNavigatorObserver.bindContainerManager(),
HeroController(),
],
onUnknownRoute: navigator.onUnknownRoute);
key: GlobalKey<BoostContainerState>(),
settings: settings,
onGenerateRoute: (RouteSettings routeSettings) {
if (routeSettings.name == '/') {
return BoostPageRoute<dynamic>(
pageName: settings.name,
params: settings.params,
uniqueId: settings.uniqueId,
animated: false,
settings: routeSettings,
builder: settings.builder,
);
} else {
return navigator.onGenerateRoute(routeSettings);
}
},
observers: <NavigatorObserver>[
ContainerNavigatorObserver.bindContainerManager(),
HeroController(),
],
onUnknownRoute: navigator.onUnknownRoute,
);
final BoostContainerSettings settings;
@override
BoostContainerState createState() => BoostContainerState();
......@@ -121,7 +131,7 @@ class BoostContainerState extends NavigatorState {
String get name => widget.settings.name;
Map get params => widget.settings.params;
Map<String, dynamic> get params => widget.settings.params;
BoostContainerSettings get settings => widget.settings;
......@@ -138,7 +148,7 @@ class BoostContainerState extends NavigatorState {
ContainerNavigatorObserver findContainerNavigatorObserver(
Navigator navigator) {
for (NavigatorObserver observer in navigator.observers) {
for (final NavigatorObserver observer in navigator.observers) {
if (observer is ContainerNavigatorObserver) {
return observer;
}
......@@ -153,11 +163,6 @@ class BoostContainerState extends NavigatorState {
backPressedHandler = () => maybePop();
}
@override
void didUpdateWidget(Navigator oldWidget) {
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
routerHistory.clear();
......@@ -172,7 +177,7 @@ class BoostContainerState extends NavigatorState {
@override
Future<bool> maybePop<T extends Object>([T result]) async {
final Route<T> route = routerHistory.last;
final Route<T> route = routerHistory.last as Route<T>;
final RoutePopDisposition disposition = await route.willPop();
if (mounted) {
switch (disposition) {
......@@ -199,7 +204,7 @@ class BoostContainerState extends NavigatorState {
}
if (canPop()) {
super.pop<T>(result);
super.pop<T>(result);
} else {
if (T is Map<String, dynamic>) {
FlutterBoost.singleton
......@@ -216,10 +221,10 @@ class BoostContainerState extends NavigatorState {
Route<T> newRoute;
if (FlutterBoost.containerManager.prePushRoute != null) {
newRoute = FlutterBoost.containerManager
.prePushRoute(name, uniqueId, params, route);
.prePushRoute<T>(name, uniqueId, params, route);
}
Future<T> future = super.push<T>(newRoute ?? route);
final Future<T> future = super.push<T>(newRoute ?? route);
routerHistory.add(route);
......@@ -233,25 +238,30 @@ class BoostContainerState extends NavigatorState {
VoidCallback addLifeCycleObserver(BoostContainerLifeCycleObserver observer) {
return FlutterBoost.singleton.addBoostContainerLifeCycleObserver(
(ContainerLifeCycle state, BoostContainerSettings settings) {
if (settings.uniqueId == uniqueId) {
observer(state, settings);
}
});
(
ContainerLifeCycle state,
BoostContainerSettings settings,
) {
if (settings.uniqueId == uniqueId) {
observer(state, settings);
}
},
);
}
}
class BoostContainerSettings {
const BoostContainerSettings({
this.uniqueId = 'default',
this.name = 'default',
this.params,
this.builder,
});
final String uniqueId;
final String name;
final Map params;
final Map<String, dynamic> params;
final WidgetBuilder builder;
const BoostContainerSettings(
{this.uniqueId = 'default',
this.name = 'default',
this.params,
this.builder});
}
class ContainerElement extends StatefulElement {
......@@ -259,13 +269,13 @@ class ContainerElement extends StatefulElement {
}
class ContainerNavigatorObserver extends NavigatorObserver {
static final Set<NavigatorObserver> boostObservers = Set<NavigatorObserver>();
ContainerNavigatorObserver();
factory ContainerNavigatorObserver.bindContainerManager() =>
ContainerNavigatorObserver();
static final Set<NavigatorObserver> boostObservers = <NavigatorObserver>{};
VoidCallback addBoostNavigatorObserver(NavigatorObserver observer) {
boostObservers.add(observer);
......@@ -278,28 +288,28 @@ class ContainerNavigatorObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
for (NavigatorObserver observer in boostObservers) {
for (final NavigatorObserver observer in boostObservers) {
observer.didPush(route, previousRoute);
}
}
@override
void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
for (NavigatorObserver observer in boostObservers) {
for (final NavigatorObserver observer in boostObservers) {
observer.didPop(route, previousRoute);
}
}
@override
void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
for (NavigatorObserver observer in boostObservers) {
for (final NavigatorObserver observer in boostObservers) {
observer.didRemove(route, previousRoute);
}
}
@override
void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
for (NavigatorObserver observer in boostObservers) {
for (final NavigatorObserver observer in boostObservers) {
observer.didReplace(newRoute: newRoute, oldRoute: oldRoute);
}
}
......
......@@ -25,26 +25,25 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
typedef Widget PageBuilder(String pageName, Map params, String uniqueId);
typedef PageBuilder = Widget Function(
String pageName, Map<String, dynamic> params, String uniqueId);
class BoostPageRoute<T> extends MaterialPageRoute<T> {
BoostPageRoute({
this.pageName,
this.params,
this.uniqueId,
this.animated,
WidgetBuilder builder,
RouteSettings settings,
}) : super(builder: builder, settings: settings);
final String pageName;
final String uniqueId;
final Map params;
final Map<String, dynamic> params;
final bool animated;
final WidgetBuilder builder;
final RouteSettings settings;
final Set<VoidCallback> backPressedListeners = Set<VoidCallback>();
BoostPageRoute(
{this.pageName,
this.params,
this.uniqueId,
this.animated,
this.builder,
this.settings})
: super(builder: builder, settings: settings);
final Set<VoidCallback> backPressedListeners = <VoidCallback>{};
static BoostPageRoute<T> of<T>(BuildContext context) {
final Route<T> route = ModalRoute.of(context);
......
This diff is collapsed.
......@@ -23,10 +23,11 @@
*/
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'boost_container.dart';
import 'container_coordinator.dart';
import '../flutter_boost.dart';
import '../support/logger.dart';
import 'boost_container.dart';
import 'container_coordinator.dart';
enum ContainerOperation { Push, Onstage, Pop, Remove }
......@@ -35,12 +36,16 @@ typedef BoostContainerObserver = void Function(
@immutable
class BoostContainerManager extends StatefulWidget {
const BoostContainerManager({
Key key,
this.initNavigator,
this.prePushRoute,
this.postPushRoute,
}) : super(key: key);
final Navigator initNavigator;
final PrePushRoute prePushRoute;
final PostPushRoute postPushRoute;
const BoostContainerManager(
{Key key, this.initNavigator, this.prePushRoute, this.postPushRoute})
: super(key: key);
@override
ContainerManagerState createState() => ContainerManagerState();
......@@ -76,15 +81,15 @@ class ContainerManagerState extends State<BoostContainerManager> {
bool get foreground => _foreground;
//Number of containers.
// Number of containers.
int get containerCounts => _offstage.length;
List<BoostContainer> get offstage => _offstage;
//Setting for current visible container.
// Setting for current visible container.
BoostContainerSettings get onstageSettings => _onstage.settings;
//Current visible container.
// Current visible container.
BoostContainerState get onstageContainer => _stateOf(_onstage);
BoostContainerState get subContainer =>
......@@ -118,8 +123,7 @@ class ContainerManagerState extends State<BoostContainerManager> {
}
BoostContainerState _stateOf(BoostContainer container) {
if (container.key != null &&
container.key is GlobalKey<BoostContainerState>) {
if (container.key is GlobalKey<BoostContainerState>) {
final GlobalKey<BoostContainerState> globalKey =
container.key as GlobalKey<BoostContainerState>;
return globalKey.currentState;
......@@ -133,7 +137,7 @@ class ContainerManagerState extends State<BoostContainerManager> {
void _onShownContainerChanged(String old, String now) {
Logger.log('onShownContainerChanged old:$old now:$now');
Map<String, dynamic> properties = new Map<String, dynamic>();
final Map<String, dynamic> properties = <String, dynamic>{};
properties['newName'] = now;
properties['oldName'] = old;
......@@ -149,7 +153,7 @@ class ContainerManagerState extends State<BoostContainerManager> {
}
if (_leastEntries != null && _leastEntries.isNotEmpty) {
for (_ContainerOverlayEntry entry in _leastEntries) {
for (final _ContainerOverlayEntry entry in _leastEntries) {
entry.remove();
}
}
......@@ -223,7 +227,7 @@ class ContainerManagerState extends State<BoostContainerManager> {
setState(() {});
for (BoostContainerObserver observer in FlutterBoost
for (final BoostContainerObserver observer in FlutterBoost
.singleton.observersHolder
.observersOf<BoostContainerObserver>()) {
observer(ContainerOperation.Onstage, _onstage.settings);
......@@ -265,7 +269,7 @@ class ContainerManagerState extends State<BoostContainerManager> {
setState(() {});
for (BoostContainerObserver observer in FlutterBoost
for (final BoostContainerObserver observer in FlutterBoost
.singleton.observersHolder
.observersOf<BoostContainerObserver>()) {
observer(ContainerOperation.Push, _onstage.settings);
......@@ -280,9 +284,11 @@ class ContainerManagerState extends State<BoostContainerManager> {
_onstage = _offstage.removeLast();
setState(() {});
for (BoostContainerObserver observer in FlutterBoost
final Set<BoostContainerObserver> observers = FlutterBoost
.singleton.observersHolder
.observersOf<BoostContainerObserver>()) {
.observersOf<BoostContainerObserver>();
for (final BoostContainerObserver observer in observers) {
observer(ContainerOperation.Pop, old.settings);
}
......@@ -294,32 +300,34 @@ class ContainerManagerState extends State<BoostContainerManager> {
pop();
} else {
final BoostContainer container = _offstage.firstWhere(
(BoostContainer container) => container.settings.uniqueId == uniqueId,
orElse: () => null);
(BoostContainer container) => container.settings.uniqueId == uniqueId,
orElse: () => null,
);
if (container != null) {
_offstage.remove(container);
setState(() {});
for (BoostContainerObserver observer in FlutterBoost
final Set<BoostContainerObserver> observers = FlutterBoost
.singleton.observersHolder
.observersOf<BoostContainerObserver>()) {
.observersOf<BoostContainerObserver>();
for (final BoostContainerObserver observer in observers) {
observer(ContainerOperation.Remove, container.settings);
}
Logger.log('ContainerObserver#2 didRemove');
}
}
return null;
}
bool canPop() => _offstage.isNotEmpty;
String dump() {
String info = 'onstage#:\n ${_onstage?.desc()}\noffstage#:';
String info;
info = 'onstage#:\n ${_onstage?.desc()}\noffstage#:';
for (BoostContainer container in _offstage.reversed) {
for (final BoostContainer container in _offstage.reversed) {
info = '$info\n ${container?.desc()}';
}
......@@ -328,21 +336,21 @@ class ContainerManagerState extends State<BoostContainerManager> {
}
class _ContainerOverlayEntry extends OverlayEntry {
bool _removed = false;
_ContainerOverlayEntry(BoostContainer container)
: super(
builder: (BuildContext ctx) => container,
opaque: true,
maintainState: true);
builder: (BuildContext ctx) => container,
opaque: true,
maintainState: true,
);
bool _removed = false;
@override
void remove() {
assert(!_removed);
if (_removed) {
return;
}
_removed = true;
super.remove();
}
......
......@@ -25,58 +25,78 @@ import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'container/boost_container.dart';
import 'container/container_manager.dart';
import 'channel/boost_channel.dart';
import 'container/boost_container.dart';
import 'container/container_coordinator.dart';
import 'container/container_manager.dart';
import 'observers_holders.dart';
export 'container/boost_container.dart';
export 'container/container_manager.dart';
typedef Widget PageBuilder(String pageName, Map params, String uniqueId);
typedef PageBuilder = Widget Function(
String pageName, Map<String, dynamic> params, String uniqueId);
typedef Route PrePushRoute(
String url, String uniqueId, Map params, Route route);
typedef PrePushRoute = Route<T> Function<T>(String url, String uniqueId,
Map<String, dynamic> params, Route<dynamic> route);
typedef void PostPushRoute(
String url, String uniqueId, Map params, Route route, Future result);
typedef PostPushRoute = void Function(
String url,
String uniqueId,
Map<String, dynamic> params,
Route<dynamic> route,
Future<dynamic> result,
);
class FlutterBoost {
FlutterBoost() {
ContainerCoordinator(_boostChannel);
}
static final FlutterBoost _instance = FlutterBoost();
final GlobalKey<ContainerManagerState> containerManagerKey =
GlobalKey<ContainerManagerState>();
final ObserversHolder _observersHolder = ObserversHolder();
final BoostChannel _boostChannel = BoostChannel();
static FlutterBoost get singleton => _instance;
static ContainerManagerState get containerManager =>
_instance.containerManagerKey.currentState;
static void onPageStart() {
WidgetsBinding.instance.addPostFrameCallback((_) {
singleton.channel.invokeMethod<Map>('pageOnStart').then((Map pageInfo) {
if (pageInfo == null || pageInfo.isEmpty) return;
final GlobalKey<ContainerManagerState> containerManagerKey =
GlobalKey<ContainerManagerState>();
final ObserversHolder _observersHolder = ObserversHolder();
final BoostChannel _boostChannel = BoostChannel();
if (pageInfo.containsKey("name") &&
pageInfo.containsKey("params") &&
pageInfo.containsKey("uniqueId")) {
static void onPageStart() {
WidgetsBinding.instance.addPostFrameCallback((Duration _) {
singleton.channel
.invokeMethod<Map<String, dynamic>>('pageOnStart')
.then((Map<String, dynamic> pageInfo) {
if (pageInfo?.isEmpty ?? true) {
return;
}
if (pageInfo.containsKey('name') &&
pageInfo.containsKey('params') &&
pageInfo.containsKey('uniqueId')) {
ContainerCoordinator.singleton.nativeContainerDidShow(
pageInfo["name"], pageInfo["params"], pageInfo["uniqueId"]);
pageInfo['name'] as String,
(pageInfo['params'] as Map<dynamic, dynamic>)
?.cast<String, dynamic>(),
pageInfo['uniqueId'] as String,
);
}
});
});
}
static TransitionBuilder init(
{TransitionBuilder builder,
PrePushRoute prePush,
PostPushRoute postPush}) {
static TransitionBuilder init({
TransitionBuilder builder,
PrePushRoute prePush,
PostPushRoute postPush,
}) {
if (Platform.isAndroid) {
onPageStart();
} else if (Platform.isIOS) {
// TODO(AlexVincent525): 未解之谜
assert(() {
() async {
onPageStart();
......@@ -89,10 +109,11 @@ class FlutterBoost {
assert(child is Navigator, 'child must be Navigator, what is wrong?');
final BoostContainerManager manager = BoostContainerManager(
key: _instance.containerManagerKey,
initNavigator: child,
prePushRoute: prePush,
postPushRoute: postPush);
key: _instance.containerManagerKey,
initNavigator: child as Navigator,
prePushRoute: prePush,
postPushRoute: postPush,
);
if (builder != null) {
return builder(context, manager);
......@@ -106,94 +127,95 @@ class FlutterBoost {
BoostChannel get channel => _boostChannel;
FlutterBoost() {
ContainerCoordinator(_boostChannel);
}
///Register a default page builder.
/// Register a default page builder.
void registerDefaultPageBuilder(PageBuilder builder) {
ContainerCoordinator.singleton.registerDefaultPageBuilder(builder);
}
///Register a map builders
/// Register a map builders
void registerPageBuilders(Map<String, PageBuilder> builders) {
ContainerCoordinator.singleton.registerPageBuilders(builders);
}
Future<Map<dynamic, dynamic>> open(String url,
{Map<dynamic, dynamic> urlParams, Map<dynamic, dynamic> exts}) {
Map<dynamic, dynamic> properties = new Map<dynamic, dynamic>();
properties["url"] = url;
properties["urlParams"] = urlParams;
properties["exts"] = exts;
return channel.invokeMethod<Map<dynamic, dynamic>>('openPage', properties);
Future<Map<String, dynamic>> open(
String url, {
Map<String, dynamic> urlParams,
Map<String, dynamic> exts,
}) {
final Map<String, dynamic> properties = <String, dynamic>{};
properties['url'] = url;
properties['urlParams'] = urlParams;
properties['exts'] = exts;
return channel.invokeMethod<Map<String, dynamic>>('openPage', properties);
}
Future<bool> close(String id,
{Map<dynamic, dynamic> result, Map<dynamic, dynamic> exts}) {
Future<bool> close(
String id, {
Map<String, dynamic> result,
Map<String, dynamic> exts,
}) {
assert(id != null);
BoostContainerSettings settings = containerManager?.onstageSettings;
Map<dynamic, dynamic> properties = new Map<dynamic, dynamic>();
final BoostContainerSettings settings = containerManager?.onstageSettings;
final Map<String, dynamic> properties = <String, dynamic>{};
if (exts == null) {
exts = Map<dynamic, dynamic>();
}
exts ??= <String, dynamic>{};
exts["params"] = settings.params;
exts['params'] = settings.params;
if (!exts.containsKey("animated")) {
exts["animated"] = true;
if (!exts.containsKey('animated')) {
exts['animated'] = true;
}
properties["uniqueId"] = id;
properties['uniqueId'] = id;
if (result != null) {
properties["result"] = result;
properties['result'] = result;
}
if (exts != null) {
properties["exts"] = exts;
properties['exts'] = exts;
}
return channel.invokeMethod<bool>('closePage', properties);
}
Future<bool> closeCurrent(
{Map<String, dynamic> result, Map<String, dynamic> exts}) {
BoostContainerSettings settings = containerManager?.onstageSettings;
if (exts == null) {
exts = Map<String, dynamic>();
}
exts["params"] = settings.params;
if (!exts.containsKey("animated")) {
exts["animated"] = true;
Future<bool> closeCurrent({
Map<String, dynamic> result,
Map<String, dynamic> exts,
}) {
final BoostContainerSettings settings = containerManager?.onstageSettings;
exts ??= <String, dynamic>{};
exts['params'] = settings.params;
if (!exts.containsKey('animated')) {
exts['animated'] = true;
}
return close(settings.uniqueId, result: result, exts: exts);
}
Future<bool> closeByContext(BuildContext context,
{Map<String, dynamic> result, Map<String, dynamic> exts}) {
BoostContainerSettings settings = containerManager?.onstageSettings;
if (exts == null) {
exts = Map<String, dynamic>();
}
exts["params"] = settings.params;
if (!exts.containsKey("animated")) {
exts["animated"] = true;
Future<bool> closeByContext(
BuildContext context, {
Map<String, dynamic> result,
Map<String, dynamic> exts,
}) {
final BoostContainerSettings settings = containerManager?.onstageSettings;
exts ??= <String, dynamic>{};
exts['params'] = settings.params;
if (!exts.containsKey('animated')) {
exts['animated'] = true;
}
return close(settings.uniqueId, result: result, exts: exts);
}
///register for Container changed callbacks
/// Register for Container changed callbacks
VoidCallback addContainerObserver(BoostContainerObserver observer) =>
_observersHolder.addObserver<BoostContainerObserver>(observer);
///register for Container lifecycle callbacks
/// Register for Container lifecycle callbacks
VoidCallback addBoostContainerLifeCycleObserver(
BoostContainerLifeCycleObserver observer) =>
_observersHolder.addObserver<BoostContainerLifeCycleObserver>(observer);
///register callbacks for Navigators push & pop
/// Register callbacks for [Navigator.push] & [Navigator.pop]
void addBoostNavigatorObserver(NavigatorObserver observer) =>
ContainerNavigatorObserver.boostObservers.add(observer);
}
......@@ -24,10 +24,10 @@
import 'dart:ui';
class ObserversHolder {
final Map<String, Set<dynamic>> _observers = Map<String, Set<dynamic>>();
final Map<String, Set<dynamic>> _observers = <String, Set<dynamic>>{};
VoidCallback addObserver<T>(T observer) {
final Set<T> set = _observers[T.toString()] ?? Set<T>();
final Set<T> set = _observers[T.toString()] as Set<T> ?? <T>{};
set.add(observer);
_observers[T.toString()] = set;
......@@ -40,5 +40,5 @@ class ObserversHolder {
void cleanObservers<T>(T observer) => _observers[T.toString()]?.clear();
Set<T> observersOf<T>() => _observers[T.toString()] ?? Set<T>();
Set<T> observersOf<T>() => _observers[T.toString()] as Set<T> ?? <T>{};
}
......@@ -27,7 +27,6 @@ class Logger {
print('FlutterBoost#$msg');
return true;
}());
//print('FlutterBoost=>$msg');
}
static void error(String msg) {
......
......@@ -17,42 +17,7 @@ dev_dependencies:
sdk: flutter
mockito: 4.1.1
# For information on the generic Dart part of this file, see the
# following page: https://www.dartlang.org/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
plugin:
androidPackage: com.idlefish.flutterboost
pluginClass: FlutterBoostPlugin
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.io/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.io/assets-and-images/#resolution-aware.
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.io/custom-fonts/#from-packages
import 'package:flutter_boost/channel/boost_channel.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_boost/channel/boost_channel.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
......@@ -22,13 +23,12 @@ void main() {
response = null;
test('sendEvent successfully', () async {
Map msg1 = Map<dynamic,dynamic>();
BoostChannel().sendEvent("name", msg1);
Map msg = Map<dynamic,dynamic>();
msg["name"] = "name";
msg["arguments"] = msg1;
final Map<String, dynamic> msg1 = <String, dynamic>{};
BoostChannel().sendEvent('name', msg1);
final Map<String, dynamic> msg = <String, dynamic>{};
msg['name'] = 'name';
msg['arguments'] = msg1;
expect(
log,
......@@ -36,13 +36,10 @@ void main() {
);
});
test('invokeMethod successfully', () async {
Map msg = <dynamic,dynamic>{};
msg["test"] = "test";
BoostChannel().invokeMethod<dynamic>("__event__1", msg);
// expect(e, isException);
final Map<String, dynamic> msg = <String, dynamic>{};
msg['test'] = 'test';
BoostChannel().invokeMethod<dynamic>('__event__1', msg);
expect(
log,
......@@ -50,11 +47,10 @@ void main() {
);
});
test('invokeListMethod successfully', () async {
Map msg = <dynamic,dynamic>{};
msg["test"] = "test";
var bb = await BoostChannel().invokeListMethod<dynamic>("__event__1", msg);
final Map<String, dynamic> msg = <String, dynamic>{};
msg['test'] = 'test';
await BoostChannel().invokeListMethod<dynamic>('__event__1', msg);
expect(
log,
......@@ -62,11 +58,10 @@ void main() {
);
});
test('invokeMapMethod successfully', () async {
Map msg = <dynamic,dynamic>{};
msg["test"] = "test";
BoostChannel().invokeMapMethod<dynamic,dynamic>("__event__1", msg);
final Map<String, dynamic> msg = <String, dynamic>{};
msg['test'] = 'test';
BoostChannel().invokeMapMethod<dynamic, dynamic>('__event__1', msg);
expect(
log,
......@@ -75,9 +70,9 @@ void main() {
});
test('invokeMapMethod successfully', () async {
Map msg = <dynamic,dynamic>{};
msg["test"] = "test";
BoostChannel().invokeMapMethod<dynamic,dynamic>("__event__1", msg);
final Map<String, dynamic> msg = <String, dynamic>{};
msg['test'] = 'test';
BoostChannel().invokeMapMethod<dynamic, dynamic>('__event__1', msg);
expect(
log,
......@@ -86,22 +81,24 @@ void main() {
});
test('addEventListener successfully', () async {
Function test = BoostChannel().addEventListener(
"addEventListener", (String name, Map arguments) async => "test");
print("xxx" + test.toString());
final VoidCallback test = BoostChannel().addEventListener(
'addEventListener',
(String name, Map<String, dynamic> arguments) async => 'test',
);
print('xxx' + test.toString());
expect(
test.toString(),
"Closure: () => Null",
'Closure: () => Null',
);
});
test('addMethodHandler successfully', () async {
Function test = BoostChannel().addMethodHandler((
MethodCall call) async => "test");
final VoidCallback test = BoostChannel().addMethodHandler(
(MethodCall call) async => 'test',
);
expect(
test.toString(),
"Closure: () => Null",
'Closure: () => Null',
);
});
});
......
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_boost/container/boost_container.dart';
// import 'package:flutter_boost/container/boost_container.dart';
import 'package:flutter_test/flutter_test.dart';
class FirstWidget extends StatelessWidget {
......@@ -149,11 +149,11 @@ void main() {
);
await tester.pumpWidget(widget);
await tester.pump(Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
await tester.tap(find.byKey(targetKey));
await tester.pump(Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(exception, isInstanceOf<FlutterError>());
expect('$exception',
......
......@@ -49,8 +49,8 @@ void main() {
testWidgets(
'obtain BoostPageRoute through the BoostPageRoute.of(context) method',
(WidgetTester tester) async {
dynamic boostPageRoute;
dynamic boostPageRouteFindByOfMethod;
BoostPageRoute<dynamic> boostPageRoute;
BoostPageRoute<dynamic> boostPageRouteFindByOfMethod;
await tester.pumpWidget(
MaterialApp(
......@@ -58,10 +58,11 @@ void main() {
boostPageRoute = BoostPageRoute<void>(
settings: settings,
builder: (BuildContext context) => Builder(
builder: (context) {
builder: (BuildContext context) {
return FloatingActionButton(
onPressed: () {
boostPageRouteFindByOfMethod = BoostPageRoute.of<dynamic>(context);
boostPageRouteFindByOfMethod =
BoostPageRoute.of<dynamic>(context);
},
);
},
......@@ -74,7 +75,7 @@ void main() {
await tester.tap(find.byType(FloatingActionButton));
await tester.pump(Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
// The route obtained from the ancestor node through the `of` method should be the same BoostPageRoute
// as the originally created BoostPageRoute
......@@ -85,15 +86,15 @@ void main() {
'try to find BoostPageRoute through the BoostPageRoute.of(context) method, '
'but it doesn\'t exist, the method should throw an Exception',
(WidgetTester tester) async {
dynamic contextCache;
BuildContext contextCache;
await tester.pumpWidget(
MaterialApp(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
settings: settings,
builder: (context) => Builder(
builder: (context) => FloatingActionButton(
builder: (BuildContext context) => Builder(
builder: (BuildContext context) => FloatingActionButton(
onPressed: () {
contextCache = context;
},
......@@ -104,7 +105,7 @@ void main() {
),
);
await tester.tap(find.byType(FloatingActionButton));
await tester.pump(Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(() => BoostPageRoute.of<dynamic>(contextCache), throwsException);
});
......@@ -112,8 +113,8 @@ void main() {
testWidgets(
'obtain BoostPageRoute through the BoostPageRoute.tryOf(context) method',
(WidgetTester tester) async {
dynamic boostPageRoute;
dynamic boostPageRouteFindByOfMethod;
BoostPageRoute<dynamic> boostPageRoute;
BoostPageRoute<dynamic> boostPageRouteFindByOfMethod;
await tester.pumpWidget(
MaterialApp(
......@@ -121,7 +122,7 @@ void main() {
boostPageRoute = BoostPageRoute<void>(
settings: settings,
builder: (BuildContext context) => Builder(
builder: (context) {
builder: (BuildContext context) {
return FloatingActionButton(
onPressed: () {
boostPageRouteFindByOfMethod =
......@@ -137,7 +138,7 @@ void main() {
);
await tester.tap(find.byType(FloatingActionButton));
await tester.pump(Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
// The route obtained from the ancestor node through the `tryOf` method should be the same BoostPageRoute
// as the originally created BoostPageRoute
......@@ -149,7 +150,7 @@ void main() {
'try to find BoostPageRoute through the BoostPageRoute.tryOf(context) method, '
'but it doesn\'t exist, the method should return null',
(WidgetTester tester) async {
dynamic boostPageRouteFindByOfMethod;
BoostPageRoute<dynamic> boostPageRouteFindByOfMethod;
await tester.pumpWidget(
MaterialApp(
......@@ -157,7 +158,7 @@ void main() {
return MaterialPageRoute<dynamic>(
settings: settings,
builder: (BuildContext context) => Builder(
builder: (context) {
builder: (BuildContext context) {
return FloatingActionButton(
onPressed: () {
boostPageRouteFindByOfMethod =
......@@ -172,7 +173,7 @@ void main() {
);
await tester.tap(find.byType(FloatingActionButton));
await tester.pump(Duration(seconds: 1));
await tester.pump(const Duration(seconds: 1));
expect(boostPageRouteFindByOfMethod, null);
});
......
......@@ -6,9 +6,6 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:flutter_boost/channel/boost_channel.dart';
import 'package:flutter_boost/container/container_coordinator.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'dart:typed_data';
class MockBoostChannel extends BoostChannel implements Mock {
MethodHandler get testHandler => _testHandler;
......@@ -17,40 +14,42 @@ class MockBoostChannel extends BoostChannel implements Mock {
MethodHandler _testHandler;
EventListener _testEventListener;
@override
VoidCallback addEventListener(String name, EventListener listener) {
_testEventListener = listener;
return super.addEventListener(name, listener);
}
@override
VoidCallback addMethodHandler(MethodHandler handler) {
_testHandler = handler;
return super.addMethodHandler(handler);
return super.addMethodHandler(handler);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
// const MessageCodec<dynamic> jsonMessage = JSONMessageCodec();
test('test onMethodCall', () async {
// Initialize all bindings because defaultBinaryMessenger.send() needs a window.
TestWidgetsFlutterBinding.ensureInitialized();
MockBoostChannel boostChannel = MockBoostChannel();
final MockBoostChannel boostChannel = MockBoostChannel();
ContainerCoordinator(boostChannel);
final Map arguments =<dynamic,dynamic> {};
arguments["pageName"] = "pageName";
arguments["params"] = <dynamic,dynamic>{};
arguments["uniqueId"] = "xxxxx";
final Map<String, dynamic> arguments = <String, dynamic>{};
arguments['pageName'] = 'pageName';
arguments['params'] = <dynamic, dynamic>{};
arguments['uniqueId'] = 'xxxxx';
MethodCall call = MethodCall('didInitPageContainer', arguments);
final MethodCall call = MethodCall('didInitPageContainer', arguments);
try {
boostChannel.testHandler(call);
} catch (e) {
expect(e, isAssertionError);
}
MethodCall call2 = MethodCall('willShowPageContainer', arguments);
final MethodCall call2 = MethodCall('willShowPageContainer', arguments);
try {
boostChannel.testHandler(call2);
......@@ -58,7 +57,7 @@ void main() {
expect(e, isNoSuchMethodError);
}
MethodCall call3 = MethodCall('didShowPageContainer', arguments);
final MethodCall call3 = MethodCall('didShowPageContainer', arguments);
try {
boostChannel.testHandler(call3);
......@@ -66,7 +65,8 @@ void main() {
expect(e, isNoSuchMethodError);
}
MethodCall call4 = MethodCall('willDisappearPageContainer', arguments);
final MethodCall call4 =
MethodCall('willDisappearPageContainer', arguments);
try {
boostChannel.testHandler(call4);
......@@ -74,7 +74,7 @@ void main() {
expect(e, isNoSuchMethodError);
}
MethodCall call5 = MethodCall('onNativePageResult', arguments);
final MethodCall call5 = MethodCall('onNativePageResult', arguments);
try {
boostChannel.testHandler(call5);
......@@ -82,14 +82,14 @@ void main() {
expect(e, isNoSuchMethodError);
}
MethodCall call6 = MethodCall('didDisappearPageContainer', arguments);
final MethodCall call6 = MethodCall('didDisappearPageContainer', arguments);
try {
boostChannel.testHandler(call6);
} catch (e) {
expect(e, isNoSuchMethodError);
}
MethodCall call7 = MethodCall('willDeallocPageContainer', arguments);
final MethodCall call7 = MethodCall('willDeallocPageContainer', arguments);
try {
boostChannel.testHandler(call7);
......@@ -97,35 +97,36 @@ void main() {
expect(e, isNoSuchMethodError);
}
Map arg = <dynamic,dynamic>{'type': 'backPressedCallback'};
final Map<String, dynamic> arg = <String, dynamic>{
'type': 'backPressedCallback'
};
try {
boostChannel.testEventListener("lifecycle", arg);
boostChannel.testEventListener('lifecycle', arg);
} catch (e) {
expect(e, isNoSuchMethodError);
}
Map arg2 = <dynamic,dynamic>{'type': 'foreground'};
final Map<String, dynamic> arg2 = <String, dynamic>{'type': 'foreground'};
try {
boostChannel.testEventListener("lifecycle", arg2);
boostChannel.testEventListener('lifecycle', arg2);
} catch (e) {
expect(e, isNoSuchMethodError);
}
Map arg3 = <dynamic,dynamic>{'type': 'background'};
final Map<String, dynamic> arg3 = <String, dynamic>{'type': 'background'};
try {
boostChannel.testEventListener("lifecycle", arg3);
boostChannel.testEventListener('lifecycle', arg3);
} catch (e) {
expect(e, isNoSuchMethodError);
}
Map arg4 = <dynamic,dynamic>{'type': 'scheduleFrame'};
final Map<String, dynamic> arg4 = <String, dynamic>{
'type': 'scheduleFrame'
};
try {
boostChannel.testEventListener("lifecycle", arg4);
boostChannel.testEventListener('lifecycle', arg4);
} catch (e) {
expect(e, isNoSuchMethodError);
}
});
}
This diff is collapsed.
import 'package:flutter_boost/container/container_manager.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_boost/container/container_manager.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('test onMethodCall', () async {
FlutterBoost.singleton.registerDefaultPageBuilder(
(String pageName, Map<String, dynamic> params, String _) =>
Container());
FlutterBoost.singleton.addContainerObserver(
(ContainerOperation operation, BoostContainerSettings settings) {},
);
FlutterBoost.singleton.addBoostContainerLifeCycleObserver(
(ContainerLifeCycle state, BoostContainerSettings settings) {},
);
FlutterBoost.singleton.addBoostNavigatorObserver(NavigatorObserver());
try {
FlutterBoost.singleton.open('url');
} catch (e) {
expect(e, isException);
}
try {
FlutterBoost.singleton.close('url');
} catch (e) {
expect(e, isNoSuchMethodError);
}
try {
FlutterBoost.singleton.closeCurrent(
result: <String, dynamic>{},
exts: <String, dynamic>{},
);
} catch (e) {
expect(e, isNoSuchMethodError);
}
// test('test onMethodCall', () async {
// FlutterBoost.singleton
// .registerDefaultPageBuilder((pageName, params, _) => Container());
// FlutterBoost.singleton.addContainerObserver(
// (ContainerOperation operation, BoostContainerSettings settings) {});
//
// FlutterBoost.singleton.addBoostContainerLifeCycleObserver(
// (ContainerLifeCycle state, BoostContainerSettings settings) {});
//
// FlutterBoost.singleton.addBoostNavigatorObserver(NavigatorObserver());
//
// try {
// FlutterBoost.singleton.open("url");
// } catch (e) {
// expect(e, isException);
// }
// try {
// FlutterBoost.singleton.close("url");
// } catch (e) {
// expect(e, isNoSuchMethodError);
// }
// try {
// FlutterBoost.singleton.closeCurrent(result: <String,dynamic>{}, exts: <String,dynamic>{});
// } catch (e) {
// expect(e, isNoSuchMethodError);
// }
//
// try {
// FlutterBoost.singleton.closeByContext(null, result: <String,dynamic>{}, exts: <String,dynamic>{});
// } catch (e) {
// expect(e, isNoSuchMethodError);
// }
// });
try {
FlutterBoost.singleton.closeByContext(
null,
result: <String, dynamic>{},
exts: <String, dynamic>{},
);
} catch (e) {
expect(e, isNoSuchMethodError);
}
});
}
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_boost/flutter_boost.dart';
import 'package:flutter_boost/container/container_coordinator.dart';
import 'package:flutter_test/flutter_test.dart';
import 'page_widgets.dart';
import 'package:flutter_boost/container/container_coordinator.dart';
class MyApp extends StatefulWidget {
@override
......@@ -15,14 +16,19 @@ class _MyAppState extends State<MyApp> {
void initState() {
super.initState();
FlutterBoost.singleton.registerPageBuilders({
'embeded': (pageName, params, _) => EmbededFirstRouteWidget(),
'first': (pageName, params, _) => FirstRouteWidget(),
'second': (pageName, params, _) => SecondRouteWidget(),
'tab': (pageName, params, _) => TabRouteWidget(),
'flutterFragment': (pageName, params, _) => FragmentRouteWidget(params),
'flutterPage': (pageName, params, _) {
print("flutterPage params:$params");
FlutterBoost.singleton.registerPageBuilders(<String, PageBuilder>{
'embeded': (String pageName, Map<String, dynamic> params, _) =>
EmbededFirstRouteWidget(),
'first': (String pageName, Map<String, dynamic> params, _) =>
FirstRouteWidget(),
'second': (String pageName, Map<String, dynamic> params, _) =>
SecondRouteWidget(),
'tab': (String pageName, Map<String, dynamic> params, _) =>
TabRouteWidget(),
'flutterFragment': (String pageName, Map<String, dynamic> params, _) =>
FragmentRouteWidget(params),
'flutterPage': (String pageName, Map<String, dynamic> params, _) {
print('flutterPage params:$params');
return FlutterRouteWidget(params: params);
},
......@@ -40,24 +46,33 @@ class _MyAppState extends State<MyApp> {
}
void _onRoutePushed(
String pageName, String uniqueId, Map params, Route route, Future _) {}
String pageName,
String uniqueId,
Map<String, dynamic> params,
Route<dynamic> route,
Future<dynamic> _,
) {}
}
class TestBoostNavigatorObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic> previousRoute) {
print("flutterboost#didPush");
print('flutterboost#didPush');
}
@override
void didPop(Route<dynamic> route, Route<dynamic> previousRoute) {
print("flutterboost#didPop");
print('flutterboost#didPop');
}
@override
void didRemove(Route<dynamic> route, Route<dynamic> previousRoute) {
print("flutterboost#didRemove");
print('flutterboost#didRemove');
}
@override
void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) {
print("flutterboost#didReplace");
print('flutterboost#didReplace');
}
}
......@@ -72,7 +87,7 @@ void main() {
);
//open firt page
ContainerCoordinator.singleton
.nativeContainerDidShow("first", <dynamic,dynamic>{}, "1000000");
.nativeContainerDidShow('first', <String, dynamic>{}, '1000000');
await tester.pump(const Duration(seconds: 1));
......@@ -80,7 +95,7 @@ void main() {
//open second page firt(1000000)->second(2000000)
ContainerCoordinator.singleton
.nativeContainerDidShow("second", <dynamic,dynamic>{}, "2000000");
.nativeContainerDidShow('second', <String, dynamic>{}, '2000000');
await tester.pump(const Duration(seconds: 1));
......@@ -89,7 +104,7 @@ void main() {
await tester.pump(const Duration(seconds: 1));
//close sencod page firt(1000000)
FlutterBoost.containerManager?.remove("2000000");
FlutterBoost.containerManager?.remove('2000000');
await tester.pump(const Duration(seconds: 1));
......@@ -97,7 +112,7 @@ void main() {
// second page ,but pageId is 2000001 firt(1000000)->second(2000001)
ContainerCoordinator.singleton
.nativeContainerDidShow("second", <dynamic,dynamic>{}, "2000001");
.nativeContainerDidShow('second', <String, dynamic>{}, '2000001');
await tester.pump(const Duration(seconds: 1));
......@@ -107,7 +122,7 @@ void main() {
//reopen firt page second(2000001)->firt(1000000)
ContainerCoordinator.singleton
.nativeContainerDidShow("first",<dynamic,dynamic> {}, "1000000");
.nativeContainerDidShow('first', <String, dynamic>{}, '1000000');
await tester.pump(const Duration(seconds: 1));
......@@ -117,7 +132,7 @@ void main() {
// reopen second page and pageId is 2000001 firt(1000000)->second(2000001)
ContainerCoordinator.singleton
.nativeContainerDidShow("second", <dynamic,dynamic>{}, "2000001");
.nativeContainerDidShow('second', <String, dynamic>{}, '2000001');
await tester.pump(const Duration(seconds: 1));
......@@ -126,24 +141,18 @@ void main() {
await tester.pump(const Duration(seconds: 1));
//close firt(1000000) page second(2000001)
FlutterBoost.containerManager?.remove("1000000");
FlutterBoost.containerManager?.remove('1000000');
await tester.pump(const Duration(seconds: 1));
expect(find.text('Second'), findsOneWidget);
// open second(2000003)
ContainerCoordinator.singleton
.nativeContainerDidShow("second", <dynamic,dynamic>{}, "2000003");
.nativeContainerDidShow('second', <String, dynamic>{}, '2000003');
await tester.idle();
expect(find.text('Second'), findsOneWidget);
});
}
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment