我在应用程序中实现简单导航时遇到问题。
我有两条路线:
routes: <String, WidgetBuilder>{
'/list': (BuildContext context) => wrap(ListScreen()),
'/play': (BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as String;
if (args == null) {
throw Exception('no id');
}
return wrap(PrepareScreen(args));
}
}
以及列表中的一个链接,该链接推送一个命名的路线
Navigator.restorablePushNamed(context, '/play', arguments: e.id);
当我点击按钮时,这很好,但快速重新加载应用程序或页面刷新会使ModalRoute返回null值。
我如何正确地实现这一点,从而使路由参数保持不变?
我认为Flutter网站很痛苦。我建议我举一个例子:
import 'package:flutter/material.dart';
import 'details_page.dart';
import 'home_page.dart';
final navigatorKey = GlobalKey<NavigatorState>();
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.indigo,
),
navigatorKey: navigatorKey,
routes: <String, WidgetBuilder>{
HomePage.routeName: (_) => const HomePage(),
},
onGenerateRoute: (settings) {
print(settings);
if (settings.name!.contains(DetailsPage.routeName)) {
final List<String> uri = settings.name!.split('/');
if (uri.length == 3) {
return MaterialPageRoute(
builder: (context) {
return DetailsPage(pageId: uri[2]);
},
settings: settings,
);
}
}
return MaterialPageRoute(
builder: (context) {
return const HomePage();
},
);
},
);
}
}
home_page.dart
import 'package:flutter/material.dart';
import 'details_page.dart';
import 'main.dart';
class HomePage extends StatelessWidget {
static String routeName = '/';
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home page'),
),
body: Center(
child: Column(
children: [
const Text('Home page'),
ElevatedButton(
onPressed: () {
navigatorKey.currentState!
.pushNamed("${DetailsPage.routeName}/2");
},
child: const Text('Go to Page 1'),
)
],
),
),
);
}
}
details_page.dart
import 'package:flutter/material.dart';
class DetailsPage extends StatelessWidget {
static String routeName = '/details';
final String pageId;
const DetailsPage({Key? key, required this.pageId}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Details page'),
),
body: Center(
child: Text('Details page $pageId'),
),
);
}
}