Flutter StatefulWidget - State class inheritance?

后端 未结 2 2041
面向向阳花
面向向阳花 2020-12-15 08:13

The point of this question, is how to handle state changes, preferably automatically by the original ancestor. It seems to me that it is not possible to keep extending these

2条回答
  •  北海茫月
    2020-12-15 08:35

    Don't. You should never extend a widget. This is anti-pattern. Instead, as stated by flutter documentation :

    You create a layout by composing widgets to build more complex widgets.

    An example would be :

    class Foo extends StatefulWidget {
      final Widget child;
    
      Foo({this.child});
    
      @override
      _FooState createState() => new _FooState();
    }
    
    class _FooState extends State {
      @override
      Widget build(BuildContext context) {
        return new Container(
          child: widget.child
        );
      }
    }
    
    
    
    class Bar extends StatefulWidget {
      final Widget child;
    
      Bar({this.child});
    
      @override
      _BarState createState() => new _BarState();
    }
    
    class _BarState extends State {
      @override
      Widget build(BuildContext context) {
        return new Foo(
          child: widget.child
        );
      }
    }
    

    In this case, Bar has no mixin or inheritance. It just wrap it's child inside a Foo.

提交回复
热议问题