Search code examples
flutterdartdart-null-safety

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?


Solution

  • 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
    )