cupertino_segmented_control.0.dart 2.59 KB
Newer Older
1 2 3 4 5 6
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/cupertino.dart';

7 8
/// Flutter code sample for [CupertinoSegmentedControl].

9 10
enum Sky { midnight, viridian, cerulean }

11
Map<Sky, Color> skyColors = <Sky, Color>{
12 13 14 15 16
  Sky.midnight: const Color(0xff191970),
  Sky.viridian: const Color(0xff40826d),
  Sky.cerulean: const Color(0xff007ba7),
};

17
void main() => runApp(const SegmentedControlApp());
18

19
class SegmentedControlApp extends StatelessWidget {
20
  const SegmentedControlApp({super.key});
21 22 23 24

  @override
  Widget build(BuildContext context) {
    return const CupertinoApp(
25 26
      theme: CupertinoThemeData(brightness: Brightness.light),
      home: SegmentedControlExample(),
27 28 29 30
    );
  }
}

31
class SegmentedControlExample extends StatefulWidget {
32
  const SegmentedControlExample({super.key});
33 34

  @override
35
  State<SegmentedControlExample> createState() => _SegmentedControlExampleState();
36 37
}

38
class _SegmentedControlExampleState extends State<SegmentedControlExample> {
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  Sky _selectedSegment = Sky.midnight;

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      backgroundColor: skyColors[_selectedSegment],
      navigationBar: CupertinoNavigationBar(
        // This Cupertino segmented control has the enum "Sky" as the type.
        middle: CupertinoSegmentedControl<Sky>(
          selectedColor: skyColors[_selectedSegment],
          // Provide horizontal padding around the children.
          padding: const EdgeInsets.symmetric(horizontal: 12),
          // This represents a currently selected segmented control.
          groupValue: _selectedSegment,
          // Callback that sets the selected segmented control.
          onValueChanged: (Sky value) {
            setState(() {
              _selectedSegment = value;
            });
          },
          children: const <Sky, Widget>{
            Sky.midnight: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
62
              child: Text('Midnight'),
63 64 65
            ),
            Sky.viridian: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
66
              child: Text('Viridian'),
67 68 69
            ),
            Sky.cerulean: Padding(
              padding: EdgeInsets.symmetric(horizontal: 20),
70
              child: Text('Cerulean'),
71 72 73 74 75 76 77 78 79 80 81 82 83
            ),
          },
        ),
      ),
      child: Center(
        child: Text(
          'Selected Segment: ${_selectedSegment.name}',
          style: const TextStyle(color: CupertinoColors.white),
        ),
      ),
    );
  }
}