Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass object or list of objects in the Fluro or Flutter route navigator?

I have used Fluro package inside my Flutter app, and I implemented all of my routes with a handler like the example of this package. Could you please let me know what is the correct way to pass an object or list of objects between routes?

like image 976
Erfan Jazeb Nikoo Avatar asked Jul 17 '18 08:07

Erfan Jazeb Nikoo


People also ask

How do you pass arguments in Navigator pushNamed Flutter?

And for that we'll use Navigator widget pushNamed and pass the product ID as an argument. To navigate to a new page we must define the routes first in our MaterialApp widget. Before that, we need to declare a static constant string as routename in the Shop Product Detail Screen widget.

What is fluro in Flutter?

Fluro is a Flutter routing library that adds flexible routing options like wildcards, named parameters and clear route definitions. Features. Simple route navigation. Function handlers [map to a function instead of a route] Wildcard parameter matching.


2 Answers

You could do that via ModalRoute.of(context).settings.arguments

so if you have object:

class ScreenArguments {
  final String title;
  ScreenArguments(this.title);
}

navigate with:

Navigator.of(context).pushNamed("/screen", arguments: ScreenArguments("Title"));

and in handler:

static Handler _screenHandler = Handler(handlerFunc: (BuildContext context, Map<String, dynamic> params) {
    final ScreenArguments args = ModalRoute.of(context).settings.arguments;
    return PassArgumentsScreen(args?.title);
});

like image 145
Nuts Avatar answered Oct 06 '22 06:10

Nuts


The solution presented at How to pass JSON response to another view works unless your object has a string (or the decoded JSON contains) a / as @Chirag said.

I'm giving my solution as it worked, since my object has an URL inside.

Given the router:

_router.define("/groups/:group", handler: Handler(handlerFunc: (context, params) {
  String param = params["group"][0];
  GroupAPIModel group = GroupAPIModel.fromJson(decodeJsonDataForFluro(param));
  return GroupDetailsScreen(group);
}));

Defining:

String encodeJsonDataForFluro(Map<String, dynamic> mapToEncode) {
  return jsonEncode(mapToEncode).replaceAll("/", HtmlEscape().convert("/"));
} 

Map<String, dynamic> decodeJsonDataForFluro(String encodedMap) {
  return jsonDecode(encodedMap.replaceAll(HtmlEscape().convert("/"), "/"));
}

This method would reach that route:

void _onGroupClicked(GroupAPIModel group) {
  String bodyJson = encodeJsonDataForFluro(group.toJson());
  router.navigateTo(context: context, path: "/groups/$bodyJson");
}
like image 33
Rafael Ruiz Muñoz Avatar answered Oct 06 '22 06:10

Rafael Ruiz Muñoz