This is the 16th day of my participation in the First Challenge 2022

This article is about the Chip widget in Flutter. We’ll look at the basics of the widget and then implement it in code. Without delay, let’s get started.

Author: Nuts

Public account: “Big Front End Tour”

Huawei Cloud sharing expert, InfoQ contract writer, Ali Cloud expert blogger, 51CTO blog chief Experience officer, one of the open source project GVA, focusing on the sharing of big front-end technologies, including Flutter, applets, Android, VUE, JavaScript.

An overview of the

A typical chip is a small box with rounded corners. It has a text label and displays information in a meaningful and compact way. Chip can display multiple interactive elements simultaneously in the same area. Some popular chip use cases are:

  • Publish tags (you can find them on many large platforms such as WordPress, VuePress, Zhihu, Nuggets, wechat or GitHub).
  • A list of deletable content (a list of email contacts, a list of favorite music genres, etc.).

In Flutter, you can use the following constructors to implement Chip widgets:

Chip({
  Key? key, 
  Widget? avatar, 
  required Widget label, 
  TextStyle? labelStyle, 
  EdgeInsetsGeometry? labelPadding, 
  Widget? deleteIcon, 
  VoidCallback? onDeleted, 
  Color? deleteIconColor, 
  bool useDeleteButtonTooltip = true, 
  String? deleteButtonTooltipMessage, 
  BorderSide? side, 
  OutlinedBorder? shape, 
  Clip clipBehavior = Clip.none, 
  FocusNode? focusNode, 
  bool autofocus = false, 
  Color? backgroundColor, 
  EdgeInsetsGeometry? padding, 
  VisualDensity? visualDensity, 
  MaterialTapTargetSize? materialTapTargetSize, 
  double? elevation, 
  Color? shadowColor
})
Copy the code

Only the label attribute is required, the others are optional. Some commonly used ones are:

  • Avatar: Displays an icon or small image in front of the label.
  • BackgroundColor: backgroundColor of the chip.
  • Padding: Padding around the chip content.
  • DeleteIcon: Lets the user delete a widget for Chip.
  • OnDeleted: Function called when deleteIcon is clicked.

You can find more details about the other attributes in the official documentation. However, for most applications, we don’t need more than half.

A simple example

This small example shows you a simple way to display multiple chips at the same time. We will use the Wrap widget as the parent of the Chip list. When the current row runs out of free space, the chips automatically go down. Thanks to the spacing property of the Wrap widget, we can also easily set the distance between chips.

Screenshots:

Code:

Scaffold(appBar (title: const Text(' big front-end '),), body: Padding(Padding: const EdgeInsets. Symmetric (vertical: 30, horizontal: 10), child: Wrap( // space between chips spacing: 10, // list of chips children: const [ Chip( label: Text('Working'), avatar: Icon( Icons.work, color: Colors.red, ), backgroundColor: Colors.amberAccent, padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), ), Chip( label: Text('Music'), avatar: Icon(Icons.headphones), backgroundColor: Colors.lightBlueAccent, padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), ), Chip( label: Text('Gaming'), avatar: Icon( Icons.gamepad, color: Colors.white, ), backgroundColor: Colors.pinkAccent, padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), ), Chip( label: Text('Cooking & Eating'), avatar: Icon( Icons.restaurant, color: Colors.pink, ), backgroundColor: Colors.greenAccent, padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10), ) ]), ), );Copy the code

In this example, chip just renders the information. In the next example, chip is interactive.

Complex example: Dynamically adding and removing chips

Application to preview

The application we will build contains a floating action button. When this button is pressed, a dialog box is displayed that lets us add a new chip. Each chip can be deleted by clicking the delete icon associated with it.

Here’s how the application works:

The complete code

Final code and explanation in main.dart:

// main.dart import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: ThemeData(primarySwatch: colors.green,), home: const HomePage(),); } } // Data model for a chip class ChipData { // an id is useful when deleting chip final String id; final String name; ChipData({required this.id, required this.name}); } class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // list of chips final List<ChipData> _allChips = []; // Text controller (that will be used for the TextField shown in the dialog) final TextEditingController _textController  = TextEditingController(); // This function will be triggered when the floating actiong button gets pressed void _addNewChip() async { await ShowDialog (context: context, Builder: (_) {return AlertDialog(title: const Text(' add '), content: TextField( controller: _textController, ), actions: [ ElevatedButton( onPressed: () { setState(() { _allChips.add(ChipData( id: DateTime.now().toString(), name: _textController.text)); }); // reset the TextField _textController.text = ''; // Close the dialog Navigator. Of (context).pop();}, child: const Text(' submit '))],); }); } // This function will be called when a delete icon associated with a chip is tapped void _deleteChip(String id) { setState(() { _allChips.removeWhere((element) => element.id == id); }); } @override Widget build(BuildContext context) {return Scaffold(appBar: appBar (title: const Text(' big front end '),), body: Padding( padding: const EdgeInsets.all(15), child: Wrap( spacing: 10, children: _allChips .map((chip) => Chip( key: ValueKey(chip.id), label: Text(chip.name), backgroundColor: Colors.amber.shade200, padding: const EdgeInsets.symmetric(vertical: 7, horizontal: 10), deleteIconColor: Colors.red, onDeleted: () => _deleteChip(chip.id), )) .toList(), ), ), floatingActionButton: FloatingActionButton( onPressed: _addNewChip, child: const Icon(Icons.add), ), ); }}Copy the code

conclusion

We have explored many aspects of the Chip widget and gone through more than one example of using it.

If you like, give nuts a thumbs up