16.4 洲省选择器

16.4 洲省选择器

img

实现步骤:


第 1 步:控制器

lib/pages/my/my_address/controller.dart

1
2
3
4
// 洲省数据
List<KeyValueModel> statesList = [];
// 洲省市选择
List<int> statesSels = [];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 取洲省数据
void _filterStates(String countryCode) {
for (var i = 0; i < continents.length; i++) {
var continent = continents[i];
var country =
continent.countries!.firstWhereOrNull((el) => el.code == countryCode);
if (country != null) {
statesList = List.generate(country.states?.length ?? 0, (index) {
var state = country.states?.elementAt(index);
return KeyValueModel<String>(
key: state?.code ?? "-",
value: state?.name ?? "-",
);
});
break;
}
}
}
1
2
3
4
5
6
7
8
9
// 初始化
Future<void> _initData() async {

// 洲省代码
String statesCode = statesController.text;
// 洲选择器数据
_filterStates(countryCode);
// 洲省选择器 - 选中 index
statesSels = [statesList.indexWhere((el) => el.key == statesCode)];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 洲省市选择
void onStatesPicker() async {
ActionBottomSheet.data(
title: 'States',
context: Get.context!,
// 数据
adapter: PickerDataAdapter<KeyValueModel>(
pickerdata: statesList,
),
// 默认选中 [index]
selecteds: statesSels,
// 确认回调
onConfirm: (value) {
if (value.isEmpty) return;
statesController.text = '${value[0].key}';
},
);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 国家选择
void onCountryPicker() async {
ActionBottomSheet.data(
...
// 确认回调
onConfirm: (value) {
if (value.isEmpty) return;
if (value.length == 2) {
countryController.text = '${value[1].key}';
_filterStates(value[1].key); // 刷新洲数据
}
},
);
}

第 2 步:视图

lib/pages/my/my_address/view.dart

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 表单
Widget _buildForm() {
return Form(
key: controller.formKey, //设置globalKey,用于后面获取FormState
autovalidateMode: AutovalidateMode.onUserInteraction,
child: <Widget>[

// State
TextFormWidget(
onTap: controller.onStatesPicker,
readOnly: true,
isMustBeEnter: true,
controller: controller.statesController,
labelText: LocaleKeys.addressState.tr,
validator: Validatorless.multiple([
Validatorless.required("The field is obligatory"),
]),
),

...

提交代码到 git