如何根据电话中选定的国家设置国家代码选择器(默认值)
Widget build(BuildContext context) => new Scaffold(
body: Center(
child: CountryCodePicker(
onChanged: print,
// Initial selection and favorite can be one of code ('IT') OR dial_code('+39')
initialSelection: 'IT',
favorite: ['+39','FR'],
// optional. Shows only country name and flag
showCountryOnly: false,
// optional. Shows only country name and flag when popup is closed.
showOnlyCountryWhenClosed: false,
// optional. aligns the flag and the Text left
alignLeft: false,
),
),
);
发布于 2022-02-23 22:50:16
看起来您使用的是包country_code_picker。
您可以从window.locale
获得一些关于用户默认语言首选项的有用信息,在这里,您可以使用countryCode
和languagueCode
等属性来设置默认语言。尽管如此,这并不确定这是用户首选的语言,但仍然是一个指标。
此包似乎在包中公开的名为List<Map<String,String>>
的codes
中列出了受支持的国家。因此,为了安全起见,应该根据这个列表检查来自window.locale.countryCode
的数据。
示例:
import 'dart:ui';
import 'package:country_code_picker/country_code_picker.dart';
import 'package:country_code_picker/country_codes.dart';
import 'package:flutter/material.dart';
import 'package:collection/collection.dart';
class CountryPickerWithLocale extends StatefulWidget {
const CountryPickerWithLocale({Key? key, required this.onCountryChanged})
: super(key: key);
final Function(CountryCode) onCountryChanged;
@override
State<CountryPickerWithLocale> createState() =>
_CountryPickerWithLocaleState();
}
class _CountryPickerWithLocaleState extends State<CountryPickerWithLocale> {
late String userCountryCode;
String fallbackCountryCode = "UK";
@override
void initState() {
super.initState();
// Get the language set as default on the users phone
String? systemCountryCode = window.locale.countryCode;
// The package you are using has supported countries defined inside a
// "codes" map.
Map<String,String>? supportedLanguage = codes.firstWhereOrNull((element) {
return element["code"] == systemCountryCode;
});
// Use a fallback if the language is unsupported in the package, or if
// there are some issues with retrieving the country code from the locale.
userCountryCode = supportedLanguage?["code"] ?? fallbackCountryCode;
}
@override
Widget build(BuildContext context) {
return Center(
child: CountryCodePicker(
onChanged: widget.onCountryChanged,
initialSelection: userCountryCode,
showCountryOnly: false,
showOnlyCountryWhenClosed: false,
alignLeft: false,
),
);
}
}
class CountryPickerScreen extends StatelessWidget {
const CountryPickerScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: CountryPickerWithLocale(
onCountryChanged: (code) {
print(code.code);
},
),
),
);
}
}
// Some code to run the above example.
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(home: CountryPickerScreen());
}
}
void main() => runApp(const App());
https://stackoverflow.com/questions/71242134
复制相似问题