在 FLUTTER/DART 中,为什么我们有时会在“String"中添加一个问号?声明变量时? [英] In FLUTTER / DART, why do we sometimes add a question mark to "String" when declaring a variable?

查看:60
本文介绍了在 FLUTTER/DART 中,为什么我们有时会在“String"中添加一个问号?声明变量时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在演示应用程序中,我们找到了一个 "final String?标题;" - >为什么要加上这个?"?在类型 String 之后?

In the demo app, we find an instance of "final String? title;" - > Why do we add this "?" after the type String ?

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  **final String? title;**

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

同理,为什么在使用的时候,我们要加一个!"?

return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: **Text(widget.title!),**
      ),
      body: Center(

推荐答案

这是具有空安全性的,问号意味着这个 String? 可能为空,flutter 将允许您分配空到它.String 不能为空,编译前会报错.

This is with null safety, the question mark means that this String? can possibly be null and flutter will allow you to assign null to it. String can never be null and you'll get an error before compiling.

如果你定义一个变量 String?name,并且您想稍后在 Text 小部件中使用它,您将收到错误消息.因为 Text 小部件只接受不可为空的类型.但是如果你确定 name 永远不会为空,你告诉 flutter 不要担心它并且你知道你在做什么,你可以通过添加 !像这样:Text(name!).

If you define a variable String? name, and you want to use it later in a Text widget, you'll get an error. Because Text widgets only accept non-nullable types. But if you are sure that name will never be null, you tell flutter to not worry about it and that you know what you are doing, you do this by adding the ! like this : Text(name!).

这篇关于在 FLUTTER/DART 中,为什么我们有时会在“String"中添加一个问号?声明变量时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆