In this guide, we will learn how to implement the Chip in Flutter. Chip is a material design widget that comes built-in with flutter. It can simply be described as a compact element holding an icon and text, usually a rounded rectangle in the background. It can serve many purposes, like it can be simply used as a button, representing a user with a CircleAvatar and text, or topic tags in the blog articles, etc.

Chips are conservative components that speak to quality, text, entity, or action. Providing a non-invalid onDeleted callback will make the chip incorporate a button for erasing the chip. Its progenitors must incorporate MaterialMediaQueryDirectionality, and MaterialLocalizations. Regularly these widgets are given by MaterialApp and Scaffold. The label and clipBehavior contentions must not be invalid.

It speaks to complex elements in small blocks, for example, a contact. Contact chips may minimally speak to contact data. Chips can be utilized for different kinds of elements, including free-form text, predefined text, rules, or contacts. Chips may likewise contain icons.

Properties of Chip Widget

labeltakes in a widget as the object to be placed inside the chip widget as the primary element.
avatarholds in a widget as the object to be displayed before the Chip label.
backgroundColorindicated the background color of the chip when it is unselected and empowered.
labelStyle utilized to apply any TextStyle to the label
labelPaddingadded some padding around the label.
elevationholds a double value as the object decide the elevated height of the Chip widget.
shadowColorcolor to the shadow of the chip when elevation is set.
deleteIconutilized to show the delete icon. This will be just obvious when onDeleted is set.
onDeletedcallback when the delete icon is squeezed inside the chip.
deleteButtonTooltipMessageset as a message to show up on the delete icon’s tooltip.
shapeutilized to offer shapes to the border of the chip.
clipBehaviortakes Clip enum as the object to decide whether the content inside the Chip widget will be clipped or not.
focusNode takes in FocusNode class as the object assign an additional focus node to the widget.

Let’s take an example of how we can implement the Chip in our flutter application.

we will create a new model name Fruit that includes the String of name description and the URL of that class name Fruit and store it into a new file inside the lib folder name fruit_model.dart.

class Fruit {
  String name, desc, url;
  Friut({
    required this.name,
    required this.desc,
    required this.url,
  });
}

Now we will again create a new file name as fruit_data.dart that includes the dummy data.

import 'package:vlogpost/model/student.dart';

List<Friut> friuts= [
  Friut(
      name: 'Apple',
      desc:
          'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the',
      url:
          'assets/apple.jpg'),
  Friut(
      name: 'Banana',
      desc:
          'banana is an elongated, edible fruit - botanically a berry - produced by several kinds of large herbaceous flowering plants in the genus Musa.',
      url:
          'assets/banana.jpg'),
  Friut(
      name: 'Grape',
      desc:
          'The grapefruit (Citrus × paradisi) is a subtropical citrus tree known for its relatively large, sour to semi-sweet, somewhat bitter fruit.',
      url:
          'assets/grape.jpg'),
  Friut(
      name: 'Mango',
      desc:
          'A mango is an edible stone fruit produced by the tropical tree Mangifera indica which is believed to have originated from the region between northwestern ...',
      url:
          'assets/mango.jpg'),
  Friut(
      name: 'Orange',
      desc:
          'An orange is a fruit of various citrus species in the family Rutaceae ); it primarily refers to Citrus × sinensis, which is also called sweet orange',
      url:
          'assets/orange.jpg'),
  Friut(
      name: 'WaterMelon',
      desc:
          'Watermelon is grown in favorable climates from tropical to temperate regions worldwide for its large edible fruit',
      url:
          'assets/watermelon.jpg'),
  Friut(
      name: 'Papaya',
      desc:
          'Papayas grow in tropical climates and are also known as papaws or pawpaws. Their sweet taste, vibrant color, and the wide variety of health benefits they ',
      url:
          'assets/papaya.jpg'),
  Friut(
      name: 'Coconut',
      desc:
          'A coconut is the edible fruit of the coconut palm (Cocos nucifera), a tree of the palm family. ',
      url:
          'assets/coconut.jpg'),
  
];

In the above line of code, I have used the local image name as an assets folder to store the image of fruits. for these, I have taken different fruit images which are shown below.

The Next Step is to include the assets folder inside the pubspec. yaml which is shown below

# To add assets to your application, add an assets section, like this:
  assets:
    - assets/

Now let’s implement the code in the Flutter application.

import 'package:flutter/material.dart';
import 'package:vlogpost/data/food_data.dart';
import 'package:vlogpost/model/student.dart';

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

  @override
  State<ChipScreen> createState() => _ChipScreenState();
}

class _ChipScreenState extends State<ChipScreen> {
  List<Fruit> fruit = [];

  @override
  void initState() {
    fruit = List.of(fruits);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Chip in Flutter'),
        centerTitle: true,
      ),
      body: Wrap(
        children: fruit
            .map((e) => Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 5.0),
                  child: Chip(
                    label: Text(
                      e.name,
                    ),
                    avatar: CircleAvatar(
                      backgroundImage: AssetImage(e.url),
                    ),
                    onDeleted: () {
                      setState(() {
                        fruit.removeWhere((element) => element.id == e.id);
                      });
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                          backgroundColor: Colors.teal,
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(15),
                          ),
                          duration: const Duration(milliseconds: 1000),
                          content: Text(
                              'Item ${e.name} has been removed from the list')));
                    },
                    deleteIcon: const Icon(
                      Icons.clear,
                      color: Colors.red,
                    ),
                  ),
                ))
            .toList(),
      ),
    );
  }
}

Meanwhile, when we run this application in the emulator or device, we should get the UI similar to the screenshot below:

Get the full snippet from here

Related: How To Implement The CheckboxListTile In Flutter

Tags: