Adjust GridView Child Height According To The Dynamic Content In Flutter


Answer :

Edit: I added the constructor StaggeredTile.fit in the 0.2.0. With that you should be able to build you app ;-).

Dynamic tile sizes

First comment: For now with StaggeredGridView, the layout and the children rendering are completely independant. So as @rmtmckenzie said, you will have to get the image size to create your tiles. Then you can use StaggeredTile.count constructor with a double value for the mainAxisCellCount parameter: new StaggeredTile.count(x, x*h/w) (where h is the height of your image and w its width. So that the tile with have the same aspect ratio as your image.

What you want to accomplish will need more work because you want to have an area below the image with some information. For that I think you will have to compute the real width of your tile before creating it and use the StaggeredTile.extent constructor.

I understand this is not ideal and I'm currently working on a new way to create the layout. I hope it will help to build scenarios like yours.


First let me tell you about how I ended up here:

In my application I wanted a grid view to display my ad cards and all the data coming from the server database and images are coming from the server and images are in different sizes. I used FutureBuilder to map those data to GridView. First I tried to use:

double cardWidth = MediaQuery.of(context).size.width / 3.3; double cardHeight = MediaQuery.of(context).size.height / 3.6; //.... GridView.count(   childAspectRatio: cardWidth / cardHeight,   //.. 

As you can see it will not dynamic to all cards. I came here like you and tried to use all answers those are great and you have to tackle a bit to understand how, but any of those answer completely solved my issue.

Using @RomainRastel answer and thanks to his StaggeredGridView package. I had to use StaggeredGridView.count as my constructor to map all cards and for the staggeredTiles property I had to again map all cards and add for each StaggeredTile.fit(2).

I'm sure you didn't get it still, so let's try a simple example so that you do not need to go somewhere else to find an answer:

First add dependency to pubspec.yaml, now version is 0.2.5. You can checkout the latest one here.

dependencies:  flutter_staggered_grid_view: ^0.2.5 

If you are fetching data from internet or if you are going to copy paste this example, you have to also ad this dependency: http: ^0.12.0.

import 'package:flutter/material.dart';  //this is what you need to have for flexible grid import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';  //below two imports for fetching data from somewhere on the internet import 'dart:convert'; import 'package:http/http.dart' as http;  //boilerplate that you use everywhere class MyApp extends StatelessWidget {   @override   Widget build(BuildContext context) {     return MaterialApp(       title: "Flexible GridView",       home: HomePage(),     );   } }  //here is the flexible grid in FutureBuilder that map each and every item and add to a gridview with ad card class HomePage extends StatelessWidget {   //this is should be somewhere else but to keep things simple for you,   Future<List> fetchAds() async {     //the link you want to data from, goes inside get     final response = await http         .get('https://blasanka.github.io/watch-ads/lib/data/ads.json');      if (response.statusCode == 200) return json.decode(response.body);     return [];   }    @override   Widget build(BuildContext context) {     return Scaffold(       appBar: AppBar(         title: Text("Dynamic height GridView Demo"),       ),       body: FutureBuilder<List>(           future: fetchAds(),           builder: (BuildContext context, AsyncSnapshot snapshot) {             if (snapshot.hasData) {               return new Padding(                 padding: const EdgeInsets.all(4.0),                 //this is what you actually need                 child: new StaggeredGridView.count(                   crossAxisCount: 4, // I only need two card horizontally                   padding: const EdgeInsets.all(2.0),                   children: snapshot.data.map<Widget>((item) {                     //Do you need to go somewhere when you tap on this card, wrap using InkWell and add your route                     return new AdCard(item);                   }).toList(),                    //Here is the place that we are getting flexible/ dynamic card for various images                   staggeredTiles: snapshot.data                       .map<StaggeredTile>((_) => StaggeredTile.fit(2))                       .toList(),                   mainAxisSpacing: 3.0,                   crossAxisSpacing: 4.0, // add some space                 ),               );             } else {               return Center(                   child:                       new CircularProgressIndicator()); // If there are no data show this             }           }),     );   } }  //This is actually not need to be a StatefulWidget but in case, I have it class AdCard extends StatefulWidget {   AdCard(this.ad);    final ad;    _AdCardState createState() => _AdCardState(); }  class _AdCardState extends State<AdCard> {   //to keep things readable   var _ad;   String _imageUrl;   String _title;   String _price;   String _location;    void initState() {     setState(() {       _ad = widget.ad;       //if values are not null only we need to show them       _imageUrl = (_ad['imageUrl'] != '')           ? _ad['imageUrl']           : 'https://uae.microless.com/cdn/no_image.jpg';       _title = (_ad['title'] != '') ? _ad['title'] : '';       _price = (_ad['price'] != '') ? _ad['price'] : '';       _location = (_ad['location'] != '') ? _ad['location'] : '';     });      super.initState();   }    @override   Widget build(BuildContext context) {     return Card(       semanticContainer: false,       shape: const RoundedRectangleBorder(         borderRadius: BorderRadius.all(Radius.circular(4.0)),       ),       child: Column(         crossAxisAlignment: CrossAxisAlignment.start,         children: <Widget>[           Image.network(_imageUrl),           Text(_title),           Text('\$ $_price'),           Text(_location),         ],       ),     );   } } 

If you have any issue, here is complete example in a git repository.

Flutter flexible grid view example

Good luck!


There are two things here:

  1. There is an existing package for doing such layout

  2. In order to make the images look good use BoxFit.cover on the DecorationImage widget.

There are tons of example in the package repo here

I just used on of the examples and modified it to include pictures:

enter image description here

class GridViewExample extends StatefulWidget {   @override   _GridViewExampleState createState() => new _GridViewExampleState(); }  class _GridViewExampleState extends State<GridViewExample> {   @override   Widget build(BuildContext context) {     return new Scaffold(       body: new Padding(         padding: const EdgeInsets.all(8.0),         child: new StaggeredGridView.countBuilder(   crossAxisCount: 4,   itemCount: 8,   itemBuilder: (BuildContext context, int index) => new Container(         decoration: new BoxDecoration(           image: new DecorationImage(             image: new NetworkImage("https://i.imgur.com/EVTkpZL.jpg"),             fit: BoxFit.cover           )         )          ),    staggeredTileBuilder: (int index) =>       new StaggeredTile.count(2, index.isEven ? 2 : 1),   mainAxisSpacing: 4.0,   crossAxisSpacing: 4.0, ),),      );   } } 

Comments

Popular posts from this blog

Chemistry - Bond Angles In NH3 And NCl3

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?