问题描述
我正在编写一个测验应用程序来学习 riverpod,这里是我的提供者:
final questionProvider = Provider((ref) => shuffled(Statics.q).sublist(0,10)); // holding the List of questions (Exam consists of 10 questions)
final indexProvider = StateProvider((ref) => 0); // Holding the index of the question (0-9)
final questionStateProvider =
StateNotifierProvider.autodispose<QStateNotifier,Question>((ref) {
final _index = ref.watch(indexProvider).state; // Index of the question
final _questions = ref.read(questionProvider); // List of questions
return QStateNotifier(_questions[_index]);
});
这是我的用户界面的一部分。
class AnswerBar extends HookWidget { // This Widget shows the clicked letters(via CharPadButton)
AnswerBar({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
var _question = useProvider(questionStateProvider);
if (_question.answer.length == 2) {
print(_question.hashCode);
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,children: [
AnswerBubble(char: _question.answerBar[0]),// AnswerBubbles are where i show the clicked chars that coming from CharPadButtons.
AnswerBubble(char: _question.answerBar[1]),],);
}
这是我获取所问问题的字符输入的按钮。
class CharPadButtons extends HookWidget { // Every CharPadButton has a Text Widget as a child which contains a letter.
CharPadButtons({Key? key,required this.char}) : super(key: key);
final String char;
bool isTapped = false;
@override
Widget build(BuildContext context) {
final _questionNotifier = useProvider(questionStateProvider.notifier);
return InkWell(
onTap: () {
if (isTapped == false) {
_questionNotifier.addAnswerBar(char);
isTapped = true;
}
},
这是我的 StateNotifier :
class QStateNotifier extends StateNotifier<Question> {
QStateNotifier(Question state) : super(state);
void addAnswerBar(String char) {
var temp = [...state.answerBar];
temp.insert(state.currentAnswerBarIndex,char);
var tempCurrentBarIndex = state.currentAnswerBarIndex + 1;
state = Question(
description: state.description,answer: state.answer,answerBar: temp,currentAnswerBarIndex: tempCurrentBarIndex);
print(state.answerBar); // I put it to see if answerBar is updated correctly and yes.
}
问题模型:
class Question extends Equatable {
final String description;
final List<String> answer;
final List<String> answerBar;
final List<String> randomBar;
final int currentAnswerBarIndex;
Question({
required this.description,required this.answer,this.answerBar = const ['','',''],this.currentAnswerBarIndex = 0,}) : randomBar = shuffleit([...answer,...randLetterChoice(answer.length)]);
@override
List<Object?> get props => [answerBar,currentAnswerBarIndex];
}
尽管 answerBar 正在正确更新自身,但不会重建 UI。StateNotifier 的状态(它是一个 Question 对象)在每次点击 CharPadButtons 小部件时更新。但是 _question.answerBar[index] 没有更新,我不明白为什么没有通知监听器并且没有重建 UI。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)