skip to Main Content
class _WorterBuchState extends State<WorterBuch> with TickerProviderStateMixin {
  var wordPair= '' ;
  
@override
void initState(){

  super.initState();
  load();
}

Future<void>     load() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setString('key', 'value');
  wordPair =  await "key : " +  (prefs.getString('key') as String);

}
  @override
  Widget build(BuildContext context)  {
print(wordPair);
    

I have this class and this async function. I run the async function in the initState call but when build method runs it prints nothing. How can i solve this problem or how can i wait how the Future to finish? Can anybody please helpp

2

Answers


  1. Future method takes some frame to fetch data, try using FutureBuilder like

      Future<String> load() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('key', 'value');
        final wordPair = "key: ${prefs.getString('key')}";
        return wordPair;
      }
      late final future = load();
    
      @override
      Widget build(BuildContext context) {
        return FutureBuilder(
          future: future,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              final wordPair = snapshot.data ;
              return Text(wordPair??'');
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }
            return const CircularProgressIndicator();
          },
        );
      }
    }
    

    More about FutureBuilder

    Login or Signup to reply.
  2. Running the build method cannot be delayed and this method cannot be asynchronous because that would block/delay the rendering of the UI making the app unresponsive.

    What you need to do is store the Future in the state and use FutureBuilder:

    class _WorterBuchState extends State<WorterBuch> with TickerProviderStateMixin {
    Future<String>? wordPairFuture;
      
    @override
    void initState(){
      super.initState();
      load();
    }
    
    Future<void> load() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      prefs.setString('key', 'value');
      wordPairFuture = "key : " + (prefs.getString('key') as String);
    }
      @override
      Widget build(BuildContext context)  {
        if (wordPairFuture == null) {
          return const Placeholder(); // display some loading here
        }
        
        return FutureBuilder(
          future: wordPairFuture,
          builder: (context, snapshot) {
            // use `snapshot.hasData` to check if the `Future` is "ready"
            if (snapshot.hasData) print(snapshot.data)
    
            // ...
          }
        )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search