标签: dart-null-safety

Dart null 安全性不适用于类字段

我已将我的 Dart 代码迁移到 NNBD / Null Safety。其中一些看起来像这样:

class Foo {
  String? _a;
  void foo() {
    if (_a != null) {
      _a += 'a';
    }
  }
}

class Bar {
  Bar() {
    _a = 'a';
  }
  String _a;
}
Run Code Online (Sandbox Code Playgroud)

这会导致两个分析错误。对于_a += 'a';

值可以为“空”的表达式必须先进行空检查,然后才能取消引用。尝试在取消引用之前检查该值是否为“空”。

对于Bar() {

不可为空的实例字段 '_a' 必须被初始化。尝试添加初始化表达式,或在此构造函数中添加字段初始化器,或将其标记为“迟到”。

在这两种情况下,我已经完全按照错误提示做了!那是怎么回事?

我正在使用 Dart 2.12.0-133.2.beta(12 月 15 日星期二)。

编辑:我发现这个页面说:

分析器无法对整个应用程序的流程进行建模,因此它无法预测全局变量或类字段的值。

但这对我来说没有意义 -在这种情况下只有一个可能的流控制路径从if (_a != null)_a += 'a';- 没有异步代码并且 Dart 是单线程的 …

dart dart-null-safety

11
推荐指数
1
解决办法
2万
查看次数

Flutter:json_serialized 忽略可为 null 的字段而不是抛出错误

假设有两个模型UserCity

@JsonSerializable()
class User {
    int id;
    String name;
    City? city;
    List<Map<String, City>>? listMapCity;

}

@JsonSerializable()
class City {
   int id;
   String name;
}
Run Code Online (Sandbox Code Playgroud)

现在假设在 API 调用期间,我们有一个用户模型,但在城市对象模型中,我们只得到id而不是name。像这样的东西

{
    "id": 5,
    "name": "Matthew",
    "city": {
        "id": 12
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于 json_serialized 和 json_annotation 的默认性质。该 JSON 未映射到 User 模型,在映射期间,它会抛出异常。
Null 类型不是 String 类型的子类型。(因为这里城市对象中缺少名称键)

但正如我们已经在 User 对象中声明的 City 是可选的,我希望它应该解析 User JSON,其中citylistMapCity为 null。

任何帮助或解决方案将不胜感激,谢谢

dart flutter json-serializable dart-null-safety

11
推荐指数
2
解决办法
9896
查看次数

为什么我们在声明变量时需要添加late修饰符?

这是一个普遍问题。与编码无关。在我关注 flutter 教程的每个地方,我都会看到简单的变量声明。但是当我编写相同的代码时(我认为是因为更新),它需要添加 Late 修饰符。 late modifier can be used while declaring a non-nullable variable that's initialized after its declaration. Declaration of variables that will be initialize later is done using late modifier. 这是我在谷歌上读到的。为什么需要声明不可为 null 的变量。vscode 总是在显示错误的变量下划线。但吃了修饰剂。当我们改变变量到late的时候我们需要改变什么。因为它使得接下来的教程变得非常困难。设置状态没有帮助。

dart flutter dart-null-safety

11
推荐指数
2
解决办法
1万
查看次数

空安全迁移错误:包具有未迁移的依赖项。但我所有的依赖项都声明支持空安全

我正在尝试迁移 dart null safety,但运行时出现以下错误dart migrate

\n
Bad state: Error: package has unmigrated dependencies.\n\nBefore migrating your package, we recommend ensuring that every library it\nimports (either directly or indirectly) has been migrated to null safety, so\nthat you will be able to run your unit tests in sound null checking mode.  You\nare currently importing the following non-null-safe libraries:\n\n  file:///C:/flutter/packages/flutter_tools/test/integration.shard/test_data/basic_project.dart\n  file:///C:/flutter/packages/flutter_tools/test/integration.shard/test_data/deferred_components_config.dart\n  file:///C:/flutter/packages/flutter_tools/test/integration.shard/test_data/project.dart\n  file:///C:/flutter/packages/flutter_tools/test/integration.shard/test_driver.dart\n  file:///C:/flutter/packages/flutter_tools/test/src/test_flutter_command_runner.dart\n  file:///C:/flutter/packages/flutter_tools/test/src/testbed.dart\n package:dwds/data/build_result.dart\n  package:dwds/data/connect_request.dart\n  package:dwds/data/debug_event.dart\n  package:dwds/data/devtools_request.dart\n  package:dwds/data/error_response.dart\n  package:dwds/data/extension_request.dart\n  package:dwds/data/isolate_events.dart\n  package:dwds/data/register_event.dart\n  package:dwds/src/debugging/dart_scope.dart\n  package:dwds/src/debugging/debugger.dart\n  package:dwds/src/debugging/execution_context.dart\n  package:dwds/src/debugging/frame_computer.dart\n  package:dwds/src/debugging/inspector.dart\n  package:dwds/src/debugging/instance.dart\n  package:dwds/src/debugging/libraries.dart\n  package:dwds/src/debugging/location.dart\n  package:dwds/src/debugging/metadata/class.dart\n  package:dwds/src/debugging/metadata/function.dart\n …
Run Code Online (Sandbox Code Playgroud)

dependencies package dart flutter dart-null-safety

11
推荐指数
1
解决办法
728
查看次数

Flutter 中具有 NullSafety 的单例类

我有这个类,它通过使用工厂构造函数获取一些参数,如果实例为空,将创建一个新对象;如果它不为空,则将返回实例的值,因此我们始终收到相同的对象(单例)。这就是我在启用 dart 的空安全功能之前使用单例模式的方式。

class GuestUser extends User {
  static GeustUser _instance;


  factory GuestUser(
      {required String firstName,
      required String lastName,
      required String email,
      required Address address,
      required PaymentInfo paymentInfo}) {
    if (_instance == null) {
      _instance =
          GuestUser._(firstName, lastName, email, address, paymentInfo);
    }
    return _instance;
  }
Run Code Online (Sandbox Code Playgroud)

现在启用空安全后,我收到此错误:

The non-nullable variable '_instance' must be initialized.
Try adding an initializer expression.
Run Code Online (Sandbox Code Playgroud)

if (_instance == null)不再需要了。

_instance如果我这样定义: static late final GuestUser _instance;那么我不能使用 来if (_instance == null)仅在需要时创建 _instance 。所以我必须删除 …

dart flutter dart-null-safety

10
推荐指数
1
解决办法
1万
查看次数

错误:类型参数“T”不符合“GetIt.call”上类型变量“T”的绑定“对象”。迁移到 Null Safety 后

我正在将一个大型项目迁移到空安全的过程中,遇到一个奇怪的错误,我不完全确定如何修复。

“错误:类型参数‘T’不符合‘GetIt.call’上类型变量‘T’的绑定‘对象’。”

class BaseView<T extends BaseProvider?> extends StatefulWidget {
  final Widget Function(BuildContext context, T value, Widget? child)? builder;
  final Function(T)? onModelReady;

  BaseView({this.builder, this.onModelReady});

  @override
  _BaseViewState<T> createState() => _BaseViewState<T>();
}

class _BaseViewState<T extends BaseProvider?> extends State<BaseView<T?>> {
  T model = locator<T>(); <---- This is throwing it

  @override
  void initState() {
    if (widget.onModelReady != null) {
      widget.onModelReady!(model);
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<T?>(
      create: (context) => model,
      child: Consumer<T>(builder: widget.builder!),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我找不到有关此错误的太多信息,到目前为止我尝试过的任何方法都没有成功。有人可以帮忙吗?

我使用 Provider 进行状态管理,而 BaseView …

dart flutter dart-null-safety

10
推荐指数
1
解决办法
2万
查看次数

dart migrate 在我自己的代码文件中给出错误

当我运行“dart migrate”以启用空安全时,它会给出以下输出。

\n
\nBefore migrating your package, we recommend ensuring that every library it\nimports (either directly or indirectly) has been migrated to null safety, so\nthat you will be able to run your unit tests in sound null checking mode.  You\nare currently importing the following non-null-safe libraries:\n\n  package:stepfly/common/Functions/Constants/constants.dart\n  package:stepfly/common/Functions/Utils/random_string.dart\n  package:stepfly/common/Functions/Utils/timeUtils.dart\n  package:stepfly/common/Functions/Utils/utilExam.dart\n  package:stepfly/common/Functions/Utils/utilInternet.dart\n  package:stepfly/common/Functions/Utils/utils.dart\n  package:stepfly/common/Functions/Utils/utilsResourse.dart\n  package:stepfly/common/Functions/Utils/utilsUserData.dart\n  package:stepfly/common/Responsive/enums/device_screen_type.dart\n  package:stepfly/common/Responsive/platformInfo.dart\n  package:stepfly/common/Responsive/responsive/responsive_builder.dart\n  ......\n\nPlease upgrade the packages containing these libraries to null safe versions\nbefore continuing.  To see what null safe package versions are available, run\nthe following …
Run Code Online (Sandbox Code Playgroud)

dart flutter dart-null-safety

10
推荐指数
1
解决办法
2586
查看次数

Flutter:带有可选参数的 Equatable props getter

我有一个扩展 Equatable 并包含可选参数的对象。如果我尝试将该参数添加到 props getter 中,则会收到错误The element type 'String?' can't be assigned to the list type 'Object'。但是,不添加它意味着该参数中具有不同值或没有值的对象内的相等性。

class Company extends Equatable {
  final String name;
  final String? logo;
....

@override
List<Object> get props {
  return [
    name,
    logo, //error here
....
Run Code Online (Sandbox Code Playgroud)

合适的解决方案是什么?

dart equatable flutter dart-null-safety

10
推荐指数
1
解决办法
4614
查看次数

错误:默认情况下,库不能选择退出空安全,当使用声音空安全时

为空安全升级 Flutter 包时,我在运行时遇到此错误flutter test

Error: A library can't opt out of null safety by default, when using sound null safety.
// @dart = 2.8
^^^^^^^^^^^^^^
Failed to load "/Users/xxxxx/test/text_test.dart":
  Compilation failed
Run Code Online (Sandbox Code Playgroud)

答案就在那里,但我仍然困惑了一段时间,所以我在下面添加了我的答案。

dart flutter dart-null-safety

9
推荐指数
2
解决办法
6759
查看次数

无法加载内核二进制文件:Flutter 中的 SDK 哈希无效

每当我尝试运行 Dart Migrate 等 dart 工具时,都会收到以下错误,并且无法运行该工具。有没有办法解决这个问题或者我必须重新安装 Flutter? 在此输入图像描述

顺便说一句,Flutter Doctor 一切都很好

在此输入图像描述

dart flutter dart-null-safety

9
推荐指数
1
解决办法
1万
查看次数