skip to Main Content

I’m having this super annoying issue of being unable to grab and display a table from my server hosted on PhpmyAdmin. (I’ve managed to grab the data and have it printed in the console, but now that I’m trying to display it in a table I can’t seem to get it working)

I’ve tried nulling my variables but I’m not really sure what the main culprit for this error is. Any help would be greatly appreciated.

Image of Error

data.dart File


class dataListing extends StatefulWidget {
  const dataListing({Key? key}) : super(key: key);

  @override
  State<dataListing> createState() => _dataListingState();
}

class _dataListingState extends State<dataListing> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class listingData{
  String? ListingID, listingName, listingDescription, address, suburbName, phoneNumber, openingHours, Email, Website;

  listingData({
    this.ListingID,
    this.listingName,
    this.listingDescription,
    this.address,
    this.suburbName,
    this.phoneNumber,
    this.openingHours,
    this.Email,
    this.Website,
  });
  //constructor
  List<listingData> datalist = [];
  factory listingData.fromJSON(Map<String, dynamic> json){
    return listingData(
      ListingID: json["ListingID"],
      listingName: json["listingName"],
      listingDescription: json["listingDescription"],
      address: json["address"],
      suburbName: json["suburbName"],
      phoneNumber: json["phoneNumber"],
      openingHours: json["openingHours"],
      Email: json["Email"],
      Website: json["Website"],
    );
  }
}

Directory.dart file

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:app/pages/data.dart';


class directoryPage extends StatefulWidget {
  @override
  State<directoryPage> createState() => _directoryPageState();
}

class _directoryPageState extends State<directoryPage> {

  // List serviceListing = [];
  //
  // getAllListing()async{
  //   String url = "URL HERE";
  //   var response = await http.get(Uri.parse(url));
  //   if (response.statusCode == 200){
  //     setState (() {
  //       serviceListing = json.decode(response.body);
  //     });
  //     print (serviceListing);
  //     return serviceListing;
  //   }
  // }
  bool error = false, dataloaded = false;
  var data;
  String dataurl = "URL HERE";


  @override
  void initState (){
    loaddata();
    super.initState();
    // getAllListing();
  }

  void loaddata() {
    Future.delayed(Duration.zero,() async {
      var res = await http.post(Uri.parse(dataurl));
      if (res.statusCode == 200) {
        setState(() {
          data = json.decode(res.body);
          dataloaded = true;

        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Directory'),
          centerTitle: true,
          elevation: 0,
          backgroundColor: Color(0xFFA30B32),
          //WSU Appbar Icon
          leading: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Image.asset("assets/wsulogo.png", scale: 8.0),
          ),
        ),
        body: Container(
          padding: EdgeInsets.all(15),
          child:dataloaded?datalist():
          Center(
            child:CircularProgressIndicator()
          ),
        )
    );
  }

  Widget datalist(){
    if(data["error"]) {
      return Text(data["errmsg"]);
    }else{
      List<listingData> datalist = List<listingData>.from(data["data"].map((i){
        return listingData.fromJSON(i);
      })
      );

      return Table( //if data is loaded then show table
        border: TableBorder.all(width:1, color:Colors.black45),
        children: datalist.map((listingdata){
          return TableRow( //return table row in every loop
              children: [
                //table cells inside table row
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.ListingID!)
                )
                ),
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.listingName!)
                )
                ),
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.listingDescription!)
                )
                ),
                TableCell(child: Padding(
                    padding: EdgeInsets.all(5),
                    child:Text(listingdata.address!)
                )
                ),
              ]
          );
        }).toList(),
      );
    }
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Looks like the issue was actually unrelated to the dart side of things, the php code wasn't properly structuring the data. Cannot have underscores or spaces.

    Correct-> $json["dballlisting"] = array (); (I renamed it to just "data" later)

    Incorrect->$json["db_all_listing"] = array ();


  2. The error seems to be originating from this line, the data['data'] is null which is expected to be an Array.

     List<listingData> datalist = List<listingData>.from(data["data"].map((i){
        return listingData.fromJSON(i);
      })
    

    You need to investigate your API call to make sure why it is happening. If the null value is expected then you need to add safeguards in your code to make sure it won’t break when it encounter such scenarios. You can add null safety checks for that one way to do it would be to

     List<listingData> datalist = List<listingData>.from((data["data"] ?? []).map((i){
        return listingData.fromJSON(i);
      })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search