【问题标题】:How to convert image(url format) to Base64 from Api response如何将图像(url 格式)从 Api 响应转换为 Base64
【发布时间】:2020-09-03 12:22:51
【问题描述】:

我正在尝试将图像(url 格式)从 Api 转换为 BASE64 字符串,但我不知道该怎么做。Api 响应看起来像这样

{
    "albumId": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "https://via.placeholder.com/600/92c952",
  },

我试过这样

    import 'package:flutter/material.dart';
    import 'dart:async';
    import 'dart:convert';
    import 'package:http/http.dart' as http;


    Future<List> getJson() async {

      String apiUrl = 'https://jsonplaceholder.typicode.com/photos';

      http.Response response = await http
       .get(apiUrl);


      return json.decode(response.body); 
    }


    void main() async {

      List _data = await getJson();

      String _body = "${_data[0]['url']}";
    String data = base64.encode(_body.bodyBytes); Error here ..The getter 'bodyBytes' isn't defined for the class 'String'.

print("$data");  

      runApp(
        new MaterialApp(
          home: new Scaffold(
            appBar: new AppBar(
              title: new Text('Json parse'),
              centerTitle: true,
              backgroundColor: Colors.orangeAccent,
            ),
            body: new Center(
              child: new Text("khan   ${_data[0]['url']}"),

            ),
          ),
        ),
      );
    }

我知道我做错了,我是新来的。如果有人还告诉我如何再次显示该字符串以进行图像处理,那就太好了。 注意:我正在存储该图像字符串以用于电子商务购物车。

【问题讨论】:

    标签: api flutter dart base64


    【解决方案1】:

    您可以在下面复制粘贴运行完整代码
    第 1 步:您可以使用

    解析 json 字符串
    Future<List<Payload>> getJson() async {
        String apiUrl = 'https://jsonplaceholder.typicode.com/photos';
        http.Response response = await http.get(apiUrl);
        return payloadFromJson(response.body);
      }
    

    第二步:获取base64字符串

    payloadList = await getJson();
        http.Response imageResponse = await http.get(
          payloadList[0].url,
        );
    base64String = base64.encode(imageResponse.bodyBytes);
    

    第 3 步:用

    显示图像
    base64String == null
                      ? Container()
                      : Image.memory(base64Decode(base64String)),
    payloadList == null
      ? Container()
      : Image.network(payloadList[0].url),
    

    工作演示

    完整代码

    import 'package:flutter/material.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    List<Payload> payloadFromJson(String str) =>
        List<Payload>.from(json.decode(str).map((x) => Payload.fromJson(x)));
    
    String payloadToJson(List<Payload> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class Payload {
      int albumId;
      String title;
      String url;
    
      Payload({
        this.albumId,
        this.title,
        this.url,
      });
    
      factory Payload.fromJson(Map<String, dynamic> json) => Payload(
            albumId: json["albumId"],
            title: json["title"],
            url: json["url"],
          );
    
      Map<String, dynamic> toJson() => {
            "albumId": albumId,
            "title": title,
            "url": url,
          };
    }
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Flutter Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          home: MyHomePage(title: 'Flutter Demo Home Page'),
        );
      }
    }
    
    class MyHomePage extends StatefulWidget {
      MyHomePage({Key key, this.title}) : super(key: key);
    
      final String title;
    
      @override
      _MyHomePageState createState() => _MyHomePageState();
    }
    
    class _MyHomePageState extends State<MyHomePage> {
      int _counter = 0;
      String base64String;
      List<Payload> payloadList;
    
      Future<List<Payload>> getJson() async {
        String apiUrl = 'https://jsonplaceholder.typicode.com/photos';
        http.Response response = await http.get(apiUrl);
        return payloadFromJson(response.body);
      }
    
      void _incrementCounter() async {
        payloadList = await getJson();
        http.Response imageResponse = await http.get(
          payloadList[0].url,
        );
        base64String = base64.encode(imageResponse.bodyBytes);
    
        setState(() {
          _counter++;
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text(widget.title),
          ),
          body: SingleChildScrollView(
            child: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  base64String == null
                      ? Container()
                      : Image.memory(base64Decode(base64String)),
                  payloadList == null
                      ? Container()
                      : Image.network(payloadList[0].url),
                  Text(
                    'You have pushed the button this many times:',
                  ),
                  Text(
                    '$_counter',
                    style: Theme.of(context).textTheme.headline4,
                  ),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: _incrementCounter,
            tooltip: 'Increment',
            child: Icon(Icons.add),
          ),
        );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 1970-01-01
      相关资源
      最近更新 更多