我正在尝试使用两个下拉菜单项(西班牙语和英语)实现一个 DropdownButton。
我希望用户选择一种语言并将其发送回 getx 翻译以更改应用程序的语言。
这是我的控制器:
import 'package:get/get.dart';
class DropdownController extends GetxController {
String selectedValue;
var language = <String>['English', 'Espanol'];
void onSelected(String value) {
selectedValue = value;
}
}
这是我的设置页面
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetBuilder<DropdownController>(builder: (controller) {
return Scaffold(
body: Column(children: [
Text('Select Language: '),
SizedBox(height: 10.0),
DropdownButton<String>(
hint: Text('Language'),
value: controller.selectedValue,
onChanged: (newValue) {
controller.onSelected(newValue);
},
elevation: 10,
items: [
DropdownMenuItem(
child: Text("English"),
value: controller.selectedValue,
),
DropdownMenuItem(
child: Text("ESpanol"),
value: controller.selectedValue,
),
]),
]),
);
});
}
}
答案 0 :(得分:1)
控制器:
class DropdownController extends GetxController {
String? selectedValue;
var language = <String>['English', 'Espanol'];
void onSelected(String value) {
selectedValue = value;
update();
print(selectedValue);
changeLanguage(selectedValue);
}
changeLanguage(String? selectedLanguage) {
switch (selectedLanguage) {
case 'English':
Get.updateLocale(Locale('en_US'));
print('Changed to En');
break;
case 'Espanol':
Get.updateLocale(Locale('en_US'));
print('Changed to Es');
break;
default:
Get.updateLocale(Locale('en_US'));
print('Fallback to En');
break;
}
}
}
设置页面:
class SettingsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetBuilder<DropdownController>(builder: (controller) {
return Scaffold(
body: Column(children: [
Text('Select Language: '),
SizedBox(height: 10.0),
DropdownButton<String>(
hint: Text('Language'),
value: controller.selectedValue,
onChanged: (newValue) {
controller.onSelected(newValue!);
},
elevation: 10,
items: [
DropdownMenuItem(
child: Text("English"),
value: 'English',
),
DropdownMenuItem(
child: Text("ESpanol"),
value: 'Espanol',
),
]),
]),
);
});
}
}