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

本文介绍了如何在Flutter中创建可复用的表单封装组件,包含输入验证、下拉选择功能,并通过实例展示了如何调用组件并处理数据格式。
摘要由CSDN通过智能技术生成

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

在这里插入图片描述

//表单组件
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(),
      )));
}


二、调用方法:

 buildFormWidget(formList, formKey: formKey),

三、数据格式:


  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']),
    ];
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以通过 `GridView` 和 `Card` 实现一个两行两列输入框的组件,每个输入框都带有标题。以下是实现的代码示例: ``` import 'package:flutter/material.dart'; class TwoByTwoInput extends StatelessWidget { final List<String> titles; final List<TextEditingController> controllers; TwoByTwoInput({required this.titles, required this.controllers}); @override Widget build(BuildContext context) { return GridView.count( crossAxisCount: 2, children: List.generate(4, (index) { return Card( child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( titles[index], style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox(height: 8), TextField( controller: controllers[index], decoration: InputDecoration( hintText: 'Enter ${titles[index]}', border: OutlineInputBorder(), ), ), ], ), ), ); }), ); } } ``` 在使用时,需要提供两个参数:`titles` 和 `controllers`。`titles` 是一个包含四个字符串的列表,分别对应四个输入框的标题;`controllers` 是一个包含四个 `TextEditingController` 对象的列表,分别对应四个输入框的文本控制器。 示例用法: ``` class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { final List<String> titles = ['Title 1', 'Title 2', 'Title 3', 'Title 4']; final List<TextEditingController> controllers = [ TextEditingController(), TextEditingController(), TextEditingController(), TextEditingController(), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Two by Two Input'), ), body: Center( child: TwoByTwoInput(titles: titles, controllers: controllers), ), ); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值