Showing all columns in a table using Flutter

I'm currently developing a test application using Dart, which is designed to display and insert data into a database hosted on 000webhost.com.

In my app, I'm trying to display JSON data in a table where all the columns are contained within a single table. Unfortunately, my current code is creating separate tables for each column as seen here.

Below is the pertinent code snippet for my project:

class ViewData extends StatelessWidget{
  final String url = 'https://fourieristic-thousa.000webhostapp.com/index.code.php?action=view';

  Future<List<dynamic>> fetchData() async {
    var result = await http.get(
      Uri.parse(url),
    );

    print(json.decode(result.body));
    return json.decode(result.body);
  }

  String _test(dynamic test, int index){
    return test[index]['testColumn'];
  } 

  int _test2(dynamic test, int index){
    return json.decode(test[index]['testColumn2']);
  }

  int _id(dynamic test, int index){
    return json.decode(test[index]['ID']);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test data table'),
      ),
      body: Container(          
        child: FutureBuilder<List<dynamic>>(
          future: fetchData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if(snapshot.hasData){
              return ListView.builder(
                shrinkWrap: true,
                scrollDirection: Axis.vertical,
                itemCount: snapshot.data.length,
                itemBuilder: (BuildContext context, int index) {
                  return SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: DataTable(
                      columns: const <DataColumn>[
                        DataColumn(
                          label: Text(
                            'Test',
                            style: TextStyle(fontStyle: FontStyle.italic),
                          ),
                        ),
                        DataColumn(
                          label: Text(
                            'Test2',
                            style: TextStyle(fontStyle: FontStyle.italic),
                          ),
                        ),
                        DataColumn(
                          label: Text(
                            'Delete',
                            style: TextStyle(fontStyle: FontStyle.italic),
                          ),
                        ),
                      ],
                      rows: <DataRow>[
                        DataRow(
                          cells: <DataCell>[
                            DataCell(
                              Text(_test(snapshot.data, index).toString())
                            ),
                            DataCell(
                              Text(_test2(snapshot.data, index).toString())
                            ),
                            DataCell(
                              Text(_id(snapshot.data, index).toString())
                            )
                          ],
                        ),
                      ],
                    ),
                  );
                }
              );
            } else {
              return Center(child: CircularProgressIndicator());
            }
          },
        ),
      ),
    );
  }
}

I've searched online for a solution but haven't found any. I've also attempted to refactor my code to identify any issues, but I can't seem to find a way to resolve the problem of displaying data in individual tables.

Answer №1

It seems you have identified the problem with your code related to the ListView.builder. The unnecessary presence of the builder is causing issues. To resolve this, consider replacing the section between if(snapshot.hasData){ and return SingleChildScrollView( with the following:

List<DataRow> dataRows = [];
for (var index = 0; index < snapshot.data.length; index++) {
  dataRows.add(
    DataRow(
      cells: <DataCell>[
        DataCell(
          Text(_test(snapshot.data, index).toString())
        ),
        DataCell(
          Text(_test2(snapshot.data, index).toString())
        ),
        DataCell(
          Text(_id(snapshot.data, index).toString())
        ),
      ],
    ),
  );
}

Then, include the dataRows variable in the rows: field of your DataTable. Your structure should follow Scaffold -> Container -> FutureBuilder -> SingleChildScrollView -> DataTable. By doing this, you will avoid creating a new table for each entry.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Nested for loops are utilized in order to extract names from a JSON array

I am faced with a challenge involving a container that contains rows with 4 columns each. My goal is to retrieve the title of each column using ajax from a json array by utilizing a for loop. Initially, I successfully achieved this for one row using a sing ...

Using jQuery's .each() method to iterate over a JSON object may only display the

Running into some trouble with jQuery.each(). I'm pulling JSON data from another PHP file and trying to display a specific key value from it. This is the JavaScript code I have: <div class="row" id="fetchmember"> <script type="text/javasc ...

Looking to set up a web service that can handle incoming posts, but unsure about the best way to send a response back to jQuery

Good morning, I have a Go code that processes a JSON post request and performs certain actions. However, I am looking to send back either the result or a message to jQuery. package main import ( "fmt" "log" "net/http" "encoding/json" ...

Sorting through JSON data obtained through YQL

Hello coding enthusiasts, After facing challenges with CORS in an AJAX project, I discovered a workaround using YQL to successfully retrieve JSON data. Now, I'm looking for ways to access and organize this data according to my preferences. Below is t ...

Extract Data from JSON Array using Jquery

I am working with a JSON array retrieved from a web API, and I need to extract specific values from it. For instance, how can I retrieve all the rides in the first place and access rides[1]. UserID or Images? { "Status":1, "Rides& ...

The data retrieved by the $.getJSON method is not displaying as a line graph

I am currently dealing with two files searh_journal.php <script type="text/javascript"> function submitForm() { var form = document.myform; var dataString = $(form).serialize(); $.ajax({ type: 'POST', url: & ...

What is the purpose of the jQuery json.text method?

I am working on creating a connect page where users can view content from various social media platforms such as Twitter, Facebook, and YouTube. Currently, I am using the getJson function in jQuery to retrieve data from the Twitter API at . However, I have ...

Exploring the intricacies of XML embedded within JSON

Utilizing YQL for jQuery, I am able to successfully execute cross-domain REST requests. The JSON response contains the desired XML data as key-value pairs. The specific request being made is: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%2 ...

Error encountered while using Google Translate with XMLHttpRequest (Missing 'Access-Control-Allow-Origin' header)

Trying to access a page that utilizes Google Translate is resulting in the following error: XMLHttpRequest cannot load http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit. No 'Access-Control-Allow-Origin' heade ...

My Ajax request in Javascript is encountering failure in Chrome due to AdBlock. What alternatives can I consider in this situation

Attempting to execute an ajax function $.ajax({ url: etsyURL, dataType: 'jsonp', success: function(data) { However, when running it on Chrome in a live environment, it fails due to adblock. I rely on javascript/jquery as my primary tools. Any ...

methods for transforming JSON array output objects into individual non-array values

I'm facing an issue with a JSON result that contains latitude and longitude as an array like [13.0801721, 80.2838331]. I need help in converting this to comma-separated values without the array brackets, similar to 13.0801721, 80.2838331. This is my ...

JSONP is unable to utilize data fetched from an external API

I attempted to run an ajax request in order to retrieve a collection of items and display them through logging: https://i.stack.imgur.com/IK1qy.jpg However, when checking the console, the items appear as undefined: https://i.stack.imgur.com/3WOCa.jpg O ...

While iterating through a dynamically generated JSON data array, omitting the display of the ID (both title and value) is preferred

I am working with a JSON data Object and using $.each to dynamically retrieve the data. However, I want to display all values except for one which is the ID. How can I achieve this and prevent the ID from being displayed in the HTML structure? Thank you. ...

Leveraging JSON Data for Dynamic Web Content Display

I have been attempting to parse and display the JSON data that is returned from a REST API without any success. When tested locally, the API's URL structure is as follows: http://localhost/apiurl/get-data.php It returns data in the following format ...

What is the process of importing a JSON file in JavaScript?

Is there a way to import a JSON file into my HTML form by calling $(document).ready(function (){});? The properties defined in the JSON file are crucial for the functionality of my form. Can anyone guide me on how to achieve this? ...

Angular JavaScript Object Notation structure

I am a beginner in AngularJS and I'm attempting to create formatted JSON based on the values of table rows (tr) and cells (td). The table rows are generated automatically. When the form is submitted, I try to create the JSON values. Once the form is ...

Trouble with retrieving JSON data?

Struggling to access the JSON object issue: Received JSON Object: {"71":"Heart XXX","76":"No Heart YYYY"} I attempted to retrieve values for 71 and 72 individually but encountered compile time problems as: Syntax error on token ".71", delete this token ...

How to extract the value of a key from JSON using JavaScript

Need help with an API call to retrieve a list of subcategories? Here's an example of the JSON format: { "description": "Flower", "name": "Flower", "parent_id": "1" }, { "description": "Moon", "n ...

Convert HTML code into a customized JSON structure

Is there a way to convert HTML into a specific JSON object? For instance This HTML page is well-structured (originally in markdown). I am interested in creating a JSON version of the different sections present on the page. In this scenario, every "h2" s ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...