Add item to list dart

void insert()

Inserts element at position index in this list.

This increases the length of the list by one and shifts all objects at or after the index towards the end of the list.

The list must be growable. The index value must be non-negative and no greater than length.

final numbers = <int>[1, 2, 3, 4]; const index = 2; numbers.insert(index, 10); print(numbers); // [1, 2, 10, 3, 4]
void insert(int index, E element);

Adding items to a list in Flutter is not difficult. Although we need to understand one key concept.

The user must have an interface through which she can send the inputs to the server.

Either we can store the data in a database. Or, we can just display them as we keep adding them.

Moreover, we can also delete any item based on the unique ID.

Anyway, in this segment we’re going to continue the expense list flutter app. And we just keep building it.

If you’ve not read the previous two posts, please go through them, so that you may have an idea what’s going on.

Until now, we have learned how to display a list using a ListView. However, there was no question of managing state. As we’ve just displayed a few items.

And, we’ve added them manually. In addition to displaying them, our main focus was the design part. The frontend of Flutter.

How do you create a dynamic list in Flutter?

We’re going to create a dynamic list, and for that, we need to maintain state.

Therefore, we have to convert the main thread to stateful widget. The stateless widget would only work, if we handled the state either with the provider, or the Riverpod package.

However, this is a small app. Hence, we can manage with the Flutter’s in-built stateful widget.

Moreover, we’re going to add items to the list dynamically. So we don’t need the manually added items anymore.

When we open the app, it looks like this:

How to create dynamic list in flutter

Now, we’re going to add Fruits as our title and the amount is 300.00.

To input the data, we need two text fields first. Next, we need a button to submit that data, so it gets added to the list.

At the same time, we need to add another functionality. We want to delete any item from the list as well.

After submitting the data the list gets updated like this:

Adding items to a list in flutter

How do I use ListView in Flutter?

As we can see in the above image, our app does look perfect. We can see the soft keys, as well.

Because, our main widget uses ListView, it doesn’t break. We can scroll the app endlessly.

We’ve started coding the app just like the following:

import 'package:flutter/material.dart'; import '../models/expense_list.dart'; import '../controllers/display_task_and_data.dart'; import '../controllers/display_amount.dart'; class ExpenseFirstPage extends StatefulWidget { ExpenseFirstPage({Key key}) : super(key: key); @override _ExpenseFirstPageState createState() => _ExpenseFirstPageState(); } class _ExpenseFirstPageState extends State<ExpenseFirstPage> { ... the code is incomplete...

Next, we need to declare the type of the List. In addition, we’ve created a List class in our model folder.

By the way, for the full code snippet, please visit my GitHub repository.

We also need two methods – one for adding the items and another for deleting a particular item.

final List<ExpenseList> expenseList = []; void addTaskAndAmount(String title, double amount) { final expense = ExpenseList( id: DateTime.now().toString(), title: title, amount: amount, date: DateTime.now(), ); setState(() { expenseList.add(expense); }); } void deleteExpenseList(String id) { setState(() { expenseList.removeWhere((element) => element.id == id); }); }

For adding the items to the expense list app, we pass two parameters. One is a string data type and the other is a double data type.

Next we need two text editing controller that flutter supplies.

final titleController = TextEditingController(); final amountController = TextEditingController();

How do you add items to the List?

We’re going to use these text editing controllers inside the Text field widget. And every action takes place inside the build method.

override Widget build(BuildContext context) { return Center( child: ListView( padding: EdgeInsets.all(8), children: [ Container( child: Card( child: Text('Chart'), elevation: 10, ), ), Container( child: Card( elevation: 10, child: Column( children: [ TextField( controller: titleController, ), TextField( controller: amountController, ), TextButton( onPressed: () { addTaskAndAmount( titleController.text, double.parse(amountController.text), ); }, child: Text( 'SUBMIT', style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, ), ), ), ], ), ), ), Container( child: Column( children: expenseList.map((e) { return Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Card( elevation: 10, child: Row( children: [ displayAmount(e), displayTaskAndDate(e), ], ), ), TextButton( onPressed: () { deleteExpenseList(e.id); }, child: Text( 'DELETE', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25, ), ), ), ], ); }).toList(), ), ), ], ), ); } }

Not only we’re going to add items to the list, but at the same time, we’re going to display them. Furthermore, we should keep a DELETE button with each item, as well.

Granted, we could have used Icon of the deletion. But, instead we’ve chosen the Text Button widget.

For managing state and handling the two functions, these two code snippets are important.

TextField( controller: titleController, ), TextField( controller: amountController, ), TextButton( onPressed: () { addTaskAndAmount( titleController.text, double.parse(amountController.text), ); }, child: Text( 'SUBMIT', style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, ), ), ), .... TextButton( onPressed: () { deleteExpenseList(e.id); }, child: Text( 'DELETE', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25, ), ), ),

The above section is responsible for adding items to the list. So it looks like this after adding two items.

Dynamically adding items to the List flutter

However, at the same time, we want to check whether our delete buttons are working as well.

The second part of the above code snippet points to that.

Therefore, if want to delete the first item, we can now easily do that.

Deleting any item of the list in flutter

We’ve successfully deleted the first item. Moreover, now we can again add items to the same list.

What Next?

Books at Leanpub
Books in Apress
My books at Amazon
GitHub repository
Technical blog
Twitter

Photo by Jinen Shah on Unsplash

In this example, we are going to show you the easiest way to add (push) and remove (pop) item or element in the list array. You will learn to remove specific string of modal object from list. See the example below:

How to Add (Push) Strings in Array List:

List<String> strings = []; strings.add("Nepal"); strings.add("India"); strings.add("United State of America"); strings.add("China"); strings.add("Canada"); strings.removeWhere((str){ return str == "Nepal"; }); //go through the loop and match content to delete from list

You can do similarly for other data type.

Modal Class:

class Person{ //modal class for Person object String id, name, phone, address; Person({required this.id, required this.name, required this.phone, required this.address}); } List<Person> persons= []; persons.add(Person(id:"1", name:"Hari Prasad Chaudhary", phone:"9812122233", address:"Kathmandu, Nepal")); persons.add(Person(id:"2", name:"Krishna Karki", phone:"9812122244", address:"Pokhara, Nepal")); persons.removeWhere((element){ return element.id == personone.id; }); //go through the loop and match content to delete from list

or by matching string:

persons.removeWhere((element){ return element.name == "hari prasad chaudhary"; }); //go through the loop and match content to delete from list

Full Code Example:

import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: MyApp(), ) ); } class MyApp extends StatefulWidget{ @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { List<Person> persons= []; @override void initState() { //adding item to list, you can add using json from network persons.add(Person(id:"1", name:"Hari Prasad Chaudhary", phone:"9812122233", address:"Kathmandu, Nepal")); persons.add(Person(id:"2", name:"Krishna Karki", phone:"9812122244", address:"Pokhara, Nepal")); persons.add(Person(id:"3", name:"Ujjwal Joshi", phone:"98121224444", address:"Bangalore, India")); persons.add(Person(id:"4", name:"Samir Hussain Khan", phone:"9812122255", address:"Karachi, Pakistan")); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text("Add And Delete List"), backgroundColor: Colors.redAccent, ), body: SingleChildScrollView( child: Container( padding: EdgeInsets.all(10), child: Column( children: persons.map((personone){ return Container( child: Card( child:ListTile( title: Text(personone.name), subtitle: Text(personone.phone + "\n" + personone.address), trailing: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.redAccent ), child: Icon(Icons.delete), onPressed: (){ //delete action for this button persons.removeWhere((element){ return element.id == personone.id; }); //go through the loop and match content to delete from list setState(() { //refresh UI after deleting element from list }); }, ), ), ), ); }).toList(), ), ), ) ); } } class Person{ //modal class for Person object String id, name, phone, address; Person({required this.id, required this.name, required this.phone, required this.address}); }

Output Screenshot:

In this way, you can add or remove item from Modal list array using Dart in Flutter App.

Video liên quan

Chủ đề