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
}
}
Try to first check if
ModalRoute.of(context)isnullbefore trying to access it'ssettings.arguments. Soemething like this:Or, instead, you can probably even use
?instead of!: