在FLUTTER/DART中,为什么我们有时在声明变量时会在“String”中添加一个问号?
在演示应用程序中,我们找到了一个“final String? title;”的实例。 -> 为什么要加这个“?” 在类型 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永远不能为空,并且在编译之前你会得到一个错误。
如果您定义了一个变量String? name,并且您想稍后在 Text 小部件中使用它,您将收到一个错误。因为 Text 小部件只接受不可为空的类型。但是如果你确定它name永远不会为空,你告诉 flutter 不要担心它并且你知道你在做什么,你可以通过添加! 这样的 : 来做到这一点Text(name!)。
回答
variable_type ? name_of_variable;意味着name_of_variable可以为空。
variable_type name_of_variable1; 意味着name_of_variable1不能为空,你应该立即初始化它。
late variable_type name_of_variable2; 意味着name_of_variable2不能为 null,您可以稍后对其进行初始化。
late variable_type name_of_variable3;
variable_type ? name_of_variable4;
name_of_variable4=some_data;
name_of_variable3=name_of_variable4!;// name_of_variable4! means that you are sure 100% it never will be null
int 类型的真实示例:
int ? a=null; // OK
int b=null; // b cannot be equal null
late int c =null; // c cannot be equal null
late int d;
d=5; //OK
late int d; // if you never initialize it, you ll got exception
int e=5;
int? f=4;
int ? z;
e=f!; // OK, You are sure that f never are null
e=z!;// You get exception because z is equal null
THE END
二维码