作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想将我的整个项目从 provider 转移到 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),
)
],
),
);
}
}
这里有几点需要注意。
useProvider
时返回的内容。关于flutter - 将 ChangeNotifier 从 provider 迁移到 hooks_riverpod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63260327/
我想将我的整个项目从 provider 转移到 riverpod。但我卡在了这一点上。 class EditQuestionScreen extends StatelessWidget { Edi
我是一名优秀的程序员,十分优秀!