Bhuwan Adhikari
Bhuwan Adhikari

Reputation: 1009

What's a good approach to handle API calls in Flutter?

Well, I am using http package of flutter to handle the api calls in flutter. Since, I am from js/react/redux background, I tried implementing similar approach.

I created a function called api as below which just acts as wrapper function to manage api calls,


Future api({
  @required String url,
  @required String method,
  body,
  extra,
}) async {
  try {
    var headers = {
      'Content-Type': 'application/json',
      "Authorization": ' jwt token of user provider'
    };

    var request = http.Request(
        method, Uri.parse("$SERVER_URL${getUrl(url, method, extra)}"));
    if (isSomething(body)) {
      request.body = json.encode(body);
    }
    request.headers.addAll(headers);

    http.StreamedResponse response = await request.send();
    print(response.statusCode);
    var responseBody = await response.stream.bytesToString();
    print(responseBody);
    return responseBody;
  } catch (e) {
    throw e;
  }

But accessing token of UserProvider seems quite complex to me, like I have to pass provider object from the widget I am using the api function every time I use it.

My UserProvider now looks like this:


class UserProvider extends ChangeNotifier {
  String id;
  String name;
  String email;
  String role;
  String jwt;

  void setUser(
      {String id, String name, String email, String role, String jwt}) {
    print("here is called");
    this.id = id;
    this.name = name;
    this.email = email;
    this.role = role;
    this.jwt = jwt;

    notifyListeners();
  }

  Map<String, dynamic> getUser() {
    return {
      "id": this.id,
      "name": this.name,
      "email": this.email,
      "role": this.role,
      "jwt": this.jwt
    };
  }
}

I don't know if I am doing the things correctly as I am new to Flutter. My question is:

  1. How can I access jwt of User provider in api function?
  2. Is this approach good or not, if not please suggest better approach.

Upvotes: 1

Views: 261

Answers (1)

esentis
esentis

Reputation: 4666

You need to pass the BuildContext in your api method, and then you can access the jwt like so :

Provider.of<UserProvider>(context, listen: false).getUser()['jwt']

Upvotes: 1

Related Questions