您好,我開始使用 AndroidStudio IDE 學習 Flutter。當我跟隨視頻學習時,我像在視頻中一樣更改了我的代碼。但是存在差異,這種差異使我出錯。
import 'package:flutterogrencitakip/models/student.dart';
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
List<Student> students = [
Student.withId(1, "Yusuf", "Erarslan", 95),
Student.withId(2, "Yusufff", "Erarslassn", 35),
Student.withId(3, "YusufffAAA", "ErAAAarslassn", 15)
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("??renci Takip Sistemi"),
),
body: buildBody());
}
Widget buildBody() {
return Column(
children:<Widget>[
Expanded(
child: ListView.builder(
itemCount: students.length,
itemBuilder: (BuildContext context, int index){
return Text(students[index].firstName);
}),
)
],
);
}
}
即使我在模型檔案夾中有 student.dart ,這段代碼也會讓我出錯。這是輸出。
lib/main.dart:40:42: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
return Text(students[index].firstName);
這是因為我使用 return 而不是 throw 還是我的 void main class 和 class myApp classes 有錯誤的定義?因為它是那樣的。
void main(){
const MyApp bla bla bla i can't remember exactly
}
截圖
我的專案檔案夾:

我的問題:

我改變的區域:

我的學生班:
class Student{
int? id;
String? firstName;
String? lastName;
int? grade;
String? status;
(String firstName, String lastName, int grade){
this.firstName= firstName;
this.lastName= lastName;
this.grade = grade;
}
//named constructor
Student.withId(int id,String firstName, String lastName, int grade){
this.id=id;
this.firstName= firstName;
this.lastName= lastName;
this.grade = grade;
}
}
uj5u.com熱心網友回復:
這里的問題是Text小部件接受String(不接受空值)而不是String?(可空值)的引數型別。
對此的一種解決方案是捕獲您提供的字串(在本例中為名字)是否為空
return Text(students[index].firstName ?? '');
''如果students[index].firstName是null,上面的代碼將輸出;
uj5u.com熱心網友回復:
在您的模型類上Student定義為 nullable String? firstName;
但是一個Text小部件需要一個真實的文本,而不是空的。所以我會建議檢查 null 然后分配它,或者你可以提供這樣的默認值:
Text(students[index].firstName ?? '');
檢查更多關于空安全
如果您絕對確定您的可為空字串實際上具有值,則可以!在末尾添加:
Text(students[index].firstName!)
Bang
!運算子只是告訴 Dart,即使我們將某個變數定義為 Nullable 型別,它也絕對不會為 null。有關bang 運算子問題的更多資訊
uj5u.com熱心網友回復:
發生這種情況是因為變數可以firstName?為空。這意味著在某個時候它可能是null,Text()只接受String所以程式明白在某個時候它可能會得到一個null而不是一個String然后拋出錯誤。
在您的模型中,使變數不可為空,它應該可以作業。
firstName 代替 firstName?
請注意,如果您這樣做,變數firstName將始終需要值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369232.html
