0

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));
    
  }
Fahad Md Kamal
  • 243
  • 6
  • 20

1 Answers1

1

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));
      }
    }
Dharman
  • 30,962
  • 25
  • 85
  • 135
Lapa Ny Aina Tanjona
  • 1,138
  • 1
  • 9
  • 19