본문 바로가기

# 02/Flutter

[Flutter] StatelessWidget 에서 시작 시 함수를 호출하는 방법

반응형
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));
}
}






출처 - https://medium.com/filledstacks/how-to-call-a-function-on-start-in-flutter-stateless-widgets-28d90ab3bf49

반응형

'# 02 > Flutter' 카테고리의 다른 글

[Flutter] GestureDetector behavior  (0) 2020.10.14
[Flutter] InheritedWidget  (0) 2020.10.05
[Flutter] final & const  (1) 2020.09.28
[Flutter] StatelessWidget & StatefulWidget  (0) 2020.09.28
[Flutter] Animated List  (0) 2020.09.25