Open In App

Insert Operation in DataTable in Flutter

A DataTable is a material design used to display data on a table or in rows and columns.  A Data table is used to show the data which have columns and rows as child, a Column is used to set the name of the column, and a Row is used to set the values of the columns. Any column in a DataTable can be sorted based on it in either an ascending or descending order. If sortColumnIndex is not null, the table will be sorted according to the values in the designated column. The sort order is determined by a boolean flag called sortAscending. In this article, we’ll see how we can create a UI for populating a DataTable.

For More, Refer to Dart Tutorial.



Creating Class Data

Used to Create Objects from Class to Avoid Duplication

For Example:

Product P1-new Product(1, 'PName');

Getting Started

First Creating Variable Data that we need by using var or Set Type(int, String)



var Var1, Var2;

Creating Constructor that Set Data and must have the same name as the Class,

ClassName( this.Var1, this.Var1,);

Syntax:

class ClassName {
    final int Col1;
    final String Col2;

    ClassName(this.Col1, this.Col2,);
}

Insert Code

Due to Data being fetched by the List, Insert will be a new Object to the List

ClassName Obj = ClassName(Col1);
List.add(Obj);

DataTable Code

DataTable(
    columns: [
        DataColumn(label: Text('Col1'),),
        rows: List.map((p) => DataRow(cells:[
            DataCell (Text(p.Col.toString()),),
        
]),
    ]
)

Code Example




import 'package:flutter/material.dart';
// Main method
void main() => runApp(InsertDataTable());
// Class person that initialize the data fields
class Persons {
  int ID, Age;
  String Name, LastName;
  Persons(this.ID, this.Name, this.LastName, this.Age);
}
 
class InsertDataTable extends StatefulWidget {
  @override
  _InsertDataTableState createState() => new _InsertDataTableState();
}
 
class _InsertDataTableState extends State<InsertDataTable> {
  List<Persons> PersonsLst = <Persons>[
    Persons(1, "Alex", "Anderson", 18),
    Persons(2, "John", "Anderson", 24),
  ];
 
  final formKey = new GlobalKey<FormState>();
  var ID_Controller = new TextEditingController();
  var Name_Controller = new TextEditingController();
  var LastName_Controller = new TextEditingController();
  var Age_Controller = new TextEditingController();
  var lastID = 2;
 
  @override
  // Method that call only once to initiate the default app.
  void initState() {
    super.initState();
    lastID++;
    ID_Controller.text = lastID.toString();
  }
  // Method that is used to refresh the UI and show the new inserted data.
  refreshList() {
    setState(() {
      ID_Controller.text = lastID.toString();
    });
  }
  // Method used to validate the user data
  validate() {
    if (formKey.currentState!.validate()) {
      formKey.currentState!.save();
      String ID = ID_Controller.text;
      String N = Name_Controller.text;
      String LN = LastName_Controller.text;
      String A = Age_Controller.text;
      Persons p = Persons(int.parse(ID), N, LN, int.parse(A));
      PersonsLst.add(p);
      lastID++;
      refreshList();
      Name_Controller.text = "";
      LastName_Controller.text = "";
      Age_Controller.text = "";
    }
  }
 // Method to check the value of age, age is int or not
  bool NotIntCheck(var N) {
    final V = int.tryParse(N);
 
    if (V == null) {
      print("Not Int");
      return true;
    } else {
      print("Int");
      return false;
    }
  }
 
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // MaterialApp with home as scaffold
      home: Scaffold(
        appBar: AppBar(
          title: Text("Insert Into  Data Table"),
        ),
        body: ListView(
          children: <Widget>[
            Form(
              key: formKey,
              child: Padding(
                padding: EdgeInsets.all(15.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text("Person ID:"),
                    TextField(
                      controller: ID_Controller,
                      enabled: false,
                    ),
                    Text("Person Name:"),
                    TextFormField(
                      controller: Name_Controller,
                      keyboardType: TextInputType.text,
                      validator: (val) =>
                          val?.length == 0 ? 'Enter Person Name' : null,
                    ),
                    Text("Person Last Name:"),
                    TextFormField(
                      controller: LastName_Controller,
                      keyboardType: TextInputType.text,
                      validator: (val) =>
                          val?.length == 0 ? 'Enter Person LastName' : null,
                    ),
                    Text("Person Age:"),
                    TextFormField(
                      controller: Age_Controller,
                      maxLength: 2,
                      keyboardType: TextInputType.number,
                      validator: (val) => NotIntCheck(val)
                          ? 'Enter Person Age,Number Required'
                          : null,
                    ),
                    SizedBox(
                      width: double.infinity,
                      child: MaterialButton(
                        color: Colors.green,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(30.0),
                        ),
                        child: Text(
                          'Insert Person',
                          style: TextStyle(
                            color: Colors.white,
                          ),
                        ),
                        onPressed: validate,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child: DataTable(
                columns: [
                  DataColumn(
                    label: Text("ID"),
                  ),
                  DataColumn(
                    label: Text("Name"),
                  ),
                  DataColumn(
                    label: Text("LastName"),
                  ),
                  DataColumn(
                    label: Text("Age"),
                  ),
                ],
                rows: PersonsLst.map(
                  (p) => DataRow(cells: [
                    DataCell(
                      Text(p.ID.toString()),
                    ),
                    DataCell(
                      Text(p.Name),
                    ),
                    DataCell(
                      Text(p.LastName),
                    ),
                    DataCell(
                      Text(p.Age.toString()),
                    ),
                  ]),
                ).toList(),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Output UI:

 

Code Explanation

Output:


Article Tags :