Flutter/Flutter FAQ

Flutter SafeArea에서 위젯의 높이를 가져오는 올바른 방법, proper way to get widget height in SafeArea

독학코딩 2023. 12. 18. 09:19
반응형

질문


위젯의 높이를 얻으려고 시도하지만 동일한 값을 출력합니다.

I/flutter (19253): 전체 높이: 976.0
I/flutter (19253): 안전한 높이: 976.0

Container가 상태 표시줄 아래에 배치되기 때문에 두 번째 값이 더 작아야 한다고 추측했습니다. 어떤 실수를 하고 있는 걸까요? 이 컨테이너에는 Wrap 위젯 (실제로 ReorderableWrap https://pub.dartlang.org/packages/reorderables#-readme-tab-)이 들어갈 예정이며, 이 위젯에는 36개의 카드가 있으며, 3행 12열로 배치되어야 하며, 카드의 높이는 컨테이너의 1/3이어야 합니다.

좋은 Reorderable Grid를 찾지 못했습니다. 그래도 내 질문은 안전 영역의 컨테이너와 전체 화면을 채우는 컨테이너가 동일한 높이를 가지는 이유입니다.

import 'package:flutter/material.dart';

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

class _MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(body: _Body()),
    );
  }
}

class _Body extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('전체 높이: ${MediaQuery.of(context).size.height}');
    return Container(
      constraints: BoxConstraints.expand(),
      decoration: BoxDecoration(color: Colors.red),
      child: SafeArea(
        child: _SafeHeightWidget(),
      ),
    );
  }
}

class _SafeHeightWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    print('안전한 높이: ${MediaQuery.of(context).size.height}');
    return Container(
      color: Colors.lightBlue,
    );
  }
}

답변


만약 안전 영역 상단 여백만 필요하고 안전 영역 위젯 자식의 높이가 필요하지 않은 경우:

final safePadding = MediaQuery.of(context).padding.top;

또는 (context 객체 없이)

final safePadding = WidgetsBinding.instance.window.padding.top;

만약 AppBar 높이가 필요한 경우:

final appBarHeight = AppBar().preferredSize.height;
반응형