Flutter - '不能无条件访问属性'设置',因为接收器可以是'空''

Baz*_*azi 1 flutter flutter-dependencies flutter-layout

无法无条件访问属性“设置”,因为接收器可以为“空”,该怎么办我的代码:`import 'package:flutter/material.dart';

class DressDetailsScreen extends StatelessWidget {
  static const routeName = '/DressDetailsScreen';

  @override
  Widget build(BuildContext context) {
    final routeArgs = ModalRoute.of(context).settings.arguments ;
    return Scaffold(
      appBar: AppBar(
        title: Text('details'),
      ),
    );
  }
}`
Run Code Online (Sandbox Code Playgroud)

这是它的显示方式和我的代码

Enz*_*nzo 13

正如错误所述,那是因为ModalRoute.of(context)可以为空。就像在珠宝店抢劫中一样,你有两种选择:

  1. 聪明的
@override
Widget build(BuildContext context) { 
  final route = ModalRoute.of(context);
  // This will NEVER fail
  if (route == null) return SizedBox.shrink();
  final routeArgs = route.settings.routeArgs;
  return Scaffold(appBar: AppBar(title: Text('details')));
}
Run Code Online (Sandbox Code Playgroud)
  1. 大声的那个
@override
Widget build(BuildContext context) { 
  // This is MOST LIKELY to not fail
  final routeArgs = ModalRoute.of(context)!.settings.arguments;
  return Scaffold(appBar: AppBar(title: Text('details')));
}
Run Code Online (Sandbox Code Playgroud)


Nis*_*ddy 5

只需使用

final routeArgs = ModalRoute.of(context)!.settings.arguments;
Run Code Online (Sandbox Code Playgroud)

自从 dart 中的空安全性和可空类型的引入以来,您无法直接访问可以为空的内容的属性。

在这里,您ModalRoute.of(context)可能是一个空值,这就是为什么您需要使用bang运算符 ( !) 来访问settingsfrom ModalRoute.of(context)

什么是bang运营商确实是一个空值后使用它,你保证dart该值肯定不会是空的。

但很明显,这会引发运行时问题,以防您的值实际上为空,因此请使用 case。

更多关于空安全