skip to Main Content
void _authKey() {
    Hmac hmacSha = new Hmac(sha256, utf8.encode("604ec80ffa552786f409590994dc89cfef040b72"));
    String hashValue = "";
    List<String> sortedKeys = _datas.keys.toList()..sort();
    sortedKeys.forEach((f) => hashValue += _datas[f]! + "+");
    print("waw");
    
    SharedPreferences.getInstance().then((prefs) => () {
      print("wow");
      String? token = prefs.getString('apitoken');

      print("the auth key is " + token.toString());

      key = hmacSha
        .convert(utf8.encode(hashValue + token.toString()))
        .toString();

    });
    
} 

Why isn’t "wow" printed ? It’s never displayed in the console… But "waw" is…
So why is the SharedPreferences.getInstance().then((prefs) => () neved trigged ?

3

Answers


  1. Because you are creating anonymous function

    (prefs) => () {
    

    What it should be

    .then((prefs) {
    
    Login or Signup to reply.
  2. you can write like this too

    final Future<SharedPreferences> sharedPreferences = SharedPreferences.getInstance();
    sharedPreferences.then((value) async => {
    
          Future.delayed(Duration.zero,  () {
    
            // code more...
    
          })
    
    });
    

    or write like this

    sharedPreferences.then((value) async {
        
              // code more...
        
        });
    
    Login or Signup to reply.
  3. Use SharedPrefs Class

    class SharedPrefs {
     static SharedPreferences _sharedPrefs;
    
    factory SharedPrefs() => SharedPrefs._internal();
    
     SharedPrefs._internal();
    
    Future<void> init() async {
    _sharedPrefs ??= await SharedPreferences.getInstance();
     }
      String get username => _sharedPrefs.getString('apitoken') ?? "";
     set apitoken(String value) {
      _sharedPrefs.setString('apitoken', value);
       }
       }
    

    **Call init function before runApp **

    await SharedPrefs().init();
     
    runApp(
    MyApp(),
    );
    
     ......
     //you can use SharedPrefs as follow
       String? token = SharedPrefs().apitoken;
    
      print("the auth key is " + token.toString());
    
        .............
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search