[flutter] 플러터 intl을 사용해서 앱의 문구를 동적으로 변경할 수 있나요?
네, 플러터의 intl 패키지를 사용하여 앱의 문구를 동적으로 변경할 수 있습니다. intl 패키지는 다국어 지원과 관련된 작업을 쉽게 처리할 수 있도록 도와줍니다.
intl 패키지를 사용하기 위해서는 먼저 pubspec.yaml
파일에 다음과 같이 의존성을 추가해야합니다:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.17.0
의존성을 추가한 후에는 앱의 코드에서 intl 패키지를 사용할 수 있습니다. 다음은 intl 패키지를 사용하여 앱의 문구를 동적으로 변경하는 간단한 예제입니다:
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Intl Example',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: [
Locale('en', 'US'),
Locale('ko', 'KR'),
],
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context).greeting),
),
body: Center(
child: Text(AppLocalizations.of(context).helloWorld),
),
);
}
}
class AppLocalizations {
static Future<AppLocalizations> load(Locale locale) {
final String name =
locale.countryCode.isEmpty ? locale.languageCode : locale.toString();
final String localeName = Intl.canonicalizedLocale(name);
return initializeMessages(localeName).then((_) {
Intl.defaultLocale = localeName;
return AppLocalizations();
});
}
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations);
}
String get greeting {
return Intl.message(
'Hello',
name: 'greeting',
desc: 'Greeting',
);
}
String get helloWorld {
return Intl.message(
'Hello, World!',
name: 'helloWorld',
desc: 'Hello World',
);
}
}
class AppLocalizationsDelegate
extends LocalizationsDelegate<AppLocalizations> {
const AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) {
return ['en', 'ko'].contains(locale.languageCode);
}
@override
Future<AppLocalizations> load(Locale locale) {
return AppLocalizations.load(locale);
}
@override
bool shouldReload(AppLocalizationsDelegate old) {
return false;
}
}
위의 예제에서는 AppLocalizations
클래스를 사용하여 다국어 문구를 관리합니다. AppLocalizations
클래스에서는 Intl.message()
함수를 사용하여 각 문구를 지원하는 언어로 동적으로 변경합니다.
또한, MyApp
클래스에서 localizationsDelegates
와 supportedLocales
를 설정하여 여러 언어의 지원을 등록할 수 있습니다. 그리고 HomePage
에서는 AppLocalizations.of(context)
를 통해 앱의 해당 언어에 따른 문구를 가져와 사용합니다.
intl 패키지를 사용하면 앱의 문구를 동적으로 변경하는 작업을 쉽게 처리할 수 있습니다. 다국어 지원이 필요한 앱을 개발할 때 intl 패키지를 사용해보세요.