Flutter - #15. Stack

Pearl Lee·2021년 6월 9일
0

Flutter Widget

목록 보기
15/50

내가 보려고 쓰는 Flutter 일기
출처 : https://api.flutter.dev/flutter/widgets/Stack-class.html
공식 문서는 정말 좋은 곳이야...




Stack

stack 클래스는 말그대로 자식 요소들을 층층이 쌓고 싶을 때 사용하면 된다. 첫번째 자식 요소를 맨 밑에 쌓고, 그 다음 자식 요소들을 그 위에 쌓아가는 형태이다.

저번에 궁금했던 그러데이션도 Stack을 쓰면 표현할 수 있다!
우선 기본적인 예시를 하나 보고, Positioned 와 같이 쓰는 것도 보도록 하자.

각각의 자식 요소 배치를 다르게 하고 싶다면, Positioned 로 자식 요소를 감싸서 위치를 지정하면 된다.








코드 예시로 알아보자 - Stack만 사용

오늘도 공식 문서의 예제 코드를 가져와 돌려보자.

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 Stack';

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


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

  
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        Container(
          width: 200,
          height: 200,
          color: Colors.red,
        ),
        Container(
          width: 150,
          height: 150,
          color: Colors.green,
        ),
        Container(
          width: 100,
          height: 100,
          color: Colors.blue,
        ),
      ],
    );
  }
}

Stack 아래에 자식 요소를 나열한 것 말고는 아무것도 설정해주지 않았는데, 사실은
alignment 라는 속성은 AlignmentDirectional.topStart로, fit 은 Stackfit.loose로 이미 초기화가 되어있다.




스택의 생성자를 뜯어보면 아래와 같다. 생성자 맞겠지?

  Stack({
    Key? key,
    this.alignment = AlignmentDirectional.topStart,
    this.textDirection,
    this.fit = StackFit.loose,
    (
      'Use clipBehavior instead. See the migration guide in flutter.dev/go/clip-behavior. '
      'This feature was deprecated after v1.22.0-12.0.pre.',
    )
    this.overflow = Overflow.clip,
    this.clipBehavior = Clip.hardEdge,
    List<Widget> children = const <Widget>[],
  }) : assert(clipBehavior != null),
       super(key: key, children: children);

children, textDirection 빼고는 모두 특정한 값으로 초기화가 되어 있는 걸 알 수 있다. 특히 overflow 속성은 이제 clipBehavior 속성으로 대체될 것이므로, overflow 속성은 가급적 쓰지 않기를 권하고 있다.




이제 위의 코드에서 alignment와 fit 속성을 조금씩 바꿔보자.
맨 왼쪽 실행화면이 children외에 아무것도 손대지 않은 위 코드 그대로이다.

StackFit.loose, AlignmentDirectional.topStartStackFit.expandAlignmentDirectional.bottomCenter
StackFit.looseStackFit.expandStackFit.expand

Positioned 까지 다루려니 글이 너무 길어져서, 다음 일기로 써봐야겠다.



오늘의 일기는 여기까지!

profile
안 되면 되게 하라

0개의 댓글