Flutter uint8list to string

To convert a Flutter `Uint8List` to a string, you can use the `base64` library.

Here’s an example along with an explanation:

import 'dart:convert';
import 'package:flutter/widgets.dart';
import 'dart:typed_data';

void main() {
  Uint8List bytes = Uint8List.fromList([97, 98, 99, 100]); // Example Uint8List
  String encodedString = base64Encode(bytes); // Conversion to base64-encoded string
  print(encodedString); // Outputs: "YWJjZA=="
  
  Uint8List decodedBytes = base64Decode(encodedString); // Conversion back to Uint8List
  print(decodedBytes); // Outputs: [97, 98, 99, 100]
}

In the example above, we have a sample `Uint8List` named `bytes` with values `[97, 98, 99, 100]`.

We use the `base64Encode` function from the `dart:convert` library to convert this byte array to a base64-encoded string named `encodedString`.

The output of `print(encodedString)` is `”YWJjZA==”`.

To reverse the process and convert the encoded string back to a `Uint8List`, we use the `base64Decode` function with `encodedString` as the parameter.

The output of `print(decodedBytes)` is `[97, 98, 99, 100]`, which matches the original byte array `bytes`.

Leave a comment