Mrak Vladar
Mrak Vladar

Reputation: 608

Functions don't get executed form initState()

I have been learning to deal with the async functions in the flutter. I have defined an async function and I have called it for two places
1. From the build function.
2. From the initState.
The Functions is when called from the build function gets executed and the text is printed to the terminal, however, calling it from the initstate no text is logged into the terminal.
Here is the Code.

import 'package:flutter/material.dart';

void main() => runApp(Test());

class Test extends StatefulWidget {
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  void initState() {
    random();
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // random();
    return MaterialApp(home: Scaffold(body: Center(child: Text("Wattup"))));
  }

  Future<void> random() async {
    await Future.delayed(Duration(seconds: 2));
    print("I'm Back baby");
  }
}

Upvotes: 2

Views: 1265

Answers (5)

M.M.Hasibuzzaman
M.M.Hasibuzzaman

Reputation: 1151

if you want to print afte 2 sec, then your random function should be like this,

 Future<void> random() async {
    await Future.delayed(Duration(seconds: 2),(){
      print("I'm Back baby");
    });
  }

This will print the line after 2 sec, and it doesn't matter if you put it before or after super.init

Upvotes: 1

Shakib Uz-Zaman
Shakib Uz-Zaman

Reputation: 621

Try executing the function after the widget has been build like this:

    @override
    void initState () {
      WidgetsBinding.instance.addPostFrameCallback((_){
        random();
      });
      super.initState();
     
    }

Or

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

Upvotes: 2

nvoigt
nvoigt

Reputation: 77324

The initState method:

If you override this, make sure your method starts with a call to super.initState().

Emphasis mine.

So whatever you do, you need to do it after your call to super.initState();

Upvotes: 2

Akif
Akif

Reputation: 7650

You need to call your method after super.initState like this:

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    random();

  }

Upvotes: 2

Abrar Malekji
Abrar Malekji

Reputation: 111

I think, Super.initState() should be called first So, put it in first line. Try this.

Upvotes: 2

Related Questions