Skip to content

Commit

Permalink
Implement Localization Management
Browse files Browse the repository at this point in the history
+ Implement change language by Bloc Architecture
+ Adapt lint and test rule
  • Loading branch information
phoenixit99 committed Nov 25, 2024
1 parent 2ec20e7 commit fafb2f8
Show file tree
Hide file tree
Showing 12 changed files with 293 additions and 127 deletions.
24 changes: 24 additions & 0 deletions lib/data/model/language_model.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import 'dart:ui';

enum Language {
english(
Locale('en', 'US'),
'English',
),
spanish(
Locale('es', 'ES'),
'Español',
),
french(
Locale('fr', 'FR'),
'Français',
);

const Language(
this.value,
this.text,
);

final Locale value;
final String text;
}
6 changes: 6 additions & 0 deletions lib/l10n/app_en.arb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"title": "Hello, World!",
"subtitle": "Welcome to Localization",
"description": "You have pushed the button this many times:",
"switch_language": "Switch language"
}
7 changes: 7 additions & 0 deletions lib/l10n/app_es.arb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

{
"title": "¡Hola, Mundo!",
"subtitle": "Bienvenido a Localización",
"description": "Has pulsado el botón tantas veces:",
"switch_language": "Cambiar idioma"
}
6 changes: 6 additions & 0 deletions lib/l10n/app_fr.arb
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"title": "Bonjour",
"subtitle": "Bienvenue dans Localisation",
"description": "Vous avez appuyé sur le bouton autant de fois :",
"switch_language": "Changer de langue"
}
144 changes: 33 additions & 111 deletions lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,125 +1,47 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'presentation/bloc/language_bloc/language_bloc.dart';
import 'presentation/homescreen/home_page.dart';

void main() {
runApp(const MyApp());
runApp(
MultiBlocProvider(
providers: [
BlocProvider<LanguageBloc>(
create: (_) => LanguageBloc(),
),
],
child: MyApp(),
),
);
}

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to Colors.green
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// TRY THIS: Try changing the color here to a specific color (to
// Colors.amber, perhaps?) and trigger a hot reload to see the AppBar
// change color while the other colors stay the same.
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
//
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
return BlocBuilder<LanguageBloc, LanguageState>(
builder: (context, state) {
return MaterialApp(
title: 'Flutter Demo',
locale: state.selectedLanguage.value,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
supportedLocales: const [
Locale('en'), // English
Locale('es'), // Spanish
Locale('fr'), // French
],
home: const MyHomePage(),
);
},
);
}
}
19 changes: 19 additions & 0 deletions lib/presentation/bloc/language_bloc/language_bloc.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import '../../../data/model/language_model.dart';
part 'language_event.dart';
part 'language_state.dart';

const languagePrefsKey = 'languagePrefs';

class LanguageBloc extends Bloc<LanguageEvent, LanguageState> {
LanguageBloc() : super(const LanguageState()) {
on<ChangeLanguage>(onChangeLanguage);
}
Future<void> onChangeLanguage(
ChangeLanguage event,
Emitter<LanguageState> emit,
) async {
emit(state.copyWith(selectedLanguage: event.selectedLanguage));
}
}
19 changes: 19 additions & 0 deletions lib/presentation/bloc/language_bloc/language_event.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
part of 'language_bloc.dart';

abstract class LanguageEvent extends Equatable {
const LanguageEvent();

@override
List<Object> get props => [];
}

class ChangeLanguage extends LanguageEvent {

const ChangeLanguage({
required this.selectedLanguage,
});
final Language selectedLanguage;

@override
List<Object> get props => [selectedLanguage];
}
25 changes: 25 additions & 0 deletions lib/presentation/bloc/language_bloc/language_state.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
part of 'language_bloc.dart';

class LanguageState extends Equatable {
const LanguageState({
this.selectedLanguage = Language.english, // Default to English
});

final Language selectedLanguage;

@override
List<Object> get props => [selectedLanguage];

LanguageState copyWith({Language? selectedLanguage}) {
return LanguageState(
selectedLanguage: selectedLanguage ?? this.selectedLanguage,
);
}
}

class LanguageInitial extends LanguageState {
const LanguageInitial()
: super(
selectedLanguage: Language.english,
); // Explicitly set default language to English
}
50 changes: 50 additions & 0 deletions lib/presentation/homescreen/home_page.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import '../widget/language_widget.dart';

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;

void _incrementCounter() {
setState(() {
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(AppLocalizations.of(context)?.title ?? ''),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
AppLocalizations.of(context)?.subtitle ?? '',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 20),
const LanguageSelector(), // Add the language selector here
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
44 changes: 44 additions & 0 deletions lib/presentation/widget/language_widget.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../data/model/language_model.dart';
import '../bloc/language_bloc/language_bloc.dart';

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

@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
context.read<LanguageBloc>().add(
ChangeLanguage(selectedLanguage: Language.english),
);
},
child: const Text('English'),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: () {
context.read<LanguageBloc>().add(
ChangeLanguage(selectedLanguage: Language.spanish),
);
},
child: const Text('Español'),
),
const SizedBox(width: 8),
ElevatedButton(
onPressed: () {
context.read<LanguageBloc>().add(
ChangeLanguage(selectedLanguage: Language.french),
);
},
child: const Text('Français'),
),
],
);
}
}
Loading

0 comments on commit fafb2f8

Please sign in to comment.