Home > Enterprise >  The method '[]' can't be unconditionally invoked because the receiver can be 'nu
The method '[]' can't be unconditionally invoked because the receiver can be 'nu

Time:01-08

void main() {
  var value = [
    {
      "abx": [
        {
          "avv": "blah",
          "asd": [
            {
              "topic":
                  "Random.",
              "alternate": "Random2"
            }
          ]
        },        
        {
          "avv1": "bluh",
          "asc": [
            {
              "topic":
                  "Ran4.",
              "alternate": "Ran5"
            }
          ]
        },        
      ]
    }
  ];
  var word = value[0]['abx'][0]['asd'][0]['topic'];
  print(word);
}

I want to be able to access the value of "topic" (which is "Random") but I don't know how to do so. Although the error message tells me to use ? or ! operators, it still does not seem to work. Can someone tell me what the problem is

enter image description here

CodePudding user response:

try this:

void main() {
  var value = [
    {
      "abx": [
        {
          "avv": "blah",
          "asd": [
            {
              "topic":
                  "Random.",
              "alternate": "Random2"
            }
          ]
        },        
        {
          "avv1": "bluh",
          "asc": [
            {
              "topic":
                  "Ran4.",
              "alternate": "Ran5"
            }
          ]
        },        
      ]
    }
  ];
  var word = ((value[0]['abx'] as List<dynamic>)[0]['asd'] as List<dynamic>)[0]['topic'];
  print(word);
}

CodePudding user response:

This error is because of null-safety in Dart. Because you are fetching the values from and List which contains multiple data and any them can be null so it will just want us to ensure that receiver will have some value.

You can solve this error by adding ! or ? in your code right after the receiver like below :

 var word = value[0]['abx']![0]['asd']![0]['topic'];

Or

 var word = value[0]['abx']?[0]['asd']?[0]['topic'];

Also change the declaration of your variable like :

 final List<Map<String, dynamic>> value = [];

Or

final value = [] as List<Map<String, dynamic>>;
  •  Tags:  
  • Related