初始化程序中只有静态成员

时间:2018-06-17 20:26:22

标签: dart flutter

我尝试做一些教程,在将一个类对象传递给我的小部件时遇到了一些问题而且我完全迷失了...

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,
    ),
  );

我完全不理解这个错误可以有人帮忙吗?

1 个答案:

答案 0 :(得分:3)

类成员变量planet,(因为它不是静态变量)将在构造函数中获取其值,因此我们不能使用一个非静态类成员变量将值赋给另一个非静态类成员。如果您不想使用planet为您的窗口小部件赋值,请将您的类更改为StatefulWidget,您可以尝试声明非最终变量_planetThumbnail并在类的iniState方法中指定其值

@override
void initState(){
  super.initState();
  _planetThumbnail = <your widget initialization code>
}

如果你只想使用StatelessWidget类,那么只需在构建方法中创建_planetThumbnil小部件并使用它。