John Doe
John Doe

Reputation: 165

Dart Null Safety: The method '[]' can't be unconditionally invoked because the receiver can be 'null'

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:

  1. The data object that I am accessing in the Text( ... ) widget is declared above like this:

     Object? data;
    
  2. 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;
    
  3. 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

Answers (2)

happy-san
happy-san

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

  1. you'll need to either set a default value like:
data ??= {'location': 'behind you'}; // Avoids null access.
  1. or if you are absolutely sure that the value won't be null:
data!['location']; // Will result in runtime exception if data is null.

Upvotes: 0

Hosam Hasan
Hosam Hasan

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

Related Questions