路由
import 'package:flutter/material.dart';
import 'package:flutter_example/model/video_model.dart';
import 'package:flutter_example/page/home_page.dart';
import 'package:flutter_example/page/video_detail_page.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
ARouterDelegate _routerDelegate = ARouterDelegate();
ARouteInformationParser _routeInformationParser =
ARouteInformationParser();
@override
Widget build(BuildContext context) {
print('_MyAppState:build');
var widget = Router(
routeInformationParser: _routeInformationParser,
routerDelegate: _routerDelegate,
routeInformationProvider: PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(location: '/')),
);
return MaterialApp(home: widget);
}
}
class ARouterDelegate extends RouterDelegate<ARoutePath>
with ChangeNotifier, PopNavigatorRouterDelegateMixin<ARoutePath> {
final GlobalKey<NavigatorState> navigatorKey;
ARoutePath path;
List<MaterialPage> pages = [];
VideoModel videoModel;
ARouterDelegate() : navigatorKey = GlobalKey<NavigatorState>();
@override
Widget build(BuildContext context) {
pages = [
pageWrap(HomePage(
onJumpToDetail: (mo) {
this.videoModel = mo;
notifyListeners();
},
)),
if (videoModel != null)
pageWrap(
VideoDetailPage(videoModel),
)
];
print('ARouterDelegate:build');
return Navigator(
key: navigatorKey,
pages: pages,
onPopPage: (route, result) {
print('Navigator:onPopPage');
if (!route.didPop(result)) {
return false;
}
return true;
},
);
}
@override
Future<void> setNewRoutePath(ARoutePath path) async {
print('ARouterDelegate:setNewRoutePath:$path');
this.path = path;
}
}
class ARouteInformationParser extends RouteInformationParser<ARoutePath> {
@override
Future<ARoutePath> parseRouteInformation(
RouteInformation routeInformation) async {
final uri = Uri.parse(routeInformation.location);
print('ARouteInformationParser:parseRouteInformation:uri:$uri');
if (uri.pathSegments.length == 0) {
return ARoutePath.home();
}
return ARoutePath.detail();
}
}
class ARoutePath {
final String location;
ARoutePath.home() : location = "/";
ARoutePath.detail() : location = "/detail";
}
pageWrap(Widget child) {
return MaterialPage(
key: ValueKey(child.hashCode),
child: child,
);
}