Home > Net >  Flutter, best way to work with optional widget inside parent widget
Flutter, best way to work with optional widget inside parent widget

Time:09-17

I'm developing an app that requires me to create widgets with lots of optional components inside them. As you can see in the code below, the Info elements inside my info List only have optional parameters. I don't know what the list is going to look like since I'm going to get it using an API.

I should be able to render just what is present inside the current element. Maybe just the label, or just the number and the image.

I haven't been able to find and example like this one.

class Info {
  int? number;
  String? label;
  Image? image;

  Info({this.number, this.image, this.label});
}

class QuickInfoCard extends StatelessWidget {
  final String title;
  final bool trasparentBackground;
  final List<Info> info;

  const QuickInfoCard({Key? key, required this.title, this.trasparentBackground = false, required this.info}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: trasparentBackground ? Colors.transparent : Theme.of(context).colorScheme.primary,
      child: TextButton(
        style: TextButton.styleFrom(padding: EdgeInsets.all(12), backgroundColor: Colors.white),
        child: Column(
          children: [
            TitleSmall(text: title, color: Theme.of(context).colorScheme.primary),
            Row(
                children: info
                    .map((i) => Column(
                          children: [
                            ButtonTextBig(
                              text: i.number.toString(),
                              color: Theme.of(context).colorScheme.secondary,
                            ),
                            if (i.label != null) CardLabel(text: i.label ?? ""), // I don't like this 
                            if (i.image != null) i.image                         // I can't do this
                          ],
                        ))
                    .toList())
          ],
        ),
        onPressed: () => () {},
      ),
    );
  }
}

Thanks a lot.

CodePudding user response:

Have you tried to create your own widget so you can pass a single Info object to create your column from there?

class InfoWidget extends StatelessWidget{
final Info info;
const InfoWidget({Key? key, required this.info}) : super(key: key);

 @override
 Widget build(BuildContext context) {
    final List<Widget> children = [
        ButtonTextBig(
           text: info.number.toString(),
           color: Theme.of(context).colorScheme.secondary,
        ),
    ];
    if (info.label != null) {
      children.add(CardLabel(text: info.label!));
    }
    if (info.image != null) {
      children.add(info.image!);
    }
    return Column(children: children);

 }

}
  • Related