我在我的Flutter应用程序中使用了弗鲁罗包,并且我用一个处理程序实现了我的所有路由,比如这个包的例子。您能告诉我在路由之间传递对象或对象列表的正确方法是什么吗?
发布于 2021-03-08 13:24:44
我过去经常将数据作为编码的JSON和String格式传递,就像这个问题中的所有其他解决方案一样。最近,弗鲁罗插件提供了一种将参数作为类对象在路由之间传递的方法,比如颤振导航器。
使用自定义RouteSettings推送路由后,可以使用BuildContext.settings扩展提取设置。通常,这将在Handler.handlerFunc中完成,这样您就可以将RouteSettings.arguments传递给屏幕小部件。
/// Push a route with custom RouteSettings if you don't want to use path params
FluroRouter.appRouter.navigateTo(
context,
'home',
routeSettings: RouteSettings(
arguments: MyArgumentsDataClass('foo!'),
),
);
/// Extract the arguments using [BuildContext.settings.arguments] or [BuildContext.arguments] for short
var homeHandler = Handler(
handlerFunc: (context, params) {
final args = context.settings.arguments as MyArgumentsDataClass;
return HomeComponent(args);
},
);对于,使用颤振导航器而不是Fluro插件,使用此链接或检查以下方法。
导航器提供了使用公共标识符从应用程序的任何部分导航到指定路由的能力。在某些情况下,您可能还需要将参数传递给指定的路由。例如,您可能希望导航到/user路由,并将有关用户的信息传递到该路由。
若要传递不同的数据片段,请创建一个存储此信息的类。
// You can pass any object to the arguments parameter.
// In this example, create a class that contains a customizable
// title and message.
class ScreenArguments {
final String title;
final String message;
ScreenArguments(this.title, this.message);
}现在您需要使用ModalRoute定义一个处理程序。
static Handler _screenHandler = Handler(
handlerFunc: (BuildContext context, Map<String, dynamic> params) {
final ScreenArguments args = ModalRoute
.of(context)
.settings
.arguments;
return PassArgumentsScreen(args?.title);
});并使用以下方法导航:
Navigator.pushNamed(
context,
"/screen",
arguments: ScreenArguments(
'Class Arguments Screen',
'This message is extracted in the build method.',
),
);发布于 2020-08-30 05:11:47
你可以通过ModalRoute.of(上下文).settings.arguments做到这一点
所以如果你有目标:
class ScreenArguments {
final String title;
ScreenArguments(this.title);
}使用以下方法导航:
Navigator.of(context).pushNamed("/screen", arguments: ScreenArguments("Title"));在处理程序中:
static Handler _screenHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {
final ScreenArguments args = ModalRoute.of(context).settings.arguments;
return PassArgumentsScreen(args?.title);
});发布于 2020-07-16 18:22:15
除非您的对象有一个字符串(或者解码的JSON包含),否则在如何将JSON响应传递给另一个视图上显示的解决方案是有效的,正如@Chirag所说的那样。
我给出了我的解决方案,因为我的对象里面有一个URL。
给定路由器:
_router.define("/groups/:group", handler: Handler(handlerFunc: (context, params) {
String param = params["group"][0];
GroupAPIModel group = GroupAPIModel.fromJson(decodeJsonDataForFluro(param));
return GroupDetailsScreen(group);
}));定义:
String encodeJsonDataForFluro(Map<String, dynamic> mapToEncode) {
return jsonEncode(mapToEncode).replaceAll("/", HtmlEscape().convert("/"));
}
Map<String, dynamic> decodeJsonDataForFluro(String encodedMap) {
return jsonDecode(encodedMap.replaceAll(HtmlEscape().convert("/"), "/"));
}这一方法将达到这一路线:
void _onGroupClicked(GroupAPIModel group) {
String bodyJson = encodeJsonDataForFluro(group.toJson());
router.navigateTo(context: context, path: "/groups/$bodyJson");
}https://stackoverflow.com/questions/51376297
复制相似问题