【发布时间】:2021-12-07 15:30:15
【问题描述】:
从其“子”提供者调用(并将值传递给)ProxyProvider 的正确方法是什么?
目前我将回调函数作为参数传递给“子”提供者,将其存储为函数,然后我可以在需要时调用它。
它的工作原理是调用了 ProxyProvider(并传递了值),但同时它破坏了 notifyListeners(),它被称为下一个 - 尽管消费者在“子”提供者中搜索 getter(并且找不到它)仅用于 ProxyProvider。
这是我收到的错误:
错误:org-dartlang-debug:synthetic_debug_expression:1:1:错误: 没有为“AudioModel”类定义 getter 'audInd'。
- “AudioModel”来自“package:quiz_game_new/models/audioModel.dart”(“lib/models/audioModel.dart”)。尝试将名称更正为 一个现有的 getter,或定义一个名为 'audInd' 的 getter 或字段。 听得见^^^^^^
代码
提供者(audioModel.dart):
class AudioModel extends ChangeNotifier {
int _audioIndex = -1;
Function? audioIndexChanged;
void setCallbacks(Function _audioPlaybackCompleted, Function _audioIndexChanged) {
audioPlaybackCompleted = _audioPlaybackCompleted;
audioIndexChanged = _audioIndexChanged;
}
//Some code that changes _audioIndex and afterwards calls audioIndexChanged!(_audioIndex)
}
ProxyProvider (commonModel.dart)
class CommonModel extends ChangeNotifier {
CommonModel(this.audioModel);
final AudioModel audioModel;
int _audioIndex = -1;
int get audioIndex => _audioIndex;
void setCallbacksForAudioPlayback() {
audioModel.setCallbacks(audioPlaybackCompleted, audioIndexChanged);
}
void audioIndexChanged(int audInd) {
_audioIndex = audInd;
notifyListeners();
}
}
初始化:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider<STTModel>(create: (context) => STTModel()),
ChangeNotifierProvider<QuestionModel>(
create: (context) => QuestionModel()),
ChangeNotifierProvider<AudioModel>(create: (context) => AudioModel()),
ChangeNotifierProxyProvider3<STTModel, QuestionModel, AudioModel,
CommonModel>(
create: (BuildContext context) => CommonModel(
Provider.of<STTModel>(context, listen: false),
Provider.of<QuestionModel>(context, listen: false),
Provider.of<AudioModel>(context, listen: false)),
update:
(context, sttModel, questionModel, audioModel, commonModel) =>
CommonModel(sttModel, questionModel, audioModel))
],
child: MaterialApp(
title: 'Flutter Demo',
initialRoute: '/',
routes: {
'/': (context) => ScreenMainMenu(),
'/game': (context) => ScreenGame(),
}));
}
}
【问题讨论】:
-
你能说明你是如何初始化这些提供者的吗?
-
好的,添加到问题描述的末尾
-
您是否尝试过在
update中直接返回commonModel而不是创建一个新的?我认为没有必要在您的场景中创建一个新实例。此外,如果您想更新CommonModel,最好在CommonModel中有一个函数来处理要更新的属性。 (例如commonModel.updateSomething(...); return commonModel;)
标签: flutter dart proxy provider flutter-provider