
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, 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 properties as described below:Advertisements
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';
// Material Icon
final IconData _iconOne = Icons.add;
final int _iconOneCodePoint = _iconOne.codePoint;
final String? _iconOneFontFamily = _iconOne.fontFamily;
final String? _iconOneFontPackage = _iconOne.fontPackage;
final bool _iconOneDirection = _iconOne.matchTextDirection;
print(
'$_iconOneCodePoint, $_iconOneFontFamily, $_iconOneFontPackage, $_iconOneDirection');
/* Run your saving code here */
// Cupertino Icon
final IconData _iconTwo = CupertinoIcons.ant_circle;
final int _iconTwoCodePoint = _iconTwo.codePoint;
final String? _iconTwoFontFamily = _iconTwo.fontFamily;
final String? _iconTwoFontPackage = _iconTwo.fontPackage;
final bool _iconTwoDirection = _iconTwo.matchTextDirection;
print(
'$_iconTwoCodePoint, $_iconTwoFontFamily, $_iconTwoFontPackage, $_iconTwoDirection');
/* Run your saving code here */
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
AdvertisementsYouÂ’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.