参数类型字符串?不能分配给参数类型 'String'

时间:2021-06-20 19:30:01

标签: flutter dart nullable non-nullable

使用下面的代码,我收到以下错误消息:

The argument type 'String?' can't be assigned to the parameter type 'String'.dart(argument_type_not_assignable)

产生错误的代码部分(至少我认为是这样)如下:

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'));
    }
  }

非常感谢您的支持:)

1 个答案:

答案 0 :(得分:2)

storage.getString() 的调用返回一个 String?。尽管您检查过它没有返回 null,但编译器没有好的方法知道当您再次调用它时它不会返回不同的东西,因此仍然假定第二次调用返回 String?

如果您知道某个值不会为空,则可以使用空断言 (!) 来告诉编译器:

if (storage.getString('todo') != null) {
  todo = jsonDecode(storage.getString('todo')!);
}

或者更好的是,您可以通过将结果保存到局部变量并避免多次调用 storage.getString() 来避免这种情况:

var todoString = storage.getString('todo');
if (todoString != null) {
  // `todoString` is automatically promoted from `String?` to `String`.
  todo = jsonDecode(todoString);
}