2

The below is just an example, not my code, but I want to understand what is happening exactly. Here I have a statefulwidget which does not extend from a State Class, but instead from the OtherClass. What is the purpose of this type of extension? Is this something that we are allowed to do in Flutter?.

class MyClass extends StatefulWidget {
  final _MyClassState myClassState = _MyClassState();
  @override
  _MyClassState createState() => myClassState;
}

class _MyClassState extends OtherClass<MyClass> {
  @override
  Widget build(BuildContext context) {

  }
}

class OtherClass<T extends StatefulWidget> extends AuthState<T> {
  @override
  void onUnAuthenticated() {
    print('Method of other class');
  }
}

Thanks all.

1 Answer 1

1

We can analyze this situation simply from the perspective of object orientation. Since this is a class like any other, the difference is that it builds our view.

There are several reasons why we use this type of extension, but quoting two simple and common examples, it is when we need to customize our view's state management or when we want to call some important methods that are repeated a lot in the code, for example. And since dart doesn't allow you to do more than one extends, generally this kind of approach can be quite useful.

For example, imagine that for 80% of your app's screens, we need to add a custom 'loading'. Note that this code, which can be a lot, will be repeated in all of them, thus providing a lot of repeated code. Which is not nice for clean, organized code. So, to avoid this repetition, we can create a super class that extends the StatefulWidget and that has a method that returns a widget, which is our custom 'loading'. So, in all screens that need a custom 'loading', just extend the super class and use this method as if it were in the current class.

In the case of your example, the onUnAuthenticated method will be available in the _MyClassState class as if it belongs to it. And the OtherClass class can be extended into any other class that wants to use the StatefulWidget and the onUnAuthenticated method as well, without having to repeat code.

I hope I managed to explain it correctly, despite my bad English.

But for more details, I recommend that you study object-oriented inheritance of similar language, like Java for example.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Edeson, this was very well explained. I am familiar with OOPs concepts, but was just confused by this usage in Flutter. So based on what you said, along with the methods or properties of the OtherClass widget, if I had a Text widget inside of the OtherClass, would I be able to use it inside of the _MyClassState widget as well?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.