我正在開發一個測驗應用程式......這個空安全的東西給了我一些錯誤,例如我不能寫:
Answer({this.answerText, this.answerColor});
沒有錯誤:引數“answerColor”因其型別而不能具有“null”值,但隱式默認值為“null”。嘗試添加顯式的非“null”默認值或“required”修飾符。
我已經嘗試改變環境:sdk:版本......它有點作業......但這給了我一個新錯誤......一旦我將版本更改為2.11.0(我有2.15.1)一個新錯誤出現:“這需要啟用 'non-nullable' 語言功能。嘗試更新您的 pubspec.yaml 以將最小 SDK 約束設定為 2.12.0 或更高版本,然后運行 ??'pub get'。” 在這部分代碼中:
class TrigoEjercicios extends StatefulWidget
const TrigoEjercicios({Key? key}) : super(key: key);
在問號上...這個錯誤出現在我的專案中的每個 .dart 檔案中 那么,我該怎么辦?如果這不夠清楚,我深表歉意......我是第一次來這里......如果您需要更多資訊,請告訴我!
uj5u.com熱心網友回復:
我同意@Patricks 的評論。空安全不是這里的問題,(我并不是粗魯的意思),但是您對空安全缺乏了解是。
如果你想在未來繼續構建 Flutter 應用程式,你只需要學習這一點,別無他法。空安全是 Dart 的一個有價值的補充,你不想被拋在后面。
假設你有這個曾經可以作業的類,但現在它給了你一個錯誤。
class Answer {
Answer({this.answerText, this.answerColor}); // error on this constructor
final String answerText;
final Color answerColor;
}
你有幾個選擇。您可以將這兩個引數都設為必需,這消除了任何可能的空值,因為編譯器會強制您傳入一個值。
class Answer {
Answer({required this.answerText, required this.answerColor}); // no more error
final String answerText;
final Color answerColor;
}
或者,如果存在值實際上可以為 null 的情況,則只需使用 a 使引數為 null 即可?。
class Answer {
Answer({this.answerText, this.answerColor}); // no more error
// these are now nullable
final String? answerText;
final Color? answerColor;
}
或者提供默認值
class Answer {
Answer({this.answerText = 'correct', this.answerColor = Colors.blue});
final String answerText;
final Color answerColor;
}
Either one of those will solve the error you mentioned in your post. If you decide to properly convert your app to null safety (you should) then you can expect to go through these errors one by one and make them null safe. It might be tedious, but its worth it.
Another common error you'll probably see is:
a value of String? can't be assigned to a value of String
String here could be any data type, it's just an example.
That is where the bang operator comes into play and you simply add a ! to whatever value you're trying to pass in to tell the compiler that you're sure it won't be null.
There's no shortage of info online about null safety in Dart. Any error you encounter has already been asked about and answered on here, guaranteed. I suggest you just take the time and learn it.
uj5u.com熱心網友回復:
您可以使用varor宣告變數dynamic,現在編譯器不會檢查變數型別。
var answerText;
dynamic answerColor;
Answer({this.answerText, this.answerColor});
如果您嘗試在沒有空安全檢查的情況下進行構建,請// @dart=2.9在 main.dart 第一行中使用此注釋行。
// @dart=2.9
import 'package:flutter/material.dart';
void main() async {
runApp(
const MyApp()
);
}
uj5u.com熱心網友回復:
但是,如果您真的想擺脫,null safety那么您可以做的就是使用--no-sound-null-safety帶有flutter run.
您也可以將其作為引數添加到launch.jsoninVSCode
"configurations": [
{
"name": "Flutter",
"request": "launch",
"type": "dart",
"flutterMode": "debug",
"args": [
"--no-sound-null-safety"
],
},
]
這只是一種替代方法,但任何開發人員都不建議這樣做。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449184.html
