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

1 Answer 1

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));
      }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.