簡體   English   中英

flutter / dart 錯誤:參數類型 'Future<file> ' 不能分配給參數類型 'File'</file>

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

我正在嘗試使用 flutter 和 firebase 構建我的第一個移動應用程序。當我嘗試顯示和存儲照片時,出現以下問題:

錯誤:無法將參數類型“Future”分配給參數類型“File”。 (argument_type_not_assignable 在 [whereassistant] lib/main.dart:85)

我可能應該做一些轉換,但我不明白如何正確地做這件事。

這是我的未來文件聲明:

Future<File> _imageFile;

我正在拍攝顯示在屏幕上的照片:

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

但是我嘗試將照片發送到 Firebase 時出現錯誤:

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

這是我根據代碼示例使用的 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要求一個File作為參數。 您傳遞的是Future<File>

你需要等待那個未來的結果來打電話。

您可以將代碼更改為

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

或者將_imageFile更改為File而不是Future<File>

對於那些仍在尋找答案的人來說,同樣的錯誤似乎有不同的原因。 就我而言,這是我作為參數傳遞給不同函數的文件的不同導入語句。 在聲明和定義的情況下,它應該是相同的文件(導入)。

例如,不要在 dart 中這樣使用

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

然后在另一個班級

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

因為

在 Dart 中,兩個庫是相同的,當且僅當它們使用相同的 URI 導入。 如果使用兩個不同的URI,即使解析到同一個文件,也會被認為是兩個不同的庫,文件內的類型會出現兩次

在這里閱讀更多

來自插件README.md

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

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

ImagePicker.pickImage()返回一個Future 您可以使用上面代碼中所示的async / awaitFuture獲取值。

要將Future<File>轉換為File ,請在函數前添加await使其參數成為 Future 類型!

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

很可能是導入錯誤

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM