In many cases, your application allows users to set and select some icons according to their wishes (for example, a task manager, a note app, or an event app). This short article shows you how to store icons in a database (or file, cloud, shared preferences, or other kinds of storage).
Actually, we cannot directly save icons to the database as saving strings or numbers. Instead, we save their IconData’s properties as described below:
Property | Required | Type |
---|---|---|
codePoint | Yes | int |
fontFamily | Optional | String |
fontPackage | Optional | String |
matchTextDirection | Optional | bool |
Example
Saving:
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() {
// Material Icon
const IconData iconOne = Icons.add;
final int iconOneCodePoint = iconOne.codePoint;
final String? iconOneFontFamily = iconOne.fontFamily;
final String? iconOneFontPackage = iconOne.fontPackage;
final bool iconOneDirection = iconOne.matchTextDirection;
debugPrint(
"$iconOneCodePoint, $iconOneFontFamily, $iconOneFontPackage, $iconOneDirection");
/* implement your persisting logic here */
// Cupertino Icon
const IconData iconTwo = CupertinoIcons.ant_circle_fill;
final int iconTwoCodePoint = iconTwo.codePoint;
final String? iconTwoFontFamily = iconTwo.fontFamily;
final String? iconTwoFontPackage = iconTwo.fontPackage;
final bool iconTwoDirection = iconTwo.matchTextDirection;
debugPrint(
'$iconTwoCodePoint, $iconTwoFontFamily, $iconTwoFontPackage, $iconTwoDirection');
/* implement your persisting logic here */
}
Output:
57415, MaterialIcons, null, false
62682, CupertinoIcons, cupertino_icons, false
Retrieving icons:
// Construct icon data from saved properties
final IconData iconData = IconData(iconOneCodePoint,
fontFamily: iconOneFontFamily,
fontPackage: iconOneFontPackage,
matchTextDirection: iconOneDirection);
Now you can use icon data to display an icon:
// Display the icon
Icon(iconData);
Wrapping Up
You’ve learned a technique to save icons to a database. This can be helpful for you in some situations you may encounter when developing apps. If you’d like to explore more new and interesting stuff about Flutter, take a look at the following articles:
- Adding and Customizing a Scrollbar in Flutter
- Sorting Lists in Dart and Flutter (5 Examples)
- How to disable Web and Desktop support in Flutter
- How to set width, height, and padding of TextField in Flutter
- 4 Ways to Store Data Offline in Flutter
You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.