Flutter - How to put List<Uint8List> into shared preferences?

1.9k Views Asked by At

I have a list of Unit8List which stores data of multiple images. I want to share the list with other activities so that other activities can use the list to display the images. So how can i share using SharedPreferences? or is there any way that i can use to pass the list having Unit8List objects?

2

There are 2 best solutions below

0
On BEST ANSWER

I believe the other answer as proposed by Christopher will give incorrect results for some binary values, at least on Android. The correct approach is to use a standard binary to printable string encoding. A common one is Base64.

// convert to Base64
var printableString = base64.encode(bytesIn);

// and back
var bytesOut = base64.decode(printableString);
5
On

You can use the following code to essentially "convert" your Uint8List to a String, which can then be easily stored in SharedPreferences with the setString method of the SharePreferences class:

String s = String.fromCharCodes(inputAsUint8List);

and converting back

var outputAsUint8List = Uint8List.fromList(s.codeUnits);

Credit to Günter Zöchbauer for the String conversion.

Alternatively(as Richard Heap suggested), you could base64 encode your data with

String s = base64.encode(inputAsList);

in the dart:convert library for potentially greater safety, though this will increase the amount of space you will use to store the string.