【发布时间】:2021-10-22 10:32:49
【问题描述】:
我是 Flutter 的新手,所以我正在试验它,我尝试在 vs 代码中创建一个自定义类和该类的构造函数,我不断收到关于类构造函数的错误消息。错误如下所示“必须初始化不可为空的实例字段作者(这是类的属性之一的名称)idk这是什么错误我已经尝试了各种在线资源但只是徒劳无功。看看代码和识别错误的帮助将非常有帮助。
代码:
import 'package:flutter/material.dart';
import 'quote_class.dart';
void main() {
runApp(const MaterialApp(
home: Home(),
debugShowCheckedModeBanner: false,
));
}
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Quotes> quotes = [
Quotes(
"Be yoursefl cause everyone else is taken","Oscar Wilde"),
Quotes(
"I have nothing to declare except my genius", "Einstien"),
Quotes(
"The truth is rarely pure and never simple", "Priyanka"),
Quotes(
"Trust those who are still in the search of truth and not those who has already found one","Hey")
];
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue[400],
appBar: AppBar(
title: const Text("Awesome Quotes"),
centerTitle: true,
backgroundColor: Colors.purple[200],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: quotes
.map((quote) => Text('${quote.text} - ${quote.author}'))
.toList(),
));
}
}
出现错误的自定义类的代码,我正在尝试使用上述 main.dart 文件中的自定义类
class Quotes {
String text;
String author;
Quotes(String text, String author) {
this.text = text;
this.author = author;
}
}
错误信息:
lib/quote.dart:5:16: Error: The parameter 'text' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
Quotes({this.text, this.author});
^^^^
lib/quote.dart:5:27: Error: The parameter 'author' can't have a value of 'null' because of its type 'String', but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.
Quotes({this.text, this.author});
^^^^^^
【问题讨论】: