Search code examples
firebasefluttergridviewinstagram

Flutter image grid from firebase (instagram style)


I want to create a image grid like the instagram search page/profilepage with images in rows of 3 and want the grid to fill up depending on how many imgaes I have in my collection.

When i press the image I want to load that photo so you can save that photo to your phone. I've tried using the wrap function but instead of getting a list with one of every photo i get 152 sets of every photo so the list is huge.

Anyone know what ive done wrong?

And since i want to be able to use onpressed to view the entire photo maybe wrap isn't the function I should use?

Here is a copy of my code:

class Imagepost {
  final String img;

  Imagepost({this.img});
}

----------------------------------------------------------------


List<Imagepost> _imageListFromSnapshot(QuerySnapshot snapshot) {
    return snapshot.documents.map((doc) {
      print(doc.data);
      return Imagepost(
        img: doc.data['img'],
      );
    }).toList();
  }

  Stream<List<Imagepost>> get img {
    return imageCollection.snapshots().map(_imageListFromSnapshot);
  }


-------------------------------------------------------------------

class ImageTile extends StatelessWidget {
  final Imagepost img;
  ImageTile({this.img});

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Wrap(
      spacing: 1,
      runSpacing: 1,
      children: List.generate(img.img.length, (index) {
        return Container(
          width: (size.width-3)/3,
          height: (size.width-3)/3,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage(img.img),
              fit: BoxFit.cover),
          ),
        );
      }),
    );
  }
}

-------------------------------------------------------------------

class MediaList extends StatefulWidget {
  @override
  _MediaListState createState() => _MediaListState();
}

class _MediaListState extends State<MediaList> {
  @override
  Widget build(BuildContext context) {

    final imagepost = Provider.of<List<Imagepost>>(context) ?? [];

    return ListView.builder(
      itemCount: imagepost.length,
      itemBuilder: (context, index) {
        return ImageTile(img: imagepost[index]);
      },
    );
  }
}

-------------------------------------------------------------

Solution

  • There is a widget called GridView which would be great for that.

    GridView.count(
      // Create a grid with 3 columns. If you change the scrollDirection to
      // horizontal, this produces 3 rows.
      crossAxisCount: 3,
      // Generate 100 widgets that display their index in the List.
      children: List.generate(100, (index) {
        return Center(
          child: Text(
            'Item $index',
            style: Theme.of(context).textTheme.headline5,
          ),
        );
      }),
    )