5.8 C
New York
Tuesday, December 5, 2023

Flutter: Save Icon to Database, File, Shared Preferences

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



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;
      '$_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;
      '$_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

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:

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


Related Articles

Latest Articles