【问题标题】:How to build a API call in flutter with response being used across multiple screens using future builder如何使用 future builder 在多个屏幕上使用响应构建 flutter 中的 API 调用
【发布时间】:2022-11-20 01:38:24
【问题描述】:

我做了一个很好的研究,但找不到一个好的 flutter 教程。但这是我正在尝试做的。

我有一个 API 调用,它为我提供了大量数据,这些数据应该在多个屏幕上显示。

使用 futurebuilder 的最佳方法是什么?理想情况下,我想在启动画面中调用 API 并保存数据并在多个屏幕上使用它,但无法获得很好的教程来做到这一点。

编辑以添加代码。

Future<ApiCallResponse> makeApiCall({
    required String callName,
    required String apiUrl,
    required ApiCallType callType,
    Map<String, dynamic> headers = const {},
    Map<String, dynamic> params = const {},
    String? body,
    BodyType? bodyType,
    bool returnBody = true,
    bool cache = false,
  }) async {
    print(apiUrl);
  //  print(body);
    print(params);
    final callRecord =
        ApiCallRecord(callName, apiUrl, headers, params, body, bodyType);
    // Modify for your specific needs if this differs from your API.
    if (_accessToken != null) {
      headers[HttpHeaders.authorizationHeader] = 'Token $_accessToken';
    }
    if (!apiUrl.startsWith('http')) {
      apiUrl = 'https://$apiUrl';
    }

    // If we've already made this exact call before and caching is on,
    // return the cached result.
    if (cache && _apiCache.containsKey(callRecord)) {
      return _apiCache[callRecord]!;
    }

    ApiCallResponse result;
    switch (callType) {
      case ApiCallType.GET:
      case ApiCallType.DELETE:
        result =
            await urlRequest(callType, apiUrl, headers, params, returnBody);
        break;
      case ApiCallType.POST:
      case ApiCallType.PUT:
      case ApiCallType.PATCH:
        result = await requestWithBody(
            callType, apiUrl, headers, params, body, bodyType, returnBody);
        break;
    }

    // If caching is on, cache the result (if present).
    if (cache) {
      _apiCache[callRecord] = result;
    }

 //   print(result.jsonBody);
 //   print(result.jsonBody['abhijit']);
 //   print(result.jsonBody['gowri']);

//    final prefs = await SharedPreferences.getInstance();
//    await prefs.setStringList('gowri', result.jsonBody['gowri']);
//    await prefs.setStringList('gouri', result.jsonBody['gouri']);

    SaveDataResponse(result);

    return result;
  }

void SaveDataResponse(ApiCallResponse result) async{
  String SunriseData = result.jsonBody['sunrise'].toString();
//  String gouriVal = result.jsonBody['gouri'].toString();

  print(SunriseData);
//  print(gouriVal);

   final prefs = await SharedPreferences.getInstance();
    prefs.setString('sunrise', SunriseData);
//    await prefs.setString('sunrise', SunriseData);
}

当我尝试在要查看数据的页面上的 initstate 中使用以下内容时

sunrise= SharedPref.getString('SunriseData') as String?;

我收到以下消息

Unhandled Exception: type 'Future<String>' is not a subtype of type 'String?' in type cast
E/flutter (18953): #0      _HomePageWidgetState._loadlatlon.<anonymous closure> (package:myApp/home_page/home_page_widget.dart:62:50)
E/flutter (18953): #1      State.setState (package:flutter/src/widgets/framework.dart:1114:30)
E/flutter (18953): #2      _HomePageWidgetState._loadlatlon (package:myApp/home_page/home_page_widget.dart:59:5)
E/flutter (18953): <asynchronous suspension>

【问题讨论】:

  • 也许你正在寻找 statemanangement,检查 riverpod2, bloc 。如果您想节省存储空间,请检查本地数据库

标签: android json flutter flutter-futurebuilder


【解决方案1】:

创建一个单独的类,例如:

class DataClass {
 static List allData = [];
 }

现在在第一个 Future 方法中,您将请求数据执行如下操作:

Future futureRequestMethod() async {

// here is the code that you will request the data with in the end as example:
 final resultOfRequest = snapshot.data;

 DataClass.allData = resultOfRequest;

return resultOfRequest;
}

在将分配给FutureBuilder 的future 属性的future 方法中,分配DataClass.allData 中的数据然后返回它。

现在您将该数据保存在课堂上,FutureBuidlder 将正常工作。

然后在下一个屏幕上无需提出新请求,您可以直接使用 allData

// on other screens
// print(DataClass.allData);

【讨论】:

  • 有我可以要求的示例代码吗?因为据我所知还无法让它发挥作用。很简单,我试图保存对 sharedpref 的响应并在另一个屏幕上使用它,但我收到一条错误消息“未处理的异常:类型‘Future<String>’不是‘String’类型的子类型?”在类型转换中”
  • 是的,包括您的方法的代码 sn-ps。
  • 更新了原始帖子并编辑了代码。
【解决方案2】:

尝试在您的initState() 中更改此设置:

sunrise= SharedPref.getString('SunriseData') as String?;

有了这个:

SharedPref.getString('SunriseData').then((value) {
  print(value);
  sunrise = value;
   SetState(() {});
 });

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 2021-07-07
    • 1970-01-01
    • 2021-12-18
    • 2023-02-18
    • 2021-02-09
    • 1970-01-01
    • 2021-12-18
    • 2020-12-15
    相关资源
    最近更新 更多