Home > Back-end >  Flutter: How to show checkbox on long press the item of ListView?
Flutter: How to show checkbox on long press the item of ListView?

Time:05-30

I can't figure out how to make ListView items choosable like in screenshots:

enter image description here

enter image description here

CodePudding user response:

You can give it a leading icon by giving it a ListTile.

CodePudding user response:

This should work. On long press using GestureDetector you should alter a property of the model in the list and set state. Showing the checkbox when that condition is true, otherwise use an empty container. You can then do whatever you need within that checkbox specifically.

import 'package:flutter/material.dart';

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

  @override
  State<TEST> createState() => _TESTState();
}

class _TESTState extends State<TEST> {
  List<MyItem> _objs = [MyItem(id: '', isSelected: false)];
  bool _showCheckboxes = false;
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: _objs.length,
      itemBuilder: (context, index) {
        var item = _objs[index];
        return GestureDetector(
          onLongPress: () {
            setState(() {
              _showCheckboxes = true;
            });
          },
          child: ListTile(
              leading: _showCheckboxes
                  ? Checkbox(
                      value: item.isSelected,
                      onChanged: (val) {
                        setState(() {
                          item.isSelected = !item.isSelected;
                        });
                      })
                  : Container()),
        );
      },
    );
  }
}

class MyItem {
  String id;
  bool isSelected;

  ///other properties...
  MyItem({required this.id, required this.isSelected});
}

Edit: Shows checkboxes for all items, as required in question.

CodePudding user response:

Its really simple to impliment You can achieve it by this package mult select flutter

  • Related