flutter Riverpod,保存未来提供商的结果,以便在应用程序中的其他地方使用

b4qexyjb  于 2023-05-01  发布在  Flutter
关注(0)|答案(1)|浏览(147)

我有一个像这样的API调用类

class GetSinglesApi{

  Future<List<SingleModel>?> getSinglesApi() async{

    String token = 'retrtert';
    final uri = Uri.https(getBaseUrl(), PEOPLE_TABLE_ID);

    final response = await http.get(uri, headers: {
      HttpHeaders.authorizationHeader: "Bearer $token",
      "Content-Type": "application/json",
      'accept': 'text/plain'
    });

    var data = jsonDecode(response.body);

    checkStatusCode(response.statusCode, data);

    try {

      SinglesResponse singlesResponse = SinglesResponse.fromJson(data);

      print("Singles response lengeth: ${singlesResponse.records?.length}");

      return singlesResponse.records;

    } catch (e) {
        print('ERROR RESADIN JSON: ${e}');
    };

    }

  }

我使用RiverPod和Flutter来打这个电话,这是我的提供商

final getSinglesApiProvider = Provider.autoDispose<GetSinglesApi>(
    (ref) {
       return GetSinglesApi();
    }
);

final getSinglesResponseProvider = FutureProvider.autoDispose<List<SingleModel>?>((ref) async {
       return ref.watch(getSinglesApiProvider).getSinglesApi();
});

如何将结果(SingleModel的列表)保存在新的提供程序中,以便它可以显示在应用程序中的其他位置?

5t7ly7z5

5t7ly7z51#

只需使用新的提供程序和ref.watch

final singleModelResponseProvider = FutureProvider.autoDispose<List<SingleModel>?>(
    (ref) => ref.watch(getSinglesResponseProvider).value);

相关问题