flutter 实现一个 两行两列输入框的组件,每个输入框都带有标题
时间: 2024-02-23 10:00:52 浏览: 168
flutter开发之组件大全
好的,可以通过 `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),
),
);
}
}
```
阅读全文