Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 850
KUNAL HIRANI Avatar asked Nov 01 '25 10:11

KUNAL HIRANI


2 Answers

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.

like image 131
Christopher Moore Avatar answered Nov 02 '25 23:11

Christopher Moore


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);
like image 26
Richard Heap Avatar answered Nov 03 '25 00:11

Richard Heap