Flutter: Highlight selected items in a ListView

Last updated on November 7, 2020 The Frog Loading... 2 comments

This article shows you how to highlight selected items in a ListView in a Flutter application.

Overview

The steps:

1. Add a value called “isSelected” to each item in the list. By default, “isSelected” is set to “false”.

2. When the user taps an item, its “isSelected” value will switch between “true” and “false”, like this:

setState(){
  myList[index]["isSelected"] = !myList[index]["isSelected"];
}

A Complete Example

Some lines of code are worth more than a thousand words.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Generating a long list to fill the ListView
  final List<Map> data = List.generate(100,
      (index) => {'id': index, 'name': 'Item $index', 'isSelected': false});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Kindacode.com'),
        ),
        body: SafeArea(
            child: ListView.builder(
          itemCount: data.length,
          itemBuilder: (BuildContext ctx, index) {
            return Card(
                margin: EdgeInsets.all(10),
                shape:
                    RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),

                // The color depends on this is selected or not
                color: data[index]['isSelected'] == true ? Colors.amber : Colors.white,
                child: ListTile(
                  onTap: (){
                    // if this item isn't selected yet, "isSelected": false -> true
                    // If this item already is selected: "isSelected": true -> false
                    setState(() {
                      data[index]['isSelected'] = !data[index]['isSelected'];
                    });
                  },
                  leading: CircleAvatar(
                      backgroundColor: Colors.blue,
                      child: Text(data[index]['id'].toString())),
                  title: Text(data[index]['name']),
                ));
          },
        )));
  }
}

Check the result:

That’s it. Happy Fluttering 🙂

Subscribe
Notify of
guest
2 Comments
Inline Feedbacks
View all comments
noshin
noshin
7 months ago

Thank you sir for great articles about flutter

A Goodman
Admin
A Goodman
7 months ago
Reply to  noshin

Thank you 🙂

Related Articles