Giter Club home page Giter Club logo

json_table's Introduction

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

Join us on Discord: https://discord.gg/7byeCn7MGF

πŸ’™ 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

json_table's People

Contributors

apgapg avatar imgbotapp avatar kechankrisna avatar singhtaranjeet avatar tamir198 avatar umaralam48 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

json_table's Issues

Pagination

As he user scrolls new to the bottom, it makes a http call, returns with the JSON and inserts them.

You want a PR ?

Nested field declaration references to wrong item

Nested field declaration does not work if child item has the same key name than its parent and parent key is introduced after child in JSON data.

final String json = '['
    '{ "sub": { "id": "A-sub" }, "id": "A" },'
    '{ "sub": { "id": "B-sub" }, "id": "B"  } '
    ']';
var columns = [
  JsonTableColumn("id", label: "Id"),
  JsonTableColumn("sub.id", label: "Sub Id")
];

Expected result:

Id   Sub Id
--   ------
A    A-sub 
A    B-sub 

Actual result:

Id   Sub Id
--   ------
A    A
A    B

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?

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.

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.

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?

Nested Data

I need support for displaying cells in cell.

Unable to get index on item click

There is no way to get index when user clicks on particular cell. Ideally we should at least get index so that we can play around more on existing data.

Type 'String' is not a subtype of type 'List<dynamic>'

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!

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...

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?

Add ability to create actions by double click or add a button column.

This is a great product.
But, It doesn't seem possible to use the table for a user to take an action based on a row selection.
Requested functionality.

  1. Ability to add a button to create actions from rows.
    or
  2. Ability to double click.
    Either 1 or 2, there is a need to define what the "index" for a row is to perform an action.

[Feature] Fetch Data on Page change

currently all data is fetched once and only trimmed list is shown based on paginationRowCount. What I need is a callback to be fired when next page button is pressed which will fetch data and then table is populated accordingly

Text Formatting for the Columns?

Excellent library. Thanks for the hard work!

I'm looking for a way to bold or italicize text in one of the columns. Am I missing something or is this not something that can be done at this time?

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.

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,
          )
        ],
      ),
      ),
    );
  }
}






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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.