Subclass a class that extends StatelessWidget or StatefulWidget class

前端 未结 4 991
醉话见心
醉话见心 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 19:09

    If you strongly need to extend a widget that already extends StatefulWidget you can do something like this:

    class WidgetFoo extends StatefulWidget {
      final String varFromFoo = 'foo';
      @override
      State createState() => WidgetFooState();
    }
    
    // Don't make this class name private (beginning with _) to allow its usage in other modules.
    class WidgetFooState  extends State {
      String varFromFooState = 'foo state';
      @override
      Widget build(BuildContext context) {
        return Text(getText());
      }
    
      String getText() {
        return 'WidgetFoo';
      }
    }
    
    class WidgetBar extends WidgetFoo {
      @override
      State createState() => _WidgetBarState();
    }
    
    class _WidgetBarState extends WidgetFooState {
      @override
      String getText() {
        return 'WidgetBar, ${varFromFooState}, ${widget.varFromFoo}';
      }
    }
    

    If you instantiate the WidgetBar it will render the WidgetBar, foo state, foo text, using variables from ancestors.

    This is not the best way to develop on Flutter but still, that's a direct answer to your question. The extension of stateless widgets is similar. You just add methods that return some default values and that can be overridden in an inherited class. That's the classics of OOP.

提交回复
热议问题