Flutter package: Json Table Widget to create table from json array

Overview

Json Table Widget GitHub stars Twitter Follow GitHub last commit Website shields.ioOpen Source Love

πŸ’™ Proudly Sponsored by FieldAssist


Request a Demo

This Flutter package provides a Json Table Widget for directly showing table from a json(Map). Supports Column toggle also.

Live Demo: https://apgapg.github.io/json_table/

Live Data Testing: https://apgapg.github.io/json_table/#/customData

Features

  • The table constructed isn't the flutter's native DataTable.
  • The table is manually coded hence serves a great learning purpose on how to create simple tables manually in flutter
  • Supports vertical & horizontal scroll
  • Supports custom columns includes default value, column name, value builder
  • Supports nested data showing
  • Supports pagination
  • Supports row select color, callback

JsonTable JsonTable JsonTable JsonTable JsonTable JsonTable

πŸ’» Installation

In the dependencies: section of your pubspec.yaml, add the following line:

Version

dependencies:
  json_table: <latest version>

❔ Usage

Import this class

import 'package:json_table/json_table.dart';

- Vanilla Implementation

//Decode your json string
final String jsonSample='[{"id":1},{"id":2}]';
var json = jsonDecode(jsonSample);

//Simply pass this json to JsonTable
child: JsonTable(json)

- Implementation with HEADER and CELL widget builders

JsonTable(
   json,
   tableHeaderBuilder: (String header) {
     return Container(
       padding: EdgeInsets.symmetric(horizontal: 8.0, vertical: 4.0),
       decoration: BoxDecoration(border: Border.all(width: 0.5),color: Colors.grey[300]),
       child: Text(
         header,
         textAlign: TextAlign.center,
         style: Theme.of(context).textTheme.display1.copyWith(fontWeight: FontWeight.w700, fontSize: 14.0,color: Colors.black87),
       ),
     );
   },
   tableCellBuilder: (value) {
     return Container(
       padding: EdgeInsets.symmetric(horizontal: 4.0, vertical: 2.0),
       decoration: BoxDecoration(border: Border.all(width: 0.5, color: Colors.grey.withOpacity(0.5))),
       child: Text(
         value,
         textAlign: TextAlign.center,
         style: Theme.of(context).textTheme.display1.copyWith(fontSize: 14.0, color: Colors.grey[900]),
       ),
     );
   },
 )

Head over to example code: simple_table.dart

- Implementation with custom COLUMNS list

  • Pass custom column list to control what columns are displayed in table
  • The list item must be constructed using JsonTableColumn class
  • JsonTableColumn provides 4 parameters, namely,
JsonTableColumn("age", label: "Eligible to Vote", valueBuilder: eligibleToVote, defaultValue:"NA")
  • First parameter is the field/key to pick from the data
  • label: The column header label to be displayed
  • defaultValue: To be used when data or key is null
  • valueBuilder: To get the formatted value like date etc

JsonTable

//Decode your json string
final String jsonSample='[{"name":"Ram","email":"[email protected]","age":23,"DOB":"1990-12-01"},'
                              '{"name":"Shyam","email":"[email protected]","age":18,"DOB":"1995-07-01"},'
                              '{"name":"John","email":"[email protected]","age":10,"DOB":"2000-02-24"},'
                              '{"name":"Ram","age":12,"DOB":"2000-02-01"}]';
var json = jsonDecode(jsonSample);
//Create your column list
var columns = [
      JsonTableColumn("name", label: "Name"),
      JsonTableColumn("age", label: "Age"),
      JsonTableColumn("DOB", label: "Date of Birth", valueBuilder: formatDOB),
      JsonTableColumn("age", label: "Eligible to Vote", valueBuilder: eligibleToVote),
      JsonTableColumn("email", label: "E-mail", defaultValue: "NA"),
    ];
//Simply pass this column list to JsonTable
child: JsonTable(json,columns: columns)

//Example of valueBuilder
String eligibleToVote(value) {
    if (value >= 18) {
      return "Yes";
    } else
      return "No";
}

Head over to example code: custom_column_table.dart

- Implementation with nested data list

Suppose your json object has nested data like email as shown below:

{"name":"Ram","email":{"1":"[email protected]"},"age":23,"DOB":"1990-12-01"}
  • Just use email.1 instead of email as key
JsonTableColumn("email.1", label: "Email", defaultValue:"NA")

JsonTable

//Decode your json string
final String jsonSample='[{"name":"Ram","email":{"1":"[email protected]"},"age":23,"DOB":"1990-12-01"},'
                               '{"name":"Shyam","email":{"1":"[email protected]"},"age":18,"DOB":"1995-07-01"},'
                               '{"name":"John","email":{"1":"[email protected]"},"age":10,"DOB":"2000-02-24"}]';
var json = jsonDecode(jsonSample);
//Create your column list
var columns = [
      JsonTableColumn("name", label: "Name"),
      JsonTableColumn("age", label: "Age"),
      JsonTableColumn("DOB", label: "Date of Birth", valueBuilder: formatDOB),
      JsonTableColumn("age", label: "Eligible to Vote", valueBuilder: eligibleToVote),
      JsonTableColumn("email.1", label: "E-mail", defaultValue: "NA"),
    ];
//Simply pass this column list to JsonTable
child: JsonTable(json,columns: columns)

Head over to example code: custom_column_nested_table.dart

Column toggle

Option for toggling column(s) also. User can customise which columns are to be shown

 showColumnToggle: true

JsonTable

Row Highlighting

Add row highlighting with custom color support

JsonTable

allowRowHighlight: true,
rowHighlightColor: Colors.yellow[500].withOpacity(0.7),

Row Select Callback

Get the index and data map of a particular selected row. Note index might return incorrect value in case of pagination

onRowSelect: (index, map) {
    print(index);
    print(map);
  },

Pagination

Just provide an int value to paginationRowCount parameter

JsonTable

paginationRowCount: 4,

TODO

  • Custom header list parameter. This will help to show only those keys as mentioned in header list
  • Add support for keys missing in json object
  • Add support for auto formatting of date
  • Extracting column headers logic must be change. Not to depend on first object
  • Nested data showing support
  • Row highlight support
  • Row select callback
  • Wrap filters in expansion tile
  • Pagination support
  • Add option to change header row to vertical row on left

⭐ My Flutter Packages

  • pie_chart GitHub stars Flutter Pie Chart with cool animation.
  • avatar_glow GitHub stars Flutter Avatar Glow Widget with glowing animation.
  • search_widget GitHub stars Flutter Search Widget for selecting an option from list.
  • animating_location_pin GitHub stars Flutter Animating Location Pin Widget providing Animating Location Pin Widget which can be used while fetching device location.

⭐ My Flutter Apps

πŸ‘ Contribution

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -m 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request
Comments
  • I can't able to load json data from url

    I can't able to load json data from url

    can you please help me to load data from api request i tried many but i can't able to load data from dynamic data please help me waiting for your fast response...

    opened by parthvirani95 7
  • Exception:  ' " while response data from stream">

    Exception: "type 'String' is not a subtype of type 'List' " while response data from stream

    Screen Shot 2019-11-24 at 2 05 43 PM The exception logged while call JsonTable(json) inside StreamBuilder. it is run well while stand alone (the commented code). It make me 4 hours, and I am stuck right now.
    opened by ntancnit 5
  • http request sample needed

    http request sample needed

    Can someone provide me sample of how to get jason from web then display please.

    the widget is really useful i will use it in my project but I was tried to show json from the web but it failed, need a good short sample thank you.

    opened by singnoi 3
  • When we have nested json data then json converted to String

    When we have nested json data then json converted to String

    String getFormattedValue(dynamic value) { if (value == null) return column?.defaultValue ?? ''; if (column?.valueBuilder != null) { return column.valueBuilder(value); } return value.toString(); }

    in Code you have return value.toString(); this cause error but if i am using only return value can work perfect for me for nested json please fix this.

    opened by shubh-151410 3
  • Different table height when korean was inserted.

    Different table height when korean was inserted.

    캑처

    Hi guys. Today I used this library for make a table from json file.

    But I have some problems like this.

    There was okay If there is only numbers and english. But if korean is inserted, its height change different.

    How can I fix it?

    opened by herbcookey 2
  • RangeError (index): Invalid value: Only valid value is 0: 4

    RangeError (index): Invalid value: Only valid value is 0: 4

    Hi guys! How are you?

    The component is great and works perfect. But i'm having trouble now:

    I am showing a json on the screen and when wanting with a button to load another of smaller size, this error appears:

    RangeError (index): Invalid value: Only valid value is 0: 4 The relevant error-causing widget was JsonTable

    But if with the button I load another one of greater size the problem does not happen

    Could you help me please?

    opened by dukenebur 2
  • importing local json file to use in json table widget

    importing local json file to use in json table widget

    i am getting an issue: 'Future' is not a subtyoe of type 'List

    code :

    import 'dart:convert';
    
    import 'package:flutter/material.dart';
    import 'package:json_table/json_table.dart';
    
    class SewingHourlyProduction extends StatefulWidget {
      @override
      _SewingHourlyProductionState createState() => _SewingHourlyProductionState();
    }
    class _SewingHourlyProductionState extends State<SewingHourlyProduction> {
      Future<dynamic> loadValue () async {    
        String jsonData = await DefaultAssetBundle.of(context).loadString("assets/HPR.json"); 
        final jsonResult = jsonDecode(jsonData);
        print(jsonResult);
        return jsonResult;
      }
      @override
      Widget build(BuildContext context) {
        dynamic json = loadValue();
        return Scaffold(
          appBar: AppBar(title: Text('Hourly Production Report')),
          body: Container(
          child: Column(
            children: <Widget>[
              JsonTable(
                json,
                showColumnToggle: true,
                tableHeaderBuilder: (String header) {
                          return Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 8.0, vertical: 4.0),
                            decoration: BoxDecoration(
                                border: Border.all(width: 0.5),
                                color: Colors.grey[300]),
                            child: Text(
                              header,
                              textAlign: TextAlign.center,
                              style: Theme.of(context).textTheme.display1.copyWith(
                                  fontWeight: FontWeight.w700,
                                  fontSize: 14.0,
                                  color: Colors.black87),
                            ),
                          );
                        },
                        tableCellBuilder: (value) {
                          return Container(
                            padding: EdgeInsets.symmetric(
                                horizontal: 4.0, vertical: 2.0),
                            decoration: BoxDecoration(
                                border: Border.all(
                                    width: 0.5,
                                    color: Colors.grey.withOpacity(0.5))),
                            child: Text(
                              value,
                              textAlign: TextAlign.center,
                              style: Theme.of(context).textTheme.display1.copyWith(
                                  fontSize: 14.0, color: Colors.grey[900]),
                            ),
                          );
                        },
                        allowRowHighlight: true,
                        rowHighlightColor: Colors.yellow[500].withOpacity(0.7),
                        paginationRowCount: 4,
              )
            ],
          ),
          ),
        );
      }
    }
    
    
    
    
    
    
    
    opened by sambitraze 2
  • Showing array from array: Error

    Showing array from array: Error

    The error say:

    Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'

    My Json :

    "listaGobernanciaPorPiso": [ { "piso": 1, "habitacionesEnPiso": 6, "pasajerosEnPiso": 8, "detalleHabitacion": [ { "habitacion": 2, "pasajerosEnHabitacion": 2, "titular": "JORGE ENRIQUE FERNANDEZ ", "fechaIn": "17-06-2019", "fechaOut": "21-06-2019" } ] }, { "piso": 2, "habitacionesEnPiso": 1, "pasajerosEnPiso": 1, "detalleHabitacion": [ { "habitacion": 10, "pasajerosEnHabitacion": 1, "titular": "ROBERT TAYLOR ", "fechaIn": "18-06-2019", "fechaOut": "23-06-2019" } ] } ],

    So, this is possible with this library? or the problem is when extract the json?

    jsonResponse['gobernanciaResponse']['listaGobernanciaPorPiso']['detalleHabitacion']

    And when extract only this:

    jsonResponse['gobernanciaResponse']['listaGobernanciaPorPiso']

    No showing error, but all data is empty. Screen Shot 2019-09-09 at 10 29 41 PM

    Can help me?

    opened by xhidnoda 2
  • Type 'String' is not a subtype of type 'List<dynamic>'

    Type 'String' is not a subtype of type 'List'

    Hello...thanks for the library!!

    But i have a problem with my own json. I pass this json to JsonTable as parameter and i use this columns:

    widget.columns = [ JsonTableColumn("titularNombres", label: "Titular Nombre"), JsonTableColumn("titularApellidos", label: "Titular Apellido"), JsonTableColumn("usuarioReserva", label: "Usuario Reserva", defaultValue: "NA"), ];

    JSON:

    { "estado": "OK", "razon": "TRANSACCION CORRECTA", "response": { "data": { "consultaReservaResponse": [ { "numeroReserva": 5575, "titularApellidos": "XXXX", "titularNombres": "XXXX", "fechaDesdeReserva": "02-06-2019", "estadoReserva": "R", "paisOrigenTitular": "PARAGUAY", "formaDePago": "EFECTIVO", "fechaHastaReserva": "02-06-2019", "solicitanteReserva": "XXXX", "formaDeReserva": "Via Email", "usuarioReserva": "XXXX", "nroConfirmacionReserva": 5086 }, { "numeroReserva": 5528, "titularApellidos": "XXXX", "titularNombres": "XXXX", "fechaDesdeReserva": "02-06-2019", "estadoReserva": "R", "paisOrigenTitular": "IRLANDA", "formaDePago": "EFECTIVO", "fechaHastaReserva": "12-06-2019", "solicitanteReserva": "XXXX", "formaDeReserva": "Via Email", "usuarioReserva": "XXXXX", "nroConfirmacionReserva": 5041 } ] } }, "token": "XXXXX", "ts": "2019-08-14 13:37:24" }

    And i get this error: Type 'String' is not a subtype of type 'List'

    Can anyone help me? Thaks!

    opened by xhidnoda 2
  • [ImgBot] Optimize images

    [ImgBot] Optimize images

    Beep boop. Your images are optimized!

    Your image file size has been reduced by 31% πŸŽ‰

    Details

    | File | Before | After | Percent reduction | |:--|:--|:--|:--| | /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png | 14.45kb | 9.69kb | 32.93% | | /src/ss3.png | 175.97kb | 119.47kb | 32.11% | | /src/ss4.png | 243.34kb | 165.71kb | 31.90% | | /src/ss6.png | 246.59kb | 168.16kb | 31.81% | | /src/ss5.png | 261.02kb | 178.52kb | 31.61% | | /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png | 45.89kb | 31.58kb | 31.18% | | /src/ss1.png | 174.66kb | 121.79kb | 30.27% | | /src/ss2.png | 229.23kb | 162.36kb | 29.17% | | /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png | 1.40kb | 1.00kb | 28.62% | | /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png | 5.79kb | 4.27kb | 26.23% | | /example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png | 3.20kb | 2.60kb | 18.77% | | /example/ios/Runner/Assets.xcassets/AppIcon.appiconset/[email protected] | 10.85kb | 10.68kb | 1.62% | | | | | | | Total : | 1,412.40kb | 975.84kb | 30.91% |


    πŸ“docs | :octocat: repo | πŸ™‹issues | πŸ…swag | πŸͺmarketplace

    opened by imgbot[bot] 0
  • Feature: Select first row on load

    Feature: Select first row on load

    A nice feature would be be able to select an active row by index on load. The table should then show the row as marked and the onRowSelect should fire with the selected row.

    good first issue 
    opened by mnn-softjoy 3
  • The provided ScrollController is currently attached to more than one ScrollPosition.

    The provided ScrollController is currently attached to more than one ScrollPosition.

    In my page I have a row with containing two widgets. One table widget and one form widget. The form widget has a ListView to enable scrolling in the form. primary is set to false.

    The other Widget is a ContainedBox with a JsonTable as child. Everything works perfectly. I only got the exception

    ════════ Exception caught by animation library ═════════════════════════════════ The provided ScrollController is currently attached to more than one ScrollPosition. ════════════════════════════════════════════════════════════════════════════════

    in the debug console when I scroll in the table. Removing the table removes the exception.

    opened by mnn-softjoy 0
  • How to know which cell belongs to which column

    How to know which cell belongs to which column

    Example I have a column for column name: "color" which has the hex color string and I want that if the cell is in column "color" then I show the color tile in it.

    opened by Tushargupta9800 2
Owner
Ayush P Gupta
Flutter || Node || Vue || Typescript
Ayush P Gupta
This library allows you to create editable tables and spreadsheets with ease, either by providing initial row and column count to display an empty table or use it with predefined rows and column data sets.

Editable ⚑️ A highly customizable, editable table package for Flutter projects. Specs This package allows you to create editable tables and spreadshee

Godwin Asuquo 94 Dec 7, 2022
Fluter-json - App Demonstrating JSON Data Parsing with various flutter widgets

users_list Flutter App to Demonstrate JSON Parsing Getting Started This project is a starting point for a Flutter application. A few resources to get

Khurram Rizvi 5 Jul 10, 2021
Json editor - A json editor on flutter

Features Support add comment; Support show errors for invalid json text; Pretty

Chan Young 12 Nov 18, 2022
State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

State Persistence Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications dat

Flutter Community 70 Sep 28, 2022
Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON.

JSON to Dart Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON. This library is designed to ge

Javier Lecuona 1.2k Dec 25, 2022
A JSON serialize class to convert 'to' and 'from' JSON format Enums, DateTime and any of your own classes.

A JSON serialize class to convert 'to' and 'from' JSON format Enums, DateTime and any of your own classes. Introduction Jsonize solves the problem of

null 2 Nov 17, 2022
Flutter table with dio and provider - A flutter Application created for Portfolio Page

My LinkedIn https://www.linkedin.com/in/marcelo-augusto-a60b6821a/ Intro This is

Marcelo Augusto 1 Jan 18, 2022
A periodic table app with 3D view of the elements built using flutter.

A flutter app which takes you on a 3d visualisation of the 118 elements of the periodic table. promo.mp4 Tech Stack Deployed using How it all began It

Shanwill Pinto 48 Nov 16, 2022
CRUD Table Flutter consists of a Lazy loading function, resizable columns, and integrated CRUD Form.

CRUD Table Flutter CRUD Table Flutter is a package for crating CURD-UI for your entity/object/class easily. It consists of a Lazy loading function, re

null 10 Dec 31, 2022
A iOS like table view including section, row, section header and divider

flutter_section_table_view A iOS like table view including section, row, section header and divider Support both Android and iOS Support drop-down ref

刘彦博 73 Nov 4, 2022
Time Table application specifically aimed towards students. Share Time-Tables. Suggest Updates.

Time-Table-App Time Table application specifically aimed towards students. Tech stack Project is created by: Flutter: 2.8.1 Dart: 2.15.1 Planned Featu

PEC ACM CSS 8 Oct 7, 2022
MindInventory 15 Sep 5, 2022
A flutter package which will help you to create a draggable widget that can be dragged around the screen.

A flutter package which will help you to create a draggable widget that can be dragged around the screen. Demo Features ?? Manually Control the positi

Adar 31 Aug 10, 2022
This package adds CustomRefreshIndicator widget that allows you to create whatever indicator you want.

Custom Refresh Indicator A flutter package that allows you to easily create a custom refresh indicator widget. TLDR; ONLINE DEMO! QUICK START CustomRe

Kamil Klyta 315 Dec 16, 2022
Widget to count the amount of nested widget tree, useful in the dynamic construction of the interface when it is important to know the depth of widget.

widget_tree_depth_counter Widget Tree Depth Counter WidgetTreeDepthCounter is a simple widget to count the amount of nested widget tree, useful in the

Riccardo Cucia 4 Aug 1, 2022
This is a Flutter plugin that takes a JSON string and converts it onto a customizable Flutter Widget.

Colored JSON Convert JSON string into customizable widget. Getting Started ColoredJson is a stateless widget that produces a structured view of JSON s

null 4 May 20, 2022
Displaying json models in a Flutter widget

Displaying json models in a Flutter widget ?? Cool solution for viewing models in debug working Getting Started Add dependency dependencies: flutter

Stanislav Ilin 54 Dec 19, 2022
A highly customizable Flutter widget to render and interact with JSON objects.

The spreadsheet with superpowers ✨ ! JSON Data Explorer A highly customizable widget to render and interact with JSON objects. Features Expand and col

rows 15 Dec 21, 2022
Flutter shareable package of object-oriented classes for local caching of user data in json

json_cache Json Cache is an object-oriented package to serve as a layer on top of local storage packages - packages that persist data locally on the u

Dartoos 10 Dec 19, 2022