플러터 i18n

LeeWonjin·2024년 5월 8일
0

플러터

목록 보기
14/15

https://docs.flutter.dev/ui/accessibility-and-internationalization/internationalization

flutter pub add flutter_localizations --sdk=flutter
flutter pub add intl:any

세팅

머티리얼 앱

localizationsDelegates와 supportedLocales 키를 넣는다.

  • 로컬라이제이션 델리게이트 : 현지화(l10n)된 값을 뱉는 팩토리들이다
    • GlobalMaterialLocalizations.delegate : 머티리얼 위젯에 대한 현지화 (현지화된 문자열 등)
    • GlobalWidgetsLocalizations.delegate : 위젯 라이브러리에 대한 텍스트 ltr, rtl설정 현지화
import 'package:flutter_localizations/flutter_localizations.dart';

...

return const MaterialApp(
  title: 'Localizations Sample App',
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
    GlobalCupertinoLocalizations.delegate,
  ],
  supportedLocales: [
    Locale('en'), // English
    Locale('ko'), // 한국어
  ],
  home: MyHomePage(),
);

사용자 정의 l10n 파일 만들기

(공식문서에 사용되는 표현은 아니다. 그냥 플러터가 기본제공하는 l10n파일이 아니라는 뜻이다.)

미리 정의되지 않은 것은 플러터가 지역화를 할 수 없다. 당연하다.
우리가 넣은 값에 대해 로케일별로 보여줄 내용을 지정해보자.

루트에 l10n 도구 설정파일 l10n.yaml을 만든다.

arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart

lib/l10n디렉토리를 만들고, 지원할 로케일들에 대해 각각 파일을 만든다.

// app_en.arb 파일
// 키가 항목 이름이 되고, 오른쪽은 특정 로케일에서 항목에 대해 보여줄 문자열
{
    "title": "It's a title."
}

// app_ko.arb 파일
{
    "title": "제목입니다."
}

그리고 자동생성한다.
하고나면 .dart-tool/flutter_gen/gen_l10n 디렉토리 밑에 파일이 생성된다.

flutter gen-l10n

플러터 독스에서는 build나 run을 해도 자동으로 생성된다고 하는데,
본인 컴퓨터 설정이 잘못됐는지 생성이 안됐음.

코드 생성이 안된다면?

에러 내용 :
$ flutter gen-l10n
Attempted to generate localizations code without having the flutter: generate flag turned on.
Check pubspec.yaml and ensure that flutter: generate: true has been added and rebuild the
project. Otherwise, the localizations source code will not be importable.

해결
pubspec.yaml의 flutter: 아래에 generate: true 추가

...

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
...

flutter:
  uses-material-design: true
  generate: true # <----- 이거

사용자 l10n 적용

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';

class MainApp extends StatelessWidget {
  const MainApp({super.key});

  final String _title = 'Rapid Gana Draw';

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'hi',
      localizationsDelegates: AppLocalizations.localizationsDelegates,
      supportedLocales: AppLocalizations.supportedLocales,
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  Home({super.key});
  
  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Text(AppLocalizations.of(context)!.title);
      // 시스템 언어가 한국어이면 '제목입니다' 가 나오고,
      // 시스템 언어가 영어이면 'It's a title'이 나온다.
    )
  } 
}
profile
노는게 제일 좋습니다.

0개의 댓글

관련 채용 정보