Home > database >  How to create custom types of widgets in Flutter?
How to create custom types of widgets in Flutter?

Time:04-14

I am trying to create a couple of widgets A that all should belong to another type of widget B, so that in the end all of them could be passed to a constructor that accepts only widgets of type B, but not other custom widgets like Container, Text, etc.

I tried something like this:

Parent class:

class ProDynamicWidget {

  const ProDynamicWidget({
    required this.height
  });

  final double height;
}

Child classes:

class ProDynamicTitle extends ProDynamicWidget {

  final String title;

  ProDynamicTitle({
    required this.title
  }) : super(height: 50.0);

  // Here should be a build method for the title

}

############################################################

class ProDynamicImage extends ProDynamicWidget {

  final String imageUrl;

  ProDynamicImage({
    required this.imageUrl
  }) : super(height: 70.0);

  // Here should be a build method for the image

}

I then wanted to create a widget that only accept widgets of type ProDynamicWidget:

class TestOneWidget extends StatelessWidget {

  const TestOneWidget({ 
    Key? key,
    required this.widget
  }) : super(key: key);

  final ProDynamicWidget widget;

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

I do not really get how can now end up with child widgets that have separate build methods and a way the constructur at the end only accepts these child widgets instead of every type of widget.

CodePudding user response:

Make ProDynamicWidget abstract and let it extend StatelessWidget:

abstract class ProDynamicWidget extends StatelessWidget{

  const ProDynamicWidget({
    required this.height
  });

  final double height;
}

Next, ProDynamicTitle and ProDynamicImage simply extend ProDynamicWidget and will thus have to define the build method:

class ProDynamicTitle extends ProDynamicWidget {

  final String title;

  const ProDynamicTitle({
    required this.title
  }) : super(height: 50.0);

  @override
  Widget build(BuildContext context) {
    return Text(title);
  }
}

class ProDynamicImage extends ProDynamicWidget {

  final String imageUrl;

  const ProDynamicImage({
    required this.imageUrl
  }) : super(height: 70.0);

  @override
  Widget build(BuildContext context) {
    return Image(image: NetworkImage(imageUrl));
  }
}

You can keep TestOneWidget as is. It will only accept descendants of ProDynamicWidget.

  • Related