How do you create a list of objects to pass to a widget in Flutter?

2

I'm new to Flutter and I am trying to find out how to create a list of objects like below and pass it to a widget so I can use it like _imageList[0].label, _imageList[0].path and etc...

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'
  });

Any help is much appreciated. Thanks in advance

flutter
dart
asked on Stack Overflow Aug 8, 2020 by zosozo • edited Aug 10, 2020 by zosozo

1 Answer

2

Create a class.

class AppImage{
  String image;
  String path;
  String active;
  String inactive;
  
  AppImage({this.image, this.path, this.active, this.inactive});
  
}

Now you can use it as a list of Objects;

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

And you can use the values accordingly:


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

To learn more, check out this article.

answered on Stack Overflow Aug 8, 2020 by Wilson Wilson • edited Aug 8, 2020 by Wilson Wilson

User contributions licensed under CC BY-SA 3.0