Subclass a class that extends StatelessWidget or StatefulWidget class

前端 未结 4 978
醉话见心
醉话见心 2020-12-01 18:13

Is it possible to create a class that extends a class extending StatelessWidget or StatefulWidget.

For example:

class MyButton extends StatelessWidge         


        
4条回答
  •  情歌与酒
    2020-12-01 18:59

    As stated by Gunter, flutter uses composition over inheritance.

    Official source : flutter faq

    Rather than having each widget provide a large number of parameters, Flutter embraces composition. Widgets are built out of smaller widgets that you can reuse and combine in novel ways to make custom widgets. For example, rather than subclassing a generic button widget, RaisedButton combines a Material widget with a GestureDetector widget. The Material widget provides the visual design and the GestureDetector widget provides the interaction design.

    This means that instead of extending a Widget, you should create a smaller one and then reuse it.

    A practical example would be a base button :

    class MyButton extends StatelessWidget {
      final Color color;
    
      MyButton({this.color = Colors.grey, Key key}): super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return Container(
          color: color,
          child: Text("My Button"),
        );
      }
    }
    

    Then reused using composition to create a more specific type of button :

    class OutlineButton extends StatelessWidget {
      final Color color;
    
      OutlineButton({this.color = Colors.grey, Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return DecoratedBox(
          decoration: BoxDecoration(
            border: Border.all(
              color: color,
              width: 2.0,
              style: BorderStyle.solid,
            ),
          ),
          child: MyButton(
            color: color,
          ),
        );
      }
    }
    

提交回复
热议问题