# 02/Flutter
[Flutter] StatelessWidget 에서 시작 시 함수를 호출하는 방법
장딴지연
2020. 9. 28. 14:17
반응형
class Example extends StatefulWidget {
Example ({Key key}) : super (key : key);
_ExampleState createState () => _ExampleState ();
}
class _ExampleState extends State <Example> {
@override
void initState () {
_getThingsOnStartup (). then ((value) {
print ( 'Async done');
});
super.initState ();
}
@override
Widget build (BuildContext context) {
return Container ();
}
Future _getThingsOnStartup () async {
await Future.delayed (Duration (seconds : 2));
}
}
/// 상태 위젯에서 onInit 호출을 제공하는 상태 저장 기능 용 래퍼
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;
}
}
class StartupCaller extends StatelessWidget {
@override
Widget build (BuildContext context) {
return StatefulWrapper (
onInit : () {
_getThingsOnStartup (). then ((value) {
print ( 'Async done');
});
},
child : Container () ,
);
}
Future _getThingsOnStartup () async {
await Future.delayed (Duration (seconds : 2));
}
}
반응형