MultiSelection Listview in Flutter with CheckboxListTile

Published October 10, 2020


How to make a Listview Multiselection in a flutter. In this post, we are going to create a Listview with Multiselection process.

This example contains below widgets

Listview

ExpansionTile
CheckboxListTile

 

Check Simple Expandable Listview Example

 

Let's Check the code

 

Here List items handle with CheckboxListTile

CheckboxListTile(
  title: new Text(item.title),
  value: item.isAdded,
  activeColor: Colors.pink,
  checkColor: Colors.white,
  onChanged: (bool value) {
    setState(() {
      item.isAdded = value;
      if(!value)
        {
          Constants.removeAll(index, k);
        }
    });
  },
)

 

main.dart file

import 'dart:core';

import 'package:flutter/material.dart';
import 'cart.dart';
import 'constnts.dart';
import 'list_item.dart';



class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.red,
      ),
      home: MyHomePage(title: 'Multi Selection- ExpansionTile'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {


  @override
  void initState() {
    super.initState();
    Constants.allItems=new List();
    for(var k=1;k<=5;k++)
    {

      Constants.allItems.add(Cart(getMenu(k), getSubMenu()));

    }
    Constants.allItems.map((s){

    }).map((list)=>list).toList();

  }

  @override
  Widget build(BuildContext context) {

    List<String>list=List();

    return Scaffold(

      appBar: AppBar(

        title: Text(widget.title),
      ),
      body: Stack(
        
        children: [
          Opacity(opacity: .6,child: Image.network( "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRwp3QntHc1KiYvEt-zoR3_k5KndhiaXTZKfw&usqp=CAU",width: double.infinity,height:double.infinity,fit: BoxFit.cover,)),
          Center(

              child: ListView.builder(
                itemCount: Constants.allItems.length,
                itemBuilder: (context,index){
                  return  ListItem(index);
                },

              )
          )
        ],
      ),

    );
  }

  String getMenu(int month)
  {
    switch(month)
    {
      case 1:
        return "Biryanis";
      case 2:
        return "Cool Drinks";
      case 3:
        return "Tiffins";
      case 4:
        return "Fast Food";
      case 5:
        return "Roties";


    }
  }

  List<SubItem> getSubMenu()
  {


    return [ SubItem("Item 1",false,0), SubItem("Item 2",false,0), SubItem("Item 3",false,0)].toList();
  }


}

class SubItem{

  var title;
  var isAdded=false;
  var count;

  SubItem(String title, bool isAdded, int count){
    this.title=title;
    this.isAdded=isAdded;
    this.count=count;
  }
}

 

list_item.dart

import 'package:flutter/material.dart';
import 'constnts.dart';
import 'multiselect_expansionlist.dart';


class ListItem extends StatefulWidget{

 int index;


  ListItem(this.index);

  @override
  State<StatefulWidget>createState()
  {
    return ListItemState();
  }
}
class ListItemState extends State<ListItem>
{
  bool isExpand=false;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    isExpand=false;
  }
  @override
  Widget build(BuildContext context) {
    List<SubItem>listItem=Constants.allItems[this.widget.index].subMenu;




    return  Padding(
      padding: (isExpand==true)?const EdgeInsets.all(8.0):const EdgeInsets.all(12.0),
      child: Container(
        decoration:BoxDecoration(
            color: Colors.white,
            borderRadius: (isExpand!=true)?BorderRadius.all(Radius.circular(8)):BorderRadius.all(Radius.circular(22)),
            border: Border.all(color: Colors.black)
        ),
        child: ExpansionTile(
          key: PageStorageKey<String>(Constants.allItems[this.widget.index].menuName),
          title: Container(
              width: double.infinity,

              child: Text(Constants.allItems[this.widget.index].menuName,style: TextStyle(color:Colors.black,fontSize: (isExpand!=true)?18:22),)),
          trailing: (isExpand==true)?Icon(Icons.arrow_drop_down,size: 32,color: Colors.pink,):Icon(Icons.arrow_drop_up,size: 32,color: Colors.pink),
          onExpansionChanged: (value){
            setState(() {
              isExpand=value;
            });
          },
          children:  getItems(listItem,this.widget.index),

        ),
      ),
    );
  }
  getItems(List listItems,index)
  {
    List<Widget> listWidget=new List();
    for(int k=0;k<listItems.length;k++)
      {
        SubItem item=listItems[k];
        listWidget.add( Padding(
            padding: const EdgeInsets.all(8.0),
            child:Container(
                decoration:BoxDecoration(
                  color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(8)),
                    border: Border.all(color: Colors.blueGrey)
                ),
              child: Column(
                children: [

                  CheckboxListTile(
                    title: new Text(item.title),
                    value: item.isAdded,
                    activeColor: Colors.pink,
                    checkColor: Colors.white,
                    onChanged: (bool value) {
                      setState(() {
                        item.isAdded = value;
                        if(!value)
                          {
                            Constants.removeAll(index, k);
                          }
                      });
                    },
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment:MainAxisAlignment.end,
                    children: [
                      InkWell(
                          onTap: (){
                            setState(() {

                              Constants.addCartItem(index, k);

                            });
                          },
                          child: Icon(Icons.add, color: Colors.green,size: 32,)),
                      Container(
                        margin: EdgeInsets.all(10),
                        child: Text(
                          "${item.count}",
                          style: TextStyle(fontSize: 18.0, color: Colors.black),
                        ),
                      ),
                      InkWell(
                          onTap:(){
                            setState(() {

                              Constants.removeCartItem(index, k);

                            });
                          },
                          child: Icon(Icons.remove, color: Colors.red,size: 32,)),
                    ],),
                ],
              ),
            )

        ));
      }
    return listWidget;
  }
}


 

cart.dart

class Cart{

  String menuName;
  List<SubItem>subMenu;

  Cart(String menu, List<SubItem> subMenu){
    this.menuName=menu;
    this.subMenu=subMenu;
  }
}

 

class Constants
{

  static List<Cart> allItems=new List();



  static addCartItem(index,childIndex)
  {
    allItems[index].subMenu[childIndex].count++;
  }
  static removeCartItem(index,childIndex) {
    if(allItems[index].subMenu[childIndex].count>1)
    allItems[index].subMenu[childIndex].count--;
  }

  static void removeAll(index, int childIndex) {

      allItems[index].subMenu[childIndex].count=0;
  }

}

 


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

3455 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions