muhammadarslannasr / SharedPreferences-Flutter

1 stars 1 forks source link

Save local string from a function inside shared preferences and use it in other pages #1

Open talbiislam96 opened 3 years ago

talbiislam96 commented 3 years ago

I wish to save the userid string that am getting from a function that parses and decodes JWT token , and be able to use it in other pages in my Flutter app . I tried to save it inside shared preferences but doesn't seem to be working .This is my function and how I used shared preferences

String userName;
dynamic authenticator;

String _decodeBase64(String str) {
  String output = str.replaceAll('-', '+').replaceAll('_', '/');

  switch (output.length % 4) {
    case 0:
      break;
    case 2:
      output += '==';
      break;
    case 3:
      output += '=';
      break;
    default:
      throw Exception('Illegal base64url string!"');
  }

  return utf8.decode(base64Url.decode(output));
}

String _userid = '';

Map<String, dynamic> parseJwt(String token) {
  final parts = token.split('.');
  if (parts.length != 3) {
    throw Exception('invalid token');
  }

  final payload = _decodeBase64(parts[1]);
  final payloadMap = json.decode(payload);
  if (payloadMap is! Map<String, dynamic>) {
    throw Exception('invalid payload');
  }
  print(payload);

  addStringToSF() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _userid = payloadMap['user_id'];
    prefs.setString('stringValue',_userid );
  }

  //print(payloadMap['user_id']);

  return payloadMap;

}

getStringValuesSF() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  //Return String
  String _userid = prefs.getString('userid');
  print (_userid);
  return _userid;

}
@override
void initState() {
  super.initState();
  getStringValuesSF();
}

authenticate() async {
  // keyclock url : key-clock-url : example : http://localhost:8080
  // my realm : name of your real.m
  var uri = Uri.parse('http://169.254.105.22:8080/auth/realms/Clients');
  // your client id
  var clientId = 'helium';
  var scopes = List<String>.of(['openid', 'profile']);
  var port = 8080;
  var issuer = await Issuer.discover(uri);
  var client = new Client(issuer, clientId);
  print(issuer.metadata);
  urlLauncher(String url) async {
    if (await canLaunch(url)) {
      await launch(url, forceWebView: true);
    } else {
      throw 'Could not launch $url';
    }
  }
  authenticator = new Authenticator(
    client,
    scopes: scopes,
    port: port,
    urlLancher: urlLauncher,
  );
  var c = await authenticator.authorize();
  closeWebView();
  var token = await c.getTokenResponse();
  var userInformation = await c.getUserInfo();
  setState(() {
    userAccessToken = token.accessToken;
    userName = userInformation.preferredUsername;
  });
  //print(token);
  //return token;
  parseJwt(userAccessToken);

}

I wish to use the userid variable here instead of the static string (id) am passing , in a way it dynamically reads the value from the function then use it inside the link to show the user's info :

  final response = await http.get('http://169.254.105.22:8093/user/v1/users/d374169b-c61f-4a5a-b00a-2a2a8d9c4e19');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return User.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load user');
  }
}

The second function is in another page (profile page), if anyone knows how I can save the userid from the function , then pass to another page (using sp or any other way) please don't hesitate to help thank you in advance

marslannasr7koncepts commented 3 years ago

One thing can you tell me once you add value in Shared Preference then Print the Value and check value is saving or not.?

addStringToSF() async { SharedPreferences prefs = await SharedPreferences.getInstance(); _userid = payloadMap['user_id']; prefs.setString('stringValue',_userid ); }

//print(payloadMap['user_id']);

return payloadMap;

}

getStringValuesSF() async { SharedPreferences prefs = await SharedPreferences.getInstance(); //Return String String _userid = prefs.getString('userid'); print (_userid); return _userid;

}

prefs.setString('stringValue',_userid ); //Your Setting stringValue as a key in Shared Preference

//Return String String _userid = prefs.getString('userid'); //And when your fetching value then the key your mentioned is not accurate it must be stringValue then data will be Populated

And make sure make SharedPreferences as global Instance not in any method again and again.

Or make a dynamic class and add SharedPreference init and access the Instance of the class.

talbiislam96 commented 3 years ago

hello @marslannasr7koncepts thanks for your feedback , I tried to print the value am saving in the console but am getting nothing , as for making SharedPreferences as global , do you have any idea how to do it ? because the string am trying to store is set and retrieved from a local function , but I want to be able to access and use it from other pages .

marslannasr7koncepts commented 3 years ago

Important is to store in sharedPreference first then make it able to fetch any page you want so you have to check first is your able to get value from function that your saving and then let me know..

talbiislam96 commented 3 years ago

yes the string am trying to store contains value , is it possible to store it when it's local in shared prefs and then use it?and how to do it thank u so much

  _userid = payloadMap['user_id'];
  print (_userid);

  //print(payloadMap['user_id']);

  return payloadMap;

here's the value am getting when I print it :

I/flutter ( 5220): 90298183-e0b7-46a9-8b75-2cf86a708e93

marslannasr7koncepts commented 3 years ago

Yes its Possible but i have to check your code for this or via screen share check your code because using that way i am not able to check where your getting issue.

Please contact me via skype if you have skype id?

talbiislam96 commented 3 years ago

My issue is that with shared preferences it's not saving , returns null

marslannasr7koncepts commented 3 years ago

Please follow this tutorial step by step and then check because i am not able to diagnose your code until not seeing it so i am sharing a link of tutorial for shared preferences follow it and then check it hope it will work for you.https://www.youtube.com/watch?v=dQBUykqbshw

johnson1940 commented 1 year ago

I have to save the auth and refresh token using the shared preferences can you help me out!