Flutter:如何显示模型 class(PokelistModel) 中的 sername、pname 数据?

Flutter : How to display sername,pname data from a model class(PokelistModel)?

我创建了一个 PokelistModel class,我想在 ServiceRequestedPage 中显示数据。但是我无法从模型 class 访问 sernamepname 以显示在 ServiceRequestedPage.

API 回应:-

{
    "service": [
        {
            "id": "444",
            "user_id": "34856",
            "service_provider_id": "289",
            "address": "235, AH45, Doordarshan Colony, Gajapati Nagar, Bhubaneswar, Odisha 751013, India",
            "date": "2022-03-28",
            "entry_time": "2022-03-28 12:16:14",
            "sername": "Barber",
            "pname": "Sabita Panda",
            "emaildta": "",
            "paddress": "Bhubaneswar, Odisha, India",
            "serphone": "9853575231",
            "serimage": "default.png",
            "review": [],
            "total_rating": 0
        },
        {
            "id": "441",
            "user_id": "34856",
            "service_provider_id": "287",
            "address": "235, AH45, Doordarshan Colony, Gajapati Nagar, Bhubaneswar, Odisha 751013, India",
            "date": "2022-02-02",
            "entry_time": "2022-02-02 16:03:11",
            "sername": "Aaya & Maid ",
            "pname": "Rabi Panda",
            "emaildta": "",
            "paddress": "  Bhubaneswar, Odisha, India",
            "serphone": "9853578231",
            "serimage": "default.png",
            "review": [
                {
                    "id": "41",
                    "user_id": "34856",
                    "service_provider_id": "287",
                    "total_rating": "5.00",
                    "review": "g",
                    "entry_time": "2022-03-22 16:45:41"
                },
                {
                    "id": "42",
                    "user_id": "34856",
                    "service_provider_id": "287",
                    "total_rating": "5.00",
                    "review": "nyc",
                    "entry_time": "2022-03-23 16:32:33"
                }
            ],
            "total_rating": 5
        },
        {
            "id": "431",
            "user_id": "34856",
            "service_provider_id": "2722",
            "address": "214, Acharya Vihar, Bhubaneswar, Odisha 751013, India",
            "date": "2021-02-19",
            "entry_time": "2021-02-19 22:05:09",
            "sername": "Hair & Spa",
            "pname": "Friends Hairstyle",
            "emaildta": "",
            "paddress": "Plot No-88/6, Jaydev Vhir Over Bridge, Acharya Vihar, Bhubaneshwar - 751013, Near Trupati Kalyani Mandap",
            "serphone": "9090531519",
            "serimage": "",
            "review": [
                {
                    "id": "37",
                    "user_id": "34856",
                    "service_provider_id": "2722",
                    "total_rating": "5.00",
                    "review": "super",
                    "entry_time": "2021-10-20 12:11:00"
                },
                {
                    "id": "38",
                    "user_id": "34856",
                    "service_provider_id": "2722",
                    "total_rating": "5.00",
                    "review": "super",
                    "entry_time": "2021-10-20 12:11:02"
                },
                {
                    "id": "43",
                    "user_id": "34856",
                    "service_provider_id": "2722",
                    "total_rating": "5.00",
                    "review": "superb ",
                    "entry_time": "2022-03-23 16:33:00"
                }
            ],
            "total_rating": 5
        }
    ],
    "status": 1,
    "message": "3 Matches Found!",
    "total_review": 3
}

Pokelist模型:-

    import 'dart:convert';

PokelistModel pokelistModelFromJson(String str) => PokelistModel.fromJson(json.decode(str));

String pokelistModelToJson(PokelistModel data) => json.encode(data.toJson());

class PokelistModel {
  PokelistModel({
    required this.service,
    required this.status,
    required this.message,
    required this.totalReview,
  });

  List<Service> service;
  int status;
  String message;
  int totalReview;

  factory PokelistModel.fromJson(Map<String, dynamic> json) => PokelistModel(
    service: List<Service>.from(json["service"].map((x) => Service.fromJson(x))),
    status: json["status"],
    message: json["message"],
    totalReview: json["total_review"],
  );

  Map<String, dynamic> toJson() => {
    "service": List<dynamic>.from(service.map((x) => x.toJson())),
    "status": status,
    "message": message,
    "total_review": totalReview,
  };
}

class Service {
  Service({
    required this.id,
    required this.userId,
    required this.serviceProviderId,
    required this.address,
    required this.date,
    required this.entryTime,
    required this.sername,
    required this.pname,
    required this.emaildta,
    required this.paddress,
    required this.serphone,
    required this.serimage,
    required this.review,
    required this.totalRating,
  });

  String id;
  String userId;
  String serviceProviderId;
  String address;
  DateTime date;
  DateTime entryTime;
  String sername;
  String pname;
  String emaildta;
  String paddress;
  String serphone;
  String serimage;
  List<Review> review;
  int totalRating;

  factory Service.fromJson(Map<String, dynamic> json) => Service(
    id: json["id"],
    userId: json["user_id"],
    serviceProviderId: json["service_provider_id"],
    address: json["address"],
    date: DateTime.parse(json["date"]),
    entryTime: DateTime.parse(json["entry_time"]),
    sername: json["sername"],
    pname: json["pname"],
    emaildta: json["emaildta"],
    paddress: json["paddress"],
    serphone: json["serphone"],
    serimage: json["serimage"],
    review: List<Review>.from(json["review"].map((x) => Review.fromJson(x))),
    totalRating: json["total_rating"],
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "user_id": userId,
    "service_provider_id": serviceProviderId,
    "address": address,
    "date": "${date.year.toString().padLeft(4, '0')}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}",
    "entry_time": entryTime.toIso8601String(),
    "sername": sername,
    "pname": pname,
    "emaildta": emaildta,
    "paddress": paddress,
    "serphone": serphone,
    "serimage": serimage,
    "review": List<dynamic>.from(review.map((x) => x.toJson())),
    "total_rating": totalRating,
  };
}

class Review {
  Review({
    required this.id,
    required this.userId,
    required this.serviceProviderId,
    required this.totalRating,
    required this.review,
    required this.entryTime,
  });

  String id;
  String userId;
  String serviceProviderId;
  String totalRating;
  String review;
  DateTime entryTime;

  factory Review.fromJson(Map<String, dynamic> json) => Review(
    id: json["id"],
    userId: json["user_id"],
    serviceProviderId: json["service_provider_id"],
    totalRating: json["total_rating"],
    review: json["review"],
    entryTime: DateTime.parse(json["entry_time"]),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "user_id": userId,
    "service_provider_id": serviceProviderId,
    "total_rating": totalRating,
    "review": review,
    "entry_time": entryTime.toIso8601String(),
  };
}

服务请求页面:-

    import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:http/http.dart';
import 'package:newbharatbiz/Model%20Class/PokelistService.dart';
import 'package:newbharatbiz/Model%20Class/pokelist_model.dart';
import 'package:newbharatbiz/Screens/AddReviewPage.dart';
import 'package:newbharatbiz/Screens/RequestedServiceDetailsPage.dart';
import 'HomePage.dart';
import 'package:http/http.dart' as http;

class ServiceRequestedPage extends StatefulWidget {
  @override
  _YourWidgetState createState() => _YourWidgetState();
}

class _YourWidgetState extends State<ServiceRequestedPage> {
  bool isLoading = false;


  late Future<PokelistModel> pokelist;

  @override
  void initState() {
    super.initState();

    pokelist = PokelistService.getProducts();
  }


  Future delete_poke() async {
    final String DeletePokeAPI =
        "https://newbharatbiz.in/mobile_api/v4/delete_poke.php";
    setState(() {
      isLoading = true;
    });
    final headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Content-Type": "application/x-www-form-urlencoded"
    };

    final Map<String, dynamic> body = {
      "id": "idd",
    };

    String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");
    //var jsonBody = json.encode(body);
    Response response = await http.post(Uri.parse(DeletePokeAPI),
        body: encodedBody, headers: headers);
    var jsonResponse = jsonDecode(response.body);
    print(jsonResponse);
    if (response.statusCode == 200) {
      setState(() {
        isLoading = false;
      });
      // If the server did return a 201 CREATED response,
      // then parse the JSON.
      //return json.decode(response.body)['services'];
      print(response);
      //  return CatwiseServiceModel.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 201 CREATED response,
      // then throw an exception.
      throw Exception('Failed to load.');
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => true,
      child: Scaffold(
          appBar: new AppBar(
            title: new Text('Service Requested List'),
            leading: new IconButton(
                icon: new Icon(Icons.arrow_back_outlined),
                onPressed: () {
                  Navigator.pop(
                      context, true); // It worked for me instead of above line
                  Navigator.pushReplacement(
                    context,
                    MaterialPageRoute(builder: (context) => HomePage()),
                  );
                }),
          ),
          body: SingleChildScrollView(
            child:
                Column(mainAxisAlignment: MainAxisAlignment.start, children: [
              FutureBuilder<PokelistModel>(
                  future: pokelist,
                  builder: (BuildContext context,  snapshot) {
                    if (snapshot.hasData) {
                      //print(idd(snapshot.data[0]));
                      return SingleChildScrollView(
                        child: Column(
                          children: <Widget>[
                            ListView.builder(
                                padding: EdgeInsets.zero,
                                shrinkWrap: true,
                                physics: NeverScrollableScrollPhysics(),
                                itemBuilder: (BuildContext context, int index) {
                                  return Container(
                                      margin: EdgeInsets.zero,
                                      child: Card(
                                          child: Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                            ListTile(
                                                leading: CircleAvatar(
                                                  child: Image.asset(
                                                      "assets/dummyprofile.png",
                                                      fit: BoxFit.fill),
                                                  backgroundColor:
                                                      Colors.transparent,
                                                ),
                                                title: Text(
                                                  sername(snapshot.data[index]),
                                                  style: TextStyle(
                                                      color: Colors.black87,
                                                      fontWeight:
                                                          FontWeight.bold,
                                                      fontSize: 16),
                                                ),

                                                /*subtitle: Row(
                                          children: <Widget>[
                                            Text("M/S : ",
                                                style: TextStyle(
                                                    color: Colors.black87,
                                                    fontWeight: FontWeight.bold,
                                                    fontSize: 13)),
                                            Text(pname(snapshot.data[index]),
                                                style: TextStyle(
                                                    color: Colors.black87)),
                                          ],
                                        ),*/
                                                subtitle: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: <Widget>[
                                                    Text(
                                                        "M/S : " +
                                                            pname(snapshot
                                                                .data[index]),
                                                        style: TextStyle(
                                                            color: Colors.black,
                                                            fontSize: 14)),
                                                    SizedBox(height: 5),
                                                    Text(
                                                        "Phone No : " +
                                                            serphone(snapshot
                                                                .data[index]),
                                                        style: TextStyle(
                                                            color: Colors.black,
                                                            fontSize: 14)),
                                                  ],
                                                ),
                                                trailing: new IconButton(
                                                  icon: new Icon(Icons.close,
                                                      color: Colors.black87,
                                                      size: 30.0),
                                                  onPressed: () {
                                                    delete_poke();
                                                  },
                                                )),
                                            SizedBox(height: 10),
                                            Padding(
                                              padding: const EdgeInsets.only(
                                                  left: 10.0),
                                              child: Text(
                                                  "Address : " +
                                                      paddress(
                                                          snapshot.data[index]),
                                                  style: TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 14)),
                                            ),
                                            SizedBox(height: 15),
                                            Padding(
                                              padding: const EdgeInsets.only(
                                                  left: 10.0, bottom: 10.0),
                                              child: Row(
                                                  mainAxisAlignment:
                                                      MainAxisAlignment.start,
                                                  children: [
                                                    SizedBox(
                                                      height: 30.0,
                                                      child: MaterialButton(
                                                        child: Text("Rating"),
                                                        textColor: Colors.white,
                                                        color: Color(0xFF00796B),
                                                        disabledColor:
                                                            Colors.blue,
                                                        shape:
                                                            RoundedRectangleBorder(
                                                          borderRadius:
                                                              BorderRadius.all(
                                                            Radius.circular(
                                                                10.0), // Change your border radius here
                                                          ),
                                                        ),
                                                        onPressed: () {
                                                          Navigator.push(
                                                            context,
                                                            MaterialPageRoute(
                                                              builder: (context) =>
                                                                  AddReviewPage(
                                                                sername: snapshot
                                                                            .data[
                                                                        index]
                                                                    ['sername'],
                                                                pname: snapshot
                                                                            .data[
                                                                        index]
                                                                    ['pname'],
                                                              ),
                                                            ),
                                                          );
                                                        },
                                                      ),
                                                    ),
                                                    SizedBox(width: 20),

                                                    SizedBox(
                                                      height: 30.0,
                                                      child: MaterialButton(
                                                        child: Text("View"),
                                                        textColor: Colors.white,
                                                        color: Color(0xFF00796B),
                                                        disabledColor:
                                                            Colors.blue,
                                                        shape:
                                                            RoundedRectangleBorder(
                                                          borderRadius:
                                                              BorderRadius.all(
                                                            Radius.circular(
                                                                10.0), // Change your border radius here
                                                          ),
                                                        ),
                                                        onPressed: () {
                                                          Navigator.push(
                                                            context,
                                                            MaterialPageRoute(
                                                              builder: (context) =>
                                                                  RequestedServiceDetailsPage(
                                                                sername: snapshot
                                                                            .data[
                                                                        index]
                                                                    ['sername'],
                                                                pname: snapshot
                                                                            .data[
                                                                        index]
                                                                    ['pname'],
                                                                paddress: snapshot
                                                                            .data[
                                                                        index][
                                                                    'paddress'],
                                                                serphone: snapshot
                                                                            .data[
                                                                        index][
                                                                    'serphone'],
                                                              ),
                                                            ),
                                                          );
                                                        },
                                                      ),
                                                    ),
                                                    //  SizedBox(height: 10),

                                                    /*  Button (),
                                                  RatingBar (),
                                                  Button ()*/
                                                  ]),
                                            )
                                          ])));
                                })
                          ],
                        ),
                      );
                    }
                    return const Center(
                      child: SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation(Colors.blue),
                        ),
                      ),
                    );
                  }
                  // By default, show a loading spinner.
                  ),
              Visibility(visible: isLoading, child: CircularProgressIndicator())
            ]),
          )),
    );
  }
}

Pokelist服务:-

    import 'dart:convert';

import 'package:http/http.dart';
import 'package:newbharatbiz/Model%20Class/pokelist_model.dart';
import 'package:http/http.dart' as http;

class PokelistService {
  static Future<PokelistModel> getProducts() async {

    final String ServiceAPI =
        "https://newbharatbiz.in/mobile_api/v4/listing_poke.php";
    final headers = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      "Content-Type": "application/x-www-form-urlencoded"
    };
    final Map<String, dynamic> body = {
      "user_id": "34856",
    };
    String encodedBody = body.keys.map((key) => "$key=${body[key]}").join("&");
    //var jsonBody = json.encode(body);
    Response response = await http.post(Uri.parse(ServiceAPI),
        body: encodedBody, headers: headers);
    var jsonResponse = jsonDecode(response.body);
    print(jsonResponse);
    if (response.statusCode == 200) {
      // If the server did return a 201 CREATED response,
      // then parse the JSON.
      //return json.decode(response.body)['services'];
      print(json.decode(response.body));;
      final body = json.decode(response.body);
      return  body.map(PokelistModel.fromJson);

      //   var data = json.decode(response.body)
      //  return CatwiseServiceModel.fromJson(jsonDecode(response.body));
    } else {
      // If the server did not return a 201 CREATED response,
      // then throw an exception.
      throw Exception('Failed to load.');
    }


  }
}

有几种方法可以做到这一点。你可以试试这个:

  1. 更改响应模型以合并所有数据。只需复制并粘贴您在此处收到的 JSON:https://app.quicktype.io

  2. 然后把这里的部分改一下:

    正文( snapshot.data[索引].service.sername, 风格:TextStyle(颜色:Colors.black87, 字体粗细:FontWeight.bold, 字体大小:16), ),

对您需要的任何其他数据使用相同的结构。也许您可以创建更通用的 ApiService 并将必要的变量作为参数传递,如下所示:

Future<ApiResponse?> post(String url, dynamic body,
      {Map<String, String>? headers}) async {
    print('API Post: ${this.url+url}');
    try {
      final response = await http.post(Uri.parse(this.url+url),
          body: body,
          headers: headers
      );
      if (response.statusCode == 200) {
        String data = response.body;
        final decodedData = jsonDecode(data);
        print('API Post: $decodedData)');
        final _apiResponse = ApiResponse.fromJson(decodedData);
        return _apiResponse;
      }
    } catch(e) {
      print('API Post: $e');
    }
    return null;
  }

我是这样访问数组的> List data = snapshot.data!.service;然后会像这样显示> sername data[index].sername

列表数据 = snapshot.data!.service;

用户名数据[索引].用户名