【发布时间】:2021-05-16 22:38:40
【问题描述】:
我刚开始使用颤振。我有一个用 nodejs 编写的 rest api 服务。下面正在生成输出“result.json”。我正在尝试通过颤振访问它。
连接到服务器。 从服务器获取 json 数据。 但我不能把它带入卡片。你能帮我吗?
Customers.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:hasta_takip/models/customers_model.dart';
import 'package:http/http.dart' as http;
class Customers extends StatefulWidget {
@override
_CustomersState createState() => _CustomersState();
}
class _CustomersState extends State<Customers> {
Future<List<CustomersModel>> _fetchCustomers() async {
var response = await http.get("http://localhost:3000/customers");
if (response.statusCode == 200) {
return (json.decode(response.body))
.map((e) => CustomersModel.fromJson(e))
.toList();
} else {
throw Exception("not connected ${response.statusCode}");
}
}
@override
void initState() {
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Customer list"),
),
body: FutureBuilder(
future: _fetchCustomers(),
builder: (BuildContext context,
AsyncSnapshot<List<CustomersModel>> snapshot) {
print(snapshot.data);
if (snapshot.hasData) {
print(snapshot);
return ListView.builder(
//itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return ListTile();
});
} else {
return Center(child: CircularProgressIndicator());
}
},
),
);
}
}
CustomersModel.dart
import 'dart:convert';
CustomersModel customersModelFromJson(String str) => CustomersModel.fromJson(json.decode(str));
String customersModelToJson(CustomersModel data) => json.encode(data.toJson());
class CustomersModel {
CustomersModel({
this.result,
});
List<Result> result;
factory CustomersModel.fromJson(Map<String, dynamic> json) => CustomersModel(
result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"result": List<dynamic>.from(result.map((x) => x.toJson())),
};
}
class Result {
Result({
this.id,
this.customerName,
this.customerLastname,
});
int id;
String customerName;
String customerLastname;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
customerName: json["customer_name"],
customerLastname: json["customer_lastname"],
);
Map<String, dynamic> toJson() => {
"id": id,
"customer_name": customerName,
"customer_lastname": customerLastname,
};
}
Result.json
{
"result": [
{
"id": 1,
"customer_name": "John",
"customer_lastname": "simon"
},
{
"id": 2,
"customer_name": "peter",
"customer_lastname": "bratt"
}
]
}
【问题讨论】:
-
But I cannot take this into card没有得到这个