Adjust GridView child height according to the dynamic content in flutter

ⅰ亾dé卋堺 提交于 2019-11-28 21:35:19

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

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.

For any of the relatively simple ways of doing this (i.e. without a deep understanding how layout in flutter works), you are going to need to get the sizes of the images before you build anything. This is an answer that describes how to do that by using ImageProvier and ImageStream.

You could then use @aziza's example of flutter_staggered_grid_view once you know the basic dimensions of the images.

An alternative could be to store the image size or at least aspect ratio wherever you store the list of images/urls (I don't know how you're populating the list of images so I can't help you there).

If you want it to be fully based on the size of the images and not grid-like at all, you might be able to do it with a Flow widget. There is a caveat to flow though - I believe that it won't handle a large amount of items very well as it would have to lay all of the children out each time, but I could be wrong about that. If you don't have a huge amount of items, you could use Flow + a SingleChildScrollView for the scrolling part.

If you are going to have a large amount of items (and/or want to do something like dynamic loading of new items), you might have to do something with a CustomMultiChildLayout - I think it would be more efficient but you'd still need to do something to know the sizes of the images.

A last possible solution (I don't know exactly how this would work though) would be to have two scrollable views side-by-side and synchronize their positions. You'd have to set shrinkwrap=true though so you could do the scrolling, and you'd still have to know the height of each image so you could decide which side to put each one in.

Hope that helps you get started at least!

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:

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,
),),

    );
  }
}

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.

Good luck!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!