flutter api调用的常用方法

Common method for flutter api calls

关于 Common class/method for flutter API calls(GET,POST,.. .) 颤抖?我已经用react native中的通用方法处理了所有API请求,我不确定如何在flutter中实现它。

您可以创建一个 class 来处理它。例如,这是我的 class 来处理用户模型

的所有服务
import 'package:http/http.dart' as http;

class UserService {
  var baseUrl = URL.devAddress;

  Future<User> getUser() async {
    final response = await http.get(
        Uri.parse(baseUrl + "user/1")
    );
    if (response.statusCode == 200) {
      final data = json.decode(response.body);
      return data
    } else {
      throw Exception("Failed");
    }
  }
}

您必须使用 url 参数调用 getRequest

Future<Response> getRequest(String url) async {
    Response response;
    try {
      response = await _dio.get(url,
          options: Options(headers: {
            HttpHeaders.authorizationHeader:
                'Bearer $accessToken'
          }));
      print('response $response');
    } on DioError catch (e) {
      print(e.message);
      throw Exception(e.message);
    }
    return response;
  }

这里是post方法

Future<Response> posRequestImage(String url, data) async {

    try {
      response = await _dio.post(
        url,
        data: formData,
        options: Options(headers: {
          HttpHeaders.authorizationHeader:
              'Bearer $accessToken'
        }),
      );
      if (response.statusCode == 200) {
        return response;
      }
      print('post response $response');
    } on DioError catch (e) {
      print(e.message);
      throw Exception(e.response?.statusMessage);
    }
    return response;
  }
Future<void> getUser(String username) async {       
 Uri uri = Uri.parse('https://example.com');

try {
    Map<String, dynamic> params = new HashMap();
    params['username'] = username;

    final response = await client.post(uri,
     body: jsonEncode(params),
   );
   print("response ${response.body}");
 } on FetchDataException {
   throw FetchDataException("No Internet connection");
 }

}