c#图片base64去转义字符_如何使用Flutter将BASE64字符串转换为Image?

I'm converting images saved in my Firebase database to Base64 and would like to decode and encode. I've researched similar questions, but am still getting errors. Here is what I have so far?

var image1 = String;

var pic = event.snapshot.value['image'];

var photo = BASE64.decode(pic);

image1 = photo;

I'm getting the following error...

A value of type "List" cannot be assigned to a variable of type "Type"

If you could please provide a reverse process for encoding an image into Base64 so they may be saved back to Firebase, that would be appreciated.

*** UPDATE

Here is my updated code that's still throwing an error.

image1 = event.snapshot.value['image'];

var image = BASE64.decode(image1.toString());

new Image.memory(image),

The error is...

FormatException: Invalid Length must be a multiple of 4

解决方案

You can convert a Uint8List to a Flutter Image widget using the Image.memory constructor. (Use the Uint8List.fromList constructor to convert a List to Uint8List if necessary.) You can use BASE64.encode to go the other way.

Here's some sample code.

import 'dart:async';

import 'dart:convert';

import 'dart:typed_data';

import 'package:flutter/material.dart';

import 'package:http/http.dart' as http;

void main() {

runApp(new MyApp());

}

class MyApp extends StatelessWidget {

@override

Widget build(BuildContext context) {

return new MaterialApp(

theme: new ThemeData.dark(),

home: new MyHomePage(),

);

}

}

class MyHomePage extends StatefulWidget {

@override

State createState() => new MyHomePageState();

}

class MyHomePageState extends State {

String _base64;

@override

void initState() {

super.initState();

(() async {

http.Response response = await http.get(

'https://flutter.io/images/flutter-mark-square-100.png',

);

if (mounted) {

setState(() {

_base64 = BASE64.encode(response.bodyBytes);

});

}

})();

}

@override

Widget build(BuildContext context) {

if (_base64 == null)

return new Container();

Uint8List bytes = BASE64.decode(_base64);

return new Scaffold(

appBar: new AppBar(title: new Text('Example App')),

body: new ListTile(

leading: new Image.memory(bytes),

title: new Text(_base64),

),

);

}

}

However, it's generally a bad idea to store large blobs of binary data in your database. It's not playing to the strengths of Firebase realtime database and you will end up wasting bandwidth transmitting data you don't need as well as unnecessary encoding and decoding. You should use the firebase_storage plugin instead, storing the path or download URL of the image in the database.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值