프로그래밍 공부 메모/flutter

life cycle 라이프 사이클 initState(), dispose()

jjs815 2022. 6. 7. 21:35

statefulwidget 클래스를 생성하여 위젯 트리에 삽입되면 initState() 메서드가 호출된다

즉 앱이 실행되어 statefulwidget이 생성되면 뭔가 실행하고 싶다면  initState() 구현하면 된다

 

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Shazam',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: ScreenB(),
    );
  }
}

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

  @override
  State<ScreenB> createState() => _ScreenBState();
}

class _ScreenBState extends State<ScreenB> {
  @override
  void initState() {
    //statefulwidget이 실행되면 initstate()가 호출됨
    super.initState();
    print('initState is called');
  }

  @override
  void dispose() {
    //위젯트리에서 와전히 제거될때 호출
    super.dispose();
    print('dispose is called');
  }

  @override
  Widget build(BuildContext context) {
    print('build is called');
    return Scaffold(
      appBar: AppBar(title: Text('ScreenB')),
      body: Center(
        child: Text(
          'ScreenB',
          style: TextStyle(fontSize: 24),
        ),
      ),
    );
  }
}
반응형