json - 如何使用 POST 方法在水平滚动视图中显示 JSON 数据?
问题描述
我想用水平视图而不是列表视图显示我的 JSON 数据,在运行以下命令后,它既不显示任何错误也不显示我的数据。但我在控制台中获取数据。
首先,我创建我的 APIServices()
并在方法中调用它initState()
,我的数据会在应用程序打开后立即显示。
class Services{
static const String url = 'http://medbo.digitalicon.in/api/medboapi/alldoctor';
static Future<List<MyDoc>> getDocFun() async{
try{
final response = await http.post(url);
if(200 == response.statusCode){
print(response.body);//getting response in console
final List<MyDoc> docs = myDocFromJson(response.body) as List<MyDoc>;
return docs;
}else{
// return List<MyDoc>();
}
}catch(e){
}
return <MyDoc>[];
}
}
叫它initState(){}
Services.getDocFun().then((docs){
setState(() {
_docsVar =docs;
});
}
);
在那之后,build(BuildContext context)
我拿了一个容器来调用我的容器,DoctorCard()
以在水平视图中显示我的 JSON 数据。
Widget build(BuildContext context) {
Widget image_carousel = new Container(
margin: EdgeInsets.all(10.0),
// padding: EdgeInsets.all(10),
height: 180,
width: MediaQuery.of(context).size.width,
// color: Colors.green,
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(10),
),
child: Carousel(
boxFit: BoxFit.contain,
images: [
AssetImage('assets/images/medbo-doctors.png'),
AssetImage('assets/images/medbo-pathological-tests.png'),
AssetImage('assets/images/medbo-home-banner.png'),
AssetImage('assets/images/medbo-surgical-packages.png'),
],
dotSize: 0.0,
indicatorBgPadding: 0.0,
autoplay: true,
),
);
return Scaffold(
appBar: AppBar(
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.topRight,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor
],
),
),
),
title: Text(
'HOME',
style: TextStyle(fontFamily: 'Roboto_Condensed'),
)),
drawer: SideDrawer(),
body: SingleChildScrollView(
child: Container(
color: Colors.lightBlue[50],
child: Stack(
alignment: Alignment.topCenter,
children: [
ClipPath(
clipper: MyClipper(),
child: Container(
height: 400,
width: MediaQuery.of(context).size.height,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.center,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor
],
),
),
),
),
Column(children: [
image_carousel,
Container(
height: 200,
// color: Colors.blue,
child: ListView.separated(
itemCount: 5,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => Container(
// color: Colors.green,
height: 100,
width: 300,
margin: EdgeInsets.all(20),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(5),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.center,
colors: [
Theme.of(context).primaryColor,
Theme.of(context).accentColor
],
),
),
child: Column(
children: [
Container(
height: 50,
width: 150,
// color: Colors.green,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Your Last Visit',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
fontFamily: 'Roboto_Condensed',
color: Colors.white),
),
Text('Date and Time:',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Colors.white,
fontFamily: 'Roboto_Condensed')),
],
),
),
SizedBox(
height: 40,
),
//=============================================================1st row===========================================================================
Container(
height: 70,
// color: Colors.green,
child: Row(
children: [
Container(
padding: EdgeInsets.all(10),
width: 145,
// color: Colors.black,
child: Column(
mainAxisAlignment:
MainAxisAlignment.center,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
'Doctors Name',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
fontFamily: 'Roboto_Condensed',
color: Colors.white),
),
Text('Doctor_speciality',
style: TextStyle(
fontWeight: FontWeight.bold,
fontFamily: 'Roboto_Condensed',
fontSize: 15,
color: Colors.white)),
],
),
),
SizedBox(
width: 10,
),
Container(
width: 145,
// color: Colors.black,
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
LastVisit()),
);
// print("tapped on container");
},
child: Container(
margin: EdgeInsets.all(10),
height: 38,
// color: Colors.green,
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.rectangle,
borderRadius:
BorderRadius.circular(5)),
child: Text(
'Details:',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: Theme.of(context)
.primaryColor),
),
),
),
),
],
),
),
],
)),
separatorBuilder: (BuildContext context, int index) =>
const Divider(
color: Colors.transparent,
),
),
),
SizedBox(
height: 25,
),
//==================================================================My Doc List UI part============================================================================================
Padding(
padding: EdgeInsets.symmetric(horizontal: 18.0),
child: Row(
children: [
Text(
"Top Doctors",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
// fontFamily: 'Roboto_Condensed',
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor),
),
Spacer(),
Text(
"View all",
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.bold,
// fontFamily: 'Roboto_Condensed',
fontFamily: 'Poppins',
color: Theme.of(context).primaryColor),
)
],
),
),
SizedBox(height: 15.0,),
Container(
width: double.infinity,
height:200.0,
child: ListView.builder(
itemCount:_docsVar.length,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context,index){
MyDoc docs = _docsVar[index];
return DoctorCard();
},
),
),
SizedBox(height: 25.0,),
我DoctorCard();
想要显示来自 Json 的数据的虚拟文本数据和图像
class DoctorCard extends StatefulWidget {
const DoctorCard({Key? key}) : super(key: key);
@override
_DoctorCardState createState() => _DoctorCardState();
}
class _DoctorCardState extends State<DoctorCard> {
// Future<List<dynamic>> fetchData() async {//============================================fetchData() function
// final response = await http.post("http://medbo.digitalicon.in/api/medboapi/alldoctor");
// // return json.decode(response.body);
// Map<String, dynamic> map = json.decode(response.body);
// return map["Data"];
// }
@override
Widget build(BuildContext context) {
return Card(
margin: EdgeInsets.only(left: 18.0, bottom: 2.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12.0),
),
child: Container(
width: 150.0,
padding: EdgeInsets.all(8.0),
child: Column(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(14.0),
child: Image.asset('assets/images/medbo-doctors.png',
fit: BoxFit.cover),
),
),
SizedBox(
height: 12.0,
),
Text(
"Dr. Tuhin",
overflow: TextOverflow.clip,
maxLines: 1,
textAlign: TextAlign.center,
),
SizedBox(height: 6.0),
Text(
"Specialist",
overflow: TextOverflow.clip,
maxLines: 1,
textAlign: TextAlign.center ,
),
],
),
),
);
}
}
我的模特班
// To parse this JSON data, do
//
// final myDoc = myDocFromJson(jsonString);
import 'dart:convert';
MyDoc myDocFromJson(String str) => MyDoc.fromJson(json.decode(str));
String myDocToJson(MyDoc data) => json.encode(data.toJson());
class MyDoc {
MyDoc({
required this.status,
required this.message,
required this.data,
});
String status;
String message;
List<Datum> data;
factory MyDoc.fromJson(Map<String, dynamic> json) => MyDoc(
status: json["Status"],
message: json["Message"],
data: List<Datum>.from(json["Data"].map((x) => Datum.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"Status": status,
"Message": message,
"Data": List<dynamic>.from(data.map((x) => x.toJson())),
};
}
class Datum {
Datum({
required this.doctorId,
required this.encDoctorId,
required this.doctorName,
required this.doctorImage,
this.linkPartner,
required this.specialisation,
this.gender,
required this.qualification,
this.fee,
this.discountedFee,
this.bookingFee,
this.timeFrom,
this.timeTo,
this.visitDay,
this.phone,
this.alternatePhone,
this.email,
this.note,
this.createBy,
this.createDate,
this.modBy,
this.modDate,
this.activeStatus,
this.permission,
});
String doctorId;
String encDoctorId;
String doctorName;
String doctorImage;
dynamic linkPartner;
String specialisation;
dynamic gender;
String qualification;
dynamic fee;
dynamic discountedFee;
dynamic bookingFee;
dynamic timeFrom;
dynamic timeTo;
dynamic visitDay;
dynamic phone;
dynamic alternatePhone;
dynamic email;
dynamic note;
dynamic createBy;
dynamic createDate;
dynamic modBy;
dynamic modDate;
dynamic activeStatus;
dynamic permission;
factory Datum.fromJson(Map<String, dynamic> json) => Datum(
doctorId: json["DoctorId"],
encDoctorId: json["EncDoctorId"],
doctorName: json["DoctorName"],
doctorImage: json["DoctorImage"],
linkPartner: json["LinkPartner"],
specialisation: json["Specialisation"],
gender: json["Gender"],
qualification: json["Qualification"],
fee: json["Fee"],
discountedFee: json["DiscountedFee"],
bookingFee: json["BookingFee"],
timeFrom: json["TimeFrom"],
timeTo: json["TimeTo"],
visitDay: json["VisitDay"],
phone: json["Phone"],
alternatePhone: json["AlternatePhone"],
email: json["Email"],
note: json["Note"],
createBy: json["CreateBy"],
createDate: json["CreateDate"],
modBy: json["ModBy"],
modDate: json["ModDate"],
activeStatus: json["ActiveStatus"],
permission: json["Permission"],
);
Map<String, dynamic> toJson() => {
"DoctorId": doctorId,
"EncDoctorId": encDoctorId,
"DoctorName": doctorName,
"DoctorImage": doctorImage,
"LinkPartner": linkPartner,
"Specialisation": specialisation,
"Gender": gender,
"Qualification": qualification,
"Fee": fee,
"DiscountedFee": discountedFee,
"BookingFee": bookingFee,
"TimeFrom": timeFrom,
"TimeTo": timeTo,
"VisitDay": visitDay,
"Phone": phone,
"AlternatePhone": alternatePhone,
"Email": email,
"Note": note,
"CreateBy": createBy,
"CreateDate": createDate,
"ModBy": modBy,
"ModDate": modDate,
"ActiveStatus": activeStatus,
"Permission": permission,
};
}
我的 JSON 响应
{
"Status": "1",
"Message": "5 doctors found.",
"Data": [
{
"DoctorId": "9",
"EncDoctorId": "fXVmzecGStqrhx1PmIgwlQ==",
"DoctorName": "Dr Ram Das",
"DoctorImage": "http://medbo.digitalicon.in/Doctor/U7MK2MZGD0QVQ7E8IR7N.jpg",
"LinkPartner": null,
"Specialisation": "ENT",
"Gender": null,
"Qualification": "kj",
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"TimeFrom": null,
"TimeTo": null,
"VisitDay": null,
"Phone": null,
"AlternatePhone": null,
"Email": null,
"Note": null,
"CreateBy": null,
"CreateDate": null,
"ModBy": null,
"ModDate": null,
"ActiveStatus": null,
"Permission": null
},
{
"DoctorId": "5",
"EncDoctorId": "pEl2B9kuumKRxIxLJO76eQ==",
"DoctorName": "Dr. Steve Buckner",
"DoctorImage": "http://medbo.digitalicon.in/Doctor/IT02Z92IHFI48TMV6BUM.jpg",
"LinkPartner": null,
"Specialisation": "Eye",
"Gender": null,
"Qualification": "Frcs, md, mbbs",
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"TimeFrom": null,
"TimeTo": null,
"VisitDay": null,
"Phone": null,
"AlternatePhone": null,
"Email": null,
"Note": null,
"CreateBy": null,
"CreateDate": null,
"ModBy": null,
"ModDate": null,
"ActiveStatus": null,
"Permission": null
},
{
"DoctorId": "8",
"EncDoctorId": "kFgorcFF0G6RQD4W+LwWnQ==",
"DoctorName": "Dr. Alim Darr",
"DoctorImage": "http://medbo.digitalicon.in/Doctor/VX4Q79ONBLQWIQ1ILQHF.jpg",
"LinkPartner": null,
"Specialisation": "ENT",
"Gender": null,
"Qualification": "FRCS",
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"TimeFrom": null,
"TimeTo": null,
"VisitDay": null,
"Phone": null,
"AlternatePhone": null,
"Email": null,
"Note": null,
"CreateBy": null,
"CreateDate": null,
"ModBy": null,
"ModDate": null,
"ActiveStatus": null,
"Permission": null
},
{
"DoctorId": "1",
"EncDoctorId": "I3uXyzcuDZf21SSe5fHnSQ==",
"DoctorName": "Dr. Mrs. Kusum Kumari Das",
"DoctorImage": "http://medbo.digitalicon.in/Doctor/JVMK97QT9PSB8KQQ7NK1.jpg",
"LinkPartner": null,
"Specialisation": "ENT, Interventional Cardiology, Medicine, Orthopetic, Specialisation, Endocrenology, Jeriasistic",
"Gender": null,
"Qualification": "MBBS DM (Cardiology)",
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"TimeFrom": null,
"TimeTo": null,
"VisitDay": null,
"Phone": null,
"AlternatePhone": null,
"Email": null,
"Note": null,
"CreateBy": null,
"CreateDate": null,
"ModBy": null,
"ModDate": null,
"ActiveStatus": null,
"Permission": null
},
{
"DoctorId": "2",
"EncDoctorId": "7Ch2aVnhokZtRWyJtuDA/A==",
"DoctorName": "Dr. Rejaul Alam",
"DoctorImage": "http://medbo.digitalicon.in/Doctor/INFX2N9V5QFH712M2LEE.jpg",
"LinkPartner": null,
"Specialisation": "Orthopetic, Specialisation",
"Gender": null,
"Qualification": "MD, DM",
"Fee": null,
"DiscountedFee": null,
"BookingFee": null,
"TimeFrom": null,
"TimeTo": null,
"VisitDay": null,
"Phone": null,
"AlternatePhone": null,
"Email": null,
"Note": null,
"CreateBy": null,
"CreateDate": null,
"ModBy": null,
"ModDate": null,
"ActiveStatus": null,
"Permission": null
}
]
}
解决方案
您必须告诉您的DoctorCard
小部件要显示哪些数据,然后在显示图像、名称等时使用这些数据。有很多方法,但一种是DoctorCard
在需要显示的医生数据中添加构造函数参数。您还必须使用Image.network
而不是Image.asset
添加itemCount
当前在您的代码中注释掉的内容。
我将假设doctorList
包含从fetchData
.
DoctorCard
班级:
class DoctorCard extends StatefulWidget {
final dynamic doctor;
const DoctorCard({Key? key, this.doctor}) : super(key: key);
@override
_DoctorCardState createState() => _DoctorCardState();
}
ListView.builder
在你的Container
:
child: ListView.builder(
itemCount: doctorList.length,
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) {
return DoctorCard(doctor: doctorList[index]);
},
),
Column
在_DoctorCardState.build
:
child: Column(
children: [
Expanded(
child: ClipRRect(
borderRadius: BorderRadius.circular(14.0),
child: Image.network(widget.doctor["DoctorImage"],
fit: BoxFit.cover),
),
),
SizedBox(
height: 12.0,
),
Text(
widget.doctor["DoctorName"],
overflow: TextOverflow.clip,
maxLines: 1,
textAlign: TextAlign.center,
),
SizedBox(height: 6.0),
Text(
widget.doctor["Specialisation"],
overflow: TextOverflow.clip,
maxLines: 1,
textAlign: TextAlign.center,
),
],
),
推荐阅读
- pandas - 如何使用正则表达式在熊猫数据框中选择包含特定子字符串的行之后的一行和固定数量的行
- react-native - 如何在 React Native 中使用预先填充的 Realm 数据库?
- html - Index.html 中的 JSON 文件
- android - 以编程方式打开连接的 Wifi 设置 Android 10
- c# - 串口在 Form3 中关闭?
- python - 如果值大于,如何插入行和插值
- rxjs - 订阅导入有什么区别
- php - 如何检查 PHP 中是否绕过了客户端输入验证?
- bash - 命令行中的 API 网关和 Lambda 函数
- swift - 通知服务扩展 - 在应用程序未运行时发出 URL 请求