[flutter] 플러터 intl을 사용해서 앱의 UI도 다국어로 변환할 수 있나요?
먼저, intl 패키지를 프로젝트에 추가해야 합니다. pubspec.yaml 파일에 아래와 같이 intl 패키지를 추가합니다:
dependencies:
flutter:
sdk: flutter
intl: ^0.17.0
다음으로, l10n
폴더를 생성하고 그 안에 언어별로 번역된 텍스트들을 정의합니다. 아래는 간단한 예시입니다:
intl_en.arb
intl_ko.arb
각 파일에는 번역할 문자열과 해당 언어로 번역된 문자열이 포함되어야 합니다. 예를 들면:
{
"title": "Flutter App",
"@title": {
"description": "The title of the app"
}
}
이제 앱 코드에서 intl 패키지를 사용하여 텍스트를 번역할 수 있습니다. intl.dart
파일을 생성하고 아래의 코드를 추가합니다:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:intl/message_lookup_by_library.dart';
typedef Future<String> MessageLoader(String localeName);
MessageLookupByLibrary? _findExact(localeName) {
switch (localeName) {
case 'en':
return messagesEn;
case 'ko':
return messagesKo;
default:
return null;
}
}
final messagesEn = MessageLookupByLibrary(_findExact);
final messagesKo = MessageLookupByLibrary(_findExact);
class DemoLocalizations {
DemoLocalizations(this.localeName);
final String localeName;
static Future<DemoLocalizations> load(Locale locale) async {
final String? name = locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
final localeName = Intl.canonicalizedLocale(name);
await initializeMessages(locale.toString());
return DemoLocalizations(localeName);
}
static DemoLocalizations? of(BuildContext context) {
return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
}
String get title {
return Intl.message(
'Flutter App',
name: 'title',
desc: 'The title of the app',
locale: localeName,
);
}
}
이제 앱의 Widget에서 DemoLocalizations를 사용하여 번역된 텍스트를 가져올 수 있습니다. 예시:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
DemoLocalizations.delegate,
],
supportedLocales: [
const Locale('en'),
const Locale('ko'),
],
home: Scaffold(
appBar: AppBar(
title: Text(DemoLocalizations.of(context)!.title),
),
body: ...
),
);
}
}
이제 앱을 실행하면 설정된 로케일에 따라 번역된 텍스트가 적용되는 것을 확인할 수 있습니다.