如何创建对象列表以传递给 Flutter 中的小部件?

zos*_*ozo 7 dart flutter

我是 Flutter 新手,我试图找出如何创建如下所示的对象列表并将其传递给小部件,以便我可以使用它,例如 _imageList[0].label、_imageList[0].path 等。 ..

List<Object> _imageList = List(); <-

_imageList.add({
    'label': 'Image1',
    'path': 'lib/assets/image/image1.png',
    'active': '0xFFFFFFFF',
    'inactive': '0x32FFFFFF'
  });

_imageList.add({
    'label': 'Image2',
    'path': 'lib/assets/image/image2.png',
    'active': '0xFFFFFFFF',
    'inactive': '0x32FFFFFF'
  });
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢。提前致谢

Wil*_*son 20

创建一个类。

class AppImage{
  String? image;
  String? path;
  String? active;
  String? inactive;

// added '?'
  
  AppImage({this.image, this.path, this.active, this.inactive});
  // can also add 'required' keyword
}

Run Code Online (Sandbox Code Playgroud)

现在您可以将其用作对象列表;

List<AppImage> images = [
    AppImage(image: "imageUrl", path: "path", active: "active", inactive: "inactive"),
    
     AppImage(image: "imageUrl2", path: "path2", active: "active2", inactive: "inactive2"),
  ];
Run Code Online (Sandbox Code Playgroud)

您可以相应地使用这些值:


AppImage appImage = images[0];
  print(appImage.path);

Run Code Online (Sandbox Code Playgroud)

要了解更多信息,请查看这篇文章