I am building an app where I am creating Icons using the IconData class. I would like to store the icons in a format like string or int to the database and retrieve it then conviniently convert back to an Icon.

This is how I am creating the icons.

var iconData = IconData(58717, fontFamily: 'MaterialIcons')

var icon = Icon(iconData)

Can someone suggest how to do this. The conversion can be done either at the IconData or Icon creation stage. Thanks.


Solution 1: Kalpesh Kundanani

Well you should not need to save IconData in the database you can create a dart file to hold the IconData in static const field. But, as per your use-case you can do following to serve your purpose.

First Option:

Properties of the IconData class are either int, String or bool and these data types are accepted by the database so you should save each icon in a table row whose column types are int, String and for bool you can use int.

Use primary key of that table as a forign key of your main data with whom you want to link that Icon with.

Second Option:

Convert Icondata into JSONString and keep it into database or preferences. If you don't know how can you create JSONString from IconData or vice versa then following is the code for your reference:

import 'dart:convert';

import 'package:flutter/material.dart';

String toJSONString(IconData data) {
  Map<String, dynamic> map = <String, dynamic>{};
  map['codePoint'] = data.codePoint;
  map['fontFamily'] = data.fontFamily;
  map['fontPackage'] = data.fontPackage;
  map['matchTextDirection'] = data.matchTextDirection;
  return jsonEncode(map);
}

IconData fromJSONString(String jsonString) {
  Map<String, dynamic> map = jsonDecode(jsonString);
  return IconData(
    map['codePoint'],
    fontFamily: map['fontFamily'],
    fontPackage: map['fontPackage'],
    matchTextDirection: map['matchTextDirection'],
  );
}

In case of any doubts, please comment. If it works for you then don't forget to accept and up-vote.


Solution 2: Barnett Temwa Msiska

I have found a way to do it using a property of the IconData class called codePoint which is an int representing the icon.

var iconData = IconData(58717, fontFamily: 'MaterialIcons')

// Store this in the database
var icon iconCodePoint = iconData.codePoint;

// Restore from the database to get icon
var iconData = IconData(iconCodePointFromDataBase, fontFamily: 'MaterialIcons');