Flutter - #31. Spacer

Pearl Lee·2021년 7월 9일
0

Flutter Widget

목록 보기
30/50

내가 보려고 쓰는 Flutter 일기
참고1 : https://api.flutter.dev/flutter/widgets/Spacer-class.html








Spacer

오늘 배워볼 것은 Spacer.
이름에서도 알 수 있듯이 공간을 만들어 주는 위젯이다. 그런데 어디에서?
자식요소들을 한 줄로 나열하는 Flex Container 내에서 쓰면 된다. 즉, Row, Column 안에서 쓰면 된다. 사용법은 매우 간단하다. Spacer() 요렇게 써주면 끝.









코드 예시로 알아보자

우선 Row 로 Text 위젯 3개를 나열해보았다.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

/// This is the main application widget.
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Test Spacer';

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: SpacerWidget(),
      ),
    );
  }
}

class SpacerWidget extends StatelessWidget {
  
  Widget build(BuildContext context) {
    return Center(
      child: Row(
        children: [
          Text(
            'Begin',
            style: TextStyle(fontSize: 30),
          ),
          Text(
            'Middle',
            style: TextStyle(fontSize: 30),
          ),
          Text(
            'End',
            style: TextStyle(fontSize: 30),
          ),
        ],
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      ),
    );
  }
}

실행화면은 아래와 같다.

mainAxisAlignment 설정 안함MainAxisAlignment.spaceEvenly

Row, Column 은 기본적으로 자식 요소들을 '나열'만 하기 때문에, mainAxisAlignment 설정 안하면 자식 요소들이 다닥다닥 붙어서 나온다. 그래서 Row, Column을 쓸때는 보통 mainAxisAlignment 속성을 꼭 설정하는 편이다.







이제 Spacer()를 넣고 다시 돌려보자. 코드를 아래와 같이 바꿔준다. Spacer()를 쓸 때는 mainAxisAlignment에 설정한 속성을 싸그리 무시하더라. 고로 주석처리

 child: Row(
        children: [
          Text(
            'Begin',
            style: TextStyle(fontSize: 30),
          ),
          Spacer(),
          Text(
            'Middle',
            style: TextStyle(fontSize: 30),
          ),
          Spacer(),
          Text(
            'End',
            style: TextStyle(fontSize: 30),
          ),
        ],
        //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      ),

실행결과는 아래와 같다.

위 코드첫 번째 Spacer(flex:2)




Spacer() 에는 flex 속성을 지정해서, Spacer() 들 간의 크기를 조정 가능하다. Spacer(flex:2) 요렇게 설정하면, flex 속성을 설정하지 않은 쪽의 2배만큼의 공간을 차지한다. 저어번에 Expanded 에서도 flex 를 지정할 수 있었는데, 그것과 똑같다.

Row, Column 의 자식 요소들 나열하고 사이에 공간을 넣을 때는 SizedBox() 를 주로 쓸 생각을 했는데, Spacer() 도 굉장히 간편하다.







오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글