ccc
ccc

Reputation: 2385

initState() not called when building stateful widget

I am trying to build a widget and do something in the initState() function. I have done it before in other cases, but this time the initState() is just not called. I have put breakpoints, the application goes into the constructor (assert line) and the object in the assert is not null, so it should go on and initialize the state. But it doesn't, and I don't understand why.

Any help would be greatly appreciated. Thanks.

Here's the code:

class MyWidget extends StatefulWidget {

    SomeOtherObject someOtherObject;

    MyWidget({@required this.someOtherObject})
        :
            assert(someOtherObject != null)
    ;

    @override
    _MyWidgetState createState() => _MyWidgetState();
}


class _MyWidgetState extends State<MyWidget> {

    @override
    void initState() {
        super.initState();
        // widget.someOtherObject.addListener(update);
    }

    @override
    Widget build(BuildContext context) {
        // ...
    }
}

Upvotes: 2

Views: 5337

Answers (1)

Benjamin
Benjamin

Reputation: 6161

I would redirect you to this answer: initState function is't be called in StatefulWidget by default

Your code works just fine in a DartPad, make sure you fully restart your app, not just hot reload. Often times for me, Flutter likes to use an old version of my app so I have to hot restart. Also, just so you know, any time you edit initState(), you MUST hot restart your app for the changes to take effect.

Upvotes: 1

Related Questions