0

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.
Bhuwan Adhikari
  • 879
  • 1
  • 9
  • 21
  • If you get data from API refer my answer [here](https://stackoverflow.com/a/68709502/13997210) or [here](https://stackoverflow.com/a/68533647/13997210) or [here](https://stackoverflow.com/a/68594656/13997210) and if you post data to API refer my answer [here](https://stackoverflow.com/a/68767696/13997210) hope it's helpful to you – Ravindra S. Patil Aug 29 '21 at 04:55

1 Answers1

1

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']

esentis
  • 4,190
  • 2
  • 12
  • 28
  • isn't there any other way to do this? Like creating a API class than api function and accessing provider directly from there. – Bhuwan Adhikari Aug 29 '21 at 04:01
  • 1
    There are several ways to achieve this, you can even create a `User` class instead of passing just the arguments. Your question was how to access the user's jwt. – esentis Aug 29 '21 at 08:01