mysql - Flutter:如何显示同一张表中的所有列
问题描述
我正在 Dart 中开发一个测试应用程序。该应用程序用于显示数据并将其插入到由 000webhost.com 托管的数据库中
我正在将我的 json 数据显示到我的应用程序的表格中。我希望所有列都在一张桌子内。使用我当前的代码,它显示了一个全新表中的每一列, 如下所示:
以下是我的项目的相关代码:
class ViewData extends StatelessWidget{
final String url = 'https://fourieristic-thousa.000webhostapp.com/index.code.php?action=view';
Future<List<dynamic>> fetchData() async {
var result = await http.get(
Uri.parse(url),
);
print(json.decode(result.body));
return json.decode(result.body);
}
// First entry of each column.
String _test(dynamic test, int index){
return test[index]['testColumn'];
}
// Second entry of each column.
int _test2(dynamic test, int index){
return json.decode(test[index]['testColumn2']);
}
// Third entry of each column (Will some day be a delete function)
int _id(dynamic test, int index){
return json.decode(test[index]['ID']);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test data table'),
),
body: Container(
child: FutureBuilder<List<dynamic>>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if(snapshot.hasData){
return ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text(
'Test',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Test2',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
DataColumn(
label: Text(
'Delete',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text(_test(snapshot.data, index).toString())
),
DataCell(
Text(_test2(snapshot.data, index).toString())
),
DataCell(
Text(_id(snapshot.data, index).toString())
)
],
),
],
),
);
}
);
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}
我曾尝试在网上寻找答案,但没有结果。我也尝试过重写我的代码以试图找出其中的任何问题。我理解为什么该应用程序在单个表格中显示数据,但我找不到修复它的方法。
解决方案
你声称知道问题是什么,所以我不会深入,但主要问题是你的ListView.builder
;没有理由把它放在那里。相反,您应该将代码替换为if(snapshot.hasData){
以下内容return SingleChildScrollView(
:
List<DataRow> dataRows = [];
for (var index = 0; index < snapshot.data.length; index++) {
dataRows.add(
DataRow(
cells: <DataCell>[
DataCell(
Text(_test(snapshot.data, index).toString())
),
DataCell(
Text(_test2(snapshot.data, index).toString())
),
DataCell(
Text(_id(snapshot.data, index).toString())
),
],
),
);
}
然后将dataRows
变量放在rows:
您的DataTable
. 你的树最终应该是 Scaffold -> Container -> FutureBuilder -> SingleChildScrollView -> DataTable。这样您就不会为每个条目构建一个新表。
推荐阅读
- php - 弄清楚如何为过滤器循环合并数组
- ios - 应用程序崩溃然后重新加载 tableview 数据
- mongodb - Mongo 构建嵌套文档数组的最佳实践
- javascript - 导航菜单项冲突
- ios - NSLocalizedString 总是返回大写的文本
- optaplanner - 在其中一个从范围中获取后,如何将所有相关实体变量设置为相同的值?
- mysql - SQL - 随着时间的推移价格上涨
- python - 如何构建具有多个文件和内部依赖项的项目以上传到 PyPI
- ios - 将 DJI 视频源与 Vision Framework 结合使用
- ruby-on-rails - 如何使用两个 for 循环优化程序