将ChangeNotificationer从提供程序迁移到hooks_riverpod



我想把我的整个项目从提供者转移到riverpod。但我被困在这一点上了。

class EditQuestionScreen extends StatelessWidget {
EditQuestionScreen({this.question, this.answers});
final QuestionModel question;
final List<AnswerModel> answers;
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => QuestionProvider(
question: this.question,
answers: this.answers),
child: Container());
}
}

这是我的子窗口小部件的提供者窗口小部件。它只初始化过一次。如何使用riverpod将此类编写为HookWidget?

快速提示-使用Provider或Riverpod,您实际上不想/不需要命名您正在提供的东西thingProvider。你不是在提供一个提供者,你是在提供一件有意义的事情。

我尽了最大努力填补了你没有提供的其余代码的空白,所以希望这会有所帮助:

class QuestionModel {
QuestionModel(this.id);
final int id;
}
class AnswerModel {
AnswerModel(this.id);
final int id;
}
class QuestionWithAnswers {
QuestionWithAnswers(this.question, this.answers);
final QuestionModel question;
final List<AnswerModel> answers;
}
class QuestionAnswerNotifier extends ChangeNotifier {
QuestionAnswerNotifier(this.qwa);
final QuestionWithAnswers qwa;
QuestionModel get question => qwa.question;
List<AnswerModel> get answers => qwa.answers;
addAnswer(AnswerModel answer) {
qwa.answers.add(answer);
notifyListeners();
}
}
final questionProvider =
ChangeNotifierProvider.family<QuestionAnswerNotifier, QuestionWithAnswers>(
(ref, qwa) => QuestionAnswerNotifier(qwa));
class EditQuestionScreen extends HookWidget {
EditQuestionScreen({
@required QuestionModel question,
@required List<AnswerModel> answers,
Key key,
})  : qwa = QuestionWithAnswers(question, answers),
super(key: key);
final QuestionWithAnswers qwa;
@override
Widget build(BuildContext context) {
final provider = useProvider(questionProvider(qwa));
// Use data from provider to render your UI, for example:
return Container(
child: Column(
children: <Widget>[
Text('${provider.question}n${provider.answers}'),
RaisedButton(
onPressed: () => provider.addAnswer(AnswerModel(5)),
child: Icon(Icons.add),
)
],
),
);
}
}

这里有几点需要注意。

  1. 在Riverpod中,家族是我们将参数传递给提供者的方式
  2. QuestionWithAnswers类将要通过系列提供的额外参数传递给提供者的模型捆绑在一起
  3. 提供者的名称以提供者为后缀,而不是以提供者的名称命名
  4. 我们提供了ChangeNotifier,因此当调用useProvider时会返回该值

相关内容

  • 没有找到相关文章

最新更新