1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
| import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
// ── Gestor de locale ───────────────────────────────────────────────────────────
class LocaleNotifier extends ChangeNotifier {
static const _prefKey = 'app_locale';
static const _supportedLocales = [Locale('es'), Locale('en')];
Locale _locale = const Locale('es'); // valor por defecto
Locale get locale => _locale;
List<Locale> get supportedLocales => _supportedLocales;
/// Carga el locale guardado desde SharedPreferences
Future<void> load() async {
final prefs = await SharedPreferences.getInstance();
final code = prefs.getString(_prefKey);
if (code != null) {
final saved = _supportedLocales.firstWhere(
(l) => l.languageCode == code,
orElse: () => const Locale('es'),
);
_locale = saved;
notifyListeners();
}
}
/// Cambia el locale activo y lo persiste
Future<void> setLocale(Locale locale) async {
if (locale == _locale) return;
_locale = locale;
notifyListeners();
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_prefKey, locale.languageCode);
}
}
// ── Entrada de la app ──────────────────────────────────────────────────────────
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final localeNotifier = LocaleNotifier();
await localeNotifier.load(); // cargar preferencia antes de renderizar
runApp(
ChangeNotifierProvider.value(
value: localeNotifier,
child: const MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
// Escuchar cambios de locale
final localeNotifier = context.watch<LocaleNotifier>();
return MaterialApp(
title: 'Flutter i18n Runtime',
locale: localeNotifier.locale,
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: localeNotifier.supportedLocales,
home: const HomeScreen(),
);
}
}
// ── Pantalla principal ─────────────────────────────────────────────────────────
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final localeNotifier = context.watch<LocaleNotifier>();
final currentLocale = localeNotifier.locale;
return Scaffold(
appBar: AppBar(
title: Text(l10n.appTitle),
actions: [
// Selector de idioma en la barra de navegación
_LanguageButton(current: currentLocale),
],
),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ── Bienvenida ───────────────────────────────────────────────
Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(l10n.welcomeMessage,
style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
Text(l10n.greeting('Flutter'),
style: Theme.of(context).textTheme.bodyLarge),
const SizedBox(height: 4),
Text(l10n.currentDate(DateTime.now()),
style: const TextStyle(color: Colors.grey)),
],
),
),
),
const SizedBox(height: 24),
// ── Selector de idioma expandido ──────────────────────────────
Text(l10n.languageLabel,
style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 8),
...localeNotifier.supportedLocales.map((locale) {
final isSelected = locale == currentLocale;
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: ListTile(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(
color: isSelected
? Theme.of(context).colorScheme.primary
: Colors.grey.shade300,
width: isSelected ? 2 : 1,
),
),
leading: Text(
_localeFlag(locale),
style: const TextStyle(fontSize: 28),
),
title: Text(_localeName(locale)),
subtitle: Text(locale.toLanguageTag()),
trailing: isSelected
? Icon(Icons.check_circle,
color: Theme.of(context).colorScheme.primary)
: null,
onTap: () => localeNotifier.setLocale(locale),
),
);
}),
const Spacer(),
// ── Locale actual ────────────────────────────────────────────
_ActiveLocaleCard(locale: currentLocale),
],
),
),
);
}
String _localeFlag(Locale l) => switch (l.languageCode) {
'es' => '🇪🇸',
'en' => '🇬🇧',
_ => '🌐',
};
String _localeName(Locale l) => switch (l.languageCode) {
'es' => 'Español',
'en' => 'English',
_ => l.toLanguageTag(),
};
}
// ── Botón de idioma compacto para la AppBar ────────────────────────────────────
class _LanguageButton extends StatelessWidget {
final Locale current;
const _LanguageButton({required this.current});
@override
Widget build(BuildContext context) {
final localeNotifier = context.read<LocaleNotifier>();
return PopupMenuButton<Locale>(
icon: Text(
_flag(current),
style: const TextStyle(fontSize: 20),
),
tooltip: 'Cambiar idioma',
onSelected: (locale) => localeNotifier.setLocale(locale),
itemBuilder: (context) => localeNotifier.supportedLocales
.map(
(l) => PopupMenuItem(
value: l,
child: Row(
children: [
Text(_flag(l), style: const TextStyle(fontSize: 20)),
const SizedBox(width: 8),
Text(_name(l)),
if (l == current) ...[
const Spacer(),
const Icon(Icons.check, size: 16),
],
],
),
),
)
.toList(),
);
}
String _flag(Locale l) => switch (l.languageCode) {
'es' => '🇪🇸',
'en' => '🇬🇧',
_ => '🌐',
};
String _name(Locale l) => switch (l.languageCode) {
'es' => 'Español',
'en' => 'English',
_ => l.toLanguageTag(),
};
}
// ── Tarjeta de locale activo ───────────────────────────────────────────────────
class _ActiveLocaleCard extends StatelessWidget {
final Locale locale;
const _ActiveLocaleCard({required this.locale});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.green.shade50,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.green.shade200),
),
child: Row(
children: [
const Icon(Icons.check_circle, color: Colors.green),
const SizedBox(width: 8),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Locale activo: ${locale.toLanguageTag()}',
style: const TextStyle(fontWeight: FontWeight.bold)),
const Text(
'Guardado en SharedPreferences — sobrevive al reinicio',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
],
),
],
),
);
}
}
|