Flutter

timeago 라이브러리

merrytang 2024. 10. 24. 23:39

timeago 라이브러리

특정 시점으로부터 얼마만큼 시간이 지났는지를 표현해주는 라이브러리이다. 예를 들어, "5분 전", "2일 전", "방금"과 같은 시간 형식을 지원한다. 이런 기능은 주로 소셜 미디어 앱이나 뉴스 앱처럼 시간 경과를 직관적으로 보여줄 필요가 있을 때 유용하게 쓰인다.

 

설치

flutter pub add timeago

 

사용법

1) 상단에서 해당 라이브러리 import 해준다

import 'package:timeago/timeago.dart' as timeago;

 

2) 한국어로 설정해준다.

timeago.setLocaleMessages('ko', timeago.KoMessages());

 

예시코드

import 'package:flutter/material.dart';
import 'package:timeago/timeago.dart' as timeago;

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // 한국어 메시지 설정을 initState에서 한 번만 실행
    timeago.setLocaleMessages('ko', timeago.KoMessages());
  }

  @override
  Widget build(BuildContext context) {
    final modelCreatedAt = DateTime.now().subtract(Duration(minutes: 5)); // 임의의 시간 예시

    return Scaffold(
      appBar: AppBar(title: Text('Timeago Example')),
      body: Center(
        child: Text(
          timeago.format(modelCreatedAt, locale: 'ko'), // 5분 전
          style: TextStyle(
            color: Color(0xff999999),
            fontSize: 14,
          ),
        ),
      ),
    );
  }
}

void main() => runApp(MaterialApp(home: MyApp()));