Flutter

[FLUTTER] Container (margin & padding & alignment / boxDecoration)

Eunice99 2023. 3. 14. 16:43

[Container]

Container는 Box 형태의 기본적인 위젯으로 다방면으로 많이 사용

Container(
  width: 200, // 폭
  height: 200, // 높이
  color: Colors.amber, // 박스 색상
  child: Text("I Love Flutter!"), // 자식 위젯
),

- 아래와 같이 사용

body: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              TextField(
                decoration: InputDecoration(labelText: "이메일"),
              ),
              TextField(
                obscureText: true, // 비밀번호 안보이도록 조정
                decoration: InputDecoration(labelText: "비밀번호"),
              ),
              //Container 위젯이 ElevatedButton 위젯을 감싸게됨.
              Container(
                  width: double.infinity,
                  child: ElevatedButton(
                      onPressed: () {}, child: Text('로그인'))) // 익명함수
            ],
          ),
        ),

: 추가한 Container 위젯에 width: double.infinity,라고 추가하면, Container의 폭이 부모를 가득 채우게 되고, 버튼도 함께 최대 크기로 늘어난다.

 

비밀번호를 입력하는 TextField와 로그인 버튼 사이에 여백을 추가

- 기존 간격

아래 코드와 같이 Container에 margin: EdgeInsets.only(top: 24),라고 추가

 Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 24),
                  child: ElevatedButton(
                      onPressed: () {}, child: Text('로그인')))
Container에 margin 속성은 Container 바깥 영역에 여백을 줄 때 사용한다.

- 여백 추가한 화면

  • 전체코드 및 화면
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        // 화면에 보이는 영역
        appBar: AppBar(
          title: Text(
            "Hello Flutter",
            style: TextStyle(fontSize: 28),
          ),
          centerTitle: true,
        ),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              TextField(
                decoration: InputDecoration(labelText: "이메일"),
              ),
              TextField(
                obscureText: true, // 비밀번호 안보이도록 조정
                decoration: InputDecoration(labelText: "비밀번호"),
              ),
              //Container 위젯이 ElevatedButton 위젯을 감싸게됨.
              Container(
                  width: double.infinity,
                  margin: EdgeInsets.only(top: 24),
                  child: ElevatedButton(
                      onPressed: () {}, child: Text('로그인'))) // 익명함수
            ],
          ),
        ),
      ),
    );
  }
}

 

[margin (박스 바깥 영역) & padding (박스 안쪽 영역) & alignment (child 정렬)]

/// Copyright 2022. ⓒ DevStory.co.kr All rights reserved.

// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Container(
          width: 200,
          height: 200,
          color: Colors.pinkAccent, // 박스 색상
          padding: EdgeInsets.all(20), // 박스 안쪽 영역
          margin: EdgeInsets.all(50), // 박스 바깥 영역
          alignment: Alignment.topLeft, // child 정렬 // center로 지정하면 가운데로 옴
          child: Text(
            "I Love Flutter!",
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
            ),
          ),
        ),
      ),
    );
  }
}

: 아래와 같은 구조를 가짐

<EdgeInset 사용법>

  • 전방위 모두 동일하게 적용
EdgeInsets.all(8)
  • 특정 방위만 적용
EdgeInsets.only(
  left: 8,
  right: 8,
)
  • 위아래 또는 좌우 적용
EdgeInsets.symmetric(
	vertical: 8,
	horizontal: 8,
)

[boxDecoration]

Container의 테두리(border), 그림자, 색상 등을 꾸밀 때 사용
/// Copyright 2022. ⓒ DevStory.co.kr All rights reserved.

// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: Container(
            width: 200,
            height: 200,
            // color : Colors.amber, // decoration와 함께 사용 불가
						decoration: BoxDecoration(
              color: Colors.amber, // decoration 안에 color를 활용해주세요.
              borderRadius: BorderRadius.circular(50), // 모서리를 둥글게
              border: Border.all(color: Colors.blue, width: 5), // 테두리	
							boxShadow: [
                BoxShadow( // 그림자 효과
                  color: Colors.grey.withOpacity(0.7), // 투명도 70% 회색
                  spreadRadius: 5, // 퍼짐 효과
                  blurRadius: 7, // 뭉갬 효과
                  offset: Offset(5, 5), // 그림자를 우측 5 아래 5만큼 이동
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

위에 코드를 보면 color : Colors.amber, // decoration와 함께 사용 불가라고 되어있는데, 아래와 같이 color와 decoration을 동시에 사용하면 애러가 나온다.

Container(
	color: Colors.amber,
  decoration: BoxDecoration(),
),

에러가 나지않게 하려면 아래와 같이 color를 decoration 안에 넣으면 된다.

Container(
	decoration: BoxDecoration(
		color: Colors.amber,
	),
),