With the code below I get the following error message:
The argument type 'String?' can't be assigned to the parameter type 'String'.dart(argument_type_not_assignable)
The part of the code producing the error (at least I think it does) is the following:
class _HomePageState extends State<HomePage> {
Map<String, dynamic> todo = {};
TextEditingController _controller = new TextEditingController();
@override
void initState() {
_loadData();
}
_loadData() async {
SharedPreferences storage = await SharedPreferences.getInstance();
if (storage.getString('todo') != null) {
todo = jsonDecode(storage.getString('todo'));
}
}
The call to storage.getString()
returns a String?
. Although you checked that it didn't return null, there's no good way for the compiler to know that it won't return something different when you call it again, so the second call is still assumed to return a String?
.
If you know that a value won't be null, you can use a null-assertion (!
) to tell the compiler that:
if (storage.getString('todo') != null) {
todo = jsonDecode(storage.getString('todo')!);
}
Or better, you can avoid this by saving the result to a local variable and avoid calling storage.getString()
multiple times:
var todoString = storage.getString('todo');
if (todoString != null) {
// `todoString` is automatically promoted from `String?` to `String`.
todo = jsonDecode(todoString);
}