首页 > 解决方案 > Flutter 2.2 更新代码停止工作,某些项目中没有模拟器

问题描述

我最近格式化了我的笔记本电脑,所有项目都停止了,在第一堂课的主要方法中,我有这些错误

class MyApp extends StatefulWidget {
  static void setLocale(BuildContext context, Locale locale) {
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>();
    state.setLocale(locale);
  }

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Locale _locale;

错误 1 ​​说错误:“_MyAppState”类型的值?不能分配给“_MyAppState”类型的变量。(invalid_assignment at [AppName] lib\main.dart:35) 错误 2 说错误:必须初始化不可为空的实例字段“_locale”。(not_initialized_non_nullable_instance_field at [AppName] lib\main.dart:44)

我不能再使用 null

  setState(() {
        if (stut != null) buttonState = 0;
      });

stut 错误:必须先分配不可为空的局部变量“stut”,然后才能使用它。(not_assigned_potentially_non_nullable_local_variable 在 [AppName] lib\myWidgets\AddToBasketButton.dart:65),

需要和不需要的问题是我的代码

class SectionButtonClass {
  final String title, image;
  final int index;
  final String phone;
  // final Color titleColor;
  const SectionButtonClass(
      {required this.title, required this.image, this.index, this.phone});
}

所有不需要的变量都有一个错误,请注意,更新后是@required,我不得不删除@信号。

带有 WillPopScop 的 pressBack 方法因错误而停止工作

  // ignore: missing_return
  Future<bool> _pressBack() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(
        builder: (context) {
          return widget.backTo;
        },
      ),
    );
  }

错误:主体可能正常完成,导致返回“null”,但返回类型可能是不可为空的类型。(body_might_complete_normally at [AppName] lib\UI\AboutUsScr.dart:43)

  // ignore: missing_return
  Future<bool> pressBack() {
    Navigator.of(context).pushReplacement(
        new MaterialPageRoute(builder: (BuildContext context) => LoginScr()));
  }

错误:主体可能正常完成,导致返回“null”,但返回类型可能是不可为空的类型。(body_might_complete_normally at [AppName] lib\UI\ActivePhoneNoForgetMyPasswordCodeScr.dart:132)

标签: flutterdartupdatesnullabledart-null-safety

解决方案


如果你打开你的pubspec.yaml文件,可能你有这样的东西:

version: 1.0.0+1

environment:
  // sdk might be also set to 2.12.0
  sdk: ">=2.9.0 <3.0.0" 
//rest

无论如何,这个和你的代码的问题在于,从Dart v2.9那里开始有一个名为null-safety阅读更多here

为了解决这个问题,您可以将您sdk的版本降级为低于2.9.0例如 like的版本2.7.0,这可能是更容易的选择,但不是更好。

为了真正使用最新标准,您需要开始在您的代码中实现空安全,例如Key key现在将是Key? key.

更多信息也在这里:https ://dart.dev/null-safety


推荐阅读