我想创建一个表,其中包含要从互联网(API)获取的表中的数据作为,我们构建ListView.builder
有什么方法可以构建table
颤振吗?
问问题
1324 次
1 回答
0
要创建表并将数据动态插入其中,首先需要一个数据模型。有关更多详细信息,请参见下面的示例。
data.dart(数据模型):
class NameOne{
String sn, name, address, phone;
NameOne({
this.sn,
this.name,
this.address,
this.phone
});
//constructor
factory NameOne.fromJSON(Map<String, dynamic> json){
return NameOne(
sn: json["sn"],
name: json["name"],
address: json["address"],
phone: json["phone"]
);
}
}
主要.dart
import 'package:flutter/material.dart';
import 'package:testapp/data.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget{
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget{
@override
Widget build(BuildContext context) {
List<NameOne> namelist = []; //list of names, you can generate it using JSON as well
namelist.add(NameOne(sn:"1", name:"Name 1", address:"Address 1", phone: "Phone 1"));
namelist.add(NameOne(sn:"2", name:"Name 2", address:"Address 2", phone: "Phone 2"));
namelist.add(NameOne(sn:"3", name:"Name 3", address:"Address 3", phone: "Phone 3"));
//add more adata here
return Scaffold(
appBar: AppBar(
title:Text("Dynamic Data Table"), //title of app
backgroundColor: Colors.redAccent, //background color of app bar
),
body: Container(
padding: EdgeInsets.all(15),
child:Table( //if data is loaded then show table
border: TableBorder.all(width:1, color:Colors.black45),
children: namelist.map((nameone){ //display data dynamically from namelist List.
return TableRow( //return table row in every loop
children: [
//table cells inside table row
TableCell(child: Padding(
padding: EdgeInsets.all(5),
child:Text(nameone.sn)
)
),
TableCell(child: Padding(
padding: EdgeInsets.all(5),
child:Text(nameone.name)
)
),
TableCell(child: Padding(
padding: EdgeInsets.all(5),
child:Text(nameone.address)
)
),
TableCell(child: Padding(
padding: EdgeInsets.all(5),
child:Text(nameone.phone)
)
),
]
);
}).toList(),
)
)
);
}
}
这是您可以动态向 Flutter 表插入数据的方式,请访问如何在 Flutter App 中动态地从 PHP MySQL JSON 中创建表和插入数据,以查看更多详细信息,以从使用 REST API 获取的 JSON 数据创建表。
于 2021-03-22T09:54:31.077 回答