[Flutter] UI - 위젯소개

Array.prototype·2022년 5월 25일
0

Flutter

목록 보기
1/1
post-thumbnail

Hello world

import 'package:flutter/material.dart';

void main() {
  runApp(
    Center(
      child: Text(
        'Hello, world!',
        textDirection: TextDirection.ltr,
      ),
    ),
  );
}

runApp()은 주어진 위젯을 가지고 위젯트리의 루트로 만든다.
위 예제에서 위젯트리는 2개의 위젯으로 구성된다.
Center위젯과 그 하위 위젯인 Text위젯.
프레임워크는 루트위젯이 화면을 덮도록 강제한다. 그렇다는건 위 소스는 'Hello world!' 라는 텍스트가 화면의 중앙에 위치한다는 것을 뜻한다.

앱을 작성할 때 일반적으로 새 위젯을 작성하게 된다.
새롭게 작성하는 위젯은 아래 위젯의 하위 클래스이다.

  • StatelessWidget
  • StatefulWidget

이름에서도 알 수 있듯이 상태값을 가지는 위젯과 상태값이 없는 위젯이다.
위젯의 주기능은 다른 하위레벨 위젯들을 묘사하는 build함수를 구현하는 것이다.
프레임워크는 프로세스가 완료될 때까지 이런 위젯들을 계산하고 묘사하여 차례로 구축한다.

Basic Widget

Flutter는 강력한 기본 위젯과 함께 제공된다. 그 중 일반적으로 사용되는 것은 다음과 같다.

Text

Text위젯은 텍스트를 만들 수 있게 해준다.

Row, Column

수평, 수직방향에 유연한 레이아웃 위젯을 만들 수 있다. 웹의 flexbox layout model기반임.

Stack

그려진 순서대로 각각 쌓이게 한다. 그 후 Positioned위젯을 사용해서 위치를 잡을 수 있다. 스택은 웹의 absolute positioning layout model기반임.

Container

Container위젯으로 직사각형의 보이는 요소를 만들 수 있다. BoxDecoration으로 배경, 보더, 그림자 등을 꾸밀 수 있고 마진, 패딩값도 가지며 또한 매트릭스를 이용해 3차원공간 변형도 가능하다.

이러한 위젯과 몇가지 위젯들을 결합해보자면 아래처럼 사용할 수 있겠다.

import 'package:flutter/material.dart';

class MyAppBar extends StatelessWidget {
  MyAppBar({this.title});

  // Fields in a Widget subclass are always marked "final".

  final Widget title;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 56.0, // in logical pixels
      padding: const EdgeInsets.symmetric(horizontal: 8.0),
      decoration: BoxDecoration(color: Colors.blue[500]),
      // Row is a horizontal, linear layout.
      child: Row(
        // <Widget> is the type of items in the list.
        children: <Widget>[
          IconButton(
            icon: Icon(Icons.menu),
            tooltip: 'Navigation menu',
            onPressed: null, // null disables the button
          ),
          // Expanded expands its child to fill the available space.
          Expanded(
            child: title,
          ),
          IconButton(
            icon: Icon(Icons.search),
            tooltip: 'Search',
            onPressed: null,
          ),
        ],
      ),
    );
  }
}

class MyScaffold extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Material is a conceptual piece of paper on which the UI appears.
    return Material(
      // Column is a vertical, linear layout.
      child: Column(
        children: <Widget>[
          MyAppBar(
            title: Text(
              'Example title',
              style: Theme.of(context).primaryTextTheme.title,
            ),
          ),
          Expanded(
            child: Center(
              child: Text('Hello, world!'),
            ),
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    title: 'My app', // used by the OS task switcher
    home: MyScaffold(),
  ));
}
profile
frontend developer

0개의 댓글