使用flutter画一个类似于表格的图形化界面,点击哪一个方格改变方格为动态颜色边框和动态颜色和动态数据显示
时间: 2023-12-14 07:37:35 浏览: 155
以下是一个简单的示例,演示如何使用Flutter绘制类似表格的图形化界面,并在点击单元格时更改其外观和显示数据。
```dart
import 'package:flutter/material.dart';
class GridCell {
String text;
Color borderColor;
Color backgroundColor;
GridCell({this.text = "", this.borderColor = Colors.black, this.backgroundColor = Colors.white});
}
class GridViewExample extends StatefulWidget {
@override
_GridViewExampleState createState() => _GridViewExampleState();
}
class _GridViewExampleState extends State<GridViewExample> {
List<List<GridCell>> _gridData = List.generate(
5,
(i) => List.generate(5, (j) => GridCell(text: "${i + j}")),
);
GridCell _selectedCell;
void _setSelectedCell(int row, int col) {
setState(() {
if (_selectedCell != null) {
_selectedCell.borderColor = Colors.black;
_selectedCell.backgroundColor = Colors.white;
}
_selectedCell = _gridData[row][col];
_selectedCell.borderColor = Colors.blue;
_selectedCell.backgroundColor = Colors.lightBlue;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Grid View Example"),
),
body: Column(
children: [
Expanded(
child: GridView.builder(
itemCount: _gridData.length * _gridData[0].length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: _gridData[0].length,
childAspectRatio: 1,
),
itemBuilder: (context, index) {
int row = index ~/ _gridData[0].length;
int col = index % _gridData[0].length;
return GestureDetector(
onTap: () => _setSelectedCell(row, col),
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: _gridData[row][col].borderColor,
width: 2,
),
color: _gridData[row][col].backgroundColor,
),
child: Center(
child: Text(_gridData[row][col].text),
),
),
);
},
),
),
Container(
padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
child: Text(
"Selected cell: ${_selectedCell != null ? _selectedCell.text : ""}",
style: TextStyle(fontSize: 18),
),
),
],
),
);
}
}
```
在这个示例中,我们首先定义了一个`GridCell`类,它表示格子的数据和外观。然后创建了一个包含这些`GridCell`对象的二维数组`_gridData`。
在`_GridViewExampleState`类中,我们定义了一个`_selectedCell`变量,它表示当前选中的单元格。当用户点击任何单元格时,我们将调用`_setSelectedCell`方法,它会更新`_selectedCell`变量,并更改选定单元格的边框和背景颜色。
最后,在`build`方法中,我们使用`GridView.builder`构建了一个网格视图,它从`_gridData`数组中生成单元格,并为每个单元格添加`GestureDetector`以捕获用户的点击事件。我们还在屏幕底部显示了当前选定单元格的文本。
阅读全文