简体   繁体   English

输入&#39;列表<dynamic> &#39; 不是类型 &#39;Uint8List 的子类型

[英]type 'List<dynamic>' is not a subtype of type 'Uint8List

I was using a flutter plugin named device_apps to get the application information installed in my android device.我正在使用名为device_apps的 flutter 插件来获取安装在我的 android 设备中的应用程序信息。

It returns a List<Application> which porvides icon if I cast the Object from Application to ApplicationWithIcon .如果我将 Object 从 Application 转换为ApplicationWithIcon它会返回一个List<Application> ,它提供图标。

But the icon it retuns is a Uint8 List type and i want to save it locally and use it later in Image.memory().但是它返回的图标是 Uint8 List 类型,我想将它保存在本地并稍后在 Image.memory() 中使用它。

If i directly use it without saving locally then it works fine as Image.memory(app.icon).But When i saved the icon in a json file and then used it then it shows the error :如果我直接使用它而不在本地保存,那么它作为 Image.memory(app.icon) 可以正常工作。但是当我将图标保存在 json 文件中然后使用它时,它会显示错误:

type 'List' is not a subtype of type 'Uint8List' “List”类型不是“Uint8List”类型的子类型

How can i save it locally and then use it ?如何将其保存在本地然后使用?

import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:device_apps/device_apps.dart';
import 'package:app_settings/app_settings.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: MyApp(),
    ),
  );
}

const String dataFile = 'data1.json';

class MyApp extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<MyApp> {
  String data;

  File _filePath;
  bool _fileExists = false;
  String jsonString;

  List<dynamic> _json = [];
  List<dynamic> _jsonshow = [];

  List<Application> appsDetail;

  void checkFile() async {
    // chek if file exists
    String dir = (await getApplicationDocumentsDirectory()).path;
    String savePath = '$dir/$dataFile';

//for a directory: await Directory(savePath).exists();
    if (await File(savePath).exists()) {
      print("File exists");
    } else {
      print("File don't exists");
    }
  }

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    print(directory.path);
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/$dataFile');
  }

  void appDetail() async {
    print("Getting app informations using 'device_apps' : ");
    List<Application> apps = await DeviceApps.getInstalledApplications(
      includeSystemApps: true,
      includeAppIcons: true,
      onlyAppsWithLaunchIntent: true,
    );
    print("Printing apps detail from appDetail() Funtion  apps : ");
    // for (int i = 0; i < apps.length; i++) print(apps[i]);

    print(apps);

    appsDetail = apps;

    for (int i = 0; i < apps.length; i++) {
      ApplicationWithIcon icon = apps[i] as ApplicationWithIcon;

      print(icon.icon.runtimeType);

      // print(apps[i]);
      _json.add({
        "totalApps": apps.length,
        "appName": apps[i].appName,
        "apkFilePath": apps[i].apkFilePath,
        "packageName": apps[i].packageName,
        "versionName": apps[i].versionName,
        "versionCode": apps[i].versionCode,
        "dataDir": apps[i].dataDir,
        "systemApp": apps[i].systemApp,
        "installTimeMillis": apps[i].installTimeMillis,
        "updateTimeMillis": apps[i].updateTimeMillis,
        "icon": icon.icon,

        // "category": apps[i].category
      });
    }

    print(_json);
  }

  void writeJsonfile() async {
    print("Writing json file : ");

    _filePath = await _localFile;

    print("json before encoding : ");
    print("$_json");

    jsonString = jsonEncode(_json);

    print("jsonString after encoding : ");

    print(jsonString);
    _filePath.writeAsString(
      jsonEncode(jsonString),
    );
  }

  Future<List<Object>> Apps() async {
    print("Reading Json file");

    _filePath = await _localFile;
    _fileExists = await _filePath.exists();
    print('0. File exists? $_fileExists');

    if (_fileExists) {
      try {
        String jsonString = await _filePath.readAsString();
        _json = jsonDecode(jsonString);
        print('printing json file after reading : ');
        print(_json);
        return _json;
      } catch (e) {
        // Print exception errors
        print('Tried reading _file error: $e');
        // If encountering an error, return null
      }
    } else {}
  }

  @override
  void initState() {
    super.initState();
    appDetail();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Reading and Writing data')),
        body: Column(
          children: <Widget>[
            IconButton(icon: Icon(Icons.ac_unit), onPressed: Apps),
            _json.length >= 1
                ? GridView.builder(
                    shrinkWrap: true,
                    physics: ScrollPhysics(),
                    scrollDirection: Axis.vertical,
                    itemCount: _json.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 5, childAspectRatio: 2.0),
                    itemBuilder: (BuildContext context, int index) {
                      return Column(
                        children: <Widget>[
                          Expanded(child: Text(_json[index]["appName"])),
                          Expanded(child: Image.memory(_json[index]["icon"])),
                        ],
                      );
                    })
                : Text("No Data Found"),
          ],
        ));
  }
}

I have found a silly solution and I don't know why this is working!我找到了一个愚蠢的解决方案,但我不知道为什么会这样!

Just insert _json[index]['icon'] into a variable and then use it inside Image.memory() that's it.只需将_json[index]['icon']插入一个变量,然后在 Image.memory() 中使用它,就是这样。

var icon = `_json[index]['icon']` ;

Image.memory(icon)

Here is the full code :这是完整的代码:


import 'dart:async';
import 'dart:convert';
import 'dart:ffi';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:device_apps/device_apps.dart';
import 'package:app_settings/app_settings.dart';
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: MyApp(),
    ),
  );
}

const String dataFile = 'data1.json';

class MyApp extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<MyApp> {
  String data;

  File _filePath;
  bool _fileExists = false;
  String jsonString;

  List<dynamic> _json = [];
  List<dynamic> _jsonshow = [];

  List<Application> appsDetail;

  void checkFile() async {
    // chek if file exists
    String dir = (await getApplicationDocumentsDirectory()).path;
    String savePath = '$dir/$dataFile';

//for a directory: await Directory(savePath).exists();
    if (await File(savePath).exists()) {
      print("File exists");
    } else {
      print("File don't exists");
    }
  }

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    print(directory.path);
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/$dataFile');
  }

  void appDetail() async {
    print("Getting app informations using 'device_apps' : ");
    List<Application> apps = await DeviceApps.getInstalledApplications(
      includeSystemApps: true,
      includeAppIcons: true,
      onlyAppsWithLaunchIntent: true,
    );
    print("Printing apps detail from appDetail() Funtion  apps : ");
    // for (int i = 0; i < apps.length; i++) print(apps[i]);

    print(apps);

    appsDetail = apps;

    for (int i = 0; i < apps.length; i++) {
      ApplicationWithIcon icon = apps[i] as ApplicationWithIcon;

      print(icon.icon.runtimeType);

      // print(apps[i]);
      _json.add({
        "totalApps": apps.length,
        "appName": apps[i].appName,
        "apkFilePath": apps[i].apkFilePath,
        "packageName": apps[i].packageName,
        "versionName": apps[i].versionName,
        "versionCode": apps[i].versionCode,
        "dataDir": apps[i].dataDir,
        "systemApp": apps[i].systemApp,
        "installTimeMillis": apps[i].installTimeMillis,
        "updateTimeMillis": apps[i].updateTimeMillis,
        "icon": icon.icon,

        // "category": apps[i].category
      });
    }

    print(_json);
  }

  void writeJsonfile() async {
    print("Writing json file : ");

    _filePath = await _localFile;

    print("json before encoding : ");
    print("$_json");

    jsonString = jsonEncode(_json);

    print("jsonString after encoding : ");

    print(jsonString);
    _filePath.writeAsString(
      jsonEncode(jsonString),
    );
  }

  Future<List<Object>> Apps() async {
    print("Reading Json file");

    _filePath = await _localFile;
    _fileExists = await _filePath.exists();
    print('0. File exists? $_fileExists');

    if (_fileExists) {
      try {
        String jsonString = await _filePath.readAsString();
        _json = jsonDecode(jsonString);
        print('printing json file after reading : ');
        print(_json);
        return _json;
      } catch (e) {
        // Print exception errors
        print('Tried reading _file error: $e');
        // If encountering an error, return null
      }
    } else {}
  }

  @override
  void initState() {
    super.initState();
    appDetail();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Reading and Writing data')),
        body: Column(
          children: <Widget>[
            IconButton(icon: Icon(Icons.ac_unit), onPressed: Apps),
            _json.length >= 1
                ? GridView.builder(
                    shrinkWrap: true,
                    physics: ScrollPhysics(),
                    scrollDirection: Axis.vertical,
                    itemCount: _json.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 5, childAspectRatio: 2.0),
                    itemBuilder: (BuildContext context, int index) {
                      print("Checking");
                      print(_json[index]["icon"].runtimeType);
                      var icon = _json[index]["icon"];
                      return Column(
                        children: <Widget>[
                          Expanded(child: Text(_json[index]["appName"])),
                          Expanded(child: Image.memory(icon)),
                        ],
                      );
                    })
                : Text("No Data Found"),
          ],
        ));
  }
}

I had the same issue while passing image from native module (Android) to Flutter.我在将图像从本机模块(Android)传递到 Flutter 时遇到了同样的问题。 (I was making a plugin) (我在做一个插件)

Flutter by default will handle data types coming from underlying platform and map it to proper datatype in Dart, check this table here to see datatypes.默认情况下,Flutter 会处理来自底层平台的数据类型并将其映射到 Dart 中的正确数据类型,请在此处查看此表以查看数据类型。 but it my case sounds like Flutter intercepeted value of type byte[] as List<dynamic> so simply just cast it from List<dynamic> to List<Int> where Flutter can deal with it.但在我的情况下,Flutter 将byte[]类型的值截取为List<dynamic>所以只需将它从List<dynamic>List<Int> ,Flutter 可以处理它。

  • Just copy this method and give it your List and it will cast &return Unit8List that can be used anywhere in Flutter such as image.memory() .只需复制这个方法并给它你的 List ,它就会转换 &return Unit8List ,它可以在 Flutter 的任何地方使用,比如image.memory()

  Uint8List _getImageBinary(dynamicList) {
    List<int> intList = dynamicList.cast<int>().toList(); //This is the magical line.
    Uint8List data = Uint8List.fromList(intList);
    return data;
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 颤振:输入“未来”<dynamic> &#39; 不是类型 &#39;Uint8List&#39; 的子类型 - Flutter: type 'Future<dynamic>' is not a subtype of type 'Uint8List' Uint8List 到文件 - Uint8List to file 输入'未来<dynamic> ' 不是类型 'List 的子类型<application> ?</application></dynamic> - type 'Future<dynamic>' is not a subtype of type 'List<Application>?' _TypeError(输入&#39;列表<dynamic> &#39; 不是类型 &#39;PlaceDetails&#39; 的子类型) - _TypeError (type 'List<dynamic>' is not a subtype of type 'PlaceDetails') 类型列表<dynamic>不是 Map 的子类型<string,dynamic></string,dynamic></dynamic> - type List<dynamic> is not a subtype of Map<String,dynamic> 输入'列表<dynamic> ' 不是类型 'List 的子类型<expense> ? 在类型转换中</expense></dynamic> - type 'List<dynamic>' is not a subtype of type 'List<Expense>?' in type cast 输入'列表<dynamic> ' 不是类型 'Map 的子类型<dynamic, dynamic> ' 在 flutter 应用程序中</dynamic,></dynamic> - type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>' in flutter app 颤振:输入&#39;列表<dynamic> &#39; 不是 &#39;List 类型的子类型<DropdownMenuItem<String> &gt;&#39; - flutter: type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<String>>' _TypeError(类型为“列表” <dynamic> &#39;不是&#39;Map类型的子类型 <String, dynamic> &#39;)扑 - _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>') flutter _InternalLinkedHashMap <String, dynamic> &#39;不是&#39;List类型的子类型 <Map<dynamic, dynamic> &gt;” - _InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<Map<dynamic, dynamic>>'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM