自从更新了AsyncNotifier,我仍然不知道该怎么做:
final tableServices = Provider<TableServices>((ref) => TableServices());
class TableServices {
Future<void> themMon(AddMealToTableRequest item) async {
final response = await addMealToTable(item);
if (response.ErrorMsg != '') {
throw Exception(response.ErrorMsg);
// then show alert dialog ..
} else {
return //state true or sthing to show snackbar
}
}
}
我想在桌子上添加一顿饭,它会调用api,如果它有效,response.data和response.error消息将为'',或者如果它不起作用,则返回一些错误。 所以我想显示snackbar听它,但不知道怎么做,我尝试了旧的StateNotifier,但出错了,我以前使用过Provider。阅读和观看了很多教程但没有找到答案。
那么接下来要做什么来声明监听器
如果您从小部件/屏幕调用此函数,您可以使用此方法:
void showSnackBar(BuildContext context, String message) {
const snackBar = SnackBar(
content: Text(message),
);
ScaffoldMessenger.of(context).showSnackBar(snackBar);
}
然后像这样修改你的函数:
Future<void> themMon(BuildContext context, AddMealToTableRequest item) async {
final response = await addMealToTable(item);
if (response.ErrorMsg != '') {
// Show the error snackbar
if(context.mounted) showSnackBar(context, 'Error');
throw Exception(response.ErrorMsg);
} else {
// Show the success snackbar
if(context.mounted) showSnackBar(context, 'Success');
}
}
最后你可以像这样从你的小部件中调用该方法:
await ref.read(tableServices).themMon(context, item);