chips_choice 1.2.0

  • Readme
  • Changelog
  • Example
  • Installing
  • 92

chips_choice #

Lite version of smart_select package, zero dependencies, an easy way to provide a single or multiple choice chips.

Demo #

Preview #

Demo Preview

Download #

Demo App

Features #

  • Select single or multiple choice
  • Display in scrollable or wrapped List
  • Build choice option from any List
  • Customizable choice widget

Usage #

For a complete usage, please see the example.

To read more about classes and other references used by chips_choice, see the documentation.

Single Choice #

int tag = 1;
List<String> options = [
  'News', 'Entertainment', 'Politics',
  'Automotive', 'Sports', 'Education',
  'Fashion', 'Travel', 'Food', 'Tech',
  'Science',
];

// ChipsChoice<T>.single
ChipsChoice<int>.single(
  value: tag,
  options: ChipsChoiceOption.listFrom<int, String>(
    source: options,
    value: (i, v) => i,
    label: (i, v) => v,
  ),
  onChanged: (val) => setState(() => tag = val),
);

Multiple Choice #

List<String> tags = [];
List<String> options = [
  'News', 'Entertainment', 'Politics',
  'Automotive', 'Sports', 'Education',
  'Fashion', 'Travel', 'Food', 'Tech',
  'Science',
];

// ChipsChoice<T>.multiple
ChipsChoice<String>.multiple(
  value: tags,
  options: ChipsChoiceOption.listFrom<String, String>(
    source: options,
    value: (i, v) => v,
    label: (i, v) => v,
  ),
  onChanged: (val) => setState(() => tags = val),
);

Build Options List #

options property is List<ChipsChoiceOption<T>>, it can be input directly as in the example below, more info about ChipsChoiceOption can be found on the API Reference

ChipsChoice<T>.single/multiple(
  ...,
  ...,
  options: <ChipsChoiceOption<T>>[
    ChipsChoiceOption<T>(value: 1, label: 'Entertainment'),
    ChipsChoiceOption<T>(value: 2, label: 'Education'),
    ChipsChoiceOption<T>(value: 3, label: 'Fashion'),
  ],
);

options also can be created from any list using helper provided by this package, like the example below

List<Map<String, String>> days = [
  { 'value': 'mon', 'title': 'Monday' },
  { 'value': 'tue', 'title': 'Tuesday' },
  { 'value': 'wed', 'title': 'Wednesday' },
  { 'value': 'thu', 'title': 'Thursday' },
  { 'value': 'fri', 'title': 'Friday' },
  { 'value': 'sat', 'title': 'Saturday' },
  { 'value': 'sun', 'title': 'Sunday' },
];

ChipsChoice<T>.single/multiple(
  ...,
  ...,
  options: ChipsChoiceOption.listFrom<T, Map<String, String>>(
    source: days,
    value: (index, item) => item['value'],
    label: (index, item) => item['title'],
  ),
);

Scrollable or Wrapped List #

ChipsChoice<T>.single/multiple(
  ...,
  ...,
  isWrapped: false/true,
);

License #

Copyright (c) 2020 Irfan Vigma Taufik

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

[1.2.0] - 2020-04-05 #

  • Add labelStyle to ChipsChoiceItemConfig

[1.1.0] - 2020-03-07 #

  • Improve performance, since Theme.of(context) in default choice widget is moved outside, so this only fired once
  • ChipsChoiceBuilder parameter select function now only need one parameter bool selected
  • Add meta to ChipsChoiceOption, this useful with custom choice widget
  • Add more option to ChipsChoiceItemConfig
  • Add more usage example

[1.0.0] - 2020-01-24 #

  • Initial release
  • Select single or multiple choice
  • Display in scrollable or wrapped List
  • Customizable choice input
  • Build choice option from any List

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:chips_choice/chips_choice.dart';
import 'package:async/async.dart';
import 'package:dio/dio.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter ChipsChoice',
      theme: ThemeData(
        primarySwatch: Colors.red,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

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

class _MyHomePageState extends State<MyHomePage> {

  int tag = 1;
  List<String> tags = [];

  List<String> options = [
    'News', 'Entertainment', 'Politics',
    'Automotive', 'Sports', 'Education',
    'Fashion', 'Travel', 'Food', 'Tech',
    'Science',
  ];

  String user;
  final usersMemoizer = AsyncMemoizer<List<ChipsChoiceOption<String>>>();

  Future<List<ChipsChoiceOption<String>>> getUsers() async {
    String url = "https://randomuser.me/api/?inc=gender,name,nat,picture,email&results=25";
    Response res = await Dio().get(url);
    return ChipsChoiceOption.listFrom<String, dynamic>(
      source: res.data['results'],
      value: (index, item) => item['email'],
      label: (index, item) => item['name']['first'] + ' ' + item['name']['last'],
      avatar: (index, item) => CircleAvatar(
        backgroundImage: NetworkImage(item['picture']['thumbnail']),
      ),
    )..insert(0, ChipsChoiceOption<String>(value: 'all', label: 'All'));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter ChipsChoice'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.help_outline),
            onPressed: () => _about(context),
          )
        ],
      ),
      body: ListView(
        padding: EdgeInsets.all(5),
        children: <Widget>[
          Content(
            title: 'Scrollable List Single Choice',
            child: ChipsChoice<int>.single(
              value: tag,
              options: ChipsChoiceOption.listFrom<int, String>(
                source: options,
                value: (i, v) => i,
                label: (i, v) => v,
              ),
              onChanged: (val) => setState(() => tag = val),
            ),
          ),
          Content(
            title: 'Scrollable List Multiple Choice',
            child: ChipsChoice<String>.multiple(
              value: tags,
              options: ChipsChoiceOption.listFrom<String, String>(
                source: options,
                value: (i, v) => v,
                label: (i, v) => v,
              ),
              onChanged: (val) => setState(() => tags = val),
            ),
          ),
          Content(
            title: 'Wrapped List Single Choice',
            child: ChipsChoice<int>.single(
              value: tag,
              options: ChipsChoiceOption.listFrom<int, String>(
                source: options,
                value: (i, v) => i,
                label: (i, v) => v,
              ),
              onChanged: (val) => setState(() => tag = val),
              isWrapped: true,
            ),
          ),
          Content(
            title: 'Wrapped List Multiple Choice',
            child: ChipsChoice<String>.multiple(
              value: tags,
              options: ChipsChoiceOption.listFrom<String, String>(
                source: options,
                value: (i, v) => v,
                label: (i, v) => v,
              ),
              onChanged: (val) => setState(() => tags = val),
              isWrapped: true,
            ),
          ),
          Content(
            title: 'Disabled Choice Item',
            child: ChipsChoice<int>.single(
              value: tag,
              options: ChipsChoiceOption.listFrom<int, String>(
                source: options,
                value: (i, v) => i,
                label: (i, v) => v,
                disabled: (i, v) => [0, 2, 5].contains(i),
              ),
              onChanged: (val) => setState(() => tag = val),
              isWrapped: true,
            ),
          ),
          Content(
            title: 'Hidden Choice Item',
            child: ChipsChoice<String>.multiple(
              value: tags,
              options: ChipsChoiceOption.listFrom<String, String>(
                source: options,
                value: (i, v) => v,
                label: (i, v) => v,
                hidden: (i, v) => ['Science', 'Politics', 'News', 'Tech'].contains(v),
              ),
              onChanged: (val) => setState(() => tags = val),
              isWrapped: true,
            ),
          ),
          Content(
            title: 'Append an Item to Options',
            child: ChipsChoice<int>.single(
              value: tag,
              options: ChipsChoiceOption.listFrom<int, String>(
                source: options,
                value: (i, v) => i,
                label: (i, v) => v,
              )..insert(0, ChipsChoiceOption<int>(value: -1, label: 'All')),
              onChanged: (val) => setState(() => tag = val),
            ),
          ),
          Content(
            title: 'Selected without Checkmark and Brightness Dark',
            child: ChipsChoice<int>.single(
              value: tag,
              onChanged: (val) => setState(() => tag = val),
              options: ChipsChoiceOption.listFrom<int, String>(
                source: options,
                value: (i, v) => i,
                label: (i, v) => v,
              )..insert(0, ChipsChoiceOption<int>(value: -1, label: 'All')),
              itemConfig: const ChipsChoiceItemConfig(
                showCheckmark: false,
                labelStyle: TextStyle(
                  fontSize: 20
                ),
                selectedBrightness: Brightness.dark,
                // unselectedBrightness: Brightness.dark,
              ),
            ),
          ),
          Content(
            title: 'Async Options and Brightness Dark',
            child: FutureBuilder<List<ChipsChoiceOption<String>>>(
              initialData: [],
              future: usersMemoizer.runOnce(getUsers),
              builder: (context, snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Padding(
                    padding: const EdgeInsets.all(20),
                    child: Center(
                      child: SizedBox(
                        width: 20,
                        height: 20,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                        )
                      ),
                    ),
                  );
                } else {
                  if (!snapshot.hasError) {
                    return ChipsChoice<String>.single(
                      value: user,
                      options: snapshot.data,
                      onChanged: (val) => setState(() => user = val),
                      itemConfig: ChipsChoiceItemConfig(
                        selectedColor: Colors.green,
                        unselectedColor: Colors.blueGrey,
                        selectedBrightness: Brightness.dark,
                        unselectedBrightness: Brightness.dark,
                        showCheckmark: false,
                      ),
                    );
                  } else {
                    return Container(
                      padding: const EdgeInsets.all(25),
                      child: Text(
                        snapshot.error.toString(),
                        style: const TextStyle(color: Colors.red),
                      ),
                    );
                  }
                }
              },
            ),
          ),
          Content(
            title: 'Works with FormField and Validator',
            child: FormField<List<String>>(
              autovalidate: true,
              initialValue: tags,
              validator: (value) {
                if (value.isEmpty) {
                  return 'Please select some categories';
                }
                if (value.length > 5) {
                  return "Can't select more than 5 categories";
                }
                return null;
              },
              builder: (state) {
                return Column(
                  children: <Widget>[
                    Container(
                      alignment: Alignment.centerLeft,
                      child: ChipsChoice<String>.multiple(
                        value: state.value,
                        options: ChipsChoiceOption.listFrom<String, String>(
                          source: options,
                          value: (i, v) => v,
                          label: (i, v) => v,
                        ),
                        onChanged: (val) => state.didChange(val),
                        itemConfig: ChipsChoiceItemConfig(
                          selectedColor: Colors.indigo,
                          selectedBrightness: Brightness.dark,
                          unselectedColor: Colors.indigo,
                          unselectedBorderOpacity: .3,
                        ),
                        isWrapped: true,
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.fromLTRB(15, 0, 15, 15),
                      alignment: Alignment.centerLeft,
                      child: Text(
                        state.errorText ?? state.value.length.toString() + '/5 selected',
                        style: TextStyle(
                          color: state.hasError
                            ? Colors.redAccent
                            : Colors.green
                        ),
                      )
                    )
                  ],
                );
              },
            ),
          ),
          Content(
            title: 'Custom Choice Widget',
            child: ChipsChoice<String>.multiple(
              value: tags,
              options: ChipsChoiceOption.listFrom<String, String>(
                source: options,
                value: (i, v) => v,
                label: (i, v) => v,
              ),
              itemBuilder: (item, selected, select) {
                return CustomChip(item.label, selected, select);
              },
              onChanged: (val) => setState(() => tags = val),
            ),
          ),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class CustomChip extends StatelessWidget {

  final String label;
  final bool selected;
  final Function(bool selected) onSelect;

  CustomChip(
    this.label,
    this.selected,
    this.onSelect,
    { Key key }
  ) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      height: 100,
      width: 70,
      margin: EdgeInsets.symmetric(
        vertical: 15,
        horizontal: 5,
      ),
      duration: Duration(milliseconds: 300),
      decoration: BoxDecoration(
        color: selected ? Colors.green : Colors.transparent,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(
          color: selected ? Colors.green : Colors.grey,
          width: 1,
        ),
      ),
      child: InkWell(
        onTap: () => onSelect(!selected),
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Visibility(
              visible: selected,
              child: Icon(
                Icons.check_circle_outline,
                color: Colors.white,
                size: 32,
              )
            ),
            Positioned(
              left: 9,
              right: 9,
              bottom: 7,
              child: Container(
                child: Text(
                  label,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: selected ? Colors.white : Colors.black45,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Content extends StatelessWidget {

  final String title;
  final Widget child;

  Content({
    Key key,
    @required this.title,
    @required this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 2,
      margin: EdgeInsets.all(5),
      clipBehavior: Clip.antiAliasWithSaveLayer,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(15),
            color: Colors.blueGrey[50],
            child: Text(
              title,
              style: TextStyle(
                color: Colors.blueGrey,
                fontWeight: FontWeight.w500
              ),
            ),
          ),
          child,
        ],
      ),
    );
  }
}

void _about(BuildContext context) {
  showDialog(
    context: context,
    builder: (_) => Dialog(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          ListTile(
            title: Text(
              'chips_choice',
              style: Theme.of(context).textTheme.headline.copyWith(color: Colors.black87),
            ),
            subtitle: Text('by davigmacode'),
            trailing: IconButton(
              icon: Icon(Icons.close),
              onPressed: () => Navigator.pop(context),
            ),
          ),
          Flexible(
            fit: FlexFit.loose,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    'Easy way to provide a single or multiple choice chips.',
                    style: Theme.of(context).textTheme.body1.copyWith(color: Colors.black54),
                  ),
                  Container(height: 15),
                ],
              ),
            ),
          ),
        ],
      ),
    ),
  );
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  chips_choice: ^1.2.0

2. Install it

You can install packages from the command line:

with Flutter:


$ flutter pub get

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:chips_choice/chips_choice.dart';
  
Popularity:
Describes how popular the package is relative to other packages. [more]
83
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
92
Learn more about scoring.

We analyzed this package on Apr 7, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.7.1
  • pana: 0.13.6
  • Flutter: 1.12.13+hotfix.8

Health suggestions

Format lib/chips_choice.dart.

Run flutter format to format lib/chips_choice.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.1.0 <3.0.0
flutter 0.0.0
Transitive dependencies
collection 1.14.11 1.14.12
meta 1.1.8
sky_engine 0.0.99
typed_data 1.1.6
vector_math 2.0.8
Dev dependencies
flutter_test