White Cat's Paw

플러터/화면구현

[플러터] 화면구현 용어 기초 - 1

JungMayo 2025. 1. 8. 18:24

 

플러터 , 선언형 UI
명령형 UI
  - 상태 변경에 따른 UI 업데이트를 직접 명령한다
  - UI를 보다 세밀하게 제어 할 수 있다.
  - 예시 ) JavaScript를 이용한 DOM 조작
ViewA a = ViewA();
ViewB b = ViewB();
a.setColor(red) // 빨간색이 되어라
b.setColor(yello) // 노란색이 되어라
a.add(b) // b는 a의 child가 되어라​

 

선언형 UI

  - 상태만 선언하면 UI는 자동으로 업데이트 된다.
  - 최종 상태 선언에만 집중할 수 있다.
  - 예시 ) Flutter StatefulWidget  

// 빨간색 A가 노란색 B를 child로 가지고 있다.
return ViewA(
  color: red,
  child: ViewB(
		color: yello,
	),
);​
위젯의 종류

 

1. 플랫폼별 위젯

  • Material 위젯 (Android)
  • Cupertino 위젯 (iOS)

2. 기본 위젯

  • Text: 다양한 스타일의 텍스트를 표현합니다.
  • Row와 Column: CSS의 flexbox와 유사한 방식으로 수평, 수직 레이아웃을 구성함.
  • Stack: 위젯들을 겹쳐 배치할 수 있으며, Positioned 위젯과 함께 사용하여 정교한 위치 조정이 가능함.
  • Container: 다재다능한 박스 위젯으로, 배경, 테두리, 그림자 등 다양한 스타일링이 가능함.

상태 관리에 따른 위젯 분류

Flutter에서는 상태 관리 방식에 따라 위젯을 두 가지로 분류합니다:

  • Stateless Widget: 내부 상태가 없는 정적 위젯으로, 한 번 렌더링된 후 변경되지 않다.
  • Stateful Widget: 동적 상태를 가진 위젯으로, 사용자 상호작용이나 이벤트에 따라 UI가 변경될 수 있다.

빌드시 한번만 생성되기때문에 성능 최적화를 위해서는 Stateless Widget을 사용하는것이 좋음

 

Basic Widget 살펴 보기

  1. layout 위젯
  2. visible 위젯
  • 간단하고 기본적인 visible 위젯은 다음과 같음.

Text 위젯

Text('Hello World')

Image 위젯

Image.asset('images/lake.jpg')

Icon 위젯

Icon(Icons.home)

 

 

Container 위젯

  • 박스를 지정하여 padding, margin, border, background color 등을 설정할 수 있는 기본 위젯
  • Container 내에 여러 위젯을 나열하는 것이 일반적임

margin과 padding

  • 전부: EdgeInsets.all(10),
  • 특정 지정: EdgeInsets.only(top: 10, bottom: 10, left: 10, right: 10),
  • 인덱스, 위로, 오른쪽, 아래쪽: EdgeInsets.fromLTRB(50, 10, 30, 40),
  • 가로, 세로: EdgeInsets.symmetric(horizontal: 20, vertical: 50),

 

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.amber,
      margin: EdgeInsets.all(10),
      child: Center(
        child: Text('Hello World', textDirection: TextDirection.ltr),
      ),
    );
  }
}

 

border

  • Container 위젯에 border를 적용하려면, decoration: BoxDecoration()을 넣어줘야 함
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return Container(
	    // color: Colors.blue,  decoration: color 사용시 선언하면 오류 발생! 
      margin: EdgeInsets.all(10),
      decoration: BoxDecoration(
        // Container 의 color 선언과 decoration: BoxDecoration() 을 둘다 적용하면,
        // BoxDecoration() 안에서 color 를 선언하라고 가이드함(에러남)
        color: Colors.blue,
        border: Border.all(
          color: Colors.amber,
          width: 5,
        ),
      ),
      child: Center(
        child: Text('Hello World', textDirection: TextDirection.ltr),
      ),
    );
  }
}

 

border radius

  • 전부 적용1: BorderRadius.circular(10)
  • 전부 적용2: BorderRadius.all(Radius.circular(10))
  • 특정 방향만 적용: BorderRadius.only(topLeft: Radius.circular(10))
borderRadius: BorderRadius.only(
  topLeft: Radius.circular(50),
  topRight: Radius.circular(50),
  bottomLeft: Radius.circular(50),
  bottomRight: Radius.circular(50),
),

 

Row와 Column 위젯

  • Row 위젯: 위젯들을 수평으로 배치하는 위젯
  • Column 위젯: 위젯들을 수직으로 배치하는 위젯
  • Column과 Row 위젯은 children property를 가져서, 여러 자식을 가질 수 있음
    • children은 여러 자식을 가지므로, [] 리스트로 위젯을 표기해야 함
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          color: Colors.red,
          width: 50,
          height: 50,
          margin: EdgeInsets.all(10),
        ),
        Container(
          color: Colors.blue,
          width: 50,
          height: 50,
          margin: EdgeInsets.all(10),
        ),
      ],
    );
  }
}

 

mainAxisAlignment

: Row 위젯에서는 수평 정렬, Column 위젯에서는 수직 정렬을 설정

  • start: 주축의 시작점에서 자식 위젯들을 배치
  • end: 주축의 끝점에서 자식 위젯들을 배치
  • center: 주축의 중간에 자식 위젯들을 배치
  • spaceBetween: 자식 위젯 사이에 공간을 균등하게 배치
  • spaceAround: 자식 위젯 사이에 공간을 균등하게 배치하고, 첫 번째와 마지막 자식 위젯 앞뒤에 균등한 공간의 절반을 배치
  • spaceEvenly: 자식 위젯 사이에 공간을 균등하게 배치하고, 첫 번째와 마지막 자식 위젯 앞뒤에 균등한 공간을 배치

 

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Row(
        textDirection: TextDirection.ltr,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          Container(color: Colors.blue, width: 50, height: 50),
          Container(color: Colors.yellow, width: 50, height: 50),
        ],
      ),
      Row(
        textDirection: TextDirection.ltr,
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          Container(color: Colors.blue, width: 50, height: 50),
          Container(color: Colors.yellow, width: 50, height: 50),
        ],
      ),
      Row(
        textDirection: TextDirection.ltr,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          Container(color: Colors.blue, width: 50, height: 50),
          Container(color: Colors.yellow, width: 50, height: 50),
        ],
      ),
      Row(
        textDirection: TextDirection.ltr,
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          Container(color: Colors.blue, width: 50, height: 50),
          Container(color: Colors.yellow, width: 50, height: 50),
        ],
      ),
      Row(
        textDirection: TextDirection.ltr,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          Container(color: Colors.blue, width: 50, height: 50),
          Container(color: Colors.yellow, width: 50, height: 50),
        ],
      ),
      Row(
        textDirection: TextDirection.ltr,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(color: Colors.red, width: 50, height: 50),
          Container(color: Colors.blue, width: 50, height: 50),
          Container(color: Colors.yellow, width: 50, height: 50),
        ],
      ),
    ]);
  }
}

 

기초적인 Flutter 화면을 구성하는 패턴

  1. 'package:flutter/material.dart' 임포트
  2. MaterialApp으로 메인 위젯 트리 감싸기
  3. title과 theme과 같은 속성 설정
  4. home : 속성을 주 페이지로 정의
  5. Scaffold:
    • 앱의 시각적 레이아웃에 대한 기본 구조 제공
    • appBar 및 body와 같은 속성 설정
      • 레이아웃 요소 제공 (예: AppBar, Drawer, BottomNavigationBar)
        • 각 구성요소는 또 다른 위젯으로 각각의 사용법은 이후에 정리하기로 함
      • body에 실제 화면 관련 위젯 정의
  6. 'package:flutter/material.dart' 임포트
  7. MaterialApp으로 메인 위젯 트리 감싸기
  8. title과 theme과 같은 속성 설정
  9. home : 속성을 주 페이지로 정의
  10. Scaffold:
    • 앱의 시각적 레이아웃에 대한 기본 구조 제공
    • appBar 및 body와 같은 속성 설정
      • 레이아웃 요소 제공 (예: AppBar, Drawer, BottomNavigationBar)
        • 각 구성요소는 또 다른 위젯으로 각각의 사용법은 이후에 정리하기로 함
      • body에 실제 화면 관련 위젯 정의

MaterialApp의 주요 property와 사용법

  • theme: 앱의 전체 테마, 색상 구성 등이 포함 (예, theme: ThemeData(primarySwatch: Colors.red))
  • home: 앱이 시작할 때 보여질 기본 경로 또는 위젯
home: Scaffold(
  appBar: AppBar(title: const Text('FunCoding')),
),