Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

how to fix it Data not showing in list in flutter

I want to show a list of data to parse the JSON, I have written all the codes but data not show in listview I don't understand what is the mistake in my code. I am sharing my codes.plz suggest to me

This is JSON which I have parsed

[ { "customer_name": "ridge_valley, Ridge Valley School", "mobile": "9796005602", "product_id": "47265", "imei": "868004027863425", "serial_no": "2016172679", "name": "L-100 [2G] ", "id": "36", "complain_no": "11212", "complain_id": "CMP/160720/11211", "fault": "device not showing ", "mobile_no": "5756200501797", "customer_product_id": "10514", "kyc_id": null, "vehicle_no": "HR55R0561" } ]

This is my code.

import 'package:deviceinstallation/complaint.dart';
import 'package:deviceinstallation/ordercountdetail.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:http/http.dart' as http;
import 'dashboard_screen.dart';
import 'model/complaint_count_model.dart';

//void main()=> runApp(ComplaintCountDetails());

class ComplaintCountDetails  extends StatelessWidget{
  String cID;
  ComplaintCountDetails(this.cID);

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    print("id"+cID);
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "FLutter Demo",
      theme: ThemeData(
          primarySwatch: Colors.blue
      ),
      home: ComplaintCountDetailsScreen(cID: cID,),
    );

  }
}

class ComplaintCountDetailsScreen extends StatefulWidget {
  //final String title;
  String cID;
  //ComplaintCountDetailsScreen({this.cID});
  ComplaintCountDetailsScreen({Key key, this.cID}): super(key: key);

  @override
  ComplaintCountStates createState() => ComplaintCountStates(cID);
}

class ComplaintCountStates extends State<ComplaintCountDetailsScreen> {
  Icon cusIcon =Icon(Icons.search);
  Widget cusSearchBar= Text("Complaint List");
  String cID;
  ComplaintCountStates(this.cID);
  String sUrl= "https://fasttracksoft.us/api_v2/device_installation/";
  bool isLoading= false;
  List<ComplaintCountDetailModel> complaintCountList;
  Future<List<ComplaintCountDetails>> getComplaintCountList()async{
    setState(() {
      isLoading=true;
    });
     final prefs= await SharedPreferences.getInstance();
      var params= "complaindetail.php?id="+prefs.getString('id')+"&cid="+cID;
     // print("param:"+params);
     try{
       var response= await http.get(sUrl+params);
       print("sURL:"+sUrl);
       print("param:"+params);
      // print("response+url_param:$response");
       print("customerID:"+prefs.getString('id'));
       print("url+params:"+sUrl+params);

       if(response.statusCode==200){
         complaintCountList=complaintCountDetailModelFromJson(response.body);
         print("listJSON:"+complaintCountList.toString());
         print(complaintCountList[0].toString());
         if(complaintCountList!=null){
           setState(() {
             isLoading=false;
           });
         }
       }
     }catch(e){
       //return complaintCountList;
     }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      isLoading=true;
      getComplaintCountList();
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: Colors.white),
          onPressed: (){
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => ComplaintScreen()),
            );
          },
        ),
        title: cusSearchBar,
        actions: <Widget>[
          IconButton(
            //tooltip: 'Search',
            //icon: const Icon(Icons.search),
            //Don't block the main thread
            onPressed: () {
              setState(() {
                if(this.cusIcon.icon==Icons.search){
                  this.cusIcon=Icon(Icons.cancel);
                  this.cusSearchBar=TextField(
                    textInputAction: TextInputAction.go,
                    decoration: InputDecoration(
                      border: InputBorder.none,
                      hintText: "Search here",
                    ),
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.0,
                    ),
                  );
                }else{
                  this.cusIcon =Icon(Icons.search);
                  this.cusSearchBar= Text("AppBar");
                }
              });
            },
            icon: cusIcon,
          ),
        ],
      ),
      body:SafeArea(
          child: Column(
              children: <Widget>[
                Container(
                  padding: const EdgeInsets.fromLTRB(0.0, 5.0, 5.0, 0.0),
                  height: MediaQuery.of(context).size.height / 15.2,
                  width: MediaQuery.of(context).size.width * 15.5,
                 // color: Colors.teal,
                  child: Text("Customer Name :",
                  style: TextStyle(
                    fontSize: 25.0,
                    fontWeight: FontWeight.bold,
                    color: Colors.teal

                  ),),
                ),
                Container(
                  padding: const EdgeInsets.fromLTRB(0.0, 5.0, 5.0, 0.0),
                  height: MediaQuery.of(context).size.height / 15.2,
                  width: MediaQuery.of(context).size.width * 15.5,
                //  color: Colors.teal,
                  child:  Text("Complaint List for Engineer",
                    style: TextStyle(
                      fontStyle: FontStyle.italic,
                      fontSize: 20.0,
                      color: Colors.teal,
                      fontWeight: FontWeight.bold
                    ),),
                ),
                Visibility(
                    maintainSize: true,
                    maintainAnimation: true,
                    maintainState: true,
                    visible: isLoading,
                    child: Container(
                      child: CircularProgressIndicator(),
                    )),
                Expanded(
                    child: ListView.builder(
                        itemCount: null==complaintCountList ? 0:complaintCountList.length,
                        itemBuilder: (BuildContext context, index){
                          ComplaintCountDetailModel countModel= complaintCountList[index];
                          return Container(
                            child: Padding(
                              padding: const EdgeInsets.only(top: 0.0, bottom: 0.0, left: 5.0, right: 5.0),
                              child: Card(
                                child: Container(
                                  padding: const EdgeInsets.only(top: 10.0, bottom: 10.0, left: 15.0, right: 15.0),
                                  child: Column(
                                    crossAxisAlignment: CrossAxisAlignment.stretch,
                                    mainAxisSize: MainAxisSize.max,
                                    //crossAxisAlignment: CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Text('IMEI :'+countModel.imei,
                                        style: TextStyle(
                                          //fontSize: 20.0,
                                          color: Colors.green,
                                          fontWeight: FontWeight.bold,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                      Text('Complaint ID :'+countModel.id,
                                        style: TextStyle(
                                          // fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                      Text('Serial No :'+countModel.serialNo,
                                        style: TextStyle(
                                          //fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                      Text('Customer Name :'+countModel.customerName,
                                        style: TextStyle(
                                          //fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                      Text('Mobile :'+countModel.mobile,
                                        style: TextStyle(
                                          //fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                      Text('Device Model :'+countModel.productId,
                                        style: TextStyle(
                                          // fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),

                                      Text('Vehicle No :'+countModel.vehicleNo,
                                        style: TextStyle(
                                          //fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                      Text('Complaint issue :'+countModel.fault,
                                        style: TextStyle(
                                          //fontSize: 20.0,
                                          color: Colors.black,
                                          // backgroundColor: Colors.green
                                        ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ),
                          );
                        }
                    ))
              ],
          ))
    );
  }
}
See Question&Answers more detail:<a href="https://stackoverflow.com/questions/62958249/how-to-fix-it-data-not-showing-in-lis

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a class to decode the json object. To do this easily paste your json here [https://app.quicktype.io/]

    List<DecoderClass> decoderClassFromJson(String str) => 

    List<DecoderClass>.from(json.decode(str).map((x) => DecoderClass.fromJson(x)));
    
    String decoderClassToJson(List<DecoderClass> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class DecoderClass {
        DecoderClass({
            this.customerName,
            this.mobile,
            this.productId,
            this.imei,
            this.serialNo,
            this.name,
            this.id,
            this.complainNo,
            this.complainId,
            this.fault,
            this.mobileNo,
            this.customerProductId,
            this.kycId,
            this.vehicleNo,
        });
    
        final String customerName;
        fina

l String mobile;
    final String productId;
    final String imei;
    final String serialNo;
    final String name;
    final String id;
    final String complainNo;
    final String complainId;
    final String fault;
    final String mobileNo;
    final String customerProductId;
    final dynamic kycId;
    final String vehicleNo;

    factory DecoderClass.fromJson(Map<String, dynamic> json) => DecoderClass(
        customerName: json["customer_name"],
        mobile: json["mobile"],
        productId: json["product_id"],
        imei: json["imei"],
        serialNo: json["serial_no"],
        name: json["name"],
        id: json["id"],
        complainNo: json["complain_no"],
        complainId: json["complain_id"],
        fault: json["fault"],
        mobileNo: json["mobile_no"],
        customerProductId: json["customer_product_id"],
        kycId: json["kyc_id"],
        vehicleNo: json["vehicle_no"],
    );

    Map<String, dynamic> toJson() => {
        "customer_name": customerName,
        "mobile": mobile,
        "product_id": productId,
        "imei": imei,
        "serial_no": serialNo,
        "name": name,
        "id": id,
        "complain_no": complainNo,
        "complain_id": complainId,
        "fault": fault,
        "mobile_no": mobileNo,
        "customer_product_id": customerProductId,
        "kyc_id": kycId,
        "vehicle_no": vehicleNo,
    };
}

Then pass this to a future Function

  Future<DecoderClass> _future;
  Future<DecoderClass> getData() async {
    final http.Response response = await http.get(
        'https://fasttracksoft.us/api_v2/device_installation/',
        );

    if (response.statusCode < 200 ||
        response.statusCode > 400 ||
        json == null) {
      throw new Exception("Error while fetching data");
    } else {
      return DecodeClass.fromJson(json.decode(response.body));
    }
  }
  @override
void initState() {
super.initState();
_future = getData();
}

use a future builder to receive this class

FutureBuilder<DecodeClass>(
    future: _future,
    builder: (context, snapshot) {
   return ListView.builder(
                  shrinkWrap: true,
                  itemBuilder: (context, i) {})})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...