투케이2K

4. (Flutter/플러터) [Mac] : [환경] : 플러터 프로젝트 시작 진입 점 main.dart 코드 분석 및 설명 본문

Flutter

4. (Flutter/플러터) [Mac] : [환경] : 플러터 프로젝트 시작 진입 점 main.dart 코드 분석 및 설명

투케이2K 2024. 5. 19. 10:44

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Dart

 

[원본 : main.dart 소스 코드]

import 'package:flutter/material.dart';

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

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

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // TRY THIS: Try running your application with "flutter run". You'll see
        // the application has a purple toolbar. Then, without quitting the app,
        // try changing the seedColor in the colorScheme below to Colors.green
        // and then invoke "hot reload" (save your changes or press the "hot
        // reload" button in a Flutter-supported IDE, or press "r" if you used
        // the command line to start the app).
        //
        // Notice that the counter didn't reset back to zero; the application
        // state is not lost during the reload. To reset the state, use hot
        // restart instead.
        //
        // This works for code too, not just values: Most code changes can be
        // tested with just a hot reload.
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // TRY THIS: Try changing the color here to a specific color (to
        // Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
        // change color while the other colors stay the same.
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          //
          // TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
          // action in the IDE, or press "p" in the console), to see the
          // wireframe for each widget.
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
 

[분석 및 설명 : main.dart 소스 코드]

import 'package:flutter/material.dart';


// -----------------------------------------------------------------------------------------
// TODO [main] : [application 의 진입점 역할]
// -----------------------------------------------------------------------------------------
void main() {
  runApp(const MyApp());
}





// -----------------------------------------------------------------------------------------
// TODO [MyApp] : [상태가 변경 되지 않는 Widget] : [StatelessWidget 상속 및 화면에 표시될 Widget]
// -----------------------------------------------------------------------------------------
// StatelessWidget 은 상태가 없는 위젯으로 생성 시점에 모든 구성이 결정되며, 데이터 변경에 따라 다시 Rendering 되지 않습니다
// -----------------------------------------------------------------------------------------
class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // [빌드 환경 설정]
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',

      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),

      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}





// -----------------------------------------------------------------------------------------
// TODO [MyHomePage] : [상태 변경 상태 표시 Widget] : [StatefulWidget 상속 및 화면에 표시될 Widget]
// -----------------------------------------------------------------------------------------
// StatefulWidget 은 상태가 있는 위젯으로, 동적 데이터를 관리하고, 데이터가 변경될 때마다 UI가 업데이트될 수 있습니다
// -----------------------------------------------------------------------------------------
// 특징 :
// - 동적인 상호작용 지원
// - State 객체를 통해 상태 관리가 이루어지며, setState 메소드를 호출하면 build 메소드가 다시 실행되어 UI가 업데이트됩니다
// -----------------------------------------------------------------------------------------
class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}





// -----------------------------------------------------------------------------------------
// TODO [_MyHomePageState] : [State 객체를 통해 동적 상태 관리 및 UI 업데이트] : [State<MyHomePage> 상속]
// -----------------------------------------------------------------------------------------
class _MyHomePageState extends State<MyHomePage> {

  // [카운트 증가 변수]
  int _counter = 0;



  // [카운트 증가 메소드 및 UI 업데이트]
  void _incrementCounter() {
    setState(() { // [build 메소드가 다시 실행되어 UI 업데이트]
      _counter++;
    });
  }



  // [빌드 설정]
  @override
  Widget build(BuildContext context) {

    // ----------------------------------------------------
    // [Scaffold : 기본적인 Material Deisgn Layout 구조를 구현]
    // ----------------------------------------------------
    // AppBar : 화면 상단에 위치하며 앱의 타이틀, 액션 아이템, 오버플로우 메뉴 등을 포함할 수 있습니다.
    // Body : 앱의 주요 콘텐츠가 표시되는 부분으로, 다양한 위젯들을 이곳에 배치할 수 있습니다.
    // FloatingActionButton : 화면에 부동하는 버튼으로, 일반적으로 액션을 유도하는 메인 기능에 사용됩니다.
    // BottomNavigationBar : 화면 하단에 위치하는 네비게이션 바로, 여러 탭으로 구성될 수 있습니다.
    // Drawer : 화면의 옆에서 슬라이드하여 나오는 메뉴로, 네비게이션 링크나 옵션을 포함할 수 있습니다
    // SnackBar : 간단한 메시지를 잠깐 동안 보여주는데 사용되며, 화면 하단에 일시적으로 표시됩니다.
    // BottomSheet : 화면 하단에서 올라오는 패널로, 추가 정보나 입력 폼을 제공할 수 있습니다.
    // ----------------------------------------------------
    return Scaffold(

      // [앱 : 액션바] : [애플리케이션의 제목, 탐색 버튼, 상태 표시줄 등이 포함]
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
      ),


      // [앱 : Body] : [페이지의 본문 콘텐츠를 제공]
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headlineMedium,
            ),
          ],
        ),
      ),


      // [앱 : floatingActionButton] : [페이지의 하단에 표시되는 플로팅 버튼을 제공]
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.

    );

  }

}
 

[결과 출력]

 

 

반응형
Comments