flutterfirebasegoogle-cloud-firestorenullableuint8list

How to fix nullable error in flutter Uint8List


I am quite new to flutter and challenging to create to show images in grid downloading file saved in firebase storage.

Getting error code as below and I would like to know how I can fix nullable part...

lib/artfolder.dart:53:21: Error: A value of type 'Uint8List?' can't be assigned to a variable of type 'Uint8List' because 'Uint8List?' is nullable and 'Uint8List' isn't.

Here is my code;;

import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'dart:typed_data';
import 'package:cloud_firestore/cloud_firestore.dart';


class Artfolder extends StatelessWidget {
  User user;

  Artfolder({required this.user, Key? key}) : super(key: key);

  Widget makeImageGrid() {
    return GridView.builder(
        itemCount: 5,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3),
        itemBuilder: (context, index) {
          return ImageGridItem(index);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("ART Folder"),
        automaticallyImplyLeading: false,
      ),
      body: Container(
        child: makeImageGrid(),
      ),
    );
  }
}

class ImageGridItem extends StatefulWidget {
  int? _index;
  ImageGridItem(int index){
    this._index = index;
  }
  @override
  _ImageGridItemState createState() => _ImageGridItemState();
}
class _ImageGridItemState extends State<ImageGridItem>{
  Uint8List  imageFile;
  Reference photosReference = FirebaseStorage.instance.ref().child("photo");
  getImage(){
    int MAX_SIZE = 10*1024*1024;
    photosReference.child("Image_${widget._index}.jpeg").getData(MAX_SIZE).then((data) {
      this.setState(() {
        imageFile = data;
      });
    }).catchError((error){

    });
  }
Widget decideGridTileWidget(){
    if(imageFile == null) {
    return Center(child: Text("Nodata"));
    } else {
      return Image.memory(imageFile,fit: BoxFit.cover,);
    }
    }
@override
void initState(){
    super.initState();
        getImage();
}
  @override
  Widget build(BuildContext context){
    return GridTile(child:decideGridTileWidget());
  }
}

Solution

  • You just need to declare it as a nullable and check if its null.

    Step 1:

    Uint8List?  imageFile;
    

    Step 2:

    if(data!=null){
       imageFile = data;
    }
    

    Step 3:

     if(imageFile == null) {
              return Center(child: Text("Nodata"));
            } else {
              return Image.memory(imageFile!,fit: BoxFit.cover,);
            }