TIL: Flutter | [노마드코더] Widget Lifecycle

Lumpen·2023년 1월 23일
0

Flutter

목록 보기
16/17

life cycle

StateWidget 은 생명주기가 있다
이벤트에 따라 생명주기를 달리한다

Stateful Widget 은 initState() 메소드를 가지고 있다
상태를 초기화하는 메소드로 대부분의 경우 생략 가능하다
부모 요소에 의존하는 데이터를 초기화해야 할 경우
context를 초기화하거나, API 업데이트를 구독해야할 경우 사용된다

initState() 메소드는 항상
build() 메소드보다 먼저 호출되고
한 번만 호출된다

아마 componentWillMount 와 비슷한 것 같다

dispose() 메소드는 componentWillUnmount 와 비슷한 것 같다

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // This widget is the root of your application.
  bool showTitle = true;

  void toggleTitle() {
    setState(() {
      showTitle = !showTitle;
    });
  }

  
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
          textTheme: const TextTheme(
              titleLarge: TextStyle(
        color: Colors.red,
      ))),
      title: 'Flutter Demo',
      home: Scaffold(
        backgroundColor: const Color.fromARGB(178, 233, 220, 189),
        body: Center(
            child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            showTitle ? const LargeTitle() : const Text('nothing'),
            IconButton(
                onPressed: toggleTitle, icon: const Icon(Icons.remove_red_eye))
          ],
        )),
      ),
    );
  }
}

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

  
  State<LargeTitle> createState() => _LargeTitleState();
}

class _LargeTitleState extends State<LargeTitle> {
  
  void initState() {
    // TODO: implement initState

    print('initState');
  }

  
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('dispose');
  }

  
  Widget build(BuildContext context) {
    print('build');
    return Text(
      'Large Title',
      style: TextStyle(
          color: Theme.of(context).textTheme.titleLarge!.color, fontSize: 30),
    );
  }
}
profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글