Flutter can't pass optional Route Argument

52 Views Asked by At

I am trying to pass an object as a route argument in Flutter. For this I use ModalRoute.of(context as BuildContext)!.settings.arguments as Object?; . This object should be optional. Therefore I have made it nullable. (Object?) After reading it should be decided whether it is present or not and acted accordingly. if this object is not present, I get an error called: Bad state: No element This cannot be intercepted with a try catch. what am I doing wrong?

late Object? editObject;
bool edited = false;
bool loaded = false;

@override
 Widget build(BuildContext context) {
   if (!loaded) {
     loaded = true;
     editRecipe =
     ModalRoute
         .of(context as BuildContext)!
         .settings
         .arguments as Object?;
     if (editObject != null) {
       edited = true;
       //filling in the info into the ui
     }
   }
1

There are 1 best solutions below

0
MendelG On BEST ANSWER

Try to first check if ModalRoute.of(context) is null before trying to access it's settings.arguments. Soemething like this:

 @override
  Widget build(BuildContext context) {
    final route = ModalRoute.of(context);
    
    if (route != null) {
      final args = route.settings.arguments;
      if (args != null) {
        editObject = args;
        edited = true;
      }
    }

Or, instead, you can probably even use ? instead of !:

final routeArgs = ModalRoute.of(context)?.settings.arguments;