Skip to content

Instantly share code, notes, and snippets.

@ponnamkarthik
Last active March 17, 2021 08:10
Show Gist options
  • Save ponnamkarthik/b0752728ba9acd313271a8a5c29a7965 to your computer and use it in GitHub Desktop.
Save ponnamkarthik/b0752728ba9acd313271a8a5c29a7965 to your computer and use it in GitHub Desktop.
Flutter Multi select ChoiceChip #Flutter #Android #ios
# Flutter Multi select ChoiceChip
Hello Everyone
In this article we will see how to use `ChoiceChip` to accept multiple selections
Let's get started
First things first
I will create a demo project and in the main.dart in build sections i will create a `RaisedButton` so when i click on the button a dialog will be poped showing options to select.
https://gist.github.com/8a6c263b25be0fe77df6514ac6fe31c1
Now onPressed we need to call the open Dialog
https://gist.github.com/9285ea7c61af090f9bfaf7ec210f62d3
Now i will create a Widget to hold and return the `ChoiceChip`
Here is the widget which accepts a `List<String>` so i can populate the Chips using it
Now our widget has a single Choice "Not Interested"
https://gist.github.com/e8e0fe51f9e059e062aa0544cf4a765a
Now in `_showReportDialog` function we need to call Our widget.
https://gist.github.com/0af4b238e2911fa1e640ec4443f57ef4
Now lets populate the chips based on the reportList Now our Widget will become this one
https://gist.github.com/4e89129db0b58a21730bb0ea4c083795
Now we have a single select chip in order to make it multi select chip we need to save out selectedChoice to a list lets work it out.
Now to achive this we use some methods aviable with the `List`
`selectedChoices.contains(item)`
`selectedChoices.remove(item)`
`selectedChoices.add(item)`
Now our `_buildChoiceList` will look like below
https://gist.github.com/aeed6058f8916a8ff669e59db7efaa2b
The login we used here is if the list contains the item then we make it selected else unselected in the same way then a chip is selected if the `List` already contains the item then we remove the exisitng one else we add the item in to the `List`
`selected: selectedChoices.contains(item),`
and
https://gist.github.com/348e8f972a8530fc9f15c99e58a43936
Now the part is to pass the selected choices back we can achive this by passing a function which accepts a `List<String>` in to our `Widget` this how our code will be
In content of our `AlertDialog` in `_showReportDialog`
https://gist.github.com/30401acf77db6a4c7a0d53c088d838c9
Our `MultiSelectChip` Will be like below
https://gist.github.com/39eba2bb22dc99a01cb3ef190cd1ddac
When ever out selection of chip changed we will trigger the `onSelectionChanged`
Our HomePageState build method will be as below
https://gist.github.com/6c1520fbdd7593e62f7a84b7c6e5dcca
So this is how can make a multi select choice chip
To get all options aviable with `ChoiceChip` check [here](https://docs.flutter.io/flutter/material/ChoiceChip-class.html)
To get Full Source code check out [my github repo](https://github.com/PonnamKarthik/MultiSelectChoiceChip)
**Thanks for your time.**
Hope you like it, if yes **clap & share.**
@NavinRiyaz
Copy link

Hello bro! I am using this Package. This Package already has contents to view chips but I want to load contents from API to select chips Please Help me to do this.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:multiselect_formfield/multiselect_formfield.dart';
import 'package:multi_select_flutter/multi_select_flutter.dart';
import 'package:http/http.dart' as http;

import 'Includes/APILinks.dart';

void main() => runApp(Sample());

class Sample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List _myActivities;
  String _myActivitiesResult;
  final formKey = new GlobalKey<FormState>();

  @override
  void initState() {
    super.initState();
    _myActivities = [];
    this.fetchData();
  }

  _saveForm() {
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
      setState(() {
        _myActivitiesResult = _myActivities.toString();
      });
    }
  }

  fetchData() async{
    var url = https://url.com;
    var response = await http.get(url);
    if(response.statusCode == 200){
      var items = json.decode(response.body);
      print(items);
      setState(() {
        _myActivities = items;
      });
    } else {
      setState(() {
        _myActivities = [];
      });
    }
  }

  @override
  Widget build(BuildContext context) {

    final double maxWidth = MediaQuery.of(context).size.width;
    final double maxHeight = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: AppBar(
        title: Text('MultiSelect Formfield Example'),
      ),
      body: Center(
        child: Form(
          key: formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                height: maxHeight/2,
                width: maxWidth,
                padding: EdgeInsets.all(16),
                child: getListView(),
              ),
              Container(
                padding: EdgeInsets.all(8),
                child: RaisedButton(
                  child: Text('Save'),
                  onPressed: _saveForm,
                ),
              ),
              Container(
                padding: EdgeInsets.all(16),
                child: Text(_myActivitiesResult),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget getListView() {
    return ListView.builder(
        itemCount: _myActivities.length,
        itemBuilder: (context, index){
          return cardView(_myActivities[index]);
        },
    );
  }

  Widget cardView(item) {

    var fullName = item;

    return MultiSelectDialogField(
      items: _myActivities,
      title: Text("Animals"),
      selectedColor: Colors.blue,
      decoration: BoxDecoration(
        color: Colors.blue.withOpacity(0.1),
        borderRadius: BorderRadius.all(Radius.circular(40)),
        border: Border.all(
          color: Colors.blue,
          width: 2,
        ),
      ),
      buttonIcon: Icon(
        Icons.pets,
        color: Colors.blue,
      ),
      buttonText: Text(
        "Favorite Animals",
        style: TextStyle(
          color: Colors.blue[800],
          fontSize: 16,
        ),
      ),
      onConfirm: (results) {
        _myActivities = results;
      },
    );
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment