【问题标题】:Riverpod FutureProvider keeps on firiging again and againRiverpod FutureProvider 不断触发一次又一次
【发布时间】:2021-08-22 20:44:14
【问题描述】:

我正在与家人一起使用 Riverpod 的 FutureProvider。 FutureProvider 一次又一次地运行。它仅显示加载对话框。热重载也停止工作。 FutureProvider 在没有家人的情况下工作正常。请帮助找出问题所在。

final ephemerisProvider =
    Provider((ref) => ApiService("https://localhost"));

final ephemerisFutureProvider = FutureProvider.family
    .autoDispose<EpheModel, Map<String, dynamic>>((ref, data) async {
  var response = await ref.read(ephemerisProvider).getData(data);
  print(EpheModel.fromJSON(response));
  return EpheModel.fromJSON(response);
});

class Kundlis extends ConsumerWidget {
  static const routeName = "/kundlis";
  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final AsyncValue<EpheModel> kundlis = watch(ephemerisFutureProvider({}));
    return Scaffold(
        appBar: AppBar(
          title: Text("Kundlis"),
        ),
        drawer: AppDrawer(),
        body: kundlis.when(
            data: (kundli) => Center(child: Text(kundli.toString())),
            loading: () => ProgressDialog(message: "Fetching Details..."),
            error: (message, st) =>
                CustomSnackBar.buildErrorSnackbar(context, '$message')));
  }
}

class ApiService {
  final String url;
  ApiService(this.url);
  Future<Map<String, dynamic>> getData(Map<String, dynamic> data) async {
    try {
      http.Response response = await http.post(url + "/ephe",
          headers: <String, String>{'Content-Type': 'application/json'},
          body: jsonEncode(data));
      if (response.statusCode == 200) {
        return data;
      } else {
        throw Exception("Error Fetching Details");
      }
    } on SocketException {
      throw Exception("No Internet Connection");
    } on HttpException {
      throw Exception("Error Fetching Details");
    }
  }
}

【问题讨论】:

  • 注意:不要在提供程序中使用ref.read。首选ref.watch
  • @alexhartford 我正在使用 ref.watch。发生了同样的错误。在观看了 ResoCoder 的 YouTube 教程后,刚刚将手表更改为阅读。它也没有工作。

标签: flutter dart flutter-provider riverpod


【解决方案1】:

{} != {}。因为.family,每次调用watch(ephemerisFutureProvider({})) 时,您都在创建一个全新的提供程序。要通过家庭选择先前构建的提供程序,您必须传递相同的值。并且 {} 永远不会与 {} 相同,这是有保证的。 :)

【讨论】:

  • 谢谢。情况就是这样。但是我怎样才能在家庭中传递地图值呢?
  • 它必须是一个常量。所以如果你说const empty = {}; 并且每次都使用empty,那将是相同的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多