英文:
Trying to declare a class, needs a "home" body?
问题
// 一个按编号索引的事件列表
class EventList{
Map<int, String> event_list = {};
EventList(){
event_list[0] = "你好!";
}
}
// 但是,当我尝试在我的主类中使用它时,我收到一个错误:
EventList eventList();
错误信息:
错误: 'eventList' 必须有一个方法体,因为 '_homeState' 不是抽象的。
英文:
I am trying to make a class with a list of numbered events and then will use that in another class.
import 'package:flutter/material.dart';
// a list of events indexed by number
class EventList{
Map<int, String> event_list = {};
EventList(){
event_list[0] = "Hello!";
}
}
However, when I try an use it in my main class, I get an error:
EventList eventList();
The error is:
error: 'eventList' must have a method body because '_homeState' isn't abstract. (concrete_class_with_abstract_member at [citadel_test] lib\pages\home.dart:12)
I realize I can't use an empty constructor, but even when I change it to use an optional color paramter, I get the same error.
答案1
得分: 2
更新你的代码如下:
// 一个以数字为索引的事件列表
class EventList {
Map<int, String> event_list = {};
EventList() {
event_list = {0: "你好!"};
}
}
然后像这样使用它:
EventList eventList = EventList();
英文:
Update your code like this
// a list of events indexed by number
class EventList {
Map<int, String> event_list = {};
EventList() {
event_list = {0: "Hello!"};
}
}
then use it like this
EventList eventList = EventList();
答案2
得分: 0
这不是一个构造函数调用。这是一个名为`eventList`的方法声明,不接受任何参数并返回一个`EventList`。这只是一个声明,没有方法体(在`{`和`}`中的代码)。这就是为什么会出现错误,因为您的类不能有一个没有方法体的方法。
如果您想要在您的类中拥有一个类型为`EventList`的字段,它应该是:
EventList eventList = EventList();
这将创建一个类型为`EventList`的字段,并使用构造函数调用的结果填充它。
英文:
EventList eventList();
This is not a constructor call. This is the declaration of a method called eventList
, taking no parameters and returning an EventList
. It is just the declaration, with no body (code in {
and }
). That is why you get the error, that you class cannot have a method with no body.
If you want a field of type EventList
in your class, it needs to be:
EventList eventList = EventList();
This creates a field of type EventList
and fills it with the result of the constructor call.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论