Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Select Item Of List In Flutter

In some cases, we need to choose more than one thing from the list and play out some action i.e delete the selected item and so forth.

This blog will explore the Select Item Of List In Flutter. We perceive how to execute a demo program. We will learn how to select an item from the list in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to select the items of the list in a flutter and shows how a select item will work in your flutter applications. We will show the user long press the items, then the items will be selected or deselected. Also, the user selected/ de-selected all items with a single click. It will be shown on your devices.

Demo Module ::


Code Implement:

You need to implement it in your code respectively:

Create a new dart file called data.dart inside the lib folder.

First of all, we need some data to make the app look like a real app and take some real scenarios. Create a data.dart file.

class MyData {
static List<Map> data = [
{
"id": 1,
"name": "Rahul",
"email": "rahul240@gamil.com",
"address": "120 kanpur India"
},
{
"id": 2,
"name": "Yogesh",
"email": "yogi@gamil.com",
"address": "1A/24 Delhi India"
},
{
"id": 3,
"name": "Rakhi",
"email": "rakhi@inc.com",
"address": "221 Bihar India"
},
{
"id": 4,
"name": "Thomas",
"email": "roy@yahoo.com",
"address": "406 Mumbai India"
},
{
"id": 5,
"name": "Manoj",
"email": "mnaoj24@aeo.com",
"address": "54 Noida Dadri"
},
{
"id": 6,
"name": "Mohit",
"email": "mohit5@gamil.com",
"address": "35 Greater Noida"
},
{
"id": 7,
"name": "Sadman",
"email": "khan6@gamil.com",
"address": "132 Pune India"
},
{
"id": 8,
"name": "Nadeem",
"email": "nawab7@gamil.com",
"address": "121 Lucknow India"
},
{
"id": 9,
"name": "Yashwant",
"email": "yash@gmail.com",
"address": "32 Delhi India"
},
{
"id": 10,
"name": "Prasad",
"email": "prasad@yahoo.com",
"address": "217 Mumbai India"
},
{
"id": 11,
"name": "Pragati",
"email": "pragati@tumblr.com",
"address": "3 Dehradun India"
},
{
"id": 12,
"name": "Imojean",
"email": "iwalbrookb@zdnet.com",
"address": "91904 Fieldstone Lane"
},
{
"id": 13,
"name": "Rochell",
"email": "rsharplesc@drupal.org",
"address": "46 Schmedeman Place"
},
{
"id": 14,
"name": "Fayina",
"email": "fwellwoodd@mapquest.com",
"address": "1 Anderson Street"
},
{
"id": 15,
"name": "Dilan",
"email": "dgethinge@wsj.com",
"address": "87297 High Crossing Alley"
},
{
"id": 16,
"name": "Berkie",
"email": "bmousbyf@si.edu",
"address": "5611 Colorado Drive"
},
{
"id": 17,
"name": "Aliza",
"email": "aabelsg@de.vu",
"address": "56 Dunning Way"
},
{
"id": 18,
"name": "Gene",
"email": "gernih@slashdot.org",
"address": "0479 Jay Court"
},
{
"id": 19,
"name": "Devland",
"email": "dlindbladi@geocities.jp",
"address": "0971 Johnson Terrace"
},
{
"id": 20,
"name": "Leigh",
"email": "larlidgej@xinhuanet.com",
"address": "430 Hanover Park"
},
{
"id": 21,
"name": "Annamaria",
"email": "agerreyk@jiathis.com",
"address": "03345 Larry Junction"
},
{
"id": 22,
"name": "Agace",
"email": "arubenczykl@meetup.com",
"address": "119 Stuart Alley"
},
{
"id": 23,
"name": "Ninette",
"email": "nhuglim@npr.org",
"address": "746 Calypso Plaza"
},
{
"id": 24,
"name": "Sosanna",
"email": "scopestaken@cloudflare.com",
"address": "81924 North Parkway"
},
{
"id": 25,
"name": "Millard",
"email": "mcullumo@jigsy.com",
"address": "6215 Hoepker Park"
},
];
}

The code will seem to be like the given snippet. Presently you go the data and now is the ideal time to render the data in the application and move towards the choice feature.

Create a new dart file called HomePage.dart inside the lib folder.

Now we will make the UI using the ListView.builder. The data will be loaded from the data. dart.

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Map> staticData = MyData.data;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
);
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Now will be added Selection Mode:

If I discuss myself, I will most likely utilize a long press. i.e When you long-press on the list item then it chooses the long-pressed thing and enables the determination mode.

On the off chance that anything is chosen from the list, the selection model is empowered.

We want a variable to flag the choice status of the item. To monitor the list of item determinations, we will utilize Map. The Map will store the unique id as the key and the boolean as the choice flag.

Adding Flag Variable for tracing selection Status:

Presently we want to follow which thing is chosen and which isn’t. To store this we want a variable of some sort. As we have a list of data so we likewise need a variable that can store the list of data.

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
bool isSelectionMode = false;
List<Map> staticData = MyData.data;
Map<int, bool> selectedFlag = {};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
);
}

void onTap(bool isSelected, int index) {
if (isSelectionMode) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
} else {
// Open Detail Page
}
}

void onLongPress(bool isSelected, int index) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
}

Widget _buildSelectIcon(bool isSelected, Map data) {
if (isSelectionMode) {
return Icon(
isSelected ? Icons.check_box : Icons.check_box_outline_blank,
color: Theme.of(context).primaryColor,
);
} else {
return CircleAvatar(
child: Text('${data['id']}'),
);
}
}
}

We can utilize a list yet using a map will be better and more powerful here. We can have user_id as the key to map and value as a boolean. As the list thing has an id and it’s extraordinary so utilizing a map is the most ideal choice here.

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Selected Output

Now Adding Select All Button:

Presently we will add the select all button so we can choose every one of the things on the list utilizing one tap/click. This is vital in the creation application and this feature makes life simpler when there is an extremely extensive list.

Add this line of code to the Scaffold

floatingActionButton: _buildSelectAllButton(),

The button will be apparent when the selectionMode is empowered. The floating Button icon button changed based on the item chosen.

Widget? _buildSelectAllButton() {
bool isFalseAvailable = selectedFlag.containsValue(false);
if (isSelectionMode) {
return FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: _selectAll,
child: Icon(
isFalseAvailable ? Icons.done_all : Icons.remove_done,
),
);
} else {
return null;
}
}

void _selectAll() {
bool isFalseAvailable = selectedFlag.containsValue(false);
selectedFlag.updateAll((key, value) => isFalseAvailable);
setState(() {
isSelectionMode = selectedFlag.containsValue(true);
});
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';

class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);

@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
bool isSelectionMode = false;
List<Map> staticData = MyData.data;
Map<int, bool> selectedFlag = {};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
floatingActionButton: _buildSelectAllButton(),
);
}

void onTap(bool isSelected, int index) {
if (isSelectionMode) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
} else {
// Open Detail Page
}
}

void onLongPress(bool isSelected, int index) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
}

Widget _buildSelectIcon(bool isSelected, Map data) {
if (isSelectionMode) {
return Icon(
isSelected ? Icons.check_box : Icons.check_box_outline_blank,
color: Theme.of(context).primaryColor,
);
} else {
return CircleAvatar(
child: Text('${data['id']}'),
);
}
}

Widget? _buildSelectAllButton() {
bool isFalseAvailable = selectedFlag.containsValue(false);
if (isSelectionMode) {
return FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: _selectAll,
child: Icon(
isFalseAvailable ? Icons.done_all : Icons.remove_done,
),
);
} else {
return null;
}
}

void _selectAll() {
bool isFalseAvailable = selectedFlag.containsValue(false);
selectedFlag.updateAll((key, value) => isFalseAvailable);
setState(() {
isSelectionMode = selectedFlag.containsValue(true);
});
}
}

Conclusion:

In the article, I have explained the Select Item basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Select Item On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying Select Items From the List in your flutter projectsWe will show you make a demo program for working with selecting an item from the list in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

Your email address will not be published. Required fields are marked with *.