Select Items in a ListView in Flutter

This Article is posted by seven.srikanth at 10/25/2019 6:48:09 AM



In this example, I'm going to share an example of how to select items in a ListView.
Here is how the output of the program is going to look like. You can see the items are slightly turned into blue on long press.
In order to achieve this, I've taken advantage of onLongPress method available in ListTile.
Here is the full code from main.dart file. Copy-paste and run the program to see the above output.
import 'dart:developer';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  double padValue = 0;
  List<Paint> paints = <Paint>[
    Paint(1'Red'Colors.red),
    Paint(2'Blue'Colors.blue),
    Paint(3'Green'Colors.green),
    Paint(4'Lime'Colors.lime),
    Paint(5'Indigo'Colors.indigo),
    Paint(6'Yellow'Colors.yellow)
  ];
  @override
  Widget build(BuildContext context) {
    
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Selectable ListView Example"),
        ),
        body: ListView(
          children: List.generate(paints.length, (index) {
            return ListTile(
              onLongPress: () {
                setState(() {
                  paints[index].selected = !paints[index].selected;
                  log( paints[index].selected.toString());
                });
              },
              selected: paints[index].selected,
              leading: Container(
                width: 100.0,
                height: 100.0,
                color: paints[index].colorpicture,
              ),
              title: Text('ID: ' + paints[index].id.toString()),
              subtitle: Text(paints[index].title),              
            );
          }),
        ),
      ),
    );
  }
}
class Paint {
  final int id;
  final String title;
  final Color colorpicture;
  bool selected = false;
  Paint(this.id, this.title, this.colorpicture);
}
Hope this will be useful to you.
Thanks,
Srikanth

Tags: Select items in ListView; OnLongPress ListTile; ListView Example;








0 Comments
Login to comment.
Recent Comments












© 2018 - Fluttercentral | Email to me - seven.srikanth@gmail.com