0

In GridView.builder, we must give a fixed value for the itemCount property. So what is the best way to update this property when we adding a new image to the grid view by uploading it to firebase storage? Here I just used the image name to get the image from the firebase storage. But I need to change this to get the image url and show the image. Here's my code,

class ImagesScreen extends StatelessWidget {

  // building grid view 
  Widget makeImagesGrid(){
    return GridView.builder(
      itemCount: 12, //number of grid items
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
      ),
      itemBuilder: (context, index){
        return ImageGridItem(index + 1); //populating with grid items
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Grid'),
      ),
      drawer: NavDrawer(),
      body: Container(
        child: makeImagesGrid(),
      ),
    );
  }
}

class ImageGridItem extends StatefulWidget {
  int _index; //each grid item index
  ImageGridItem(int index) {
    this._index = index;
  }

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

class _ImageGridItemState extends State<ImageGridItem> {
  Uint8List imageFile; //to store image file

  //firebase storage reference
  StorageReference photosReference =
      FirebaseStorage.instance.ref().child("photos");

  //getting image from the firestore
  getImage() {
    if (!requestedIndex.contains(widget._index)) {
      //when requested index does not cotain in the list

      int MAX_SIZE = 7 * 1024 * 1024; //maximum file size for an image

      //accessing firebase storage to get the photo
      photosReference
          .child('${widget._index}.jpg')
          .getData(MAX_SIZE)
          .then((value) {
        //value is image reference
        this.setState(() {
          imageFile = value; //updating imageFile
        });
        //insert image file to the imageData map
        imageData.putIfAbsent(widget._index, () {
          return value;
        });
      }).catchError((error) {});
      //insert image file index to the requestedIndex list in the data_holder.dart
      requestedIndex.add(widget._index);
    }
  }

  //to decide whether to show the default text or actual image
  Widget decideGrideTileWidget() {
    if (imageFile == null) {
      //showing default text until it show the image
      return Center(child: Text('No Data'));
    } else {
      return Hero(
        tag: imageFile.toString(),
        child: Image.memory(
            //showing the actual image
            imageFile,
            fit: BoxFit.cover),
      );
    }
  }

  @override
  void initState() {
    super.initState();
    if (!imageData.containsKey(widget._index)) {
      //when imageData map does't cotains the key
      getImage();
    } else {
      //if its already contains get the image from the imageData map
      imageFile = imageData[widget._index];
    }
  }

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Padding(
        padding: const EdgeInsets.all(3.0),
        child: GridTile(
          child: decideGrideTileWidget(),
        ),
      ),
      onTap: () {}
    );
  }
}
sithum dilanga
  • 427
  • 7
  • 14
  • use a dynamic ``length`` variable for the ``GridView.builder``. Deine a variable ``int items = 12;`` and then pass this variable to the ``GridView.builder(length: items, ....)`` and once you upload a new image just increment the ``items`` value by ``+ 1`` using `` setState(() { items += 1; });`` doing so will rebuild the layout with the new item. – OMi Shah Aug 14 '20 at 09:03
  • @OMiShah That's also a good solution. But later I found a better solution. We can pass the number of firestore documents by calling images.length (images is the list of firestore documents received). this way is better I think. So what do you think about this ? – sithum dilanga Aug 18 '20 at 17:37
  • I meant to say something like that too. – OMi Shah Aug 18 '20 at 18:11
  • @OMiShah Alright thanks for the reply. Appreciate it – sithum dilanga Aug 19 '20 at 08:00

0 Answers0