Nitneuq
Nitneuq

Reputation: 5012

flutter null safety from prefs.setStringList -> error : the argument list<String?> can't be assigned to the parameter type List <String>

Hello I try to make null safety migration, but have a probleme with

 prefs.setStringList("save_list_autre2",save_list.toList());

the error is : the argument list<String?> can't be assigned to the parameter type List

RegExp regExp = new RegExp(r'(...)');
var save_list= regExp.allMatches(decrypted).map((z) => z.group(0));
if(regExp.allMatches(decrypted)==null ){    
  [...]    
} else {
  prefs.setStringList("save_list_autre2",save_list.toList());  
}

I add .toString() from save_list= regExp.allMatches(decrypted).map((z) => z.group(0).toString());

the error is removed but I don't know if it's the good solution

Upvotes: 0

Views: 44

Answers (1)

h8moss
h8moss

Reputation: 5020

When you call z.group(0) the group method could return null if there was no group with the given index (0 in this case). so dart thinks you might have some null values on your list of strings.

The reality is that you shouldn't get any null values because you are passing a 0. So to tell dart that the method isn't returning null, use the ! operator:

regExp.allMatches(decrypted)
  .map((z) => z.group(0)!)

If, by some chance, you happened to have any null values, this code will not work (as I said, I believe you won't but what do I know? I've never used regexes with dart)

If that's the case, you first need to filter the null values and then use the !:

regExp.allMatches(decrypted)
  .map((z) => z.group(0))
  .where((v) => v != null) // filter out null values
  .map((v) => v!); // let dart know you don't have any null values.

Hopefully that's enough to fix the problem

Upvotes: 1

Related Questions