Home > Back-end >  Passing Variable Token Key value in a Flutter Project
Passing Variable Token Key value in a Flutter Project

Time:11-15

I have an api_service.dart file and when the user logs in I save the json.decode(response.body)['key'] in a variable as Tkey. I want to be able to access it in the same file but in a different function when I am trying to access user details:

I am not sure how to apply this answer How to pass access token value in flutter to my code

class APIService {
  static var client = http.Client();
  static Future<bool> login(
    LoginRequestModel model,
  ) async {
    Map<String, String> requestHeaders = {
      'Content-Type': 'application/json', };
    var url = Uri.parse(
      Config.apiURL   Config.loginAPI,    );

    var response = await client.post(
      url,
      headers: requestHeaders,
      body: jsonEncode(model.toJson()),    );

    if (response.statusCode == 200) {
      await SharedService.setLoginDetails(
        loginResponseJson(
          response.body,        ),      );
      print("No.2 Test ${response.body}"); <-------{"key":"xxxxxxxxxx"}
      var Tkey = json.decode(response.body)['key'];
      print("No.2 Test $Tkey"); <-------------- xxxxxxxxxxxxx
      return true;
    } else {
      return false;    }  }

  static Future<User> fetchUser() async {
    var url = Uri.parse(Config.apiURL   Config.userProfileAPI);
    final response = await http.get(
      url,
      headers: {
        HttpHeaders.authorizationHeader:
            'Token $Tkey', <--------------- I want to print here the value of the key
      }, );

    final responseJson = jsonDecode(response.body);
    print(responseJson);

    if (response.statusCode == 200) {
      return User.fromJson(jsonDecode(response.body));
    } else {
      throw Exception('Failed to load User');
    }  }}

My question how can I get access to the key to be used in the fetchUser() ?

CodePudding user response:

declare a global variable in the global scope or in a separate file, then when this method is executing, assign that key to it, then use it everywhere else in your app.

in a separate file:

String GlobalTkey = "";

now in your method replace the following:

   print("No.2 Test ${response.body}"); <-------{"key":"xxxxxxxxxx"}
  var Tkey = json.decode(response.body)['key'];
  print("No.2 Test $Tkey"); <-------------- xxxxxxxxxxxxx

with this:

   print("No.2 Test ${response.body}"); <-------{"key":"xxxxxxxxxx"}
  var Tkey = json.decode(response.body)['key'];
  GlobalTkey = Tkey; // you need to import the file where the variable exists
  print("No.2 Test $Tkey"); <-------------- xxxxxxxxxxxxx

now everywhere in your app including different files, methods, widgets, classes... you can use GlobalTkey

  • Related