5

I have a screen made using Stateless Widget.
I want to run some code when the screen is loaded or when the Stateless widget is created.

In android we could do this in onCreate() method.
i.e. is there some equivalent of onCreate() in flutter.

6
  • You can use a StatefulWidget instead and use the initState method, if you are modifying the state of the widget. Commented Mar 28, 2019 at 9:26
  • 1
    Is this the only way. Because I won't be modifying any state of the widget. Commented Mar 28, 2019 at 9:28
  • Could you specify what you are trying to do onCreate? Commented Mar 28, 2019 at 9:29
  • 2
    You can simply include it in your main method: void main() => {startAlarm(); runApp(MyApp());} Commented Mar 28, 2019 at 9:39
  • 1
    umm, depends on what you mean by created.. why not just use the constructor? Commented Mar 28, 2019 at 10:27

1 Answer 1

2

The terminology for this is "mount". So you want to run the code when the widget is mounted. In Flutter, all widgets have a mounted property and it turns true when the buildContext is assigned to a widget.

But I don't think you can do something to workaround with that property.

bool get mounted => _element != null;

relevant line

I think what you can do is turn your widget into Stateful widget and use initState()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.