10

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.

Gabriel Costache
  • 859
  • 1
  • 6
  • 17

3 Answers3

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.

Aidan Marshall
  • 521
  • 6
  • 16
  • 2
    Great, here the ticket about the implementation and a image showing the behavior. https://github.com/flutter/flutter/pull/42775 – heat Mar 01 '20 at 23:44
1

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!

Ashkan Sarlak
  • 7,124
  • 6
  • 39
  • 51
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

Jamalianpour
  • 150
  • 1
  • 6