Creare un color picker in Flutter con flutter_material_color_picker
flutter_material_color_picker è un package per Flutter che ci consente di creare un color picker.
Facile da usare, in quanto basta inserirlo in dialog; inoltre la palette colori a disposizione possiamo sia crearla a mano che usando fullMaterialColors.
Per installarlo:
flutter pub add flutter_material_color_picker
Qui un esempio di codice:
import 'package:flutter/material.dart';
import 'package:flutter_material_color_picker/flutter_material_color_picker.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Test',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.deepPurple,
),
useMaterial3: true,
),
// home: const MyHomePage(),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ColorSwatch _colorSwatch = Colors.amber;
void _pickColor() async {
showDialog(
context: context,
builder: (_) {
return AlertDialog(
contentPadding: const EdgeInsets.all(5.0),
actions: [
TextButton(
onPressed: Navigator.of(context).pop,
child: const Text('Chiudi'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop;
print(_colorSwatch.value);
},
child: const Text('Invia'),
),
],
content: MaterialColorPicker(
selectedColor: _colorSwatch,
allowShades: false,
colors: fullMaterialColors,
onMainColorChange: (color) {
setState(() {
_colorSwatch = color!;
});
},
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: const Text('Flutter Test'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
_pickColor();
},
child: const Text('Pick color'),
),
),
);
}
}
Enjoy!
dart flutter flutter_material_color_picker
Commentami!