Flutter中是否有类似HTML <fieldset>的组件用于分组Widget?
Flutter 实现类似 HTML
你可以通过自定义Widget来实现和HTML <fieldset> 一致的效果,核心思路是用带边框的Container配合Stack把标题悬浮在边框上方,用背景色覆盖边框的一部分,模拟<legend>标签的效果。以下是完整的实现方案:
自定义FieldSet组件
import 'package:flutter/material.dart'; class FieldSet extends StatelessWidget { final String title; final Widget child; final EdgeInsets padding; final Color borderColor; final double borderWidth; final TextStyle titleStyle; final double borderRadius; const FieldSet({ super.key, required this.title, required this.child, this.padding = const EdgeInsets.all(16.0), this.borderColor = Colors.grey, this.borderWidth = 1.0, this.titleStyle = const TextStyle(fontSize: 16, fontWeight: FontWeight.w500), this.borderRadius = 4.0, }); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(vertical: 12.0), padding: padding, decoration: BoxDecoration( border: Border.all(color: borderColor, width: borderWidth), borderRadius: BorderRadius.circular(borderRadius), ), child: Stack( clipBehavior: Clip.none, children: [ // 悬浮的标题 Positioned( top: -12, left: 16, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8.0), color: Theme.of(context).scaffoldBackgroundColor, child: Text(title, style: titleStyle), ), ), // 表单内容 child, ], ), ); } }
在表单中使用
Form( child: Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ FieldSet( title: "个人信息", child: Column( children: [ TextFormField( decoration: const InputDecoration(labelText: "姓名"), ), const SizedBox(height: 12), TextFormField( decoration: const InputDecoration(labelText: "手机号"), ), ], ), ), FieldSet( title: "地址信息", borderColor: Colors.blue, titleStyle: const TextStyle(color: Colors.blue, fontSize: 17), child: Column( children: [ TextFormField( decoration: const InputDecoration(labelText: "省份"), ), const SizedBox(height: 12), TextFormField( decoration: const InputDecoration(labelText: "详细地址"), ), ], ), ), ], ), ), )
自定义调整说明
- 修改
borderColor、borderWidth可以调整边框样式 - 通过
titleStyle自定义标题的字体、颜色、大小 - 调整
borderRadius可以设置圆角边框 - 修改
Positioned的top和left参数,能调整标题的悬浮位置
内容的提问来源于stack exchange,提问作者Abhishek Thankachan
相关产品推荐
相关产品推荐

