0

目前我正在发送每个请求的标头,如下所示,这是非常重复的。是否有任何流程可以使我的所有请求都自动具有请求标头?或者如何避免以下行的代码重复:

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String token = sharedPreferences.getString('accessToken');
    headers: {
        'Contet-type': 'application/json',
        'Authorization': 'Bearer $token',
      }

我完整的 API 请求代码:

Future<http.Response> getAUser(userId) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String token = sharedPreferences.getString('accessToken');
    
    return await http.get(
      '$baseUrl/user/$userId/',
      headers: {
        'Contet-type': 'application/json',
        'Authorization': 'Bearer $token',
      },
    ).timeout(Duration(seconds: 30));
    
  }
4

1 回答 1

0

是的,您可以将标题集中在一个单独的类中!

class BaseService {
      Map<String, String> baseHeaders;
    
      Future initBaseService() async {
    final preferences = await SharedPreferences.getInstance();
    baseHeaders= {
      "Accept": "application/json",
      "Content-Type": "application/json; charset=utf-8",
      "Authorization": "Bearer ${preferences.getString("TOKEN")}",
    };
  }
}

然后,您可以使用基类继承您的类以访问这些方法。

 class UserService extends BaseService {
      Future<http.Response> getAUser(userId) async {
        await initBaseService();
    
        return await http
            .get(
              '$baseUrl/user/$userId/',
              headers: baseHeaders,
            )
            .timeout(Duration(seconds: 30));
      }
    }
于 2020-08-18T12:55:14.903 回答