【问题标题】:Flutter file picker unexpected null value颤振文件选择器意外的空值
【发布时间】:2021-08-23 20:24:35
【问题描述】:

我喜欢你对这个的支持。 问题是我试图使用带有颤振的文件选择器将文件上传到firebase。 这是我的代码:

import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:hire_me/firebase/firebaseApi.dart';
import 'package:hire_me/buttonWidget.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart';

class ImageUploader extends StatefulWidget {
  const ImageUploader({Key? key}) : super(key: key);

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

class _ImageUploaderState extends State<ImageUploader> {
  UploadTask? task;
  File? file;

  @override
  Widget build(BuildContext context) {
    final fileName =
        file != null ? basename(file!.path) : 'No File Selected Yet';
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Upload Image'),
      ),
      body: Container(
        padding: EdgeInsets.all(32),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              ButtonWidget(
                icon: Icons.attach_file,
                text: 'Select File',
                onClicked: selectFile,
              ),
              SizedBox(
                height: 8,
              ),
              Text(fileName,
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              SizedBox(
                height: 48,
              ),
              ButtonWidget(
                  icon: Icons.cloud_upload_outlined,
                  text: 'Upload File',
                  onClicked: uploadFile)
            ],
          ),
        ),
      ),
    );
  }

  Future selectFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();

    if (result != null) {
      final path = result.files.single.path!;

      setState(() => file = File(path));
    }
  }

  Future uploadFile() async {
    if (file == null) return;

    final fileName = basename(file!.path);
    final destination = 'files/$fileName';

    FirebaseApi.uploadFile(destination, file!);
    setState(() {});

    if (task == null) return;

    final snapshot = await task!.whenComplete(() => {});
    final urlDownload = await snapshot.ref.getDownloadURL();

    print('Download Link: $urlDownload');
  }
}

当我点击上传文件按钮时,它会打开平台文件选择器,然后在选择图像后出现以下错误:

Error: Unexpected null value.
    at Object.throw_ [as throw] (http://localhost:51207/dart_sdk.js:5037:11)
    at Object.nullCheck (http://localhost:51207/dart_sdk.js:5362:30)
    at imageUploader._ImageUploaderState.new.selectFile
    (http://localhost:51207/packages/hire_me/screens/imageUploader.dart.lib.js:417:27)
    at selectFile.next (<anonymous>)
    at http://localhost:51207/dart_sdk.js:37374:33
    at _RootZone.runUnary (http://localhost:51207/dart_sdk.js:37245:59)
    at _FutureListener.thenAwait.handleValue (http://localhost:51207/dart_sdk.js:32501:29)
    at handleValueCallback (http://localhost:51207/dart_sdk.js:33028:49)
    at Function._propagateToListeners (http://localhost:51207/dart_sdk.js:33066:17)
    at _Future.new.[_completeWithValue] (http://localhost:51207/dart_sdk.js:32914:23)
    at async._AsyncCallbackEntry.new.callback (http://localhost:51207/dart_sdk.js:32935:35)
    at Object._microtaskLoop (http://localhost:51207/dart_sdk.js:37497:13)
    at _startMicrotaskLoop (http://localhost:51207/dart_sdk.js:37503:13)
    at http://localhost:51207/dart_sdk.js:33274:9

我已经在 chrome 和 android 上测试过了。

【问题讨论】:

    标签: image flutter file-upload


    【解决方案1】:

    我遇到了同样的问题。 在这种情况下,您创建的变量-

    UploadTask? task;
    File? file;
    

    您必须分配这些变量。这就是他们显示 Unexpected null 错误的原因。

    在我的例子中,我有一个布尔变量,我给它分配了 false ->

    this.isActive = false,
    

    所以你应该为你的变量创建一个构造函数。如:

        class ImageUploader extends StatefulWidget {
          UploadTask? task;
          File? file;
          const ImageUploader({Key? key, this.task, this.file}) : super(key: key);
        
          @override
          _ImageUploaderState createState() => _ImageUploaderState();
        }
        
        class _ImageUploaderState extends State<ImageUploader> {
          
        
          @override
          Widget build(BuildContext context) {
            final fileName =
                file != null ? basename(file!.path) : 'No File Selected Yet';
            return Scaffold(
              appBar: AppBar(
                centerTitle: true,
                title: Text('Upload Image'),
              ),
              body: Container(
                padding: EdgeInsets.all(32),
                child: Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ButtonWidget(
                        icon: Icons.attach_file,
                        text: 'Select File',
                        onClicked: selectFile,
                      ),
                      SizedBox(
                        height: 8,
                      ),
                      Text(fileName,
                          style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                      SizedBox(
                        height: 48,
                      ),
                      ButtonWidget(
                          icon: Icons.cloud_upload_outlined,
                          text: 'Upload File',
                          onClicked: uploadFile)
                    ],
                  ),
                ),
              ),
            );
          }
        
          Future selectFile() async {
            FilePickerResult? result = await FilePicker.platform.pickFiles();
        
            if (result != null) {
              final path = result.files.single.path!;
        
              setState(() => file = File(path));
            }
          }
        
          Future uploadFile() async {
            if (file == null) return;
        
            final fileName = basename(file!.path);
            final destination = 'files/$fileName';
        
            FirebaseApi.uploadFile(destination, file!);
            setState(() {});
        
            if (task == null) return;
        
            final snapshot = await task!.whenComplete(() => {});
            final urlDownload = await snapshot.ref.getDownloadURL();
        
            print('Download Link: $urlDownload');
          }
        } 
    

    如果这仍然显示 unexpected null 错误,那么您必须在构造函数中分配变量。

    希望它对你有用。

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2022-11-21
      • 2021-09-15
      • 2020-01-22
      • 2021-02-28
      • 2021-02-01
      相关资源
      最近更新 更多