Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asynchronous 用于图像散列的颤振计算函数_Asynchronous_Flutter_Strong Typing - Fatal编程技术网

Asynchronous 用于图像散列的颤振计算函数

Asynchronous 用于图像散列的颤振计算函数,asynchronous,flutter,strong-typing,Asynchronous,Flutter,Strong Typing,hii我正在尝试实现计算功能。我正在尝试使用image_picker插件通过摄像头单击图像。然后我尝试获取图像文件的哈希摘要。由于这是一个非常激烈的操作,我试图使用compute函数,但无法做到这一点。 这就是我到目前为止所做的 final File picture = await ImagePicker.pickImage( source: ImageSource.camera); setState(() { _imageFile = picture;

hii我正在尝试实现计算功能。我正在尝试使用image_picker插件通过摄像头单击图像。然后我尝试获取图像文件的哈希摘要。由于这是一个非常激烈的操作,我试图使用compute函数,但无法做到这一点。 这就是我到目前为止所做的

final File picture = await ImagePicker.pickImage(
        source: ImageSource.camera);
    setState(() {
      _imageFile = picture;
    });
var result = await compute(generateImageHash(), _imageFile);
    print(result);
这是我的generateImageHash函数,我正试图将其传递给compute函数

generateImageHash() async{
    var image_bytes =  _imageFile.readAsBytesSync().toString();
    var bytes = utf8.encode(image_bytes); // data being hashed
    String digest = sha256.convert(bytes).toString();
    print("This is image Digest :  $digest");
    return digest;
  }
但是当我用手机点击图片时,我发现了以下错误

 Unhandled Exception: type 'Future<dynamic>' is not a subtype of type '(File) => FutureOr<dynamic>'
未处理的异常:类型“Future”不是类型“(文件)=>FutureOr”的子类型

我不熟悉强类型语言,请帮助。谢谢

第一期请更改

var result = await compute(generateImageHash(), _imageFile); 

你不需要这个()
相似的

第二个问题请从计算中删除wait关键字

var result = compute(generateImageHash, _imageFile);
您需要修改

Future<String> generateImageHash(File file) async{
Future generateImageHash(文件)异步{
把它放在课外

我只提供完整的工作代码和演示图片。 您可以在这张图片中看到摘要字符串

// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:crypto/crypto.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Picker Demo',
      home: MyHomePage(title: 'Image Picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Future<String> generateImageHash(File file) async{
  var image_bytes =  file.readAsBytesSync().toString();
  var bytes = utf8.encode(image_bytes); // data being hashed
  String digest = sha256.convert(bytes).toString();
  print("This is image Digest :  $digest");
  return  digest;
}

class _MyHomePageState extends State<MyHomePage> {
  File _imageFile;
  dynamic _pickImageError;
  bool isVideo = false;
  VideoPlayerController _controller;
  String _retrieveDataError;



  void _onImageButtonPressed(ImageSource source) async {
    if (_controller != null) {
      _controller.setVolume(0.0);
      _controller.removeListener(_onVideoControllerUpdate);
    }
    if (isVideo) {
      ImagePicker.pickVideo(source: source).then((File file) {
        if (file != null && mounted) {
          setState(() {
            _controller = VideoPlayerController.file(file)
              ..addListener(_onVideoControllerUpdate)
              ..setVolume(1.0)
              ..initialize()
              ..setLooping(true)
              ..play();
          });
        }
      });
    } else {
      try {
        print("_imageFile start");
        _imageFile = await ImagePicker.pickImage(source: source);
        print("_imageFile end");

        print("compute start");
        var result = compute(generateImageHash, _imageFile);
        print("compute end");
        print(result);
      } catch (e) {
        _pickImageError = e;
      }
      setState(() {});
    }
  }

  void _onVideoControllerUpdate() {
    setState(() {});
  }

  @override
  void deactivate() {
    if (_controller != null) {
      _controller.setVolume(0.0);
      _controller.removeListener(_onVideoControllerUpdate);
    }
    super.deactivate();
  }

  @override
  void dispose() {
    if (_controller != null) {
      _controller.dispose();
    }
    super.dispose();
  }

  Widget _previewVideo(VideoPlayerController controller) {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (controller == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    } else if (controller.value.initialized) {
      return Padding(
        padding: const EdgeInsets.all(10.0),
        child: AspectRatioVideo(controller),
      );
    } else {
      return const Text(
        'Error Loading Video',
        textAlign: TextAlign.center,
      );
    }
  }

  Widget _previewImage() {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_imageFile != null) {
      return Image.file(_imageFile);
    } else if (_pickImageError != null) {
      return Text(
        'Pick image error: $_pickImageError',
        textAlign: TextAlign.center,
      );
    } else {
      return const Text(
        'You have not yet picked an image.',
        textAlign: TextAlign.center,
      );
    }
  }

  Future<void> retrieveLostData() async {
    final LostDataResponse response = await ImagePicker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      setState(() {
        if (response.type == RetrieveType.video) {
          isVideo = true;
          _controller = VideoPlayerController.file(response.file)
            ..addListener(_onVideoControllerUpdate)
            ..setVolume(1.0)
            ..initialize()
            ..setLooping(true)
            ..play();
        } else {
          isVideo = false;
          _imageFile = response.file;
        }
      });
    } else {
      _retrieveDataError = response.exception.code;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Platform.isAndroid
            ? FutureBuilder<void>(
          future: retrieveLostData(),
          builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return const Text(
                  'You have not yet picked an image.',
                  textAlign: TextAlign.center,
                );
              case ConnectionState.done:
                return isVideo
                    ? _previewVideo(_controller)
                    : _previewImage();
              default:
                if (snapshot.hasError) {
                  return Text(
                    'Pick image/video error: ${snapshot.error}}',
                    textAlign: TextAlign.center,
                  );
                } else {
                  return const Text(
                    'You have not yet picked an image.',
                    textAlign: TextAlign.center,
                  );
                }
            }
          },
        )
            : (isVideo ? _previewVideo(_controller) : _previewImage()),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () {
              isVideo = false;
              _onImageButtonPressed(ImageSource.gallery);
            },
            heroTag: 'image0',
            tooltip: 'Pick Image from gallery',
            child: const Icon(Icons.photo_library),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(ImageSource.camera);
              },
              heroTag: 'image1',
              tooltip: 'Take a Photo',
              child: const Icon(Icons.camera_alt),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.gallery);
              },
              heroTag: 'video0',
              tooltip: 'Pick Video from gallery',
              child: const Icon(Icons.video_library),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.camera);
              },
              heroTag: 'video1',
              tooltip: 'Take a Video',
              child: const Icon(Icons.videocam),
            ),
          ),
        ],
      ),
    );
  }

  Text _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }
}

class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller.value.initialized) {
      initialized = controller.value.initialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller.addListener(_onVideoControllerUpdate);
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller.value?.aspectRatio,
          child: VideoPlayer(controller),
        ),
      );
    } else {
      return Container();
    }
  }
}
//Chromium作者版权所有。保留所有权利。
//此源代码的使用受BSD样式许可证的约束,该许可证可以
//在许可证文件中找到。
导入“dart:async”;
导入“dart:io”;
进口“包装:颤振/材料.省道”;
导入“包:image_picker/image_picker.dart”;
导入“package:video_player/video_player.dart”;
导入“dart:async”;
导入“dart:convert”;
进口“包装:颤振/基础.dart”;
导入“包:crypto/crypto.dart”;
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“图像选择器演示”,
主页:MyHomePage(标题:“图像选择器示例”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
Future generateImageHash(文件)异步{
var image_bytes=file.readAsBytesSync().toString();
var bytes=utf8.encode(图像字节);//正在散列的数据
字符串摘要=sha256.convert(字节).toString();
打印(“这是图像摘要:$Digest”);
返回摘要;
}
类_MyHomePageState扩展状态{
文件imageFile;
动态误差;
bool isVideo=false;
视频播放控制器\u控制器;
字符串_retrieveDataError;
void _onImageButtonPressed(图像源)异步{
如果(_controller!=null){
_控制器。设置音量(0.0);
_控制器。removeListener(\u onVideoControllerUpdate);
}
如果(isVideo){
pickVideo(源代码:source).then((文件){
if(文件!=null&&mounted){
设置状态(){
_控制器=VideoPlayerController.file(文件)
..addListener(视频控制器更新)
..设置音量(1.0)
…初始化()
..设置循环(真)
…玩();
});
}
});
}否则{
试一试{
打印(“_imagefilestart”);
_imageFile=await ImagePicker.pickImage(源:源);
打印(“_imagefileend”);
打印(“计算开始”);
var result=compute(generateImageHash,_imageFile);
打印(“计算结束”);
打印(结果);
}捕获(e){
_pickImageError=e;
}
setState((){});
}
}
void _onVideoControllerUpdate(){
setState((){});
}
@凌驾
无效停用(){
如果(_controller!=null){
_控制器。设置音量(0.0);
_控制器。removeListener(\u onVideoControllerUpdate);
}
super.deactivate();
}
@凌驾
无效处置(){
如果(_controller!=null){
_controller.dispose();
}
super.dispose();
}
小部件预览视频(视频播放器控制器){
最终文本检索错误=_getRetrieveErrorWidget();
如果(retrieveError!=null){
返回检索错误;
}
如果(控制器==null){
返回常量文本(
“您尚未选择视频”,
textAlign:textAlign.center,
);
}else if(controller.value.initialized){
返回填充(
填充:常数边集全部(10.0),
子项:AspectRatioVideo(控制器),
);
}否则{
返回常量文本(
“加载视频时出错”,
textAlign:textAlign.center,
);
}
}
小部件_previewImage(){
最终文本检索错误=_getRetrieveErrorWidget();
如果(retrieveError!=null){
返回检索错误;
}
如果(_imageFile!=null){
返回Image.file(_imageFile);
}else if(_pickImageError!=null){
返回文本(
'拾取图像错误:$\u pickImageError',
textAlign:textAlign.center,
);
}否则{
返回常量文本(
“您尚未选择图像。”,
textAlign:textAlign.center,
);
}
}
未来的检索速度数据()异步{
最终LostDataResponse响应=等待ImagePicker.retrieveLostData();
if(response.isEmpty){
返回;
}
if(response.file!=null){
设置状态(){
if(response.type==RetrieveType.video){
isVideo=true;
_controller=VideoPlayerController.file(response.file)
..addListener(视频控制器更新)
..设置音量(1.0)
…初始化()
..设置循环(真)
…玩();
}否则{
isVideo=false;
_imageFile=response.file;
}
});
}否则{
_retrieveDataError=response.exception.code;
}
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:中(
子:Platform.isAndroid
?未来建设者(
future:retrieveLostData(),
生成器:(BuildContext上下文,异步快照){
交换机(快照.连接状态)
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:crypto/crypto.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Image Picker Demo',
      home: MyHomePage(title: 'Image Picker Example'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

Future<String> generateImageHash(File file) async{
  var image_bytes =  file.readAsBytesSync().toString();
  var bytes = utf8.encode(image_bytes); // data being hashed
  String digest = sha256.convert(bytes).toString();
  print("This is image Digest :  $digest");
  return  digest;
}

class _MyHomePageState extends State<MyHomePage> {
  File _imageFile;
  dynamic _pickImageError;
  bool isVideo = false;
  VideoPlayerController _controller;
  String _retrieveDataError;



  void _onImageButtonPressed(ImageSource source) async {
    if (_controller != null) {
      _controller.setVolume(0.0);
      _controller.removeListener(_onVideoControllerUpdate);
    }
    if (isVideo) {
      ImagePicker.pickVideo(source: source).then((File file) {
        if (file != null && mounted) {
          setState(() {
            _controller = VideoPlayerController.file(file)
              ..addListener(_onVideoControllerUpdate)
              ..setVolume(1.0)
              ..initialize()
              ..setLooping(true)
              ..play();
          });
        }
      });
    } else {
      try {
        print("_imageFile start");
        _imageFile = await ImagePicker.pickImage(source: source);
        print("_imageFile end");

        print("compute start");
        var result = compute(generateImageHash, _imageFile);
        print("compute end");
        print(result);
      } catch (e) {
        _pickImageError = e;
      }
      setState(() {});
    }
  }

  void _onVideoControllerUpdate() {
    setState(() {});
  }

  @override
  void deactivate() {
    if (_controller != null) {
      _controller.setVolume(0.0);
      _controller.removeListener(_onVideoControllerUpdate);
    }
    super.deactivate();
  }

  @override
  void dispose() {
    if (_controller != null) {
      _controller.dispose();
    }
    super.dispose();
  }

  Widget _previewVideo(VideoPlayerController controller) {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (controller == null) {
      return const Text(
        'You have not yet picked a video',
        textAlign: TextAlign.center,
      );
    } else if (controller.value.initialized) {
      return Padding(
        padding: const EdgeInsets.all(10.0),
        child: AspectRatioVideo(controller),
      );
    } else {
      return const Text(
        'Error Loading Video',
        textAlign: TextAlign.center,
      );
    }
  }

  Widget _previewImage() {
    final Text retrieveError = _getRetrieveErrorWidget();
    if (retrieveError != null) {
      return retrieveError;
    }
    if (_imageFile != null) {
      return Image.file(_imageFile);
    } else if (_pickImageError != null) {
      return Text(
        'Pick image error: $_pickImageError',
        textAlign: TextAlign.center,
      );
    } else {
      return const Text(
        'You have not yet picked an image.',
        textAlign: TextAlign.center,
      );
    }
  }

  Future<void> retrieveLostData() async {
    final LostDataResponse response = await ImagePicker.retrieveLostData();
    if (response.isEmpty) {
      return;
    }
    if (response.file != null) {
      setState(() {
        if (response.type == RetrieveType.video) {
          isVideo = true;
          _controller = VideoPlayerController.file(response.file)
            ..addListener(_onVideoControllerUpdate)
            ..setVolume(1.0)
            ..initialize()
            ..setLooping(true)
            ..play();
        } else {
          isVideo = false;
          _imageFile = response.file;
        }
      });
    } else {
      _retrieveDataError = response.exception.code;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Platform.isAndroid
            ? FutureBuilder<void>(
          future: retrieveLostData(),
          builder: (BuildContext context, AsyncSnapshot<void> snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return const Text(
                  'You have not yet picked an image.',
                  textAlign: TextAlign.center,
                );
              case ConnectionState.done:
                return isVideo
                    ? _previewVideo(_controller)
                    : _previewImage();
              default:
                if (snapshot.hasError) {
                  return Text(
                    'Pick image/video error: ${snapshot.error}}',
                    textAlign: TextAlign.center,
                  );
                } else {
                  return const Text(
                    'You have not yet picked an image.',
                    textAlign: TextAlign.center,
                  );
                }
            }
          },
        )
            : (isVideo ? _previewVideo(_controller) : _previewImage()),
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
            onPressed: () {
              isVideo = false;
              _onImageButtonPressed(ImageSource.gallery);
            },
            heroTag: 'image0',
            tooltip: 'Pick Image from gallery',
            child: const Icon(Icons.photo_library),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              onPressed: () {
                isVideo = false;
                _onImageButtonPressed(ImageSource.camera);
              },
              heroTag: 'image1',
              tooltip: 'Take a Photo',
              child: const Icon(Icons.camera_alt),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.gallery);
              },
              heroTag: 'video0',
              tooltip: 'Pick Video from gallery',
              child: const Icon(Icons.video_library),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: FloatingActionButton(
              backgroundColor: Colors.red,
              onPressed: () {
                isVideo = true;
                _onImageButtonPressed(ImageSource.camera);
              },
              heroTag: 'video1',
              tooltip: 'Take a Video',
              child: const Icon(Icons.videocam),
            ),
          ),
        ],
      ),
    );
  }

  Text _getRetrieveErrorWidget() {
    if (_retrieveDataError != null) {
      final Text result = Text(_retrieveDataError);
      _retrieveDataError = null;
      return result;
    }
    return null;
  }
}

class AspectRatioVideo extends StatefulWidget {
  AspectRatioVideo(this.controller);

  final VideoPlayerController controller;

  @override
  AspectRatioVideoState createState() => AspectRatioVideoState();
}

class AspectRatioVideoState extends State<AspectRatioVideo> {
  VideoPlayerController get controller => widget.controller;
  bool initialized = false;

  void _onVideoControllerUpdate() {
    if (!mounted) {
      return;
    }
    if (initialized != controller.value.initialized) {
      initialized = controller.value.initialized;
      setState(() {});
    }
  }

  @override
  void initState() {
    super.initState();
    controller.addListener(_onVideoControllerUpdate);
  }

  @override
  Widget build(BuildContext context) {
    if (initialized) {
      return Center(
        child: AspectRatio(
          aspectRatio: controller.value?.aspectRatio,
          child: VideoPlayer(controller),
        ),
      );
    } else {
      return Container();
    }
  }
}
static  generateImageHash(String fileBytes){
print('fileBytes = $fileBytes');
var bytes = utf8.encode(fileBytes); // data being hashed
String digest = sha256.convert(bytes).toString();
print("This is image Digest :  $digest");
return digest;
}



var imageBytes =  image.readAsBytesSync().toString();
var result = await compute(generateImageHash, imageBytes);
Future<String> generateImageHash(File file) async{
  Digest digest = await sha256.bind(file).openRead()).first;
  print("This is image Digest :  ${digest.toString()}");
  return  digest.toString();
}