Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions don't get executed form initState()

Tags:

flutter

dart

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");
  }
}
like image 356
Mrak Vladar Avatar asked May 06 '26 03:05

Mrak Vladar


2 Answers

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

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

  }
like image 74
Akif Avatar answered May 09 '26 01:05

Akif


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

like image 22
Abrar Malekji Avatar answered May 09 '26 01:05

Abrar Malekji