Flutter - Chip Widget: A Versatile Component for User Interaction

In the world of mobile app development, creating intuitive and interactive user interfaces is crucial to providing an excellent user experience. Flutter, Google's open-source UI software development toolkit, has gained immense popularity for its ability to build beautiful, native-like applications across various platforms. One of the essential elements in crafting user-friendly interfaces is the "Chip" widget. In this blog post, we'll explore what the Chip widget is, its functionalities, and provide a hands-on example of how to use it effectively.

What is the Chip Widget?

The Chip widget in Flutter is a versatile component used to display small pieces of information or allow users to make selections from a list of options. It represents a compact element, typically in the form of a rounded rectangle, that can contain text, icons, or images. Chips are commonly used for tags, filter options, contact details, and many other scenarios where you want to represent concise pieces of information.

Key Features of Chip Widget:

  1. Label: The main content of a chip is its label, which can be a simple text or a combination of text and icons.
  2. Avatar: Chips can also have an optional avatar on the left side, typically used to display user profile images or icons representing the chip's category.
  3. Delete Icon: Some chips allow users to delete them once selected. The delete icon can be displayed on the right side of the chip, providing a way to remove the selection.
  4. Selection State: Chips can have two main states: selected and unselected. They can be styled differently based on their state.
  5. Interactivity: You can make chips interactive by adding tap or press handlers, allowing users to perform specific actions when a chip is selected or deleted.

Example: Creating a Simple Chip Selection UI

Let's demonstrate the usage of the Chip widget by building a simple app that allows users to select their favorite sports from a list of options. We'll use the ChoiceChip class, a subclass of the Chip widget, for this example.

Step 1: Set Up a Flutter Project

Assuming you have Flutter installed, create a new Flutter project using your preferred IDE or the command line:

flutter create chip_example 

Step 2: Implementing the Chip Selection

Open the main.dart file in your project's lib folder, and replace the default code with the following:

import 'package:flutter/material.dart';


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


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


class ChipSelectionScreen extends StatefulWidget {
  @override
  _ChipSelectionScreenState createState() => _ChipSelectionScreenState();
}


class _ChipSelectionScreenState extends State<ChipSelectionScreen> {
  List<String> sports = [
    'Football',
    'Basketball',
    'Tennis',
    'Baseball',
    'Cricket',
    'Swimming',
    'Running',
  ];
  List<String> selectedSports = [];


  void toggleSportSelection(String sport) {
    setState(() {
      if (selectedSports.contains(sport)) {
        selectedSports.remove(sport);
      } else {
        selectedSports.add(sport);
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Favorite Sports'),
      ),
      body: ListView.builder(
        itemCount: sports.length,
        itemBuilder: (context, index) {
          final sport = sports[index];
          return Padding(
            padding: const EdgeInsets.all(8.0),
            child: ChoiceChip(
              label: Text(sport),
              selected: selectedSports.contains(sport),
              onSelected: (isSelected) => toggleSportSelection(sport),
            ),
          );
        },
      ),
    );
  }
}

Step 3: Run the App

Save the changes and run the app on an emulator or a physical device using the following command:

flutter run 

Step 4: Interact with the Chip Selection

Once the app is running, you'll see a list of sports displayed as chips. Tap on a chip to select or deselect it. You can select multiple sports, and the selected chips will be visually highlighted.

Congratulations! You've just built a simple chip selection UI using the Chip widget in Flutter. The Chip widget's flexibility and interactivity make it an excellent choice for various use cases, ranging from simple selection tasks to more complex data representation.

Complete Source Code

import 'package:flutter/material.dart';


void main() {
  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});


  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.green),
        useMaterial3: true,
      ),
      home: const ChipSelectionScreen(),
    );
  }
}


class ChipSelectionScreen extends StatefulWidget {
  const ChipSelectionScreen({super.key});


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


class _ChipSelectionScreenState extends State<ChipSelectionScreen> {
  List<String> sports = [
    'Football',
    'Basketball',
    'Tennis',
    'Baseball',
    'Cricket',
    'Swimming',
    'Running',
  ];
  List<String> selectedSports = [];


  void toggleSportSelection(String sport) {
    setState(() {
      if (selectedSports.contains(sport)) {
        selectedSports.remove(sport);
      } else {
        selectedSports.add(sport);
      }
    });
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('FlutterforGeeks'),
        backgroundColor: Colors.green.shade300,
      ),
      body: Column(
        children: [
          const Padding(
            padding: EdgeInsets.all(8.0),
            child: Text(
              'Horizontal ListView',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          SizedBox(
            height: 80,
            child: ListView.builder(
              itemCount: sports.length,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context, index) {
                final sport = sports[index];
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ChoiceChip(
                    label: Text(sport),
                    selected: selectedSports.contains(sport),
                    onSelected: (isSelected) => toggleSportSelection(sport),
                  ),
                );
              },
            ),
          ),
          const Text(
            'Vertical ListView',
            style: TextStyle(fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 500,
            child: ListView.builder(
              itemCount: sports.length,
              itemBuilder: (context, index) {
                final sport = sports[index];
                return Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: ChoiceChip(
                    label: Text(sport),
                    selected: selectedSports.contains(sport),
                    onSelected: (isSelected) => toggleSportSelection(sport),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

Video Demo


Conclusion

In this blog post, we explored the Chip widget in Flutter, understanding its features and usage in creating interactive and user-friendly interfaces. We also implemented a practical example to demonstrate how to use the Chip widget effectively. By incorporating the Chip widget in your Flutter app, you can enhance user engagement and provide a delightful user experience.

Remember, Flutter offers a wide range of widgets and tools to build impressive applications. Experiment with different widgets and explore Flutter's capabilities to create unique and engaging mobile experiences. Happy coding!

Description of the image

Related Posts