Create a Segmented Control Widget with slider button - Flutter
Asked Answered
H

3

12

How do I create something similar to this?:

Demo :
Demo

I know flutter has

CupertinoSegmentedControl()

But this creates something similar to tabs, nothing that slides like something a Switch with a button inside.

Heddie answered 5/10, 2019 at 20:47 Comment(0)
P
28

Best thing I have found is the CupertinoSlidingSegmentedControl():

class _ViewState extends State<View> {
  int segmentedControlGroupValue = 0;
  final Map<int, Widget> myTabs = const <int, Widget>{
    0: Text("Item 1"),
    1: Text("Item 2")
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CupertinoSlidingSegmentedControl(
          groupValue: segmentedControlGroupValue,
          children: myTabs,
          onValueChanged: (i) {
            setState(() {
              segmentedControlGroupValue = i;
            });
          }),
    );
  }
}

Hope this helps. See the docs here.

Pomp answered 1/3, 2020 at 23:16 Comment(1)
Great, here the ticket about the implementation and a image showing the behavior. github.com/flutter/flutter/pull/42775Heiney
P
2

Check out the package https://pub.dev/packages/material_segmented_control for controls like enter image description here

Also check out https://pub.dev/packages/custom_sliding_segmented_control for these kinds of controls

enter image description here

Both of them let you customize visual aspects of the control like corner radius, color, etc. Personally I'm using them because CupertinoSegmentedControl and CupertinoSlidingSegmentedControl don't allow for changing the corner radius, which I needed for an app.

Kudos to the writers!

Poult answered 30/11, 2022 at 1:13 Comment(0)
O
1

Duo to material 3 without any package and easily you can use SegmentedButton:

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

For more info read this document: https://api.flutter.dev/flutter/material/SegmentedButton-class.html

Orison answered 16/5, 2023 at 14:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.