简体   繁体   English

flutter / dart 错误:参数类型 'Future<file> ' 不能分配给参数类型 'File'</file>

[英]flutter / dart error: The argument type 'Future<File>' can't be assigned to the parameter type 'File'

I'm trying to build my first mobile application with flutter and firebase. When I try to display and store a photo I have the following issue:我正在尝试使用 flutter 和 firebase 构建我的第一个移动应用程序。当我尝试显示和存储照片时,出现以下问题:

error: The argument type 'Future' can't be assigned to the parameter type 'File'.错误:无法将参数类型“Future”分配给参数类型“File”。 (argument_type_not_assignable at [whereassistant] lib/main.dart:85) (argument_type_not_assignable 在 [whereassistant] lib/main.dart:85)

I should probably do some casting but I don't understand hox to do it properly.我可能应该做一些转换,但我不明白如何正确地做这件事。

Here's my Future file declaration:这是我的未来文件声明:

Future<File> _imageFile;

I'm taking a Photo which is displayed on screen:我正在拍摄显示在屏幕上的照片:

    setState(() {
      _imageFile = ImagePicker.pickImage(source: source);
    });

But I have the error when trying to send the photo to Firebase:但是我尝试将照片发送到 Firebase 时出现错误:

    final StorageUploadTask uploadTask = ref.put(_imageFile);
    final Uri downloadUrl = (await uploadTask.future).downloadUrl;

Here's the class I'm using based on a code example:这是我根据代码示例使用的 class:

class _MyHomePageState extends State<MyHomePage> {
  Future<File> _imageFile;

  void _onImageButtonPressed(ImageSource source) async {
    GoogleSignIn _googleSignIn = new GoogleSignIn();
    var account = await _googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth = await account.authentication;
    final FirebaseUser user = await _auth.signInWithGoogle(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );
    assert(user.email != null);
    assert(user.displayName != null);
    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final FirebaseUser currentUser = await _auth.currentUser();
    assert(user.uid == currentUser.uid);

    setState(() {
      _imageFile = ImagePicker.pickImage(source: source);
    });
    var random = new Random().nextInt(10000);
    var ref = FirebaseStorage.instance.ref().child('image_$random.jpg');
    final StorageUploadTask uploadTask = ref.put(_imageFile);
    final Uri downloadUrl = (await uploadTask.future).downloadUrl;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('Where Assistant'),
      ),
      body: new Center(
        child: new FutureBuilder<File>(
          future: _imageFile,
          builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
            debugPrint('test recup image');
            print(snapshot);

            if (snapshot.connectionState == ConnectionState.done &&
                snapshot.data != null) {
              return new Image.file(snapshot.data);
            } else if (snapshot.error != null) {
              return const Text('Error picking image.');
            } else {
              return const Text('No image so far.');
            }
          },
        ),
      ),
      floatingActionButton: new Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          new FloatingActionButton(
            onPressed: () => _onImageButtonPressed(ImageSource.gallery),
            tooltip: 'Pick an image from gallery',
            child: new Icon(Icons.photo_library),
          ),
          new Padding(
            padding: const EdgeInsets.only(top: 16.0),
            child: new FloatingActionButton(
              onPressed: () => _onImageButtonPressed(ImageSource.camera),
              tooltip: 'Take a Photo',
              child: new Icon(Icons.camera_alt),
            ),
          ),
        ],
      ),
    );
  }
}

ref.put asks for a File as parameter. ref.put要求一个File作为参数。 What you are passing is a Future<File> .您传递的是Future<File>

You need to wait for the result of that future to make your call.你需要等待那个未来的结果来打电话。

You can change your code to您可以将代码更改为

final StorageUploadTask uploadTask = ref.put(await _imageFile);
final Uri downloadUrl = (await uploadTask.future).downloadUrl;

Or change _imageFile to File instead of Future<File>或者将_imageFile更改为File而不是Future<File>

For those who are still looking for answers, as it seems there are different reasons for the same error.对于那些仍在寻找答案的人来说,同样的错误似乎有不同的原因。 In my case, it was the different import statement for a file which I was passing as parameters to a different function.就我而言,这是我作为参数传递给不同函数的文件的不同导入语句。 It should be same file(import) in case of declaration and definition.在声明和定义的情况下,它应该是相同的文件(导入)。

for example, don't use like this in dart:例如,不要在 dart 中这样使用

import 'GitRepoResponse.dart';
import 'GitRowItem.dart';

and then in some another class然后在另一个班级

import 'package:git_repo_flutter/GitRepoResponse.dart';
import 'package:git_repo_flutter/GitRowItem.dart';

because因为

In Dart, two libraries are the same if, and only if, they are imported using the same URI.在 Dart 中,两个库是相同的,当且仅当它们使用相同的 URI 导入。 If two different URIs are used, even if they resolve to the same file, they will be considered to be two different libraries and the types within the file will occur twice如果使用两个不同的URI,即使解析到同一个文件,也会被认为是两个不同的库,文件内的类型会出现两次

Read more here 在这里阅读更多

From the plugin README.md来自插件README.md

  Future getImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      _image = image;
    });
  }

ImagePicker.pickImage() returns a Future . ImagePicker.pickImage()返回一个Future You can use async / await like shown in the code above the get the value from the Future .您可以使用上面代码中所示的async / awaitFuture获取值。

要将Future<File>转换为File ,请在函数前添加await使其参数成为 Future 类型!

File file2 = await fixExifRotation(imageFile.path);
setState(() {
  _imageFile = ImagePicker.pickImage(source: source);
});

It's most likely an import error很可能是导入错误

import 'dart:io' as io; // use io.File even if File without io. works also

Future<io.File> method(){ // good, use as imported 
    File file = ...myfile // bad: it's not the imported type File
    return file; // FutureOr error
}

暂无
暂无

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

相关问题 Flutter 错误:参数类型'Stream <querysnapshot<map<string, dynamic> &gt;&gt;' 不能分配给参数类型'Future <querysnapshot<object?> &gt; </querysnapshot<object?></querysnapshot<map<string,> - Flutter error: The argument type 'Stream<QuerySnapshot<Map<String, dynamic>>>' can't be assigned to the parameter type 'Future<QuerySnapshot<Object?>> 参数类型'Future<bool> ' 不能分配给参数类型 'Widget' [Flutter]</bool> - The argument type 'Future<bool>' can't be assigned to the parameter type 'Widget' [Flutter] 参数类型'Future<dynamic> ' 不能分配给参数类型 'String' Flutter Firestore</dynamic> - The argument type 'Future<dynamic>' can't be assigned to the parameter type 'String' Flutter Firestore 参数类型“Future”不能分配给参数类型“String” - The argument type 'Future' can't be assigned to the parameter type 'String' 参数类型 'Future<dynamic> ' 不能分配给参数类型 'String'</dynamic> - The argument type 'Future<dynamic>' can't be assigned to the parameter type 'String' 参数类型“用户?” 不能分配给参数类型“未来”<object?> ?</object?> - The argument type 'User?' can't be assigned to the parameter type 'Future<Object?>?' 参数类型“用户”不能分配给参数类型“未来”<dynamic> '</dynamic> - The argument type 'User' can't be assigned to the parameter type 'Future<dynamic>' 参数类型“对象?” 不能分配给参数类型“字符串”。 颤动 - The argument type 'Object?' can't be assigned to the parameter type 'String'. with flutter 参数类型'Future <list<exercise> &gt;' 不能分配给参数类型'Future <list<exercise> &gt;? </list<exercise></list<exercise> - The argument type 'Future<List<Exercise>>' can't be assigned to the parameter type 'Future<List<Exercise>>?' 参数类型 &#39;Null&#39; 不能分配给参数类型 &#39;FirebaseUser&#39;.dart(argument_type_not_assignable) - The argument type 'Null' can't be assigned to the parameter type 'FirebaseUser'.dart(argument_type_not_assignable)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM