flutter 未来API调用抖动

ql3eal8s  于 2023-06-30  发布在  Flutter
关注(0)|答案(3)|浏览(133)

我试图在dart上创建一个简单的Network类,以便将所有调用集中到特定的API。
所以我创建了一个Service类,并使用Dio创建了一个mock和一个get函数。

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:playground/home/model/home.dart';
import 'package:playground/network/base/safe_call.dart';
import 'dart:convert';
import '../../base/api_result.dart';
import '../../base/network_error.dart';

class HomeServices {
  final Dio _dio;

  HomeServices(this._dio);

  Future<Object> getHome() async {
    try {
      final response = await Dio().get("https://jsonplaceholder.typicode.com/posts");
      // Parse the response data into a `Home` object
      final homeData = Home.fromJson(response.data);
      return homeData;
    } catch (e) {
      return networkError(e);
    }
  }

  Future<Home> mockHome() async {
    try {
      String response = await rootBundle.loadString('assets/home.json');
      Map<String, dynamic> homeMap = await jsonDecode(response);
      var homeData = Home.fromJson(homeMap);
      return homeData;
    } catch (e) {
      return Home(List.empty(), List.empty());
    }
  }
}

另一个类叫做APIClient,用来集中我所有的服务:

import 'package:playground/network/services/home/home_services.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

class ApiClient {
  late final Dio _dio = Dio()..interceptors.add(PrettyDioLogger(
  request: true,
  requestHeader: true,
  requestBody: true,
  responseHeader: false
  ));

  late HomeServices homeServices = HomeServices(_dio);
}

在我的repository类中,我想我应该这样使用:

Future<Home> readJson() async {
    await apiClient.homeServices.mockHome().then((value) {
      return value;
    }).catchError((error) {
      return error;
    });
  }

但我得到的错误:

: Error: A non-null value must be returned since the return type 'Home' doesn't allow null.
carousel_repository.dart:13
- 'Home' is from 'package:playground/home/model/home.dart' ('lib/home/model/home.dart').
home.dart:1
  Future<Home> readJson() async {

不太确定这个电话有什么问题。

ou6hu8tu

ou6hu8tu1#

您遇到的错误是因为readJson()方法应该返回Home类型的non-null值,但您当前的实现并没有在所有代码路径中提供返回值。
试试这个:

Future<Home> readJson() async {
  try {
    return await apiClient.homeServices.mockHome();
  } catch (error) {
    throw Exception(error);
  }
}
kb5ga3dv

kb5ga3dv2#

不确定我的答案,但我觉得readJson()应该返回Home,因为返回的只是Home对象。
如果函数return是Future<Home>,那么我们可以返回来自apiClient的响应。

Future<Home> readJson() async {
    // await apiClient.homeServices.mockHome().then((value) {
    //   return value;
    // }).catchError((error) {
    //   return error;
    // });
    final response = await apiClient.homeServices.mockHome();
    return response;
  }
nkhmeac6

nkhmeac63#

试试这个:

Future<Home>? readJson() async {
    await apiClient.homeServices.mockHome().then((value) {
      return value;
    }).catchError((error) {
      return error;
    });
  }

相关问题