Flutter widget life-cycle debug

Sample test

class HomeScreenBody extends StatefulWidget {
  const HomeScreenBody({Key key}) : super(key: key);


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


class _HomeScreenBodyState extends State<HomeScreenBody> {
  int value = 1;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        FlatButton(
          onPressed: () async {
            setState(() {
              value++;
            });
          },
          child: const Text('Press me!'),
        ),
        TestWidget(value: value),
      ],
    );
  }
}

class TestWidget extends StatefulWidget {
  final int value;


  const TestWidget({Key key, this.value}) : super(key: key);


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


class _TestWidgetState extends State<TestWidget> {
  @override
  Widget build(BuildContext context) {
    print('_TestWidgetState build');
    return Text('${widget.value}');
  }


  @override
  void initState() {
    super.initState();
    print('_TestWidgetState initState');
  }


  @override
  void didUpdateWidget(TestWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    print('_TestWidgetState didUpdateWidget');
  }


  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    print('_TestWidgetState didChangeDependencies');
  }
}

Output

when update new properties from parent widget, sub widget will point from didUpdateWidget 

- First run:
flutter: [D]  _HomePageState onActive /
flutter: _TestWidgetState initState
flutter: _TestWidgetState didChangeDependencies
flutter: _TestWidgetState build
flutter: _TestWidgetState didUpdateWidget
flutter: _TestWidgetState build

- When press call api to setState
flutter: _TestWidgetState didUpdateWidget
flutter: _TestWidgetState build

- In the next setState
flutter: _TestWidgetState didUpdateWidget
flutter: _TestWidgetState build

@nhancv

Liked it? Take a second to support nhancv on Patreon!

Leave a Reply

Your email address will not be published.Required fields are marked *