0

How can I get out of an "Asynchronous programming"-loop? Do I need to write every method that is using on-device-values as Future?

I can call addPassword() from outside, but still have to wait, until it is set (Future function). I just want to return those values like any other method.

My attempt:

How I store values on the device:

import 'package:shared_preferences/shared_preferences.dart';
class StorageConnector {
  static Future setInt(String key, int value) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setInt(key, value);
  }
  static Future getInt(String key) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getInt(key);
  }
}

How I receive the previously written values from the device:

class Account{
  void addPassword(int password){ //i dont want to use await/async, because of this later functions
    StorageConnector.setInt("passwords", password);
  }

  int getAtPassword(int pos) { //Attention: doesn't compile
    /* I have tried this: */
    StorageConnector.getInt("passwords").then((value) { return value;});
    /* and this: */
    return StorageConnector.getInt("passwords");
  }
}

There are similar questions, but unfortunately, I was not able to understand/apply them properly.

Similiar: FutureBuilder, .then(function), external functions

James Z
  • 12,209
  • 10
  • 24
  • 44
Paul
  • 1,349
  • 1
  • 14
  • 26
  • 1
    You cannot make asynchronous operations synchronous. If things need to wait for asynchronous function calls to complete, then those functions *must* return `Future`s. Asynchronous operations therefore are "contagious" by making all of their callers asynchronous. – jamesdlin Jul 18 '21 at 10:11
  • But how am I able to put an asynchronous variable into a build() function? For example in a Text() widget? (as Text() doesn't take Future types) Could you maybe make an example for that case? – Paul Jul 18 '21 at 16:58
  • You use a `StatefulWidget` that calls `setState` on itself to rebuild its widget tree when the `Future` completes; [`FutureBuilder`](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html) does this for you. Also see: [What is a Future and how do I use it?](https://stackoverflow.com/q/63017280/) – jamesdlin Jul 18 '21 at 19:10
  • I have found out, that there are other better ways - I have found something here https://github.com/JohannesMilke/user_profile_shared_preferences_example – Paul Jul 19 '21 at 13:12

0 Answers0