0

I keep getting this error every time I run this code on an android device:

Null check operator used on a null value.

My code:

import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:firebase_storage/firebase_storage.dart' as firabase_storage;

class ImageTest extends StatefulWidget {
  const ImageTest({super.key});

  @override
  State<ImageTest> createState() => _ImageTestState();
}

class _ImageTestState extends State<ImageTest> {

  
  String defaultPic = 
    'https://images.pexels.com/photos/10768835/pexels-photo-10768835.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1';
  String? selectFile;
  XFile? file;
  Uint8List? selectedImage;
  String imageUrl = '';


  
  _selectFile()async{
    FilePickerResult? fileResult = await FilePicker.platform.pickFiles(allowMultiple: false);

    if (fileResult != null) {
      setState(() {
        selectFile = fileResult.files.first.name;
        selectedImage = fileResult.files.first.bytes;
        //file = fileResult.files.first.path as XFile?;
      });
    }
    debugPrint(selectFile);
  }


  
  _uploadFile()async{
    try {
      firabase_storage.UploadTask uploadTask;

      firabase_storage.Reference ref = firabase_storage.FirebaseStorage.instance
        .ref()
        .child('Test')
        .child('/${selectFile!}');

      final metadata = 
        firabase_storage.SettableMetadata(contentType: 'image/jpeg');

      uploadTask = ref.putData(selectedImage!, metadata);
      //uploadTask = ref.putFile(io.File(file!.path), metadata);

      await uploadTask.whenComplete(() => null);
      String ImageUrl = await ref.getDownloadURL();
      setState((){
        imageUrl = ImageUrl;
      });
      debugPrint('Uploaded Image URL: $ImageUrl');
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          TextButton(onPressed: _selectFile, child: const Text('file')),
          Container(
            child: selectFile == null ? Image.network(defaultPic, height: 100,width: 100,) : Image.memory(selectedImage!, height: 100,width: 100,),
          ),
          TextButton(onPressed: _uploadFile, child: const Text('upload')),
        ],
      )
    );
  }
}

I tried this, but it is still showing the error.

if (selectFile == null || selectedImage == null) {
  return;
}

Is there something wrong with my functions?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • The stack trace for the error should tell you exactly on what line you're using a `!` on a `null` value. If you're struggling to find it that way, set a breakpoint on each line where you use `!`, run in the debugger, and check the value of each variable on each line to see which one is `null`. – Frank van Puffelen Feb 27 '23 at 04:14

0 Answers0