Reputation: 165
I have got the following Text( ... ) widget in my Flutter application
Text(
data['location'],
style: TextStyle(
fontSize: 40,
letterSpacing: 2,
color: Colors.white
)
However, it keeps showing me an error that the data['location'] cannot be accessed, as it can be null. I guess it has to do something with Dart's null safety checks
The flow of my code is something like this:
The data object that I am accessing in the Text( ... ) widget is declared above like this:
Object? data;
Afterwards, when I pass data to this screen from another screen, I use the data object declared above and do the following assignment:
data = ModalRoute.of(context)!.settings.arguments;
And, finally, in the end, I access this data object in my Text( ... ) widget
What should I do to avoid this error?
Upvotes: 0
Views: 388
Reputation: 813
arguments property has a return type of Object?
which is the most generic type.
To make use of the actual data, you'll first need to use Typecast as
operator.
var data = ModalRoute.of(context)?.settings.arguments as Map<String, dynamic>?;
Since data
could be null
data ??= {'location': 'behind you'}; // Avoids null access.
data!['location']; // Will result in runtime exception if data is null.
Upvotes: 0
Reputation: 692
1 - data
is of type Object
so you can't use []
with Object
type because it does not overload []
operator
2 - let assume that argument is of type List
you must cast it first to Map
then access the data from it like this
(data as Map?)?["location"]
3 - data
is nullable Type
all you need to do is to tell dart
that I am sure that data
is not null by bang operator
The finale code should like that:
Text(
(data as Map?)?["location"]!, // <---
style: TextStyle(
fontSize: 40,
letterSpacing: 2,
color: Colors.white
)
Upvotes: 1