Open In App

Insert Operation in DataTable in Flutter

Last Updated : 22 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Dart




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

  • main is a Principal Method called once the Program is Loaded.
  • Once the Program is Loaded, runApp will Run and Call the Class that we Created (InsertDataTable) to be Executed.
  • Before Creating InsertDataTable, we need to Create Classes that Creates Objects.
  • Creating Class Persons used to Create Person Objects.
  • Creating Information Variables ID, Age Integer Type, Name, and LastName as String.
  • Creating Constructor that set each Object Information, have same Class Name.
  • Now Start Creating the Main Class InsertDataTable Stateful due to State Change (New Data Fetch) and Creating its State.
  • Creating a List PersonsList that will hold Person Objects, containing 2 Objects of Person.
  • Creating a form that gonna Validates each TextField Value to Avoid saving Wrong or Null Data.
  • Due to Let User Insert his own Data, we need to Create TextEditingControllers to take Data.
  • Creating Variable LastID Initialized to 2 due to 2 Objects Created in PersonsList in the Beginning, once Insert we will increase the ID.
  • Once the page is Loaded, we’re initializing its State and Incrementing LastID to take number 3 now and Putting this Value into ID TextField Controller.
  • Create RefreshList that Refreshes DataTable Data taken from PersonsList and set a new ID to the TextField (Incremented On Insert Button Click After Validation).
  • Create a Validation Method that sees if validated. If Validated, then we’re taking each Value input by the User and Adding it to the List into Object.
  • After Adding the new Object Persons, Incrementing ID, Clear Field, and Refreshing the List to take on New Object.
  • Due to Age Being Integer Number we need to check the Value, we Create a Method that will Check it whenever int or not by returning true or false.
  • Body Contain ListView that allows scrolling and Avoids OverFlows List View take the Form known by its Key (Used to Validate Form (All TextFields)) taking Column putting Texts, TextFields and Button.
  • Each TextFormField has its Controller(Used to take Data inserted into) and a Validator that Check Data (Length 0 If no Characters were inserted, Check If int at Age) With The Error Message To Be Shown In Error Case.
  • SingleChildScrollView takes Single Child DataTable which takes Columns and Rows.
  • Columns taking DataColumns each Have Its Label, Finally rows Mapped by the List.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads