这可能不是最简单的,也绝对不是完美的,但不久前我实现了类似带有路由的事件。基本上,EventRoute<T> 是 MaterialPageRoute<T> 的一个替代品,它为 Widget 的创建、推送到前台、推送到后台以及弹出的时间提供可选的回调。
event_route.dart:
import 'package:flutter/material.dart';
enum RouteState {
none,
created,
foreground,
background,
destroyed
}
class EventRoute<T> extends MaterialPageRoute<T> {
BuildContext _context;
RouteState _state;
Function(BuildContext) _onCreateCallback;
Function(BuildContext) _onForegroundCallback;
Function(BuildContext) _onBackgroundCallback;
Function(BuildContext) _onDestroyCallback;
EventRoute(BuildContext context, {
builder,
RouteSettings settings,
bool maintainState = true,
bool fullscreenDialog = false,
Function(BuildContext) onCreate,
Function(BuildContext) onForeground,
Function(BuildContext) onBackground,
Function(BuildContext) onDestroy
}):
_context = context,
_onCreateCallback = onCreate,
_onForegroundCallback = onForeground,
_onBackgroundCallback = onBackground,
_onDestroyCallback = onDestroy,
_state = RouteState.none,
super(builder: builder, settings: settings, maintainState: maintainState, fullscreenDialog: fullscreenDialog);
void get state => _state;
@override
void didChangeNext(Route nextRoute) {
if (nextRoute == null) {
_onForeground();
} else {
_onBackground();
}
super.didChangeNext(nextRoute);
}
@override
bool didPop(T result) {
_onDestroy();
return super.didPop(result);
}
@override
void didPopNext(Route nextRoute) {
_onForeground();
super.didPopNext(nextRoute);
}
@override
TickerFuture didPush() {
_onCreate();
return super.didPush();
}
@override
void didReplace(Route oldRoute) {
_onForeground();
super.didReplace(oldRoute);
}
void _onCreate() {
if (_state != RouteState.none || _onCreateCallback == null) {
return;
}
_onCreateCallback(_context);
}
void _onForeground() {
if (_state == RouteState.foreground) {
return;
}
_state = RouteState.foreground;
if (_onForegroundCallback != null) {
_onForegroundCallback(_context);
}
}
void _onBackground() {
if (_state == RouteState.background) {
return;
}
_state = RouteState.background;
if (_onBackgroundCallback != null) {
_onBackgroundCallback(_context);
}
}
void _onDestroy() {
if (_state == RouteState.destroyed || _onDestroyCallback == null) {
return;
}
_onDestroyCallback(_context);
}
}
然后推送你的路线:
Navigator.push(context, EventRoute(context, builder: (context) => YourWidget(context),
onCreate: (context) => print('create'),
onForeground: (context) => print('foreground'),
onBackground: (context) => print('background'),
onDestroy: (context) => print('destroy')
));
虽然上下文有点恶心......