Search code examples
flutterflutter-http

How can I add request header automatically using http package


Currently I'm sending header with every request like as follow which is very repetitive. Is there any process so that all my request will have a request header automatically ? Or how can I avoid code repetition for the following lines:

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

My complete API Request code:

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));
    
  }

Solution

  • Yes you can centralize the headers in a separate class!

    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")}",
        };
      }
    }
    

    And then, you can inherit your class with the base class to have access to these methods.

     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));
          }
        }