dart - 初始化器中只有静态成员
问题描述
我正在尝试做一些教程,在将类对象传递给我的小部件时遇到了一些问题,我完全迷失了这个......
class Planet {
String id;
String name;
String location;
String distance;
String gravity;
String description;
String image;
String picture;
Planet({this.id, this.name, this.location, this.distance, this.gravity, this.description, this.image, this.picture});
}
List<Planet> planets = <Planet>[
Planet(
id: "1",
name: "Mars",
location: "Milkyway Galaxy",
distance: "54.6m Km",
gravity: "3.711 m/s ",
description:
"Mars is the fourth planet from the Sun and the second-smallest planet in the Solar System after Mercury. In English, Mars carries a name of the Roman god of war, and is often referred to as the 'Red Planet' because the reddish iron oxide prevalent on its surface gives it a reddish appearance that is distinctive among the astronomical bodies visible to the naked eye. Mars is a terrestrial planet with a thin atmosphere, having surface features reminiscent both of the impact craters of the Moon and the valleys, deserts, and polar ice caps of Earth.",
image: "assets/images/mars.png",
picture: "https://www.nasa.gov/sites/default/files/thumbnails/image/pia21723-16.jpg"),
];
在我的小部件中,我有:
class PlanetSummary extends StatelessWidget {
final Planet planet;
PlanetSummary(this.planet);
final Widget _planetThumbnail = new Container(
margin: new EdgeInsets.symmetric(vertical: 16.0),
alignment: FractionalOffset.centerLeft,
child: new Image(
image: new AssetImage(planet.image), // <---- ERROR (planet.name) only static member can be accessed in initializers
height: 92.0,
width: 92.0,
),
);
我完全不明白这个错误有人可以帮忙吗?
解决方案
类成员变量planet,(因为它不是静态变量)将在构造函数中获取它的值,所以我们不能使用一个非静态类成员变量来为另一个非静态类成员赋值。如果您不想使用行星为您的小部件分配值,请将您的类更改为 StatefulWidget,您可以尝试仅声明非最终变量 _planetThumbnail 并在类的 iniState 方法中分配其值
@override
void initState(){
super.initState();
_planetThumbnail = <your widget initialization code>
}
如果您只想使用 StatelessWidget 类,那么只需在 build 方法中创建 _planetThumbnil 小部件并使用它。
推荐阅读
- linux - 如何修改 Apigee 默认 LDAP 策略
- python - 无法使用请求从网页中抓取某个字段,即使该字段在页面源中可用
- c - 如何在C中的一个块中分配具有数组的结构?
- typescript - 输入一个接受任何纯一元函数作为可选参数的高阶函数
- java - 如何避免 Java 可执行 jar 中的 NullPointerException?
- c++ - ServerSupportFunction 询问 DWORD 是否为空终止字符串,在 64 位上怎么办?
- pygame - 在 Pygame 中将新对象绘制在顶部后,如何防止以前绘制的对象被点击?
- amazon-web-services - AWS Athena alb 日志:每天获取请求 url 每分钟的最大点击次数
- vue.js - Laravel 7 Auth Intended 不适用于 Vue SPA
- javascript - 访问 dataLayer 中的数组并发送到自定义维度