본문 바로가기
Development Solutions/Flutter & Dart

[Flutter] Make the height of the widget variably change depending on the length of the text input string. (Text 입력 문자열 길이에 따라 위젯의 높이가 가변적으로 변하도록 만들기)

by studio ODOC 2023. 9. 18.
반응형

[Flutter]

Make the height of the widget variably change depending on the length of the text input string.

(Text 입력 문자열 길이에 따라 위젯의 높이가 가변적으로 변하도록 만들기)

 

문제 상황 (Problem)

Text에 입력으로 들어오는 문자열 길이에 따라서 위젯의 높이가 가변적으로 변하면 좋겠는 상황이다. 코드를 어떻게 수정해야할까?

 

[Eng] (This is a situation where it would be nice to have the height of the widget change variably depending on the length of the string that is input to the text. How should I modify the code?)

반응형

해결 방법 (Solution)

TextPainter 위젯을 사용하면 Text의 높이를 측정할 수 있다.

아래와 같이 measureTextHeight() 함수를 선언하고, 각 Text 위젯에서 위젯 자신의 높이를 갱신해주면 되겠다.

 

[Eng] (Using the TextPainter widget, you can measure the height of text.
You can declare the measureTextHeight() function as shown below and update the widget's own height in each Text widget.)

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';

class WelfareDetail extends StatefulWidget {
  final WelfareItem welfareItem;
  const WelfareDetail({required this.welfareItem, Key? key}) : super(key: key);

  @override
  State<WelfareDetail> createState() => _WelfareDetailState();
}

class _WelfareDetailState extends State<WelfareDetail> {
  double serviceNameHeight = 0;
  double organizationHeight = 0;

  @override
  void initState() {
    super.initState();
    // 초기 높이 측정
    measureTextHeight(widget.welfareItem.serviceName, (height) {
      setState(() {
        serviceNameHeight = height;
      });
    });

    measureTextHeight(widget.welfareItem.organization, (height) {
      setState(() {
        organizationHeight = height;
      });
    });
  }

  void measureTextHeight(String text, Function(double) callback) {
    final textPainter = TextPainter(
      text: TextSpan(
        text: text,
        style: TextStyle(
          color: Colors.black,
          fontSize: 20,
          fontFamily: 'Inter',
          fontWeight: FontWeight.w600,
        ),
      ),
      maxLines: 1000, // 충분한 줄 수로 설정
      textDirection: TextDirection.ltr,
    );

    textPainter.layout(maxWidth: 327.54);
    callback(textPainter.height);
  }

 

반응형