assets
└── langs
├── ko.json
└── en.json
import 'package:flutter/material.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter_phoenix/flutter_phoenix.dart';
import 'package:localization_example/screens/home_screen.dart';
import 'package:localization_example/widgets/language_button.dart';
import 'constants.dart';
void main() async {
// main 메서드에서 비동기 메서드 사용시 반드시 추가
WidgetsFlutterBinding.ensureInitialized();
// 패키지 초기화
await EasyLocalization.ensureInitialized();
runApp(
Phoenix(
child: EasyLocalization(
supportedLocales: const [en, ko], // 지원하는 언어 리스트
path: 'assets/langs', // 언어 파일이 있는 경로
fallbackLocale: en, // 기본값
child: const MyApp(),
),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: context.localizationDelegates,
supportedLocales: context.supportedLocales,
locale: context.locale,
home: const HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
// 기기의 언어 설정이 한국어일경우 ko, 영어일 경우 en, 그 외일경우 기본값인 en 출력
debugPrint('Locale : ${context.locale}');
return Scaffold(
appBar: AppBar(
title: const Text('appBar').tr(),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
LanguageButton(
text: '한국어',
locale: ko,
),
SizedBox(height: 12),
LanguageButton(
text: 'English',
locale: en,
),
],
),
),
);
}
}
class LanguageButton extends StatelessWidget {
const LanguageButton({
Key? key,
required this.text,
required this.locale,
}) : super(key: key);
final String text;
final Locale locale;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () async{
await context.setLocale(locale);
await EasyLocalization.ensureInitialized();
Phoenix.rebirth(context);
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: const BorderRadius.all(Radius.circular(4)),
),
child: Text(text),
),
);
}
}