flutter_application_1/lib/widgets/language_switcher_widget.dart

105 lines
3.3 KiB
Dart
Raw Normal View History

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class LanguageSwitcher extends StatefulWidget {
final Locale currentLocale;
final Function(Locale) onLocaleChanged;
const LanguageSwitcher({
super.key,
required this.currentLocale,
required this.onLocaleChanged,
});
@override
LanguageSwitcherState createState() => LanguageSwitcherState();
}
class LanguageSwitcherState extends State<LanguageSwitcher> {
late Locale _selectedLocale;
@override
void initState() {
super.initState();
_selectedLocale = widget.currentLocale;
}
@override
Widget build(BuildContext context) {
final localizations = AppLocalizations.of(context)!;
final isMobile = Theme.of(context).platform == TargetPlatform.iOS || Theme.of(context).platform == TargetPlatform.android;
return Theme(
data: ThemeData.light().copyWith(
popupMenuTheme: PopupMenuThemeData(
color: CupertinoColors.extraLightBackgroundGray,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
textStyle: const TextStyle(color: CupertinoColors.black),
),
tooltipTheme: TooltipThemeData(
decoration: BoxDecoration(
color: CupertinoColors.black,
borderRadius: BorderRadius.circular(4.0),
),
textStyle: const TextStyle(color: CupertinoColors.white),
),
),
child: Container(
decoration: BoxDecoration(
color: CupertinoColors.extraLightBackgroundGray,
borderRadius: BorderRadius.circular(100.0),
boxShadow: const [
BoxShadow(
color: Colors.black26,
blurRadius: 8.0,
offset: Offset(0, 4),
),
],
),
child: PopupMenuButton<Locale>(
key: const Key('languagePopupMenu'),
offset: Offset(0.0, isMobile ? 55 : 45),
onSelected: (Locale locale) {
setState(() {
_selectedLocale = locale;
});
widget.onLocaleChanged(locale);
},
tooltip: localizations.choose_language,
icon: const Icon(
CupertinoIcons.globe,
color: CupertinoColors.black,
),
itemBuilder: (BuildContext context) {
return [
PopupMenuItem<Locale>(
value: const Locale('en'),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(AppLocalizations.of(context)!.language_english),
if (_selectedLocale.languageCode == 'en') const Icon(CupertinoIcons.checkmark_alt, size: 20),
],
),
),
PopupMenuItem<Locale>(
value: const Locale('de'),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(AppLocalizations.of(context)!.language_german),
if (_selectedLocale.languageCode == 'de') const Icon(CupertinoIcons.checkmark_alt, size: 20),
],
),
),
];
},
),
),
);
}
}