Kinda Code
Home/Flutter/Flutter: Save Icon to Database, File, Shared Preferences

Flutter: Save Icon to Database, File, Shared Preferences

Last updated: April 26, 2023

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:

PropertyRequiredType
codePointYesint
fontFamilyOptionalString
fontPackageOptionalString
matchTextDirectionOptionalbool

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:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.