flutter_note007 화면 배치에 쓰는 기본 위젯 2.

5yattree·2023년 1월 2일
0

Flutter 정리 노트

목록 보기
7/13

화면 배치에 쓰는 기본 위젯 2.


Column 위젯.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Simple Page',
      debugShowCheckedModeBanner: false,
      home: SimplePage(),
    );
  }
}

class SimplePage extends StatelessWidget {
  const SimplePage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'My Simple Page',
          style: TextStyle(color: Colors.black45, fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
        backgroundColor: Colors.orangeAccent,
        elevation: 0.0,
      ),
      body: Column(
        children: [
          Container(
            child: Center(
              child: Text(
                'Container 1',
                style: TextStyle(color: Colors.white70),
              ),
            ),
            color: Colors.red,
            width: 100,
            height: 100,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.all(8.0),
          ),
          Container(
            child: Center(
              child: Text(
                'Container 2',
                style: TextStyle(color: Colors.white70),
              ),
            ),
            color: Colors.green,
            width: 100,
            height: 100,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.all(8.0),
          ),
          Container(
            child: Center(
              child: Text(
                'Container 3',
                style: TextStyle(color: Colors.white70),
              ),
            ),
            color: Colors.blue,
            width: 100,
            height: 100,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.all(8.0),
          ),
        ],
      ),
    );
  }
}

Column() 위젯은 수직 방향으로 위젯들을 나란히 배치하는 위젯이다.

https://docs.flutter.dev/development/ui/widgets/layout

또한 Column()위젯은 Multi-child layout widget 중 하나로 지난 시간 다뤄보았던 Container() 위젯과는 다른 성질을 가진다. Container() 위젯의 경우 Single-child layout widget 으로 child(자식) 요소를 단 하나만 가질 수 있었으나 Column() 위젯은 여러개의 child(자식) 요소를 가질 수 있다. 따라서 child가 아닌 children 으로 자식 요소들을 표현하며 작성한다.

위의 코드는 폭 100px, 높이 100px의 컨테이너 위젯을 3개를 구성하고 각 컨테이너 위젯 안에는 Text() 위젯을 사용하여 각 컨테이너의 이름을 지정해 주었으며, 이러한 Text() 위젯을 Center() 위젯을 사용하여 Container() 위젯의 중앙으로 배치시켰다. 또한 각 컨테이너 별로 색상을 지정하고 각각 padding과 margin을 8px씩 적용시켜주었으며 Column() 위젯을 사용하여 수직 방향으로 나란히 배치할 수 있도록 간단히 작성한 예시 코드이다.

Column(
        children: [ ... ],
     ),

위의 코드에서 살펴 볼 수 있는 것처럼 Column() 위젯은 Muti-child layout widget으로 여러개의 자식 요소(자식 위젯)를 가질 수 있는데 Dart 언어를 사용하여 앱을 개발하는 Flutter는 이러한 자식 위젯들을 표현하고 관리하기 위해서 Dart 언어의 데이터 타입 중 리스트, List 타입으로 관리하는 것을 알 수 있다.


Row 위젯.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Simple Page',
      debugShowCheckedModeBanner: false,
      home: SimplePage(),
    );
  }
}

class SimplePage extends StatelessWidget {
  const SimplePage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          'My Simple Page',
          style: TextStyle(color: Colors.black45, fontWeight: FontWeight.bold),
        ),
        centerTitle: true,
        backgroundColor: Colors.orangeAccent,
        elevation: 0.0,
      ),
      body: Row(
        children: [
          Container(
            child: Center(
              child: Text(
                'Container 1',
                style: TextStyle(color: Colors.white70),
              ),
            ),
            color: Colors.red,
            width: 100,
            height: 100,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.all(8.0),
          ),
          Container(
            child: Center(
              child: Text(
                'Container 2',
                style: TextStyle(color: Colors.white70),
              ),
            ),
            color: Colors.green,
            width: 100,
            height: 100,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.all(8.0),
          ),
          Container(
            child: Center(
              child: Text(
                'Container 3',
                style: TextStyle(color: Colors.white70),
              ),
            ),
            color: Colors.blue,
            width: 100,
            height: 100,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.all(8.0),
          ),
        ],
      ),
    );
  }
}

Row() 위젯은 Column() 위젯과 반대로 수평 방향으로 위젯들을 나란히 배치하는 위젯이다.

Row() 위젯 또한 Column() 위젯과 마찬가지로 Multi-child layout widget 에 속한다. Column() 위젯과 마찬가지로 여러 자식 요소들을 가지며 children 으로 자식 요소들을 표현하며 작성한다.
위의 코드는 첫번째 예시 코드에서 Column() 위젯을 Row() 위젯으로 변형한 것으로 세부적인 사항은 같으며 Column()위젯과는 달리 Container() 위젯을 왼쪽으로 오른쪽으로 수평 방향으로 위젯을 나란히 배치하고 있다.


Main Axis / Cross Axis

Axis는 (사물의) (중심) 축, 축선 을 의미한다.
위젯을 올바르게 배치하기 위해서는 Main Axis와 Cross Axis의 방향을 이해해야 할 필요가 이다.
한마디로 Main Axis는 주된 축 즉 주축을 Cross Axis는 교차 축을 의미한다고 이해할 수있다. Column() 위젯과 Row() 위젯은 각각 수직과 수평으로 자식 위젯들을 나란히 배치하는 위젯들로 서로가지는 주축과 교차 축은 다음 그림과 같이 이해할 수 있다.

Column() 위젯은 수직 방향(아랫쪽)이 mainAxis가 되고 Row() 위젯은 수평 방향(오른쪽)이 mainAxis가 된다. 쉽게 말해 위젯이 배열되는 방향이 곧 Main Axis(주축), 위젯이 배열되는 방향과 교차되는 축을 Cross Axis(교차축)으로 이해할 수 있다.


MainAxisAlignment와 CrossAxisAlignment 가지고 놀기.

Row 위젯에서의 적용

위의 예시로 작성한 Row() 위젯의 코드에 아래의 속성들을 통해 어떻게 변화하는 지 알아보자

mainAxisAlignment: MainAxisAlignment.start

body: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          ...
        ],
      ),

아무런 변화가 발생하지 않는다. 이는 mainAxisAlignment의 속성의 기본값으로 MainAxisAlignment.start 가 기본적으로 적용된다는 것을 의미하며 Row() 위젯을 생성했을때 주축에 대한 정렬은 기본값으로 start로 설정된다는 것을 알 수 있다.

mainAxisAlignment: MainAxisAlignment.center

body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ...
        ],
      ),

Row() 위젯 내의 Container() 자식 위젯들이 가운데 정렬로 배치가 되는 것을 확인할 수 있다.
MainAxisAlignment.center 는 주 축의 중앙으로 자식 위젯을 배열한다.

mainAxisAlignment: MainAxisAlignment.end

body: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          ...
        ],
      ),

Row() 위젯 내의 Container() 자식 위젯들이 오른쪽 정렬로 배치가 되는 것을 확인할 수 있다.
MainAxisAlignment.end 는 주 축의 끝으로 자식 위젯을 배열한다.


Column 위젯에서의 적용

이러한 배열은 Column() 위젯 역시도 Main Axis와 Cross Axis 의 방향만 잘 이해한다면 쉽게 이해할 수 있다.

mainAxisAlignment: MainAxisAlignment.start

아무런 변화가 발생하지 않는다. 이는 mainAxisAlignment의 속성의 기본값으로 MainAxisAlignment.start 가 기본적으로 적용된다는 것을 의미하며 Column() 위젯을 생성했을때 주축에 대한 정렬은 기본값으로 start로 설정된다는 것을 알 수 있다.

body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          ...
        ],
      ),

mainAxisAlignment: MainAxisAlignment.center

body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ...
        ],
      ),

mainAxisAlignment: MainAxisAlignment.end

body: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          ...
        ],
      ),


이 밖에 spaceEvenly, spaceBetween, spaceAround

mainAxisAlignment: MainAxisAlignment.spaceEvenly

Main Axis(주축)의 시작과 끝 사이에 동일한 간격으로 자식 위젯을 배치.

body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          ...
        ],
      ),

mainAxisAlignment: MainAxisAlignment.spaceBetween

Main Axis(주축)의 시작 부분부터 동일한 간격으로 자식 위젯을 배치하는 방식으로 첫 번째 자식 위젯은 주축의 시작부분에 있고 마지막 자식 위젯은 주축의 끝에 위치하여 배치.

body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          ...
        ],
      ),

mainAxisAlignment: MainAxisAlignment.spaceAround

Main Axis(주축)의 시작 부분과 끝 부분에 즉 앞/뒤 영역을 두고 사이에 동일한 간격으로 배치하며
위의 spaceEvenly와 굉장히 유사하지만 첫번째 자식 위젯과 제일 마지막 자식 위젯이 각각 시작 지점과 끝 지점에 자식 위젯간 사이의 절반만큼을 공간으로 두고 배치된다는 것이 차이점.

body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          ...
        ],
      ),

profile
오얏나무 한 그루

0개의 댓글