TIL 23.10.28 | Build Context, Widget Lifecycle

HyeonWooGa·2023년 10월 28일
0

TIL

목록 보기
37/39
  1. Build Context

    • It's type of build function of Widget.
    • It handles to the location of a widget in the widget tree.
    • We can use theme because of Build Context, Build Context can pass theme from top to bottom of Widget Tree
    • It is example code
      // 상위 트리 클래스 MyApp 에서 theme 지정
      ...
      
      Widget build(BuildContext context) {
       return MaterialApp(
         theme: ThemeData(
           textTheme: const TextTheme(
             titleLarge: TextStyle(
               color: Colors.red,
             ),
           ),
         ),
       ...
      
       // 하위 트리 클래스 _MyLargeTitle 에서 theme 사용
      
      Widget build(BuildContext context) {
       return Text(
         'Click Count',
         style: TextStyle(
           fontSize: 30,
           color: Theme.of(context)
               .textTheme
               .titleLarge!
               .color, 
         ),
       );
      }
  2. Widget Lifecycle

    • Widget has Lifecycle and Lifecycle functions that we can use.

    • It has initState(), build, dispose()

      • initState() is called before build, so it can be used when calling API
      • build is build, it means when UI is drew first or drew again cause setState
      • dispose() is called after Widget is removed on Widget Tree
    • We can implement well by using Widget Lifecycle 👍

    • It's example code.

      class _MyLargeTitle extends StatefulWidget {
        const _MyLargeTitle();
      
        
        State<_MyLargeTitle> createState() => _MyLargeTitleState();
      }
      
      class _MyLargeTitleState extends State<_MyLargeTitle> {
        // int count = 0;
      
      // build 를 하기 전에 먼저 호출
      // 대표적으로 API 불러올때 사용
        
        void initState() {
          print('initState!');
          super.initState();
        }
      
      // 해당 위젯이 화면에서 사라질때 호출된다.
        
        void dispose() {
          print('dispose');
          super.dispose();
        } 
      
        
        Widget build(BuildContext context) {
          print('build!');
          return Text(
            'Click Count',
            style: TextStyle(
              fontSize: 30,
              color: Theme.of(context)
                  .textTheme
                  .titleLarge!
                  .color, // titleLarge 는 항상 있다는 뜻 (!), titleLarge 는 있을 수도 없을 수도 있다는 뜻 (?)
            ),
          );
        }
      }
      
profile
Aim for the TOP, Developer

0개의 댓글