Home > database >  how to take token from login data using shared preferences
how to take token from login data using shared preferences

Time:05-31

below Getchallenge method has the hardcoded value of token which is receive from headers "Authorization" I need it to be taken from shared preferences login data. I have already added shared preferences to LoginData(). how can I get a token without hardcode value in GetChallange() method. appreciate your help on this.

Future _Getchallenge() async {
 // final prefs = await SharedPreferences.getInstance();
  try {
    final response = await Dio()
        .get(BASE_API   "challenge/getChallengeByUserAndType/calories",
            options: Options(headers: {
              'Authorization':
                  'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOnsiaWQiOjIsImFkbWluX25hbWUiOiJqYW1lc2JhbiIsImVtYWlsX2FkZHJlc3MiOiJqYW1lc2JhbkBnbWFpbC5jb20iLCJzdGF0dXMiOiJBRE1JTiJ9LCJpYXQiOjE2NTAzNDk0MTc5MTMsImV4cCI6MTY1MDM1MDYyNzUxM30.dDSTVe6ii7KCuF6x8Lgj3Pl2I2dO9Cp71DAMnkw1NPo', //HEAD
             // "Authorization": loginUserData["token"],
            }));

   // prefs.setString('token', response.data["token"].toString());

    Map<String, dynamic> responseJson = await json.decode(response.toString());
    ch = responseJson['data'].reversed.toList();
    print(ch);

    print("length:"   ch.length.toString());
  } catch (e) {
    print(e);
  }
}

 Future LoginData() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      isLoading = true;
      typing = false;
    });
    try {
      var response = await Dio().post(BASE_API   'user/login', data: {
        "username": username,
        "password": password,
        "wallet_address": wallet_address,
      });
     // print(response.data["sub"]["id"]);
    //  print(response);

      if (response.data["status"] == "LoginSuccess") {
        setState(() {
          prefs.setString('token', response.data["token"].toString());
          isLoading = false;
          loginUserData["id"] = response.data["sub"]["id"].toString();
          loginUserData["username"] = response.data["username"].toString();
          loginUserData["wallet_address"] = response.data["wallet_address"].toString();
        });
        final myString = prefs.getString('token') ?? '';
        print(myString);
        Get.snackbar(
          "success",
          "logged in successfully",
          backgroundColor: buttontext.withOpacity(0.5),
          colorText: textWhite,
          borderWidth: 1,
          borderColor: Colors.grey,
        );

        Get.to(BottomNavigation());
      } else {
        setState(() {
          isLoading = false;
          typing = true;
        });
        Get.snackbar(
          "error",
          "No User Found",
          backgroundColor: buttontext.withOpacity(0.5),
          colorText: textWhite,
          borderWidth: 1,
          borderColor: Colors.grey,
        );
      }
      print("res: $response");
      setState(() {
        isLoading = false;
        typing = true;
      });
    } catch (e) {
      setState(() {
        isLoading = false;
        typing = true;
      });
      Get.snackbar("Error", "Something went wrong.Please contact admin",
          backgroundColor: buttontext.withOpacity(0.5),
          borderWidth: 1,
          borderColor: Colors.grey,
          colorText: Colors.white,
          icon: const Icon(
            Icons.error_outline_outlined,
            color: Colors.red,
            size: 30,
          ));
      print(e);
    }
  }

CodePudding user response:

Just declare a variable named as token then wait for Shared Preferences to get the instance once get just use the key you set while saving token in Shared Preference and pass that value to your API

  Future _Getchallenge() async {
          String? token;
          final prefs = await SharedPreferences.getInstance();
    token = prefs.getString('token');
          try {
            final response = await Dio()
                .get(BASE_API   "challenge/getChallengeByUserAndType/calories",
                    options: Options(headers: {
                      'Authorization':
                          'Bearer $token', //HEAD
                     // "Authorization": loginUserData["token"],
                    }));
        
           // prefs.setString('token', response.data["token"].toString());
        
            Map<String, dynamic> responseJson = await json.decode(response.toString());
            ch = responseJson['data'].reversed.toList();
            print(ch);
        
            print("length:"   ch.length.toString());
          } catch (e) {
            print(e);
          }
        }

CodePudding user response:

You can simply get token from SharedPreferences by getString method like you have saved it in login by setString method.

Future _Getchallenge() async {
final prefs = await SharedPreferences.getInstance();
  try {
    final response = await Dio()
        .get(BASE_API   "challenge/getChallengeByUserAndType/calories",
            options: Options(headers: {
              'Authorization':
                  'Bearer ${prefs.getString('token')}'
            }));
    
    Map<String, dynamic> responseJson = await json.decode(response.toString());
    ch = responseJson['data'].reversed.toList();
    print(ch);

    print("length:"   ch.length.toString());
  } catch (e) {
    print(e);
  }
}
  • Related