flutter 实现表单的封装包含下拉框和输入框

一、表单封装组件实现效果

c 复制代码
//表单组件
Widget buildFormWidget(List<InputModel> formList,
    {required GlobalKey<FormState> formKey}) {
  return Form(
      key: formKey,
      child: Column(
        children: formList.map((item) {
          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  item.isRequired
                      ? Icon(Icons.star,
                          size: 10,
                          color: Theme.of(Get.context!).colorScheme.error)
                      : SizedBox(),
                  Text(
                    item.label,
                    style:
                        Theme.of(Get.context!).inputDecorationTheme.labelStyle,
                  )
                ],
              ),
              SizedBox(
                height: 16,
              ),
              GestureDetector(
                onTap: item.type == 'select'
                    ? () {
                        showBottomSheet(item.bottomSheetList!, item.label,
                            selectProp: item.selectProp,
                            selectController: item.selectController,
                            controller: item.controller);
                      }
                    : null,
                child: TextFormField(
                  controller: item.controller,
                  enabled: item.type == 'text',
                  keyboardType: item.keyboardType,
                  validator: (value) {
                    // 添加表单验证
                    if (item.isRequired && (value == null || value.isEmpty)) {
                      return '请${item.type == 'select' ? '选择' : '输入'}${item.label}';
                    }
                    //正则表达式验证
                    if (item.pattern.isEmpty &&
                        (value == null || value.isEmpty)) {
                      RegExp regex = RegExp(item.pattern);
                      if (!regex.hasMatch(value!)) {
                        return '请输入正确的${item.label}';
                      }
                    }
                    return null;
                  },
                  decoration: InputDecoration(
                    suffixIcon: item.type == 'select'
                        ? Icon(Icons.arrow_forward_ios,
                            color: Color(0x6615171E))
                        : null,
                    focusedBorder: Theme.of(Get.context!)
                        .inputDecorationTheme
                        .focusedBorder,
                    disabledBorder: Theme.of(Get.context!)
                        .inputDecorationTheme
                        .disabledBorder,
                    enabledBorder: Theme.of(Get.context!)
                        .inputDecorationTheme
                        .enabledBorder,
                    errorBorder:
                        Theme.of(Get.context!).inputDecorationTheme.errorBorder,
                    errorStyle:
                        Theme.of(Get.context!).inputDecorationTheme.errorStyle,
                    hintText:
                        '请${item.type == 'select' ? '选择' : '输入'}${item.label}',
                    isDense: true,
                    filled: true,
                    fillColor:
                        Theme.of(Get.context!).inputDecorationTheme.fillColor,
                  ),
                ),
              ),
              SizedBox(
                height: 16,
              ),
            ],
          );
        }).toList(),
      ));
}


//bottomSheet
void showBottomSheet(List<Map<String, dynamic>> list, String title,
    {Map? selectProp,
    RxMap<String, dynamic>? selectController,
    TextEditingController? controller}) {
  showGenderPanel(
      title,
      buildCheckList(list, (item) {
        controller?.text = item[selectProp?['label']];
        Get.back();
      }, props: selectProp, selected: selectController));
}


// 底部弹出层
void showGenderPanel(String title, Widget sheetContent) {
  showModalBottomSheet(
      context: Get.context!,
      builder: (context) {
        return Container(
            height: 800,
            child: Column(
              children: [
                Container(
                    // height: 100,
                    padding: Theme.of(Get.context!).dialogTheme.actionsPadding,
                    child: Stack(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              title,
                              overflow: TextOverflow.ellipsis, // 显示省略号
                              style: Theme.of(Get.context!)
                                  .dialogTheme
                                  .titleTextStyle,
                            ),
                          ],
                        ),
                        Positioned(
                          right: 20,
                          // top: 14,
                          child: GestureDetector(
                            onTap: () {
                              Navigator.pop(context);
                            },
                            child: Icon(Icons.cancel_outlined,
                                color: Theme.of(Get.context!)
                                    .dialogTheme
                                    .iconColor),
                          ),
                        ),
                      ],
                    )),
                Divider(
                  height: 1,
                  // color: Theme.of(Get.context!).dividerColor,
                ),
                Container(
                  // padding: EdgeInsets.all(16),
                  child: sheetContent,
                )
              ],
            ));
      });
}


//单选列表
Widget buildCheckList(List<Map<String, dynamic>> list, Function? onChanged,
    {Map? props, RxMap<String, dynamic>? selected}) {
  props ??= {'label': 'label', 'value': 'value'};
  String label = props['label'] ?? 'label';
  String value = props['value'] ?? 'value';
  return Obx(() => Container(
      width: Get.width,
      child: Column(
        children: list.asMap().entries.map((entry) {
          int index = entry.key;
          dynamic item = entry.value;
          print('渲染');
          return Column(
            children: [
              GestureDetector(
                  onTap: () {
                    selected?.value = item;
                    if (onChanged != null) {
                      onChanged(item);
                    }
                  },
                  child: Container(
                    width: Get.width,
                    decoration: BoxDecoration(
                      color: Colors.blue.withOpacity(0),
                    ),
                    padding: const EdgeInsets.symmetric(
                        vertical: 16, horizontal: 16),
                    child: Row(
                      children: [
                        Icon(
                            (selected?.value[value] ?? '') == item[value]
                                ? Icons.check_circle
                                : Icons.circle_outlined,
                            size: 22,
                            color: (selected?.value[value] ?? '') == item[value]
                                ? Color.fromRGBO(50, 73, 223, 1)
                                : Color.fromRGBO(21, 23, 30, 0.40)),
                        SizedBox(width: 6),
                        Text(
                          item[label],
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                      ],
                    ),
                  )),
              Divider(
                height: 1,
                color: index + 1 == list.length
                    ? Color.fromRGBO(128, 130, 145, 0)
                    : Color.fromRGBO(128, 130, 145, 0.20),
              ),
            ],
          );
        }).toList(),
      )));
}

二、调用方法:

c 复制代码
 buildFormWidget(formList, formKey: formKey),

三、数据格式:

c 复制代码
  Map<String, dynamic> controllers = {
    'phone': TextEditingController(text: '仓库1'),
    'phoneSelect': <String, dynamic>{'id': '18', 'name': '仓库1'}.obs,
    'code': TextEditingController(text: '123'),
  };
  
 formList = [
      InputModel(
          label: '入库仓库',
          isRequired: true,
          type: 'select',
          controller: controllers['phone'],
          selectController: controllers['phoneSelect'],
          bottomSheetList: bottomSheetList,
          selectProp: {'label': 'name', 'value': 'id'}),
      InputModel(
          label: '入库数量',
          isRequired: true,
          keyboardType: TextInputType.number,
          controller: controllers['code']),
    ];
相关推荐
m0_7482478016 小时前
Flutter Intl包使用指南:实现国际化和本地化
前端·javascript·flutter
迷雾漫步者17 小时前
Flutter组件————PageView
flutter·跨平台·dart
迷雾漫步者1 天前
Flutter组件————FloatingActionButton
前端·flutter·dart
coder_pig1 天前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
捡芝麻丢西瓜1 天前
flutter自学笔记5- dart 编码规范
flutter·dart
恋猫de小郭1 天前
什么?Flutter 可能会被 SwiftUI/ArkUI 化?全新的 Flutter Roadmap
flutter·ios·swiftui
sunly_2 天前
Flutter:导航,tab切换,顶部固定,列表分页滚动
开发语言·javascript·flutter
敲代码的小强2 天前
Flutter项目兼容鸿蒙Next系统
flutter·华为·harmonyos
Zh-jie3 天前
flutter 快速实现侧边栏
前端·javascript·flutter
truemi.733 天前
flutter --no-color pub get 超时解决方法
android·flutter