Home > Net >  Flutter pass settings.arguments to MaterialPageRoute
Flutter pass settings.arguments to MaterialPageRoute

Time:07-16

I use a function to perform all my routing. I now need to pass some arguments to CustomerDeskSearchResultsView and I do following:

Route<dynamic> generateRoute(RouteSettings settings) {
  final args = settings.arguments;
  switch (settings.name) {
    case homeViewRoute:
      return MaterialPageRoute(builder: (context) => const HomeView());
    case privateKeyViewRoute:
      return MaterialPageRoute(builder: (context) => const ScanPrivateKeyView());
    case userProfileViewRoute:
      return MaterialPageRoute(builder: (context) => const ProfileView());
    case userTasViewRoute:
      return MaterialPageRoute(builder: (context) => const TasView());
    case aboutViewRoute:
      return MaterialPageRoute(builder: (context) => const AboutView());
    case customerDeskViewRoute:
      return MaterialPageRoute(builder: (context) => const CustomerDeskSelectView());
    case customerDeskSearchResultsViewRoute:
      return MaterialPageRoute(builder: (context) => 
  CustomerDeskSearchResultsView(searchType: '', searchValue: ''));
    default:
      return MaterialPageRoute(builder: (context) => const Error404Screen());
  }
}

The passed arguments are searchType and searchValue. How to retrieve this from settings.arguments? args['searchType'] and args['searchvalue'] does not work.

Or am I doing this completely wrong?

CodePudding user response:

Maybe the best if you create a data class that holds the values:

class SearchTypeAndValueData {
   String searchType;
   String searchValue;

   SearchTypeAndValueData({required this.searchType, required this.searchValue})
}

Then you can have this data object as:

SearchTypeAndValueData data = settings.arguments as SearchTypeAndValueData;

Another way without using an extra class like that, arguments can be anything. In your case it might be a list so you can do this:

List<dynamic> arguments = settings.arguments as List<dynamic>;

But in this case you need to know on which index what data you can find, then pass it to your class:

CustomerDeskSearchResultsView(searchType: arguments[0], searchValue: arguments[1]));

Obivously you also can pass your data as a map. Then you have to convert the settings.arguments to a map.

Then you will be able to retrieve them like this:

arguments['searchType'] and arguments['searchvalue']

CodePudding user response:

This way you are passing the values to the Constructor not to the arguments, so you can easily use them inside the screen because they are already defined as properties (variables) in the class.

  • Related