Home > front end >  Flutter: Instantiate object with multiple parameters
Flutter: Instantiate object with multiple parameters

Time:02-01

I've encountered a syntactical (i guess?) problem when trying to instantiate an object from my predefined constructor.

Category(String kategorieName, Image cover){
  kategorieTitel = kategorieName;
  kategorieCover = cover;
}

I tried to create a dynamic list which will later be used to auto-fill constructors in a ListView.builder.

  List kategorien = [
{
  'name' : 'Location1',
  'pic' : Asset.Image('assets/img/Locations.jpg')
},
{
  'name' : 'Location2',
   ...
}];

Auto-Filling the name works fine but I wasn't able to call the constructor with the according image-file.

  child: ListView.builder(
    itemCount: kategorien.length,
    itemBuilder: (context, index){
      return Padding(
        padding: EdgeInsets.all(5.0),
        child: Category('${kategorien[index]['name']}'),

I've tried concatenation like Category('${kategorien[index]['name']}', '${kategorien[index][pic]}')

I have no idea how to give the constructor the image by the list. I'd be very thankful for help!

CodePudding user response:

You can try the following code:

/// Category needs to be a widget so it can be assigned
/// to the child property of the Padding widget.
class Category extends StatelessWidget {
  final String kategorieName;
  final ImageProvider cover; // AssetImage is part of the ImageProvider interface not Image.

  const Category(this.kategorieName, this.cover);

  // As Category is a widget you will need to override the build method.
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 100, // You can adapt the height depending on your needs
      decoration: BoxDecoration(
        image: DecorationImage(image: cover),
      ),
    );
  }
}
final kategorien = <Map<String, dynamic>>[
  {
    'name': 'Location1',
    'pic': const AssetImage('assets/img/Locations.jpg'), // AssetImage is the correct way of casting your image.
  },
  {
    'name': 'Location2',
    'pic': const AssetImage('assets/img/Locations.jpg'),
  },
];
class MyImages extends StatelessWidget {
  const MyImages({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: kategorien.length,
      itemBuilder: (_, index) {
        final element = kategorien.elementAt(index);
        return Padding(
          padding: const EdgeInsets.all(5.0),
          child: Category(
            '${element['name']}',
            element['pic'] as ImageProvider, // You need to cast the pic field as ImageProvider.
          ),
        );
      },
    );
  }
}
  •  Tags:  
  • Related