본문 바로가기
공부기록/Flutter

[Flutter] 텍스트 길이가 길 경우 말 줄임표 사용하는 방법

by 책읽는 개발자 ami 2023. 7. 13.
728x90
반응형

Flutter에서 말 줄임표 사용하는 방법

아래 그림과 같이 Text가 너무 길 경우 말 줄임표로 나타내는 방법에 대해서 알아보도록 하겠습니다.

 

코드

Text(
     itemList[index]['title'].toString(),
     style: const TextStyle(
         fontSize: 24.0,
         color: Colors.black,
    ),
    overflow: TextOverflow.ellipsis,
)

코드 설명

 overflow: TextOverflow.ellipsis 부분은 텍스트가 위젯의 경계를 벗어날 경우 어떻게 처리할 것인지를 정의합니다. TextOverflow.ellipsis는 텍스트가 해당 영역을 벗어날 경우, 벗어나는 부분은 생략되고 대신에 말줄임표 (...)가 표시됩니다. 이렇게 하면 사용자는 텍스트가 더 있음을 알 수 있지만, 전체 내용은 화면에 표시되지 않아 공간을 절약할 수 있습니다. 

TextOverflow 속성 자세히 알아보기

`TextOverflow`는 텍스트가 박스를 넘어서는 경우 어떻게 처리할지를 정의하는 열거형입니다. Flutter에서는 주로 다음 네 가지 타입을 제공합니다:

1. `TextOverflow.clip`: 텍스트가 박스를 넘어서면 그 부분을 잘라내고 보여주지 않습니다. 이는 넘치는 텍스트에 대한 어떠한 시각적인 표시도 제공하지 않아, 사용자는 잘린 텍스트의 존재를 알 수 없습니다.

2. `TextOverflow.fade`: 텍스트가 박스를 넘어서면, 넘치는 부분이 점점 흐려지는 효과를 주어 텍스트가 흐려지면서 사라지게 됩니다. 이 효과는 주로 끝이 넘치는 긴 텍스트를 처리할 때 사용됩니다.

3. `TextOverflow.ellipsis`: 텍스트가 박스를 넘어서면, 넘치는 부분은 생략되고 그 대신에 말줄임표 (...)가 표시됩니다. 이는 보통 넘치는 텍스트를 생략하면서, 사용자에게 텍스트가 더 있다는 것을 알려줄 때 사용됩니다.

4. `TextOverflow.visible`: 넘치는 텍스트를 그대로 보여줍니다. 이는 텍스트가 그것의 박스를 넘어서도록 허용하며, 이로 인해 인접한 위젯에 겹치거나 화면 밖으로 나갈 수 있습니다. 이 옵션은 주의해서 사용해야 합니다.

TextOverflow 예시
  

 
전체 코드는 접은글을 참조해주세요.

더보기

tab1.dart

import 'package:flutter/material.dart';
import 'package:musicalapp/search.dart';
import 'package:musicalapp/verticalList.dart';

class Tab1Page extends StatelessWidget {
  List<Map<String, String>> itmList = [
    {
      'title': 'Title 1 제목이 너무 길어서 잘리는 경우 어떻게 해야할까',
      'period': '2023-06-19~2023-06-30',
      'location': 'Loc 1',
      'url':
          'https://cdn.pixabay.com/photo/2023/05/19/15/40/man-8004816_1280.jpg'
    },
    {
      'title': 'Title 2',
      'period': '2023-06-19~2023-06-30',
      'location': 'Loc 2',
      'url':
          'https://cdn.pixabay.com/photo/2023/06/17/22/51/shoes-8070908_640.jpg'
    },
    {
      'title': 'Title 3',
      'period': '2023-06-19~2023-06-30',
      'location': 'Loc 3',
      'url':
          'https://cdn.pixabay.com/photo/2023/05/30/17/20/woman-8029209_640.jpg'
    }
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.all(16.0),
            child: Text(
              '탭1 리스트',
              style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(child: VerticalListWidget(itemList: itmList)),
        ],
      ),
    );
  }
}

 

verticalList.dart

import 'package:flutter/material.dart';

class VerticalListWidget extends StatefulWidget {
  final List<Map<String, String>> itemList;

  VerticalListWidget({required this.itemList});

  @override
  _VerticalListWidgetState createState() => _VerticalListWidgetState();
}

class _VerticalListWidgetState extends State<VerticalListWidget> {
  late List<Map<String, String>> itemList;
  late List<bool> _isAlarmActiveList;

  @override
  void initState() {
    super.initState();
    itemList = widget.itemList; // Access widget property in initState
    _isAlarmActiveList = List<bool>.filled(itemList.length, false);
    // Initialize alarm toggle state based on alarmyn value
    for (int i = 0; i < itemList.length; i++) {
      if (itemList[i]['alarmyn'] == 'Y') {
        _isAlarmActiveList[i] = true;
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: itemList.length,
      itemBuilder: (context, index) {
        //bool isAlarmActive = itemList[index]['alarmyn'] == 'Y';
        bool isAlarmActive = _isAlarmActiveList[index];
        return Container(
          padding: EdgeInsets.all(16.0),
          child: Row(
            children: [
              Expanded(
                flex: 8,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      itemList[index]['title'].toString(),
                      style: const TextStyle(
                        fontSize: 24.0,
                        color: Colors.black,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8.0),
                    Text(
                      itemList[index]['period'] == null
                          ? ''
                          : itemList[index]['period'].toString(),
                      style: const TextStyle(
                        fontSize: 16.0,
                        color: Colors.grey,
                      ),
                    ),
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            itemList[index]['location'] == null
                                ? itemList[index]['dt'].toString()
                                : itemList[index]['location'].toString(),
                            style: TextStyle(
                              fontSize: 16.0,
                              color: Colors.grey.shade700,
                            ),
                          ),
                          Visibility(
                            visible: itemList[index]['location'] == null,
                            child: GestureDetector(
                              onTap: () {
                                setState(() {
                                  _isAlarmActiveList[index] =
                                      !_isAlarmActiveList[index];
                                });
                              },
                              child: Padding(
                                padding: const EdgeInsets.only(right: 18.0),
                                child: Icon(
                                  isAlarmActive
                                      ? Icons.notifications_active
                                      : Icons.notifications_none_outlined,
                                  color: isAlarmActive
                                      ? Colors.yellow
                                      : Colors.grey.shade700,
                                ),
                              ),
                            ),
                          )
                        ]),
                  ],
                ),
              ),
              Expanded(
                flex: 2,
                child: Image.network(
                  itemList[index]['url'].toString(),
                  fit: BoxFit.cover,
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
728x90
반응형