CupertinoPicker in Flutter

18-Sep-2024

Learn how to use CupertinoPicker to create iOS-style pickers for selection in Flutter

CupertinoPicker is a widget that provides an optional rotation wheel and is commonly used on iOS devices.
Allows the user to select one option from a list of choices

There Are Some Common Attributes for CupertinoPicker

itemExtent itemExtent property is used to set the height of each item in the picker
onSelectedItemChanged
onSelectedItemChanged callback is used to update the _selectedIndex when the user selects an item from the picker.

Here's a simple example of using a CupertinoPicker in Flutter:

File open lib->main.dart file −



import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
runApp(
MyApp()
);
}
class MyApp extends StatefulWidget{

@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
int _selectedIndex = 0;
// List of items for the dropdown
List<String> _items = ['Flutter', 'Java', 'Kotlin', 'JetPack'];
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Text('CupertinoPicker Example',
style:TextStyle(fontSize: 20,color: Colors.white)),
),
body:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [

SizedBox(
height: 200,
child: CupertinoPicker(
itemExtent: 60, // Height of each item
onSelectedItemChanged: (index) {
setState(() {
_selectedIndex = index;
});
},
children: _items.map((String item) {
return Center(
child: Text(item),
);
}).toList(),
),
),
SizedBox(height: 20),
Text('Selected Item : ${_items[_selectedIndex]}'),
],
),
)

));

}
}









Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.


Output:


Comments