问题描述
我正在尝试了解 Flutter Riverpod。我可以从服务中获取和显示数据,并了解使用 AsyncValue 的好处。但是,当我尝试在 StateNotifier 中调用 requestWeather 函数时,该函数应该依次调用 retrieveWeather 并获得新地点的天气信息。但是我收到了这个错误。
未为类型“AsyncValue”定义方法“requestWeather”。 尝试将名称更正为现有方法的名称,或定义名为“requestWeather”的方法。dartundefined_method
从 main.dart 中,我尝试使用 Provider 访问 requestWeather 函数。
class InputLocationBox extends ConsumerWidget {
String result = "";
// final weatherListState = watch(weatherListControllerProvider);
@override
Widget build(BuildContext context,ScopedReader watch) {
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
new TextField(
decoration: new Inputdecoration(hintText: "Type in here"),//onChanged is called whenever we add or delete something on Text Field
onChanged: (String str) {
result = str;
// watch(weatherRepositoryProvider).retrieveWeather(location: str);
}),//displaying input text
new ElevatedButton(
onpressed: () {
context
.read(weatherListControllerProvider)
.requestWeather(location: result);
},child: Text('Get user info'),)
],),);
}
}
Weather_list_controller.dart 定义了 requestWeather 函数。
class WeatherListController extends StateNotifier<AsyncValue<Weather>> {
final Reader _read;
WeatherListController(this._read) : super(AsyncValue.loading()) {
requestWeather();
}
Future<void> requestWeather({bool isRefreshing = false,String? loc}) async {
if (isRefreshing) state = AsyncValue.loading();
if (loc == null) {
loc = 'Los Angeles';
}
try {
final weathers =
await _read(weatherRepositoryProvider).retrieveWeather(location: loc);
if (mounted) {
state = AsyncValue.data(weathers);
// print(state);
}
// return weathers;
} catch (e) {
throw Exception(
'Something went wrong in WeatherListController !! ' + e.toString());
}
}
}
解决方法
当使用 StateNotifier 并尝试访问方法时,它需要像这样的 provider.notifier
context
.read(weatherListControllerProvider.notifier)
.requestWeather(loc: result);
我无法访问requestWeather
的小部件class InputLocationBox extends ConsumerWidget {
String result = "";
@override
Widget build(BuildContext context,ScopedReader watch) {
final weatherListState = watch(weatherListControllerProvider.notifier);
return Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
new TextField(
decoration: new InputDecoration(hintText: "Type in here"),//onChanged is called whenever we add or delete something on Text Field
onChanged: (String str) {
result = str;
// watch(weatherRepositoryProvider).retrieveWeather(location: str);
}),//displaying input text
new ElevatedButton(
onPressed: () {
// context
// .read(weatherListControllerProvider)
// .requestWeather(location: result);
print(result);
context
.read(weatherListControllerProvider.notifier)
.requestWeather(loc: result);
},child: Text('Get Weather'),)
],),);
}
}