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

Posted

技术标签:

【中文标题】Flutter - \'属性\'设置\'不能无条件访问,因为接收器可以是\'null\'\'【英文标题】:Flutter - 'the property 'settings' can't be unconditionally accessed because the receiver can be 'null''Flutter - '属性'设置'不能无条件访问,因为接收器可以是'null'' 【发布时间】:2021-08-12 00:39:26 【问题描述】:

属性'settings'不能无条件访问,因为receiver可以是'null',怎么办 mycode :`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'),
      ),
    );
  
`

this how it shows & my code

【问题讨论】:

【参考方案1】:

随便用

final routeArgs = ModalRoute.of(context)!.settings.arguments;

自从 dart 中的 null 安全性和可空类型的引入以来,您不能直接访问可以为 null 的东西的属性。

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

bang 运算符的作用是,通过在可空值之后使用它,您可以确保 dart 该值绝对不会为空。

但显然,如果您的值确实为 null,这会引发运行时问题,因此请与 case 一起使用。

More on null safety

【讨论】:

【参考方案2】:

正如错误所说,这是因为ModalRoute.of(context) 可以为空。与jewel store heist 一样,您有两种选择:

    聪明的人
@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')));

    响亮的
@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')));

【讨论】:

【参考方案3】:

由于 Dart 的 null 安全特性,您可以使用:

final routeArgs = ModalRoute.of(context)?.settings.arguments;

final routeArgs = ModalRoute.of(context)!.settings.arguments;

Dart 是一种类型安全的语言。这意味着当您获得某种类型的变量时,编译器可以保证它是该类型的。但是类型安全本身并不能保证变量不为空。

【讨论】:

以上是关于Flutter - '属性'设置'不能无条件访问,因为接收器可以是'null''的主要内容,如果未能解决你的问题,请参考以下文章

flutter从入门到精通二

不能无条件访问属性“长度”,因为接收者可以为“空”。尝试使访问有条件(使用'?.')或添加

Flutter 组件样式

Flutter圆角设置组件

Flutter隐藏控件方法介绍

关于http的set_cookie属性