How to use Segmented Button in Flutter?

As a flutter developer, you might have stumbled upon a use case where you need to create a button that has multiple size options just like when you shop for a dress in an e-commerce store like S, M,L, etc. Also, a use case where there are options to sort a list in a particular order.

To achieve this functionality Segmented Button is the right widget for the job. This widget is super useful for creating a great user experience for your Flutter apps. Let’s learn how to integrate this widget into your Flutter app.

What is Segmented Button in Flutter?

Segmented Button widgets are used to help people select options, switch views, or sort elements. They are typically used in cases where there are only 2-5 options. To understand this widget’s functionality let’s take a look at its constructor

Constructor

SegmentedButton({
 Key? key,
 required List<ButtonSegment<T>> segments,
 required Set<T> selected,
 void onSelectionChanged(Set<T>)?,
 bool multiSelectionEnabled = false,
 bool emptySelectionAllowed = false, 
 ButtonStyle? style,
 bool showSelectedIcon = true, 
Widget? selectedIcon})

These are the parameters you need to pass to this widget. Now let’s take a look at its properties

Properties

emptySelectionAllowed: Determines if having no selected segments is allowed.
multiSelectionEnabled: Determines if multiple segments can be selected at one time.
emptySelectionAllowed: Determines if having no selected segments is allowed.
multiSelectionEnabled: Determines if multiple segments can be selected at one time.
onSelectionChanged: The function that is called when the selection changes.
runtimeType: A representation of the runtime type of the object.
segments: Descriptions of the segments in the button.
selected: The set of ButtonSegment.values that indicate which segments are selected.
selectedIcon: An icon that is used to indicate a segment is selected.
showSelectedIcon: Determines if the selectedIcon (usually an icon using Icons.check) is displayed on the selected segments.
style : Customizes this button’s appearance.

These are what each parameters do.

How to implement Segmented Button in Flutter?

Lets see how we can implemented Segmented Button example in Flutter by the following code.

SegmentedButton<Calendar>(
      segments: const <ButtonSegment<Calendar>>[
        ButtonSegment<Calendar>(
            value: Calendar.day,
            label: Text('Day'),
            icon: Icon(Icons.calendar_view_day)),
        ButtonSegment<Calendar>(
            value: Calendar.week,
            label: Text('Week'),
            icon: Icon(Icons.calendar_view_week)),
        ButtonSegment<Calendar>(
            value: Calendar.month,
            label: Text('Month'),
            icon: Icon(Icons.calendar_view_month)),
        ButtonSegment<Calendar>(
            value: Calendar.year,
            label: Text('Year'),
            icon: Icon(Icons.calendar_today)),
      ],
      selected: <Calendar>{calendarView},
      onSelectionChanged: (Set<Calendar> newSelection) {
        setState(() {
          calendarView = newSelection.first;
        });
      },
    )

In the above code, we add each ButtonSegment Widget to the SegmentedButton which represents different buttons with their respective icons.Each button has its own feature or functionality.

Complete Implementation

import 'package:flutter/material.dart';

/// Flutter code sample for [SegmentedButton.styleFrom].

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Scaffold(
        body: Center(
          child: SegmentedButtonExample(),
        ),
      ),
    );
  }
}

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

  @override
  State<SegmentedButtonExample> createState() => _SegmentedButtonExampleState();
}

enum Calendar { day, week, month, year }

class _SegmentedButtonExampleState extends State<SegmentedButtonExample> {
  Calendar calendarView = Calendar.week;

  @override
  Widget build(BuildContext context) {
    return SegmentedButton<Calendar>(
      style: SegmentedButton.styleFrom(
        backgroundColor: Colors.grey[200],
        foregroundColor: Colors.red,
        selectedForegroundColor: Colors.white,
        selectedBackgroundColor: Colors.green,
      ),
      segments: const <ButtonSegment<Calendar>>[
        ButtonSegment<Calendar>(
            value: Calendar.day,
            label: Text('Day'),
            icon: Icon(Icons.calendar_view_day)),
        ButtonSegment<Calendar>(
            value: Calendar.week,
            label: Text('Week'),
            icon: Icon(Icons.calendar_view_week)),
        ButtonSegment<Calendar>(
            value: Calendar.month,
            label: Text('Month'),
            icon: Icon(Icons.calendar_view_month)),
        ButtonSegment<Calendar>(
            value: Calendar.year,
            label: Text('Year'),
            icon: Icon(Icons.calendar_today)),
      ],
      selected: <Calendar>{calendarView},
      onSelectionChanged: (Set<Calendar> newSelection) {
        setState(() {
          // By default there is only a single segment that can be
          // selected at one time, so its value is always the first
          // item in the selected set.
          calendarView = newSelection.first;
        });
      },
    );
  }
}

Conclusion

In this article we learned how to use Segmeneted Button widget which helps people select options, switch views, or sort elements.Using this widget it enhances the usability,aesthetics and user experience of their applications.Try experimenting with different styles and parameters to use this widget according to the use case.

Wanna Level up Your Flutter game? Then check out our ebook The Complete Guide to Flutter Developement where we teach you how to build production grade cross platform apps from scratch.Do check it out to completely Master Flutter framework from basic to advanced level.

Also Read

How to disable text field in flutter

Expansion Tile in Flutter

Leave a comment