对空值使用空检查运算符

2023-12-15

我是新来的Flutter

当我运行我的简单扑动应用程序时,出现此错误。我不明白为什么会发生这个错误。

Error

Null check operator used on a null value

我在 main.dart 中的代码

import 'package:flutter/material.dart';
import './ui/login.dart';

void main() {
  
  runApp(new MaterialApp(
    title: "Login Template",
    home: new Login(),
  ));
}

我在login.dart中的代码

import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new LoginState();
  }
}

class LoginState extends State<Login> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Login"),
        centerTitle: true,
        backgroundColor: Colors.blueAccent.shade50,
      ),
      backgroundColor: Colors.blueGrey,
      body: new Container(

      ),
    );
  }
}

代码错误追踪

Running Gradle task 'assembleDebug'...
✓ Built build/app/outputs/flutter-apk/app-debug.apk.
Installing build/app/outputs/flutter-apk/app.apk...
Waiting for SM J710F to report its views...
D/vndksupport(29495): Loading /vendor/lib/hw/[email protected] from current namespace instead of sphal namespace.
Debug service listening on ws://127.0.0.1:39899/9RorUiKtUb4=/ws
Syncing files to device SM J710F...
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 582) vi=Rect(0, 48 - 0, 582) or=1
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_WINDOW_FOCUS_CHANGED 1
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@3049fea nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=96
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@aad92db nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_RESIZED: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
D/ViewRootImpl@4ac1ef4[MainActivity](29495): Relayout returned: old=[0,0][720,1280] new=[0,0][720,1280] result=0x1 surface={valid=true 3791374336} changed=false
D/libGLESv2(29495): STS_GLApi : DTS, ODTC are not allowed for Package : com.sivaram.login_template

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
Null check operator used on a null value
Login file:///home/kadavul/IdeaProjects/login_template/lib/main.dart:8:15
════════════════════════════════════════════════════════════════════════════════════════════════════
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@a0ff0af nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=87
D/InputTransport(29495): Input channel destroyed: fd=96
D/SurfaceView(29495): windowStopped(true) false 77b9092 of ViewRootImpl@4ac1ef4[MainActivity]
D/SurfaceView(29495): BG show() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@0) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/SurfaceView(29495): surfaceDestroyed 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@a78fcbc nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=91
D/InputTransport(29495): Input channel destroyed: fd=87
D/SurfaceView(29495): windowStopped(false) true 77b9092 of ViewRootImpl@4ac1ef4[MainActivity]
D/SurfaceView(29495): BG show() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@1) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
V/Surface (29495): sf_framedrop debug : 0x4f4c, game : false, logging : 0
D/SurfaceView(29495): surfaceCreated 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/mali_winsys(29495): EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, egl_color_buffer_format *, EGLBoolean) returns 0x3000,  [720x1280]-format:1
D/SurfaceView(29495): surfaceChanged (720,1280) 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/SurfaceView(29495): BG destroy() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@0) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/ViewRootImpl@4ac1ef4[MainActivity](29495): Relayout returned: old=[0,0][720,1280] new=[0,0][720,1280] result=0x3 surface={valid=true 3791374336} changed=false
D/ViewRootImpl@4ac1ef4[MainActivity](29495): MSG_RESIZED_REPORT: frame=Rect(0, 0 - 720, 1280) ci=Rect(0, 48 - 0, 0) vi=Rect(0, 48 - 0, 0) or=1
V/InputMethodManager(29495): Starting input: tba=android.view.inputmethod.EditorInfo@7ed1445 nm : com.sivaram.login_template ic=null
D/InputMethodManager(29495): startInputInner - Id : 0
I/InputMethodManager(29495): startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport(29495): Input channel constructed: fd=92
D/InputTransport(29495): Input channel destroyed: fd=91
D/SurfaceView(29495): windowStopped(true) false 77b9092 of ViewRootImpl@4ac1ef4[MainActivity]
D/SurfaceView(29495): BG show() Surface(name=Background for - SurfaceView - com.sivaram.login_template/com.sivaram.login_template.MainActivity@77b9092@1) io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}
D/SurfaceView(29495): surfaceDestroyed 1 #1 io.flutter.embedding.android.FlutterSurfaceView{77b9092 V.E...... ........ 0,0-720,1280}

我的颤振医生输出


fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
Doctor summary (to see all details, run flutter doctor -v):
Failed to find the latest git commit date: VersionCheckError: Command exited with code 128: git -c log.showSignature=false log -n 1 --pretty=format:%ad --date=iso
Standard out: 
Standard error: fatal: your current branch 'master' does not have any commits yet

Returning 1970-01-01 05:30:00.000 instead.
[✓] Flutter (Channel unknown, 0.0.0-unknown, on Linux, locale en_US.UTF-8)
 
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[✓] Android Studio (version 4.0)
[!] VS Code (version 1.50.0)
    ✗ Flutter extension not installed; install from
      https://marketplace.visualstudio.com/items?itemName=Dart-Code.flutter
[✓] Connected device (1 available)

! Doctor found issues in 1 category.

任何人都可以为此提供解决方案吗?


不要降级 Flutter

Problem:

当您使用 bang 运算符 (!)在未初始化的可为空实例上。

例如:

String? string; // Nullable String

void main() {
  var len = string!.length; // Runtime error: Null check operator used on a null value
}

解决方案:

打开日志,肯定有一行指向项目中发生错误的文件:

对空值使用空检查运算符

#0 主要(包:example/main.dart:22:16)

到达那里后,您可以使用以下任一方法来修复它:

  • 使用局部变量

    var s = string;
    if (s != null) {
      var len = s.length; // Safe 
    }
    
  • Use ?. and ??

    var len = string?.length ?? 0; // Provide a default value if string was null.
    

堆栈跟踪还可以指向不属于您的项目的文件。例如:

1. 对于那些正在使用Navigator or MediaQuery

当您尝试访问BuildContext异步地。

因此,您应该首先检查小部件是否是mounted访问之前BuildContext.

Future<void> foo() async {
  // Some async operation
  await compute();  

  // Check `mounted` before accessing 'context'.
  if (mounted) {
    MediaQuery.of(context).size;
    Navigator.of(context).pop();  
  }
}

2. 对于那些正在使用Color

你正在使用

Colors.blueAccent.shade50

哪个没有50th 阴影。如果你查看源代码,你会发现:

Color get shade50 => this[50]!; // <-- This bang operator is causing the error.

要解决此错误,您应该使用一些其他颜色,而不是null,也许是100阴凉处。

Colors.blueAccent[100]
// or
Colors.blue.shade100

3. 对于那些正在使用FutureBuilder/StreamBuilder:

您可以通过两种方式解决该错误:

  • 指定您的类型FutureBuilder/StreamBuilder

    FutureBuilder<List<int>>( // <-- type 'List<int>' is specified.
      future: _listOfInt(),
      builder: (_, snapshot) {
        if (snapshot.hasData) {
          List<int> myList = snapshot.data!; // <-- Your data
        }
        return Container();
      },
    )
    
  • Use as沮丧Object根据您的类型,说出List or Map.

    FutureBuilder(
      future: _listOfInt(),
      builder: (_, snapshot) {
        if (snapshot.hasData) {
          var myList = snapshot.data! as List<int>; // <-- Your data using 'as'
        }
        return Container();
      },
    )
    
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对空值使用空检查运算符 的相关文章

随机推荐

  • 公共字段类型的多态性

    这个问题可以通过以下方式解决吗功能惯用语方法 可以generics or 受歧视的工会是答案吗 当函数使用一些公共字段时 是否可以通过将不同类型传递给函数来实现多态性 想法是能够调用和重用不同类型的函数并使用公共属性 字段 type Car
  • 如何在 C# 中使用开放硬件监视器源代码?我尝试了一切都不起作用

    我在 Form1 中有这段代码 using System using System Collections Generic using System ComponentModel using System Data using System
  • pip 安装 /usr/local/opt/python/bin/python2.7: 错误的解释器: 没有这样的文件或目录

    我不知道这是怎么回事 但我一直遵循一些 stackoverflow 解决方案 但毫无进展 你能帮我解决这个问题吗 Monas MacBook Pro CS764 mona sudo python get pip py The directo
  • 下载的 Facebook 应用程序取代了我的应用程序的 Facebook 登录页面

    我即将完成我的申请 但我在使用 facebook 和 twitter 时遇到了一些问题 1 我已经在我的设备中下载并安装了 facebook 应用程序 但现在当我的应用程序按照流程在 facebook 上重定向时 它会打开已安装的 face
  • 换行符后带有三个点的python字符串...这是什么东西?

    我今天才第一次看到这个 这个三点的东西叫什么 它的用途是什么 我的猜测是为了帮助提高可读性 这是我看到的例子 g S gt NP VP PP gt P NP NP gt Det N Det N PP I VP gt V NP VP PP D
  • 阻止扫描仪读取用户输入java?

    我正在尝试编写这个方法 它会不断从用户那里读取数据 直到输入 退出 一词 我尝试使用break和for循环 它不起作用 我尝试使用 while 但即使输入 退出 一词 它也不会停止 任何想法如何解决这一问题 谢谢 public void r
  • msysgit - sh.exe - fork:权限被拒绝 - Vista 64 位

    我在其他 Windows 机器上安装 msysgit 没有任何问题 在这个 Vista 64 位 Ultimate 机器上 我安装了 3 个最新版本的 msysgit 在所有三个安装中 当我在此处执行 git bash 时 我会在命令窗口中
  • ggplot 中 Hmisc 标记对象的问题

    我收到消息 错误 没有适用于 round any 的方法应用于对象 标记 类 当我尝试使用绘制图表时ggplot2和 R 我已经在我的数据框中标记了我的变量Hmisc label我认为这就是问题所在 我该如何解决这个问题 我的标签如下所示
  • 为什么css高度100%不适用于普通div?

    这是我的简单代码 div div CSS高度100 不适用于DIV 我知道一些其他的 css 代码来获取这个 但为什么这段代码不起作用 如何在没有任何脚本的情况下处理高度 100 和宽度 100 For 要工作 您需要设置高度parent
  • 使用 travis-ci 和 wxpython 测试

    我正在尝试添加一些 wxPython 测试以与 travis ci 一起使用 但我不知道如何在构建环境中安装 wxPython 我使用brew在我的计算机上安装了wxPython 但是我无法让brew与travis ci一起使用 在 tra
  • 如何使用 PHP-Parser 获取全局变量名称并更改它

    我想用PHP解析器库来获取全局方法 POST GET REQUEST 获取 PHP 中的值 我在用着PHP解析器我想检查节点名称是否等于 POST GET REQUEST 我还是 PHP Parser 的初学者 不知道如何获取这些全局变量
  • 尽管值在 getPreviewFpsRange 的范围内,但 setPreviewFpsRange 不起作用

    这个简单的代码 Camera Parameters params currentCamera getParameters params setPreviewFpsRange 10000 15000 currentCamera setPara
  • JSPDF - 如何将具有不同页面尺寸(高度和宽度)的多个图像导出到单个 pdf 文件

    我有多个不同尺寸 高度和宽度 的图像 需要使用 jspdf 将其转换为 PDF 但使用时遇到问题addPage 函数来做到这一点 是否可以将不同页面大小的图像导出到单个 pdf 中 我实际上可以使用以下命令添加具有不同图像尺寸的多个页面ad
  • JPanel 上的 MouseEvent - 坐标错误

    我用Java编写了以下微型画笔程序 import java awt BorderLayout import java awt Color import java awt Container import java awt Graphics
  • Clojure 的 :require 和 Instaparse

    我正在尝试使用即时解析我的 Clojure 项目的 lib 我在项目依赖项中使用 leiningen 2 0 和 clojure 1 5 1 我将 instaparse 添加到我的项目依赖项中 如下所示 defproject bachelo
  • 实现 DHCP 客户端

    在使用 C 的 UNIX 上 我的客户端正在以超级用户模式侦听端口 68 发送 DHCP 发现消息后 当我尝试接收时 它会阻塞在 recvfrom 中 这意味着没有收到消息 或者系统是否有一个进程 DHCP 客户端 在同一端口 68 上监听
  • 如何在新项目中重用 Eclipse 启动文件

    我刚刚在 eclipse 中检查了一个 svn 项目作为 java 项目 其中有几个运行启动文件我想重用 但不知道如何指向 运行 来查看这些启动文件或使用它 有什么建议吗 谢谢 通常这些会被项目自动选取并放置在运行菜单中 如果不是 请右键单
  • Google 表单中的 FILE_UPLOAD 项目类型

    谷歌最近在其表单中添加了文件上传功能 但是 我无法找到任何有关如何在谷歌脚本中使用它的文档 如果我在 google 上查看 item types API 它没有列出 https developers google com apps scri
  • iOS 音频操作 - 向后播放本地 .caf 文件

    我想要加载本地 caf 音频文件并反转音频 向后播放 我发现我基本上需要从帖子中翻转一系列缓冲区数据this 但是 我不确定如何从给定的音频文件访问此缓冲区数据 我有一些使用 AVaudioPlayer 和 ObjectAL 一个 obj
  • 对空值使用空检查运算符

    我是新来的Flutter 当我运行我的简单扑动应用程序时 出现此错误 我不明白为什么会发生这个错误 Error Null check operator used on a null value 我在 main dart 中的代码 impor