rahul  Kushwaha
rahul Kushwaha

Reputation: 2819

How to create new widget with extending custom widget in flutter?

In the flutter, I have a very complex widget and its working fine. but for the different part of the app, I want to slightly modify the widget,

To achieve that I have to copy the entire widget with a different name and add the modification,

instead of copying, can we create a new widget with inheriting the widget and overriding widget in flutter?

ex:- consider I have this widget:

class ParentWidget extends StatefulWidget {
  @override
  _ParentWidgetState createState() => _ParentWidgetState();
}

class _ParentWidgetState extends State<ParentWidget> {
  @override
  Widget build(BuildContext context) {
    return Container(

    );
  }
}

and I want to create child widget ex:-

class ChildWidget extends ParentWidget {

}

where I should we able to modify all the aspects of the parent widget.

Upvotes: 4

Views: 7878

Answers (3)

Meisam Beiranvand
Meisam Beiranvand

Reputation: 205

You can pass arguments to ChildWidget constructor method and then pass value to ParentWidget. For example you can modify height of parent Container:

ParentWidget:

class ParentWidget  extends StatefulWidget {
double height;
ParentWidget ({this.height});

@override
State<StatefulWidget> createState() {
  return _ParentWidgetState();
  }
 }
 
 class _ParentWidgetState extends State<ParentWidget> {
 @override
 Widget build(BuildContext context) {
  return Container(
    height: widget.height == null ? 40 : widget.height,
    );
    }
  }

ChildWidget:

class ChildWidget  extends ParentWidget {
  ChildWidget (double height) : super(height: height);
}

In ui you can modify height:

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Column(
          children: <Widget>[
            ParentWidget(),
            ChildWidget(220),
          ],
    );
  }
}

Upvotes: 1

user13573501
user13573501

Reputation:

You shouldn't extend widgets in Flutter

Upvotes: -3

Jitesh Mohite
Jitesh Mohite

Reputation: 34210

Let suppose you have one container which changes its size based on the screen so we can assign values to them in the method parameter like:

1. Common Widget Class

class CommonWidget {
  static Widget getContainer(double width, double height, Widget body) {
    return Container(
      width: width,
      height: height,
      child: body,
    );
  }

2. Usage

Widget body = Center(
      child: Text('Welcome to Home Screen'),
    );
    return Scaffold(
      appBar: AppBar(
        title: Text('Home'),
      ),
      body: CommonWidget.getContainer(100, 100, body), // These params you can change at your preference. 
    );

Upvotes: 1

Related Questions