how to pass data to model class and fetch data from model class in post method- http. - flutter

Viewed 2416

Im Trying to get data from post http method in flutter, but data has not been processed to ui, I dont know where i am mistaking. Can any one please answer this? In ui I got no data on screen. model was generated by online tool, snapshot has no data.

this is my http calling class.

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:my_app/src/model/doctor_res.dart';
import 'package:my_app/src/utils/commons.dart';
// import 'package:my_app/src/widget/doctorcard.dart';

class API_Manager {
  Future<DoctorModel> doctorlist() async {
    var doctorModel;
     var client = http.Client();
    try {
      var response =
          await client.post((Commons.baseURL + "/doc"), headers: {
        "content-type": "application/json",
      }, body:
       {
        "id": 5
      }
      );
      print("response");
      if (response.statusCode == 200) {
        var jsonString = response.body;
        var jsonMap = json.decode(jsonString);
        // final doctorModel = doctorModelFromJson(jsonString);
         doctorModel = DoctorModel.fromJson(jsonMap);
      }
    } catch (Exception) {
      return doctorModel;
    }
    return doctorModel;
  }
}

this is my Model class

import 'dart:convert';

DoctorModel doctorModelFromJson(String str) => DoctorModel.fromJson(json.decode(str));

String doctorModelToJson(DoctorModel data) => json.encode(data.toJson());

class DoctorModel {
    DoctorModel({
        this.status,
        this.message,
        this.data,
    });

    int status;
    String message;
    List<Datum> data;

    factory DoctorModel.fromJson(Map<String, dynamic> json) => DoctorModel(
        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({
        this.id,
        this.mobile,
        this.userImage,
        this.emrNumber,
        this.hospital,
        this.status,
        this.doctorName,
        this.docRole,
        this.email,
        this.gender,
        this.address,
        this.city,
        this.state,
        this.pincode,
        this.clinicName,
        this.appointmentDate,
        this.favourite,
    });

    String id;
    String mobile;
    String userImage;
    String emrNumber;
    String hospital;
    String status;
    String doctorName;
    String docRole;
    String email;
    String gender;
    String address;
    String city;
    String state;
    String pincode;
    String clinicName;
    String appointmentDate;
    String favourite;

    factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        mobile: json["mobile"],
        userImage: json["user_image"],
        emrNumber: json["emr_number"],
        hospital: json["hospital"],
        status: json["status"],
        doctorName: json["doctor_name"],
        docRole: json["doc_role"],
        email: json["email"],
        gender: json["gender"],
        address: json["address"],
        city: json["city"],
        state: json["state"],
        pincode: json["pincode"],
        clinicName: json["clinic_name"],
        appointmentDate: json["appointment_date"],
        favourite: json["favourite"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "mobile": mobile,
        "user_image": userImage,
        "emr_number": emrNumber,
        "hospital": hospital,
        "status": status,
        "doctor_name": doctorName,
        "doc_role": docRole,
        "email": email,
        "gender": gender,
        "address": address,
        "city": city,
        "state": state,
        "pincode": pincode,
        "clinic_name": clinicName,
        "appointment_date": appointmentDate,
        "favourite": favourite,
    };
}

this is my ui part

  class Doctor extends StatefulWidget {
      @override
      _DoctorState createState() => _DoctorState();
    }
    
    class _DoctorState extends State<Doctor> {
      Future<DoctorModel> _doctorModal;
    
      // Doctorlist doctorList;
      bool fav = true;
      @override
      void initState() {
        _doctorModal = API_Manager().doctorlist();
        
        super.initState();
      }
      @override
     
      Widget build(BuildContext context) {
        return SafeArea(child:
        
        Scaffold(
            backgroundColor: Color(0xff29ABE2),
            appBar: AppBar(
              backgroundColor: Color(0xff29ABE2),
              elevation: 0,
              // leading: Container(),
              title: Row(
                children: <Widget>[
                  Container(
                    padding:
                        EdgeInsets.only(left: 0, right: 20, top: 20, bottom: 20),
                    height: MediaQuery.of(context).size.height * 0.1,
                    child: ClipRRect(
                      child: Image.asset(
                        "assets/images/home/patient.png",
                        fit: BoxFit.fill,
                      ),
                    ),
                  ),
                  Container(
                      padding: EdgeInsets.only(left: 0, right: 100),
                      child: Text(
                        "Doc",
                        style: TextStyle(
                            fontWeight: FontWeight.w900,
                            fontFamily: "SansBold",
                            fontSize: 20),
                      )),
                  Container(
                    padding:
                        EdgeInsets.only(left: 40, right: 0, top: 25, bottom: 25),
                    height: MediaQuery.of(context).size.height * 0.1,
                    // padding: EdgeInsets.all(25),
                    child: ClipRRect(
                      child: Image.asset(
                        "assets/images/home/notification.png",
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            drawer: NavigationDrawer(),
            body:
        
                // SingleChildScrollView(child:
                Container(
                   
                    // height: MediaQuery.of(context).size.height,
                    // width: MediaQuery.of(context).size.width,
                    child:ListView(children: [
              Container(
                height: MediaQuery.of(context).size.height * 0.90,
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(40),
                    topRight: Radius.circular(40),
                  ),
                ),
                child: Padding(
                  padding: EdgeInsets.all(15),
                  child: Column(
                    children: <Widget>[
                     
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Column(
                            children: <Widget>[
                              Text(
                                "Your doctors",
                                style: TextStyle(
                                    fontSize: 18,
                                    fontFamily: "SansBold",
                                    fontWeight: FontWeight.w100),
                              ),
                              SizedBox(
                                height: 5,
                              ),
                              Text(
                                "Search doctor",
                                style: TextStyle(
                                    fontSize: 18,
                                    fontFamily: "SansRegular",
                                    fontWeight: FontWeight.w100),
                              )
                            ],
                          ),
                          Container(
                              child: FlatButton(
                            onPressed: () {
                              Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>Adddoctor()));
                            },
                            // padding: EdgeInsets.only(left: 30, right: 30),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                            child: Row(
                              children: <Widget>[
                                ImageIcon(
                                  AssetImage("assets/images/home/add_doctor.png"),
                                  color: Colors.white,
                                ),
                                SizedBox(
                                  width: 5,
                                ),
                                Text(
                                  "Add doctor",
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontWeight: FontWeight.w600,
                                      fontFamily: "SansRegular",
                                      fontSize: 20),
                                ),
                              ],
                            ),
                            color: Color(0xff29ABE2),
                          )),
                        ],
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Container(
                        width: double.infinity,
                        child: TextField(
                          style: TextStyle(
                            color: Colors.black,
                            fontFamily: 'OpenSans',
                          ),
                          decoration: InputDecoration(
                              enabledBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: Colors.black)),
                              contentPadding: EdgeInsets.only(top: 14.0),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: Color(0xff29ABE2))),
                              hintText: 'Search doctors by ID, Mobile number',
                              suffixIcon: IconButton(
                                  icon: Icon(Icons.search), onPressed: () {})),
                        ),
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: <Widget>[
                          Container(
                              child: FlatButton(
                            onPressed: () {
                            },
                            // padding: EdgeInsets.only(left: 30, right: 30),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                            child: Text(
                              "Search",
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.w600,
                                  fontFamily: "SansRegular",
                                  fontSize: 20),
                            ),
    
                            color: Color(0xff29ABE2),
                          )),
                        ],
                      ),
                     
                    Container(
                      child:FutureBuilder<DoctorModel>(
  future: _doctorModal,
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.data == null) {
        return Text('no data');
      } else {
        return Text('data present');
      }
    }
    
     else {
      return CircularProgressIndicator(); // loading
    }
  }
)
1 Answers

The reason why no data was returned from your API_Manager is because the parsed response data was never returned. Adding return when the response was parsed should solve the issue.

if (response.statusCode == 200) {
  var jsonString = response.body;
  var jsonMap = json.decode(jsonString);
  // final doctorModel = doctorModelFromJson(jsonString);
  doctorModel = DoctorModel.fromJson(jsonMap);
  
  return doctorModel; // return DoctorModel object
}
Related