본문 바로가기
[Flutter]

[Flutter] 앱 구조

by Hevton 2021. 8. 14.
반응형
import 'package:flutter/material.dart'; // a

void main() => runApp(MyApp()); // b

class MyApp extends StatelessWidget { ... } // c

class MyHomePage extends StatefulWidget { ... } // d

class _MyHomePageState extends State<MyHomePage> { ... } // e

MyHomePage와 _MyHomePageState는 앱의 화면을 나타내는 코드다. 모든 코드는 사실상 _MyHomePageState에 작성한다.

 

a.

플러터에서는 화면을 그리는 모든 디자인 요소를 위젯(widget)이라 하며, package:flutter/material.dart 패키지에는 머태리얼 디자인 위젯들이 포함되어 있다. 머태리얼 디자인을 기본으로 하는 앱은 이 패키지를 import하여 머태리얼 디자인 위젯을 사용할 수 있다.

 

 

b.

main 함수는 앱의 시작점.

 

 

c.

StatelessWidget 클래스는 상태가 없는 위젯을 정의하는 데 사용된다.

상태가 없다는 것은, 한 번 그려진 후 다시 그리지 않는 경우이며, 이러한 클래스는 프로퍼티로 변수를 가지지 않는다.

내부의 build() 메서드는 위젯을 생성할 때 호출되며, 실제로 화면에 그릴 위젯을 작성해 반환한다.

 

정리하면 StatelessWidget 클래스를 상속받은 MyApp 클래스는 MaterialApp 클래스의 인스턴스를 작성해 반환한다.

 

 

d.

StatefulWidget 클래스는 상태가 있는 위젯을 정의할 때 사용한다.

StatefulWidget 클래스를 상속받은 MyHomePage 클래스에서는, createState() 메서드를 오버라이딩하여 _MyHomePageState 클래스의 인스턴스를 반환시킨다. 이 메서드(createState)는 StatefulWidget이 생성될 때 한 번만 실행되는 메서드이다.

이 클래스 영역은 State 클래스 구성을 위한 '설정' 정도이다. 상태를 정의하고 다루는 것은 State클래스이다.

이 클래스 예제에서는 title이라는 property를 갖고 있는데, 이는 부모(App widget)으로부터 받아온 것이며 State의 build 메서드에서 사용될 것이다. 이 영역에서의 property는 final이여야 한다.

 

 

e.

State 클래스를 상속받은 클래스를 상태 클래스라고 부른다.

상태 클래스는 변경 가능한 상태를 프로퍼티 변수로 표현한다.

_MyHomePageState 클래스의 상태에 따라 화면에 그려질 코드를 build()에 작성한다.

+ 상태 클래스에서 StatefulWidget 클래스에 접근하려면 widget 프로퍼티를 사용한다.

+ State 클래스에는 주로 상태를 저장할 변수들과 그 변수를 조작할 메서드를 작성한다.

 

State 클래스에서 사용되는 setState() 메서드는, 인자로 전달된 함수를 실행한 후 화면을 다시 그리게 하는 역할을 한다.

화면은 build() 메서드가 실행되면서 그려진다고 배웠으니, setState() 메서드는 build() 메서드를 다시 실행시키는 역할을 한다.

 

 

서적 : 오준석의 플러터 생존코딩


혹은 그저 프로젝트를 만들기만 하면 기본적으로 주석으로 설명해주는데, 아주 잘 나와 있다.

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.green,
      ),
      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.
    );
  }
}

 


상태가 없는 정적인 화면은 StatelessWidget 클래스로 만든다.

상태가 있는 동적인 화면은 StatefulWidget 클래스로 만든다.

반응형