Home > OS >  How to retrieve JSON data from API and show in ListView.builder in Flutter?
How to retrieve JSON data from API and show in ListView.builder in Flutter?

Time:01-03

i`m trying to retrieve data from custom API and render it in ListView.builder inside FutureBuilder

API Function

late Future<List<customerProvider>> customer;

  List<customerProvider> _customerData = [];

  Future<List<customerProvider>> _getData() async{
    SharedPreferences prefs = await   SharedPreferences.getInstance();

    var orgID = await prefs.get('orgID') ?? null;
    

    var url = 'myURL';
    var response = await http.get(Uri.parse(url), headers : {
      "Authorization" : "bearer $secretKey"
    });

    var jsondata = json.decode(response.body);

    for(var vcl in jsondata){
     customerProvider cguy = customerProvider(
          vcl['orgID'],
          vcl['customersID'],
          vcl['customerName'],
          vcl['regNo'],
          vcl['eventName'],
          vcl['branchName'],
          vcl['branchID'],
          vcl['eventTime'],
          vcl['receivedDate'],
          vcl['motion'],
         );
      _Data.add(cguy);
    }
    setState(() {
      _customerData = jsondata;
    });
    return _customerData;
}


@override
  void initState() {
    // TODO: implement initState
    customer = _getData();
}

Class

{ `

(
  int? orgID;
  int? customersID;
  String? customerName;
  String? regNo;
  String? eventName;
  String? branchName;
  int? branchID;
  String? eventTime;
  String? receivedDate;
  );



 Provider(
     
      this.customersID,
      this.customerName,
      this.regNo,
      this.eventName,
      this.branchName,
      this.branchID,
      this.eventTime,
       this.motion,
      
      );

`

}

and here is the ListView.builder code inside FutureBuilder

FutureBuilder(
                                future: _getData(),
                                builder: (BuildContext context, AsyncSnapshot snapshot){

                                  return ListView.builder(
                                      itemCount: _customerData.length,
                                      itemBuilder: (BuildContext context, int index){
                                        var name = snapshot.data[index]['customerName'];
                                        return Column(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Stack(
                                              children: [
                                                Positioned(
                                                  child: Container(
                                                    height: 200,
                                                    width: size.width - 16,
                                                    decoration: BoxDecoration(
                                                        borderRadius: BorderRadius.circular(30),
                                                        boxShadow: [
                                                          BoxShadow(
                                                            color: Colors.grey,
                                                            blurRadius: 20,
                                                          ),
                                                        ]
                                                    ),
                                                    child: Image.asset(
                                                      "assets/images/space.jpeg",
                                                    )
                                                Positioned(
                                                  top: 15,
                                                  left: 10,
                                                  child: ListTile(
                                                    title: Text(
                                                      name,
                                                      style: TextStyle(
                                                        color: Colors.black,
                                                        fontWeight: FontWeight.bold,
                                                        fontSize: 30.30,
                                                      )
                                                    )
                                                  )
                                                ),

its not working correctly it is throwing NoSuchMethodError

The method '[]' was called on null.
Receiver: null
Tried calling [](0)

i tried changing it by creating List data = snapshot.data;

but than it was throwing Type cast or object? error when i changed it to object? or casted type it didn`t work either

i also check the api on Postman it is working fine there however the problem is in this code that i cant seem to find or solve

modelClass

Json response

{
"trackID": 4289,
"customersvehiclesID": 303,
"customerName": "Car",
"regNo": "XXYY2233",
"eventName": "Time Based",
"branchName": "",
"branchID": -1,
"latitude": 28.7083622222222,
"longitude": 77.0930844444444,
"altitude": 0,
"speed": 0,
"heading": 279,
"satellites": 0,
"location": "A-149, Vijay Vihar Phase II, Gopal Vihar, Sector 1, Rohini, Delhi, 110085, India",
"eventTime": "2021-11-27T09:40:53",
"receivedDate": "2021-11-27T09:40:53",
"tripMileage": 0,
"mileage": 8763462.66,
"mainBV": 0,
"backupBV": 0,
"rssi": null,
"motion": false,
"ignition": false

}

CodePudding user response:

1) Create a model class for your json resopnce

search for json to dart converter online and make a model class for the responce

2) Get your responce from API

Like this: -

Future<http.Response> getdata() {
  return http.get(Uri.parse('your http end point'));
}

3) Convert the response into a custom Dart object

return YourModelClassName.fromJson(jsonDecode(response.body));

4) Fetch the data on desired page with initState

Your class should be stateful class

somting like this: -

class _MyAppState extends State<MyApp> {
  late Future<YourModelClass> getdata;

  @override
  void initState() {
    super.initState();
    getdata = getdata();
  }
  // ···
}

5) Show your data with futurebuilder

Refer the code below

FutureBuilder<Album>(
  future: futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return 
        //Show your listview.builder here
    } else if (snapshot.hasError) {
      return Text('${snapshot.error}');
    }

    // By default, show a loading spinner.
    return const CircularProgressIndicator();
  },
)

5) Show your data in listview builder

Refer this code below

ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: entries.length,
  itemBuilder: (BuildContext context, int index) {
    return Container(
      //Here you can show your data with the help of the model class
      //You can you the 'index' to iterate throug every data
    );
  }
);

For more information refer these documents

Fetching data from internet

Listview Builder

Thank you

Update

Your model class will be: -

class Responce {
  int? trackID;
  int? customersvehiclesID;
  String? customerName;
  String? regNo;
  String? eventName;
  String? branchName;
  int? branchID;
  double? latitude;
  double? longitude;
  int? altitude;
  int? speed;
  int? heading;
  int? satellites;
  String? location;
  String? eventTime;
  String? receivedDate;
  int? tripMileage;
  double? mileage;
  int? mainBV;
  int? backupBV;
  Null? rssi;
  bool? motion;
  bool? ignition;

  Responce(
      {this.trackID,
      this.customersvehiclesID,
      this.customerName,
      this.regNo,
      this.eventName,
      this.branchName,
      this.branchID,
      this.latitude,
      this.longitude,
      this.altitude,
      this.speed,
      this.heading,
      this.satellites,
      this.location,
      this.eventTime,
      this.receivedDate,
      this.tripMileage,
      this.mileage,
      this.mainBV,
      this.backupBV,
      this.rssi,
      this.motion,
      this.ignition});

  Responce.fromJson(Map<String, dynamic> json) {
    trackID = json['trackID'];
    customersvehiclesID = json['customersvehiclesID'];
    customerName = json['customerName'];
    regNo = json['regNo'];
    eventName = json['eventName'];
    branchName = json['branchName'];
    branchID = json['branchID'];
    latitude = json['latitude'];
    longitude = json['longitude'];
    altitude = json['altitude'];
    speed = json['speed'];
    heading = json['heading'];
    satellites = json['satellites'];
    location = json['location'];
    eventTime = json['eventTime'];
    receivedDate = json['receivedDate'];
    tripMileage = json['tripMileage'];
    mileage = json['mileage'];
    mainBV = json['mainBV'];
    backupBV = json['backupBV'];
    rssi = json['rssi'];
    motion = json['motion'];
    ignition = json['ignition'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['trackID'] = this.trackID;
    data['customersvehiclesID'] = this.customersvehiclesID;
    data['customerName'] = this.customerName;
    data['regNo'] = this.regNo;
    data['eventName'] = this.eventName;
    data['branchName'] = this.branchName;
    data['branchID'] = this.branchID;
    data['latitude'] = this.latitude;
    data['longitude'] = this.longitude;
    data['altitude'] = this.altitude;
    data['speed'] = this.speed;
    data['heading'] = this.heading;
    data['satellites'] = this.satellites;
    data['location'] = this.location;
    data['eventTime'] = this.eventTime;
    data['receivedDate'] = this.receivedDate;
    data['tripMileage'] = this.tripMileage;
    data['mileage'] = this.mileage;
    data['mainBV'] = this.mainBV;
    data['backupBV'] = this.backupBV;
    data['rssi'] = this.rssi;
    data['motion'] = this.motion;
    data['ignition'] = this.ignition;
    return data;
  }
}
  • Related