尝试声明一个类,需要一个 “主体” 吗?

huangapple go评论58阅读模式
英文:

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 &#39;package:flutter/material.dart&#39;;

// a list of events indexed by number
class EventList{
  Map&lt;int, String&gt; event_list = {};

  EventList(){
    event_list[0] = &quot;Hello!&quot;;
  }
}

However, when I try an use it in my main class, I get an error:

EventList eventList();

The error is:

error: &#39;eventList&#39; must have a method body because &#39;_homeState&#39; isn&#39;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&lt;int, String&gt; event_list = {};

  EventList() {
    event_list = {0: &quot;Hello!&quot;};
  }
}

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.

huangapple
  • 本文由 发表于 2023年6月26日 11:21:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76553341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定