Jisho-Study-Tool/lib/view/components/search/language_selector.dart

79 lines
1.9 KiB
Dart
Raw Normal View History

2021-03-02 22:26:59 +01:00
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
2021-03-02 22:26:59 +01:00
2021-12-01 23:09:53 +01:00
import '../../../models/themes/theme.dart';
2021-03-02 22:26:59 +01:00
class LanguageSelector extends StatefulWidget {
2021-12-01 23:09:53 +01:00
const LanguageSelector({Key? key}) : super(key: key);
2021-03-02 22:26:59 +01:00
@override
2021-12-01 23:09:53 +01:00
_LanguageSelectorState createState() => _LanguageSelectorState();
2021-03-02 22:26:59 +01:00
}
2021-03-03 00:24:25 +01:00
class _LanguageSelectorState extends State<LanguageSelector> {
2021-07-26 21:39:17 +02:00
late final SharedPreferences prefs;
late List<bool> isSelected;
2021-03-02 22:26:59 +01:00
@override
void initState() {
super.initState();
isSelected = [false, false, false];
2021-12-01 23:09:53 +01:00
SharedPreferences.getInstance().then((prefs) {
this.prefs = prefs;
setState(() {
isSelected = _getSelectedStatus() ?? isSelected;
});
2021-12-01 23:09:53 +01:00
});
}
2021-12-01 23:09:53 +01:00
void _updateSelectedStatus() {
prefs.setStringList(
'languageSelectorStatus',
isSelected.map((b) => b ? '1' : '0').toList(),
);
}
2021-07-26 21:39:17 +02:00
List<bool>? _getSelectedStatus() {
return prefs
2021-12-01 23:09:53 +01:00
.getStringList('languageSelectorStatus')
?.map((s) => s == '1')
.toList();
2021-03-02 22:26:59 +01:00
}
@override
Widget build(BuildContext context) {
return ToggleButtons(
2021-08-08 23:16:54 +02:00
selectedColor: AppTheme.jishoGreen.background,
2021-03-02 23:35:47 +01:00
isSelected: isSelected,
2021-12-01 23:09:53 +01:00
children: const <Widget>[
_LanguageOption('Auto'),
_LanguageOption('日本語'),
_LanguageOption('English')
2021-03-02 22:26:59 +01:00
],
2021-12-01 23:09:53 +01:00
onPressed: (buttonIndex) {
2021-03-02 23:35:47 +01:00
setState(() {
2021-12-01 23:09:53 +01:00
for (final int i in Iterable.generate(isSelected.length)) {
2021-03-02 23:35:47 +01:00
isSelected[i] = i == buttonIndex;
}
_updateSelectedStatus();
2021-03-02 23:35:47 +01:00
});
},
2021-03-02 22:26:59 +01:00
);
}
}
2021-03-03 00:24:25 +01:00
class _LanguageOption extends StatelessWidget {
final String language;
2021-03-02 22:26:59 +01:00
const _LanguageOption(this.language);
2021-03-02 22:26:59 +01:00
@override
Widget build(BuildContext context) {
return Container(
2021-12-01 23:09:53 +01:00
padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0),
child: Center(child: Text(language)),
2021-03-02 22:26:59 +01:00
);
}
2021-12-01 23:09:53 +01:00
}