Ranko Koturic
Ranko Koturic

Reputation: 127

How to remove first part of string so I can decode it. flutter/dart

I'm getting bytes property from api as a string but it has prefix and it looks like this: data:application/octet-stream;base64,JVBERi0xLjcNJeLjz9MNCjEgMCBvYmoNPDwv.... So my question is how can i remove this part data:application/octet-stream;base64, from string so I can decode the rest of same string.

Upvotes: 0

Views: 1207

Answers (5)

jamesdlin
jamesdlin

Reputation: 89946

Use the built-in UriData class to parse data URLs and to automatically perform base64-decoding for you:

var dataUrl = 'data:application/octet-stream;base64,JVBERi0xLjcNJeLjz9MNCjEgMCBvYmoNPDwv...';
var parsedBytes = UriData.parse(dataUrl).contentAsBytes();

or a complete working example:

void main() {
  var dataUrl = Uri.dataFromBytes(
    [0, 1, 2, 3, 4, 5],
    mimeType: 'application/octet-stream',
  ).toString();

  print(dataUrl); // Prints: data:application/octet-stream;base64,AAECAwQF
  
  var parsedBytes = UriData.parse(dataUrl).contentAsBytes();
  print(parsedBytes); // Prints: [0, 1, 2, 3, 4, 5]
}

Upvotes: 3

Akshay Gupta
Akshay Gupta

Reputation: 621

I think data:application/octet-stream;base64, is base64 string of your any picture so simply you can use split method with split("data:application/octet-stream;base64,") so it will cut down the string in two part and i had a experience with bas64 string data:application/octet-stream;base64, is same every time so you can hard code it use use it like

final str = "data:application/octet-stream;base64,JVBERi0xLjcNJeLjz9MNCjEgMCBvYmoNPDwv0w".split("data:application/octet-stream;base64,")[1];

Upvotes: 0

Vivek makwana
Vivek makwana

Reputation: 19

Another way to do it is Like :

final secondHalf = str!.split(',').last; /// Answer : JVBERi0xLjcNJeLjz9MNCjEgMCBvYmoNPDwv0w

final firstHald = str!.split(',').first;  /// Answer : data:application/octet-stream;base64

Upvotes: 1

Ivo
Ivo

Reputation: 23154

Another way to do it is like:

final str = "data:application/octet-stream;base64,JVBERi0xLjcNJeLjz9MNCjEgMCBvYmoNPDwv0w";
final desiredStr = str.substring(str.indexOf(',') + 1);

Upvotes: 1

Wiktor
Wiktor

Reputation: 775

Simply use a .split() method.

  final str = "data:application/octet-stream;base64,JVBERi0xLjcNJeLjz9MNCjEgMCBvYmoNPDwv0w";
  final desiredStr = str.split(',')[1];

Upvotes: 2

Related Questions