Home > OS >  Is it possible to create flutter widgets that inherit from other widgets?
Is it possible to create flutter widgets that inherit from other widgets?

Time:12-24

I'm looking into how to write my own widgets. I've seen a number of examples that have a CustomWidget that either inherits from StatefulWidget or StatelessWidget. Is it possible to inherit from Stack or TextBox or one of the widgets that I've seen returned from build? What I'm thinking of is taking a widget like TextBox, adding custom theming, and then exporting it as a new widget to use.

I've seen a lot of examples using Material UI. For my needs, I need something less cookie-cutter that let's me deside what things are meant to look like how they should style.

Thanks.

CodePudding user response:

Yes, you can create a widget extending some other widget but you will probably need to conform to its super constructor.

You are talking about TextBox in your question but it is not a widget so I'm guessing that you were talking about the Text widget or a similar one. Here's a code sample of how you could create your own widget :

class MyText extends Text {
  const MyText() : super("my-text"); // Need to pass a data value to the super constructor.

  /// You can override the base build method to return a different widget,
  /// in this case I am returning the base super.build (which will render
  /// the Text widget) wrapped inside a red Container.
  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      child: super.build(context),
    );
  }
}

Try the full test code on DartPad

CodePudding user response:

What I'm thinking of is taking a widget like TextBox, adding custom theming, and then exporting it as a new widget to use.

Then, creating a new custom widget by extending TextBox in not the way to go.

If you do that, you will have to hardcode every properties of the constructor of TextBox in yours. It will be a pain to do and to maintain.

FLutter base principle in Composition over Inheritance.

So, in order to achieve what you need (Theming), you just have to use Theme capabilities :

// global theming once and for all for all the app
MaterialApp(
  theme: ThemeData(inputDecorationTheme: InputDecorationTheme()),
  home: const MyHomePage(),
);

or

// located theme overload just for here
Theme(data: Theme.of(context).copyWith(inputDecorationTheme: InputDecorationTheme()), child: TextFormField());

Theming only may be not enough but you really should avoid inheriting complex native widgets, prefer composition of property factorisation

  • Related