LoginSignup
3
5

More than 3 years have passed since last update.

FlutterのStatelesswidgetでinitstateしたい時

Posted at

Statelesswidgetでも画面呼び出し時に処理実行したい...

と思って調べたら良さそうなのがあったので自分用メモ

StatefulWrapperクラスを作る

StatefulWrapper.dart
class StatefulWrapper extends StatefulWidget {
  final Function onInit;
  final Widget child;

  const StatefulWrapper({@required this.onInit, @required this.child});

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

class _StatefulWrapperState extends State<StatefulWrapper> {

@override
  void initState() {
    if(widget.onInit != null) {
      widget.onInit();
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

StatefulWrapperクラスを作る

StatefulWrapperで全体をラップする。

HomePage.dart
class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StatefulWrapper(
      onInit: () {
        _getThingsOnStartup().then((value) {
          print('初回の処理が実行される!');
        });
      },
      child: Text('ほーむ'),
    );
  }

  Future _getThingsOnStartup() async {
    await Future.delayed(Duration(seconds: 2));
  }
}

参考ページ: リンク

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5