Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

flutter - What is the best way to extract duplicate code from StatefulWidget (using inheritance)?

As the title suggests, I have many StatefulWidgets that have duplicate code, and want to extract that into their own file(s) as abstract classes or mixins, whichever works best.
I will not paste code from my project into here, I will just give a simplified example of what it looks like.

So first of all, I will try to explain the hierarchy I want to achieve:

QuizType
WordQuizType            (<-- most likely a mixin)
SentenceQuizType        (<-- most likely a mixin)

^ those would be either abstract classes or mixins

I want ALL of the concerned Widgets to have all the properties and methods that are defined in QuizType.

Some of the Widgets will additionally inherit from WordQuizType
and some Widgets will additionally inherit from SentenceQuizType.
(some will inherit from neither, only from from QuizType)

My custom Widgets will not be able to extend 2 classes at the same time (StatefulWidget and Quiztype).
So my guess is, that I should also make QuizType a mixin as well, and implement my code similary to this: Flutter: inherit from abstract stateless widget.

The above example uses StatelessWidget, but I'm using StatefulWidget, so I'm not sure where to add the inheritance, to the StatefulWidget or the State<...>?

class WordWidget1 extends StatefulWidget {
  QuizModel quiz;
  WordWidget1(this.quiz);

  @override
  _WordWidget1State createState() => _WordWidget1State();
}

class _WordWidget1State extends State<WordWidget1> {
  //these should be available in ALL my widgets
  QuestionModel question;
  Map<String, dynamic> questionData;

  //these should be available only for certain Widgets
  String forWordsOnly;

  @override
  Widget build(BuildContext context) => Container();
}

class SentenceWidget1 extends StatefulWidget {
  QuizModel quiz;
  SentenceWidget1(this.quiz);

  @override
  _SentenceWidget1State createState() => _SentenceWidget1State();
}

class _SentenceWidget1State extends State<SentenceWidget1> {
  //these should be available in ALL my widgets
  QuestionModel question;
  Map<String, dynamic> questionData;

  //these should be available only for certain Widgets
  String forSentencessOnly;

  @override
  Widget build(BuildContext context) => Container();
}
question from:https://stackoverflow.com/questions/65873295/what-is-the-best-way-to-extract-duplicate-code-from-statefulwidget-using-inheri

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...