[Flutter] Auto Size Text 패키지 사용해서 글씨 크기 조절하기

2023. 6. 21. 14:29·🐦 플러터

Auto Size Text

플러터를 사용해서 Text 위젯을 사용하다보면 글씨 사이즈를 매번 조절해서 적어주는게 참 귀찮을 때가 많습니다. 그럴 때 매번 사이즈를 설정해주지 않고, 글씨 크기를 원하는 줄 수에 조정해서 정해주는 편리한 패키지가 존재합니다.

바로 auto_size_text 패키지 입니다.

Container(
      color: Colors.grey.withOpacity(0.5),

                    // Create AutoSizeText() Widget 
      child: AutoSizeText(
        'This string will be automatically resized to fit in two lines.',
        style: TextStyle(fontSize: 30),

        // Set maxLines as 2
        maxLines: 2,
      ),
),

이렇게 Text위젯 대신에 AutoSizeText 위젯을 사용해주면 됩니다. 내부 속성들도 Text 위젯과 거의 동일해서 사용하기도 매우 편리하다고 할 수 있습니다. 이렇게 maxLines를 지정해주기만 하면, 그 라인에 맞게 글씨 크기를 조절해서 화면에 출력해줍니다. 이 때, TextStyle로 지정해준 폰트 사이즈는 무시됩니다.

 

Container(
        color: Colors.grey.withOpacity(0.3),

        // Create AutoSizeText() Widget 
        child: AutoSizeText(
          "Other volcanoes behave quite differently from these violent volcanoes,and do hardly any noteworthy damage. Among these is the crater-islandof Stromboli, situated between Sicily and Calabria. This volcano hasbeen in continuous activity for thousands of years.",

          // Set maxLines as 1
          maxLines: 1,

          // Set overflowReplacement as 'Sorry String too long'
          overflowReplacement: Icon(
            Icons.cancel,
            color: Colors.red,
            size: 24,
          ),
        ),
),

또한, 이렇게 overflow가 발생하게 되었을 때, 기존 처럼 overflow를 처리해줄 수도 있지만, overflowReplacement 라는 속성을 활용해서 다른 위젯으로 대체해서 텍스트를 출력해보일 수도 있습니다.

 

사용방법이 매우 간단하고, 편리하기 때문에 매우 유용한 패키지인 것 같습니다. :D

전체 예시 코드 및 결과물

import 'package:flutter/material.dart';

// Import 'auto_size_text' plugin 
import 'package:auto_size_text/auto_size_text.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: PracticeAutoSizeText(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Auto Size Text')),
      body: Center(
          child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            Container(
              color: Colors.grey.withOpacity(0.5),

                // Create AutoSizeText() Widget 
              child: AutoSizeText(
                'This string will be automatically resized to fit in two lines.',
                style: TextStyle(fontSize: 30),

                // Set maxLines as 2
                maxLines: 2,
              ),
            ),
            SizedBox(height: 10),
          
            Container(
                color: Colors.grey.withOpacity(0.4),

                // Create AutoSizeText() Widget 
                child: AutoSizeText(
                    "Other volcanoes behave quite differently from these violent volcanoes,and do hardly any noteworthy damage. Among these is the crater-islandof Stromboli, situated between Sicily and Calabria. This volcano hasbeen in continuous activity for thousands of years.",
                    style: TextStyle(fontSize: 30),

                    // Set minFontSize as 18
                    minFontSize: 18,

                    // Set maxLines as 4
                    maxLines: 4,

                    // Set overflow as TextOverflow.ellipsis
                    overflow: TextOverflow.ellipsis)),
            SizedBox(height: 10),
            Container(
                color: Colors.grey.withOpacity(0.3),

                // Create AutoSizeText() Widget 
                child: AutoSizeText(
                  "Other volcanoes behave quite differently from these violent volcanoes,and do hardly any noteworthy damage. Among these is the crater-islandof Stromboli, situated between Sicily and Calabria. This volcano hasbeen in continuous activity for thousands of years.",

                  // Set maxLines as 1
                  maxLines: 1,

                  // Set overflowReplacement as 'Sorry String too long'
                  overflowReplacement: Icon(
                    Icons.cancel,
                    color: Colors.red,
                    size: 24,
                  ),
                ),
            ),
          ],
        ),
      )),
    );
  }
}

예시 코드 결과

 

https://pub.dev/packages/auto_size_text

 

auto_size_text | Flutter Package

Flutter widget that automatically resizes text to fit perfectly within its bounds.

pub.dev

 

저작자표시 비영리 동일조건 (새창열림)

'🐦 플러터' 카테고리의 다른 글

[Flutter] Modal_bottom_sheet 패키지를 사용해보자  (0) 2023.06.21
[Flutter] Flutter_spinkit 패키지로 로딩창을 만들어보자  (0) 2023.06.21
[Flutter] 라이트모드, 다크모드 테마 적용하기  (0) 2023.06.21
[Flutter] Button Style 지정하기  (0) 2023.06.21
[Flutter] Responsive User Interface를 구현해보자  (0) 2023.06.21
'🐦 플러터' 카테고리의 다른 글
  • [Flutter] Modal_bottom_sheet 패키지를 사용해보자
  • [Flutter] Flutter_spinkit 패키지로 로딩창을 만들어보자
  • [Flutter] 라이트모드, 다크모드 테마 적용하기
  • [Flutter] Button Style 지정하기
기멘기
기멘기
Handong Global University | Apple Developer Academy @ POSTECH
  • 기멘기
    현기의 비공식문서 🍎
    기멘기
  • 전체
    오늘
    어제

  • 링크

    • Github
    • Instagram

    • 전체 글 (87)
      • 🍎 iOS (7)
        • 애플 디벨로퍼 아카데미 (7)
      • 🐦 플러터 (32)
      • 🤔 컴공 지식 (10)
        • 알고리즘 (3)
        • 네트워크 (7)
      • 🔥 문해력 상승 (8)
        • 백 준 (8)
        • 프로 그래머 스 (0)
      • 💬 이모저모 (12)
        • CRA 방학 프로젝트 (4)
        • 캡스톤 산학 프로젝트 (5)
        • PARD IT 협업 동아리 (2)
      • 💡 인사이트 (0)
        • 전공 관련 (0)
        • 기타 (0)
      • ✏️ 하루 회고 (TIL) (11)
      • 🔍 ETC (7)
        • HTML-CSS-JS (4)

  • 인기 글


  • 최근 댓글


  • 최근 글


  • 블로그 메뉴

    • 티스토리 홈
    • 블로그 관리
    • 글 작성하기

  • hELLO· Designed By정상우.v4.10.3
기멘기
[Flutter] Auto Size Text 패키지 사용해서 글씨 크기 조절하기
상단으로

티스토리툴바