-
[Flutter] 플러터 프로젝트의 구성코딩/Flutter(플러터) 2021. 11. 4. 14:05
이 글은 저의 복습을 목적으로 작성된 글이며,
Do it! 플러터 앱 프로그래밍 책을 바탕으로 작성되었습니다.
플러터 프로젝트 주요 폴더 소개- android: 안드로이드 프로젝트 관련 파일 [안드로이드 스튜디오로 실행 가능]
- ios: iOS 프로젝트 관련 파일 [엑스코드로 실행 가능(맥 전용)]
- lib: 플러터 앱 개발을 위한 다트 파일 [플러터 SDK 설치 필요]
- test: 플러터 앱 개발 중 테스트 파일 [테스트 편의성 제공]
루트의 파일 중 pubspec.yaml 파일은 플러터에서 다양한 패키지, 이미지, 폰트 등을 사용할 수 있게 도와준다.
lib폴더 안 main.dart 파일
다트 앱을 실행하면 이 파일 안에 있는 main() 함수부터 시작한다.
main() 함수에서는 runApp() 함수를 호출한다.
runApp() 함수는 binding.dart 클래스에 정의되어 있으며 플러터 앱을 실행하는 역할을 한다.import 'package:flutter/material.dart'; void main() { runApp(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'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); // 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 _MyHomePageState 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( // 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. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // 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). 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. ); } }
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'), ); } }
class MyApp extends StatelessWidget {
플러터 앱을 구성하는 위젯은 스테이트리스(stateless)와 스테이트풀(stateful) 두 가지로 구분할 수 있다.
내용을 갱신할 필요가 없는 위젯은 화면에 보이기 전에 모든 로딩을 마친다. 즉, 앱이 위젯의 상태를 감시하고 있을 필요가 없다. 이처럼 상태를 연결할 필요가 없는 위젯을 스테이트리스 위젯이라고 하며 StatelessWidget 클래스를 상속받아서 만들게 된다. 도움말 페이지처럼 내용을 갱신할 필요가 없을 때 사용된다. 갱신할 필요가 없으므로 적은 자원으로 화면을 구성할 수 있다.
반면에 내용을 갱신해야 할 때 쓰이는 위젯을 스테이트풀 위젯 이라고 하고, StatefulWidget 클래스를 상속받아서 만든다. 앱이 위젯의 상태를 감시하다가 위젯이 특정 상태가 되면 알맞은 처리를 수행한다. 버튼을 누를 때마다 값이 화면에 동적으로 바뀌면서 출력되는 계산기가 하나의 예시이다. 언제든 상태가 변경되면 특정한 처리를 수행해야 하므로, 메모리나 CPU 등 자원을 많이 소비한다.
@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'), ); }
- @override 어노테이션을 이용해서 build() 함수를 재정의 해준다.
- build() 함수에서는 어떤 위젯을 만들것인지 정의한다.
- 처음 runApp()을 이용해 클래스를 실행할 때는 MaterialApp() 함수를 반환해야 한다.
- MaterialApp() 함수에는 title(앱 이름), theme(앱 테마), 그리고 home(앱 실행시 첫 화면에 표시할 내용) 등이 정의되어 있다.
'코딩 > Flutter(플러터)' 카테고리의 다른 글
[Flutter] 비동기(asynchronous) 처리와 스트림(Stream) 통신 (0) 2021.11.04