delmin
delmin

Reputation: 2700

Passing API (model class) to a widget

I need to reuse my filter widget. The filter Widget use so far one API (or model class) with all the logic in it. To be able to reuse the filter widget I need to pass different API to it and I just can't find a way to to that. Here is part of my code for better understanding (simplified)

class FilterWidget extends StatefulWidget {
  final DogFilter filter; //<-- I want also use this widget with CatFilter API and so on
                          // <-- How to make parameter which would take API

  const FilterWidget({this.filter});
  @override
  _FilterWidgetState createState() => _FilterWidgetState();
}

DogFilter _newFilter = DogFilter();
....

I tried this

class FilterWidget<T> extends StatefulWidget {
  final T filter; 

  const FilterWidget({this.filter});
  @override
  _FilterWidgetState createState() => _FilterWidgetState<T>();
}
....

But then I didn't get access to getters and setters. I wasn't even able to create new instance

    T _newFilter = T(); // that doesn't work

Upvotes: 1

Views: 101

Answers (1)

LonelyWolf
LonelyWolf

Reputation: 4392

Have you tried to make an abstract class, lets say animal class with all getters and setters which you use in your filter.

abstract class AnimalFilter {
  get getWhatever;
  ...
}

Then implement all your classes (DogFilter, CatFilter) from that AnimalClass

class DogFilter implements AnimalFilter {
...
}

And after that use AnimalFilter class in your filter instead of Dog or Cat class

class FilterWidget extends StatefulWidget {
  final AnimalFilter filter; 

  const FilterWidget({this.filter});
  @override
  _FilterWidgetState createState() => _FilterWidgetState();
}

Upvotes: 1

Related Questions