[Flutter] 샘플 프로젝트 살펴보기

[Flutter] 샘플 프로젝트 살펴보기

이번에는 lib 폴더 안에 있는 main.dart 를 통해 샘플 프로젝트를 살펴볼 것입니다.

Screenshot from 2021-03-24 16-00-46 (another copy)

import

import 'package:flutter/material.dart';

가장 먼저 확인할 수 있는 코드는 import 구문입니다. java 나 python 과 마찬가지로 특정 외부 라이브러리를 사용하겠다는 뜻입니다.

Flutter 를 사용하여 Application 을 만들기 위해서는 Flutter 팀에서 미리 만들어둔 텍스트, 버튼 등에 대한 디자인을 사용하여야 하는데, 이를 사용하기 위해서는 모든 파일에서 위와 같은 코드를 작성해 주어야 합니다.

main()

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

Project 를 실행하면 가장 먼저 실행되는 함수입니다. 앞의 void 는 해당 함수의 return 값이 없음을 뜻합니다. 가운데 runApp() 함수는 밑에 선언된 MyApp() 을 실행하라는 뜻입니다.

MyApp

class MyApp extends StatelessWidget {
  // 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 running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

여기 있는 MyApp 클래스가 실질적인 저희의 App 이라고 생각해주시면 됩니다.

Flutter 를 사용해서 Application 의 모든 시각적인 요소들은 Widget 이라고 불립니다. 때문에 이러한 요소들은 StatelessWidget 이나 StatfulWidget 을 꼭 상속하게 됩니다. 둘의 차이에 대해서는 다음 글 을 참고하시길 바랍니다.

StatelessWidget 을 상속받은 클래스는 build 라는 함수를 가지게 되는데, 간단하게는 Return 값을 화면에 띄우는 함수라고 생각하시면 될 것 같습니다.

build 함수의 Return 값으로 MaterialApp 이 작성되어 있는 것을 확인할 수 있습니다. 이는 Material Design 을 사용하는 Application 을 만들겠다는 것을 의미합니다. MaterialApp 의 각종 property(title, theme 과 같은 값들) 를 수정함으로써 우리가 작성하고자 하는 Application 이 가지는 전체 설정을 정할 수 있습니다.

MaterialApp 의 home property 는 Application 을 실행 시 가장 먼저 보여줄 화면이 무엇인지를 나타냅니다. 여기서는 Application 을 실행하면 MyHomePage() 를 가장 먼저 보여줄 것임을 의미합니다.

’//’ 으로 표시되어있는 것은 주석으로 실제 동작에는 영향을 주지 않는 메모라고 생각하시면 됩니다.

MyHomePage

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

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

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

마지막으로 MyHomePage 입니다. 이 클래스는 MyApp 과 달리 StatefulWidget 을 상속받았습니다.

첨부된 글에 언급되어있겠지만, 간단히 설명하면 화면이 변경되는 작업의 경우 StatefulWidget, 화면이 변경되지 않는 작업은 StatelessWidget 이라고 생각하시면 편합니다.

샘플 프로젝트 첫 화면의 경우 버튼을 누르면 숫자가 변경되는, 화면이 변경되는 작업이기 때문에 StatefulWidget 을 사용하였습니다.

StatefulWidget 은 다음과 같이 2가지로 나뉘게 되고, 둘의 항상 한 세트로 동작하게 됩니다.

  1. StatefulWidget
  2. State<클래스 이름="">

둘의 관계는 StatefulWidget 이 State 를 소유하고 있고, 변경된 내용을 화면에 보여줄 경우 State 만을 업데이트 하여 보여주는 것이라고 생각하면됩니다.

Scaffold()

위 코드에서 가장 중요한 것은 Scaffold() 라는 것입니다. 이는 Application 이 실행될 장치에 대한 뼈대를 세우는 것으로 다양한 기능을 제공하여 프론트 작업을 더욱 편하게 해주는 역할을 합니다. 또한 Material Design 을 위한 Layout 을 생성하여, 모든 요소들이 제작자가 의도한 디자인을 가지고 화면에 보일 수 있는 역할을 합니다.

이에 대한 상세한 예시는 이 글의 2.StatefulWidget 의 텍스트 예시 를 살펴보시기 바랍니다.


© 2021. All rights reserved.