小编典典

如何使用Flutter将BASE64字符串转换为Image?

flutter

我要将保存在Firebase数据库中的图像转换为Base64,并希望进行解码和编码。我已经研究了类似的问题,但仍然遇到错误。到目前为止,这是我所拥有的?

var image1 = String;

var pic = event.snapshot.value['image'];
var photo = BASE64.decode(pic);
image1 = photo;

我收到以下错误…

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

如果您可以提供将图像编码为Base64的反向过程,以便可以将其保存回Firebase,将不胜感激。

***更新

这是我的更新代码,仍然会引发错误。

image1 = event.snapshot.value['image'];
var image = BASE64.decode(image1.toString());
new Image.memory(image),

错误是…

FormatException: Invalid Length must be a multiple of 4


阅读 1706

收藏
2020-08-13

共1个答案

小编典典

您可以使用构造函数将转换Uint8List为Flutter
Image小部件Image.memory。(使用Uint8List.fromList构造函数的转换ListUint8List如果需要的话)。你可以用BASE64.encode走另一条路。

这是一些示例代码。

屏幕截图

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<MyHomePage> {
  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),
      ),
    );
  }
}

但是,将大量二进制数据存储在数据库中通常是一个坏主意。它没有发挥Firebase实时数据库的优势,最终您将浪费带宽传输不需要的数据以及不必要的编码和解码。您应该改用firebase_storage插件,在数据库中存储图像的路径或下载URL。

2020-08-13