在需要从API响应中创建表。我使用future builder创建了数据表。future构建器触发api两次,不返回任何数据
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: FutureBuilder(
future: unpaid(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Container(
padding: const EdgeInsets.all(5),
child:
Dataclass(datalist: snapshot.data as List<UnpaidDetails>));
} else {
return Container(
// padding: const EdgeInsets.all(5),
// child: Dataclass(
// datalist: snapshot.data as List<UnpaidDetails>)
);
}
},
),
);
}
Future<String?> getToken() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('token');
}
Future<List<UnpaidDetails>> unpaid() async {
String? token = await getToken();
final response = await http.get(
Uri.parse('https://test.url/api/unpaid'),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
if (response.statusCode == 200) {
var result = jsonDecode(response.body);
List jsonResponse = result["UnpaidDetails"] as List;
return jsonResponse.map((e) => UnpaidDetails.fromJson(e)).toList();
} else {
throw Exception('Failed to update album.');
}
}
}
class Dataclass extends StatefulWidget {
Dataclass({Key? key, required List<UnpaidDetails> this.datalist})
: super(key: key);
List<UnpaidDetails> datalist;
@override
DataclassState createState() {
return DataclassState();
}
}
class DataclassState extends State<Dataclass> {
@override
Widget build(BuildContext context)
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: FittedBox(
child: DataTable(
sortColumnIndex: 1,
showCheckboxColumn: false,
border: TableBorder.all(width: 1.0),
columns: const [
DataColumn(
label: Text(
"Period",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
)),
DataColumn(
label: Text(
"Amount",
style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
)),
],
rows: widget.datalist
.map((data) => DataRow(cells: [
DataCell(
Text(data.month,
style: const TextStyle(
fontSize: 26, fontWeight: FontWeight.w500)),
),
DataCell(
Text(data.price.toString(),
style: const TextStyle(
fontSize: 26, fontWeight: FontWeight.w500)),
),
]))
.toList(),
))); }}
1 API调用两次
api调用触发两次,第一个调用带来响应。第二个是发送请求没有头和接收错误。我正在使用json。创建类。帮助我以干净的方式执行future builder
对于非数据问题:
删除getter:
get datalist => null;
在Datatable类中声明一个数据变量:
class Dataclass extends StatefulWidget {
Dataclass({Key? key, required List<UnpaidDetails> this.datalist})
: super(key: key);
List<UnpaidDetails> datalist;
从你的状态中读取
rows: widget.datalist
不是
rows: datalist
还有你的第二个电话。你不需要在initstate中调用。所以你可以删除你的initstate方法,并改变你未来的构建器,像这样:
body: FutureBuilder(
future: unpaid(),