Flutter语言选择插件language_picker的使用
Flutter语言选择插件language_picker的使用
language_picker 插件简介
language_picker
提供了一个下拉菜单和对话框,用于选择语言。此插件最初由 @gomgom 在 language_pickers 中创建。由于原项目超过一年没有活动且无法编译,因此进行了重新发布,并改进了API和修复了一些问题。
使用指南
查找语言
- 通过名称查找:
Languages.korean
- 通过ISO代码查找:
Language.fromIsoCode('fr')
- 预设语言:
Languages.defaultLanguages
最小化示例
LanguagePickerDropdown(
onValuePicked: (Language language) {
print(language.name);
})
预选值
LanguagePickerDropdown(
initialValue: Languages.korean,
onValuePicked: (Language language) {
print(language.name);
})
自定义渲染
如果你不想显示ISO代码:
LanguagePickerDropdown(
itemBuilder: languageBuilder,
onValuePicked: (Language language) {
print(language.name);
})
...
// 只渲染名称。
final languageBuilder = (language) => Text(language.name);
你也可以使用 language.nativeName
。
自定义语言列表
LanguagePickerDropdown(
languages: supportedLanguages,
onValuePicked: (Language language) {
print(language.name);
})
...
final supportedLanguages = [
Languages.english,
Languages.french,
Languages.japanese,
Languages.korean,
];
程序化更改选定语言
// 预选语言是法语。
final controller = LanguagePickerDropdownController(Languages.french);
final picker = LanguagePickerDropdown(
controller: controller,
languages: [Languages.english, Languages.french, Languages.norwegian],
);
// 在其他方法中:强制切换到挪威语。
controller.value = Languages.norwegian;
LanguagePickerDropdown 示例
import 'package:language_picker/language.dart';
import 'package:language_picker/language_picker.dart';
Language _selectedDropdownLanguage = Languages.korean;
// 下拉菜单项构建函数。
Widget _buildDropdownItem(Language language) {
return Row(
children: <Widget>[
SizedBox(
width: 8.0,
),
Text("${language.name} (${language.isoCode})"),
],
);
}
// 构建下拉菜单
LanguagePickerDropdown(
initialValue: Languages.korean,
itemBuilder: _buildDropdownItem,
onValuePicked: (Language language) {
_selectedDropdownLanguage = language;
print(_selectedDropdownLanguage.name);
print(_selectedDropdownLanguage.isoCode);
},
),
LanguagePickerDialog 示例
import 'package:language_picker/language.dart';
import 'package:language_picker/language_picker.dart';
Language _selectedDialogLanguage = Languages.korean;
// 对话框项构建函数。
Widget _buildDialogItem(Language language) => Row(
children: <Widget>[
Text(language.name),
SizedBox(width: 8.0),
Flexible(child: Text("(${language.isoCode})"))
],
);
void _openLanguagePickerDialog() => showDialog(
context: context,
builder: (context) => Theme(
data: Theme.of(context).copyWith(primaryColor: Colors.pink),
child: LanguagePickerDialog(
titlePadding: EdgeInsets.all(8.0),
searchCursorColor: Colors.pinkAccent,
searchInputDecoration: InputDecoration(hintText: 'Search...'),
isSearchable: true,
title: Text('Select your language'),
onValuePicked: (Language language) => setState(() {
_selectedDialogLanguage = language;
print(_selectedDialogLanguage.name);
print(_selectedDialogLanguage.isoCode);
}),
itemBuilder: _buildDialogItem)),
);
LanguagePickerCupertino 示例
import 'package:language_picker/language.dart';
import 'package:language_picker/language_picker.dart';
Language _selectedCupertinoLanguage = Languages.korean;
// Cupertino 式选择器打开函数。
void _openCupertinoLanguagePicker() => showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return LanguagePickerCupertino(
pickerSheetHeight: 200.0,
onValuePicked: (Language language) => setState(() {
_selectedCupertinoLanguage = language;
print(_selectedCupertinoLanguage.name);
print(_selectedCupertinoLanguage.isoCode);
}),
);
});
Widget _buildCupertinoItem(Language language) => Row(
children: <Widget>[
Text("+${language.name}"),
SizedBox(width: 8.0),
Flexible(child: Text(language.name))
],
);
完整示例代码
以下是一个完整的示例代码,展示了如何在Flutter应用中使用language_picker
插件:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:language_picker/languages.dart';
import 'package:language_picker/language_picker.dart';
void main() => runApp(const MyApp(key: Key('app')));
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'language_picker Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'language_picker Example'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Language _selectedDropdownLanguage = Languages.korean;
Language _selectedDialogLanguage = Languages.korean;
Language _selectedCupertinoLanguage = Languages.korean;
// 下拉菜单项构建函数。
Widget _buildDropdownItem(Language language) {
return Row(
children: <Widget>[
const SizedBox(
width: 8.0,
),
Text("${language.name} (${language.isoCode})"),
],
);
}
// 对话框项构建函数。
Widget _buildDialogItem(Language language) => Row(
children: <Widget>[
Text(language.name),
const SizedBox(width: 8.0),
Flexible(child: Text("(${language.isoCode})"))
],
);
void _openLanguagePickerDialog() => showDialog(
context: context,
builder: (context) => Theme(
data: Theme.of(context).copyWith(primaryColor: Colors.pink),
child: LanguagePickerDialog(
titlePadding: const EdgeInsets.all(8.0),
searchCursorColor: Colors.pinkAccent,
searchInputDecoration:
const InputDecoration(hintText: 'Search...'),
isSearchable: true,
title: const Text('Select your language'),
onValuePicked: (Language language) => setState(() {
_selectedDialogLanguage = language;
print(_selectedDialogLanguage.name);
print(_selectedDialogLanguage.isoCode);
}),
itemBuilder: _buildDialogItem)),
);
// Cupertino 式选择器打开函数。
void _openCupertinoLanguagePicker() => showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return LanguagePickerCupertino(
pickerSheetHeight: 200.0,
onValuePicked: (Language language) => setState(() {
_selectedCupertinoLanguage = language;
print(_selectedCupertinoLanguage.name);
print(_selectedCupertinoLanguage.isoCode);
}),
);
});
Widget _buildCupertinoItem(Language language) => Row(
children: <Widget>[
Text("+${language.name}"),
const SizedBox(width: 8.0),
Flexible(child: Text(language.name))
],
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Center(
child: LanguagePickerDropdown(
initialValue: Languages.korean,
itemBuilder: _buildDropdownItem,
onValuePicked: (Language language) {
_selectedDropdownLanguage = language;
print(_selectedDropdownLanguage.name);
print(_selectedDropdownLanguage.isoCode);
},
),
),
),
Expanded(
child: Center(
child: MaterialButton(
onPressed: _openLanguagePickerDialog,
child: const Text("Push"),
),
),
),
Expanded(
child: Center(
child: ListTile(
title: _buildCupertinoItem(_selectedCupertinoLanguage),
onTap: _openCupertinoLanguagePicker,
),
),
),
]),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
这个示例代码展示了如何使用language_picker
插件中的LanguagePickerDropdown
、LanguagePickerDialog
和LanguagePickerCupertino
组件来实现语言选择功能。你可以根据需要调整样式和逻辑。
更多关于Flutter语言选择插件language_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter语言选择插件language_picker的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是如何在Flutter项目中使用language_picker
插件来实现语言选择的示例代码。
首先,确保你已经将language_picker
插件添加到了你的pubspec.yaml
文件中:
dependencies:
flutter:
sdk: flutter
language_picker: ^0.4.0 # 请检查最新版本号
然后,运行flutter pub get
来安装依赖。
接下来,让我们编写一些代码来展示如何使用language_picker
插件。
主应用程序代码(main.dart)
import 'package:flutter/material.dart';
import 'package:language_picker/language_picker.dart';
import 'dart:ui' as ui;
import 'package:flutter_localizations/flutter_localizations.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Language Picker Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
supportedLocales: LanguagePicker.delegate.supportedLocales,
locale: LanguagePicker.delegate.locale,
localizationsDelegates: [
LanguagePicker.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
localeResolutionCallback: (Locale locale, Iterable<Locale> supportedLocales) {
for (Locale supportedLocale in supportedLocales) {
if (supportedLocale.languageCode == locale.languageCode ||
supportedLocale.toString() == locale.toString()) {
return locale;
}
}
return supportedLocales.first;
},
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Locale currentLocale;
@override
void initState() {
super.initState();
currentLocale = Localizations.localeOf(context);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Language Picker Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Current Language: ${currentLocale?.languageCode ?? "Unknown"}',
style: TextStyle(fontSize: 24),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
Locale newLocale = await LanguagePicker.showDialog(context);
if (newLocale != null) {
setState(() {
currentLocale = newLocale;
// Optionally, you can persist this locale choice to a settings file or database
});
}
},
child: Text('Select Language'),
),
],
),
),
);
}
}
解释
-
依赖项:在
pubspec.yaml
文件中添加language_picker
插件。 -
MaterialApp配置:
supportedLocales
:从LanguagePicker.delegate
获取支持的语言列表。locale
:从LanguagePicker.delegate
获取当前语言。localizationsDelegates
:包含LanguagePicker.delegate
,以便插件可以处理本地化。localeResolutionCallback
:用于解析当前选择的语言。
-
主页面:
- 初始化时,从
Localizations.localeOf(context)
获取当前语言。 - 显示当前选择的语言。
- 提供一个按钮来调用
LanguagePicker.showDialog(context)
,让用户选择语言。选择后,更新currentLocale
状态。
- 初始化时,从
通过这种方式,你可以在你的Flutter应用中实现语言选择功能。确保你根据实际需要调整代码,并处理可能的异常情况。