'How can I allow a user to choose an Icon for something they're adding?
Is it possible to load all the icons from the Icon class and allow the user to pick one of them to be used? For example i want the user to input a text in a textfield and then pick an icon then add that text and icon to some sort of a list. I already know the text part but I can't figure out how to load all the icons and let the user choose one.
Solution 1:[1]
Flutter Icons are stored as static class members and reflect function is required to get a list of members of a class. Dart mirrors are needed to use reflect function and flutter doesn't allow using dart mirrors. So, it seems that it's not possible (or at least easy) to get a list of these members.
See here.
I suggest using material_design_icons_flutter package with below code.
@override
Widget build(BuildContext context) {
List<String> iconListKeys = iconMap.iconMap.keys.toList();
MdiIcons iconLib = new MdiIcons();
List<IconData> iconList = iconListKeys
.map<IconData>((String iconName) => iconLib[iconName])
.toList();
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: ListView(
children: iconList.map<Widget>((icon) => Icon(icon)).toList()),
),
);
}
keep in mind that the mentioned package may become outdated or discontinued. So above solution doesn't seem to be good for general usage.
Solution 2:[2]
Use this package called as Icon Picker
Example:
import 'package:flutter/material.dart';
import 'package:flutter_iconpicker/flutter_iconpicker.dart';
void main() {
runApp(
const MaterialApp(
home: HomeScreen(),
),
);
}
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Icon? _icon;
_pickIcon() async {
IconData? icon = await FlutterIconPicker.showIconPicker(context,
iconPackModes: [IconPack.cupertino]);
_icon = Icon(icon);
setState(() {});
debugPrint('Picked Icon: $icon');
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _pickIcon,
child: const Text('Open IconPicker'),
),
const SizedBox(height: 10),
AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: _icon ?? Container(),
),
],
),
),
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yamin |
Solution 2 | balu k |