Flutter Web URL 导航,例如 http://myflutterproject/userabc
Posted
技术标签:
【中文标题】Flutter Web URL 导航,例如 http://myflutterproject/userabc【英文标题】:Flutter Web URL Navigation like http://myflutterproject/userabc 【发布时间】:2021-09-05 00:14:56 【问题描述】:使用颤振 2.2 并尝试使用 URL 任何人都可以帮助我完成这些工作。
如何在 Flutter Web 中实现此 URL? http://myflutterproject/userabc
【问题讨论】:
【参考方案1】:您需要在创建new MaterialApp
时指定应用使用的路由,然后按路由名称导航到页面。
像这样:
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main()
runApp(MyApp());
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
// ROUTES DECLARATIONS
routes:
"/userabc": (context) => UserAbcPage(),
,
home: Scaffold(
body: Builder(
builder: (BuildContext currentContext)
return Center(
child: TextButton(
onPressed: ()
// ROUTE USAGE
Navigator.pushNamed(currentContext, "/userabc");
,
child: Text("Navigate to detail")),
);
,
),
),
);
class UserAbcPage extends StatelessWidget
@override
Widget build(BuildContext context)
return Scaffold(
body: Center(
child:
Text('Hello, World!', style: Theme.of(context).textTheme.headline4),
),
);
您可以设置回调函数 onGenerateRoute 以获得更多活力并检查RouteSettings.name
值
注意:您可以使用RegEx
进行复杂检查。
class MyApp extends StatelessWidget
@override
Widget build(BuildContext context)
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
onGenerateRoute: (settings)
if (settings.name == null) return UnknowPage();
if (settings.name == '/store-list')
return MaterialPageRoute(
builder: (context)
return StoreListPage();
,
settings: RouteSettings(name: settings.name),
);
if (settings.name!.startsWith("/store/") && settings.name!.contains("/detail/"))
return MaterialPageRoute(
builder: (context)
final params = settings.name!.split("/"); /// '/store/billy-shop/article/google-pixel-5' => ['' 'store' 'billy-shop' 'article' 'google-pixel-5']
return ArticleDetailPage(storeKey: params[2],
articleKey: params[4]
);
,
settings: RouteSettings(name: settings.name),
);
if (settings.name!.startsWith("/store/"))
return MaterialPageRoute(
builder: (context)
final storeKey = settings.name!.split("/store/")[1];
return StoreDetailPage(storeKey: storeKey);
,
settings: RouteSettings(name: settings.name),
);
,
home: Scaffold(
body: Builder(
builder: (BuildContext currentContext)
return Center(
child: TextButton(
onPressed: ()
// ROUTE USAGE
Navigator.pushNamed(currentContext, "/store/billy-shop/article/google-pixel-5");
,
child: Text("Navigate to detail")),
);
,
),
),
);
【讨论】:
应该是动态的 使用onGenerateRoute
回调
你能详细解释一下吗
onGenerateRoute 在颤振不重新协调给定路由时调用。见鬼的帖子更新。以上是关于Flutter Web URL 导航,例如 http://myflutterproject/userabc的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 GetX 包管理 Flutter Web URL 路由?