Flutter: Save Icon to Database, File, Shared Preferences

Last updated on May 11, 2021 The Losers Loading... Post a comment

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 don’t directly save icons to the database. Instead, we save their IconData properties as described below:

PropertyRequiredType
codePointYesint
fontFamilyOptionalString
fontPackageOptionalString
matchTextDirectionOptionalbool

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

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 FlutterSorting Lists in Dart and Flutter (5 Examples)How to disable Web and Desktop support in FlutterHow to set width, height, and padding of TextField in Flutter4 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.

Related Articles

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x