Created
October 12, 2021 01:36
-
-
Save manthri-mohan-sai/9f5f0ec52212c6567d91501c941933b6 to your computer and use it in GitHub Desktop.
Cupertino Segmented Control implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/cupertino.dart'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({Key? key}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: const MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
const MyHomePage({Key? key, required this.title}) : super(key: key); | |
final String title; | |
@override | |
State<MyHomePage> createState() => _MyHomePageState(); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
// Cupertino Segmented Control takes children in form of Map. | |
final cupertinoMap = <int, Widget>{}; | |
//The Widgets that has to be loaded when a tab is selected. | |
late List<Widget> childWidgets; | |
late List<String> cupertinoSegmentedTitles; | |
int selectedIndex = 0; | |
@override | |
void initState() { | |
super.initState(); | |
cupertinoSegmentedTitles = ['Upcoming', 'Live', 'Completed']; | |
loadCupertinoTabs(); | |
loadCupertinoChildWidgets(); | |
} | |
void loadCupertinoTabs() { | |
for (var i = 0; i < 3; i++) { | |
cupertinoMap.putIfAbsent( | |
i, | |
() => Padding( | |
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), | |
child: Text(cupertinoSegmentedTitles[i]), | |
), | |
); | |
} | |
} | |
void loadCupertinoChildWidgets() { | |
childWidgets = []; | |
for (var i = 0; i < 3; i++) { | |
childWidgets.add(Center(child: Text("child $i"))); | |
} | |
} | |
Widget childWidget() { | |
return childWidgets.elementAt(selectedIndex); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(), | |
body: Column( | |
children: [ | |
CupertinoSegmentedControl<int>( | |
onValueChanged: (value) => setState(() => selectedIndex = value), | |
children: cupertinoMap, | |
padding: const EdgeInsets.all(12), | |
groupValue: selectedIndex, | |
selectedColor: Colors.green, | |
pressedColor: Colors.green.shade100, | |
unselectedColor: Colors.white, | |
borderColor: Colors.grey.shade300, | |
), | |
Expanded( | |
child: childWidget(), | |
) | |
], | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment