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?