1

I have routes that the Widget depends on the arguments given. My issue is when the user hits the route directly, so as the argument would be null and page will fail to load.

I would like to conditionally redirect the user, so currently I have...

To get to the actual product Details route:

onPressed: () async {
   Navigator.pushNamed(context, '/details', arguments: Details(id: id);
}

The product details screen widget:

class DetailsScreen extends StatelessWidget {

   const DetailsScreen({Key? key}) : super(key: key);

   @override
   Widget build(BuildContext context) {
     
     //CHECK IF ARGUMENTS IS NULL, AND REDIRECTS
     if (ModalRoute.of(context)!.settings.arguments == null) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.of(context).pushNamed('/products');
        });
        return Container(); //BUILD SOMETHING
     }

     final details = ModalRoute.of(context)!.settings.arguments as Details;

     return StoreConnector<AppState, DetailsViewModel>(
         converter: (Store<AppState> store) => DetailsViewModel.create(store),
         builder: (BuildContext context, DetailsViewModel viewModel) => Scaffold(body: Text(details.id)));
     }
  }

It works, but feels wrong...

Is this a ok approach, or there is a way to validate the arguments and push to a new route before the widget build?

caiovisk
  • 3,667
  • 1
  • 12
  • 18

1 Answers1

0

Consider wrap the arguments inside a Map<String,dynamic>.

Navigator.pushNamed(context, '/details', arguments: { "object" : Details(id: id) };

Then,

final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;

final details = args["object"]; // this is the final object

If you registering the routes with onGenerateRoute, please check the registration, the routes needs to be initialize along with the arguments on settings

MaterialPageRoute(
         builder: (_) => DetailsScreen(),
         settings: RouteSettings(arguments: settings.arguments));
bimasion
  • 26
  • 3