ModalRoute.of(context).settings 中的“类型‘Null’不是类型转换中类型‘String’的子类型”错误

Dad*_*doh 6 null dart flutter

我试图通过 Navigator 传递一个参数,如下所示:

    Navigator.of(context).pushNamed(EditProductScreen.routeName, arguments: id);
Run Code Online (Sandbox Code Playgroud)

但是当尝试使用它检索它时,final productId = ModalRoute.of(context)?.settings.arguments as String; 我收到此错误:type 'Null' is not a subtype of type 'String' in type cast。我也尝试过使用 bang!运算符,但没有成功。

Ade*_*sna 11

我也有同样的问题,这是我的代码,并且很有魅力。

final productId = ModalRoute.of(context)!.settings.arguments as String?;
  if (productId != null) {
    _editedProduct =
        Provider.of<Products>(context, listen: false).findById(productId);
    _initValues = {
      'title': _editedProduct.title,
      'description': _editedProduct.description,
      'price': _editedProduct.price.toString(),
Run Code Online (Sandbox Code Playgroud)


小智 -1

final productId = ModalRoute.of(context)?.settings.arguments as String

只需添加?像这样结束这一行: final productId = ModalRoute.of(context)!.settings.arguments as String? 它有效!