0

I have a number of classes that all extend StatefulWidget. I want each class to provide its own version of a method bool foo(), so that I can iterate over a collection of objects of these classes, calling foo() on each. What is the best/correct way to do this in Dart/Flutter? Mixins? What would the type of that collection be?

jesper
  • 385
  • 1
  • 4
  • 15
  • Can you provide some more context? It is very rare that you need to access the data of a widget directly. Typically you set its data during creation, and the widget might update some state object or use callbacks. – Eiko Jun 09 '20 at 20:07
  • @Eiko Each aforementioned class represents a page that requires validation. There's a navigation bar that is permanently visible, always underneath the page widget. When the user presses a button in the navigation bar, progression to the next page needs to be conditional on foo() returning true. So I want to have a `List pages`, and call foo() on the currently selected page when the navigation bar button is pressed. The question then is: what does the type `Page` look like? All I currently know is that it must derive `StatefulWidget`. And `foo` needs to access member variables. – jesper Jun 09 '20 at 20:20

1 Answers1

0

The functionality described can be achieved with Interfaces in Dart

class Widget {

}

abstract class MyCustomWidget extends Widget {
  String foo( String argName);
}

class Widget1 implements MyCustomWidget {
  String foo( String argName) {
    return argName;
  }
}

class Widget2 implements MyCustomWidget {
  String foo( String argName) {
    return '$argName$argName';
  }
}

void main() {
  Widget1 w = new Widget1();
  Widget2 w2 = new Widget2();
  var widgets = [w, w2];
  for (int i = 0; i < widgets.length; i++) {
    print(widgets[i].foo('hello ${i + 1}'));
  }
}

That said, flutter recommends composition over inheritance. See: Flutter StatefulWidget - State class inheritance?

Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41