Set height to container in Gridview.builder - flutter

I am working with the following code and got struck. I wanted to set the height to the container so that the images which are displayed inside it will be fitted well. In the present condition the image gets fitted inside the container and it does not look good. I have used a grid view to display images from firebase.
class Catview extends StatefulWidget {
#override
_CatviewState createState() => _CatviewState();
}
class _CatviewState extends State<Catview> {
StreamSubscription<QuerySnapshot> subscription;
List<DocumentSnapshot> wallpaperList;
final CollectionReference collectionReference =
Firestore.instance.collection("pubg");
#override
void initState() {
super.initState();
subscription = collectionReference.snapshots().listen((datasnapshot) {
setState(() {
wallpaperList = datasnapshot.documents;
});
});
}
#override
void dispose() {
super.dispose();
subscription?.cancel();
}
#override
Widget build(BuildContext context) {
return (SafeArea(
child: Scaffold(
body: wallpaperList != null
? GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 2,
mainAxisSpacing: 4,
),
itemCount: wallpaperList.length,
itemBuilder: (context, index) {
String image = wallpaperList[index].data['image'];
return Container(
color: Colors.red,
child: Image.network(
image,
),
);
},
)
: Center(
child: CircularProgressIndicator(),
),
),
));
}
}
thank you!

You need to add preperty childAspectRatio in SliverGridDelegateWithFixedCrossAxisCount. childAspectRatio as aspectRatio, because in gridview can't support height dan width. Unless you use this library Staggered Grid View . https://pub.dev/packages/flutter_staggered_grid_view.
this is example if you use gridview without library.
Example:
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 2,
mainAxisSpacing: 4,
childAspectRatio: 0.7,
),
....

You'll have to use the childAspectRatio property present in the GridView.builder class
GridView.builder(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 8.0,
mainAxisSpacing: 8.0,
childAspectRatio: 2/3,
),
....
I like to use the popular aspect ratios present in photography which are the 2/3 (2:3) or the 3/4 (3:4) to get the kind of look I normally like.
If you want a wider width in relation to the height, use the aspect ratio in reverse (i.e. 3/2 or 4/3) depending on your need.
Hope it helps! :)

Related

Flutter. How to collapse GridView.builder when it empty (do not have any elements)

I have a GridView.builder with shrinkWrap to true. It fills dynamically, but the problem that at start it empty but takes place, like it has elements (sort of reserving place) depends on the size of maxCrossAxisExtent.
Is it possible change this? Empty space not very good..
I looked docs and google but didnt find any answer.
This is the code
class _PhotosState extends State<Photos> {
List<File> photos = [];
final ImagePicker _picker = ImagePicker();
Widget getGrid() {
return Container(
child: GridView.builder(
padding: EdgeInsets.all(0),
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
//childAspectRatio: 3 / 2,
// crossAxisSpacing: 10,
// mainAxisSpacing: 10,
//mainAxisExtent: 200,
),
itemCount: photos.length,
itemBuilder: (BuildContext ctx, index) {
return Container(
color: Colors.blueGrey,
);
},
),
);
}
The empty GridView with empty space
One element added to GridView
try
Widget getGrid() {
return photos.length<1?SizedBox():
Container(
child: GridView.builder(

How to reduce the with of GridViewItems

Example:
I want to reduce the width of this picture with childAspectRatio without knowing the values. The image above shows my layout. Is there a way to reduce the with of the GridViewItems, when I am not having the exact values of for using the child-aspect ratio properly?
Here is my code:
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
final height = MediaQuery.of(context).size.height;
logger("width => $width");
logger("height => $height");
return GridView.count(
childAspectRatio: .9/.2,
// childAspectRatio: 6,
// padding:EdgeInsets.only(right: 250),
mainAxisSpacing: 10,
crossAxisSpacing: 25,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
crossAxisCount: width < 1510
? 2
: width < 1537
? 3
: 1,
children: <Widget>[
SelectCargoDropDown(),
CargoCampaignDropDown(),
FreeCargoNumberField(),
IdSelectionDropDown(),
AuthSellingDropDown(),
PharmacyReferenceDropDown(),
InformationPersonReferenceDropDown(),
],);
I think it's useful to insert your GridView.count in an Expanded widget.
Then it will automatically take the suitable width for the screen, even it's the same widget in the screen's width or there is another.

Flutter Listview builder show data in two rows depending upon `index` is odd or event

I am fairly new in Flutter, I am fetching data from api and displaying it in a listview. I have following demo code.
/*Other codes*/
return ListView.builder(
//Other Codes
physics: const AlwaysScrollableScrollPhysics(),
itemCount: item.length,
padding: new EdgeInsets.only(top: 5.0),
itemBuilder: (context, index) {
});
My requirement is to show data in Two Rows, such that if the item in index is even show it in first row and if its odd, show it in another row? More like in the Image below.
Update: There could be many items and can be scrolled horizontally to reveal more items.
Can we achieve this without manipulating the data received from API? From API the data comes in date-wise sorted in descending order.
Thanks
GridView.builder is probably what you are looking for.
Just give it scrollDirection: Axis.horizontal to make it horizontal.
Then give it gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2) to make sure you have only 2 rows.
Then use SizedBox to restrict the height of the GridView to 90 + 90.
Finally, use the childAspectRatio property of the SliverGridDelegateWithFixedCrossAxisCount to specify that you want your aspect ratio to be 90 / 256.
Color randomColor() => Color.fromARGB(255, Random().nextInt(255), Random().nextInt(100), Random().nextInt(200));
class MyApp extends StatelessWidget {
List<String> array = ["0", "1", "2", "3"];
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Example')),
body: SizedBox(
height: 90 + 90,
child: GridView.builder(
itemCount: 4,
scrollDirection: Axis.horizontal,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
childAspectRatio: 90 / 256,
crossAxisCount: 2,
),
itemBuilder: (context, index) {
return Container(
color: randomColor(), child: Text(array[index])
);
}
),
),
),
);
}
}

Why is GridView.builder creating the same random image?

How is it that "http://lorempixel.com/300/300/" returns the same image for all the grid tiles in the following example?
Widget build(BuildContext context) {
return GridView.builder(
itemCount: 100,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
crossAxisSpacing: 2,
mainAxisSpacing: 2,
),
itemBuilder: (BuildContext context, int index) {
return Container(
color: Colors.grey,
child: Center(child: Image.network("http://lorempixel.com/300/300/")),
);
},
);
}
It seems that the result of the first request to "http://lorempixel.com/300/300" is used for all images. Why?
It's due to the structure of Image widget and its Image.network constructor which caches all Images loaded through it. They mention that in the Image widget documentation :
All network images are cached regardless of HTTP headers.

How to set grid view column height?

I am new to flutter and don't have much experience.
I am trying to develop an android app using flutter and this is my previous app design.
And I'm also able to successfully make grid view in flutter but the column height is the problem. Is their anyone who can help me with my flutter code.
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
hi(){
}
return new Scaffold(
appBar: new AppBar(
actions: <Widget>[],
title: new Text("milla"),
),
body: new Container(
child: new Center(
child: new GridView.count(
shrinkWrap: true,
scrollDirection: Axis.vertical,
childAspectRatio:1.0,
crossAxisCount: MediaQuery.of(context).size.width <= 400.0 ? 3 : MediaQuery.of(context).size.width >= 1000.0 ? 5 : 4,
// Create a grid with 2 columns. If you change the scrollDirection to
// horizontal, this would produce 2 rows.
crossAxisSpacing: 2.0,
// Generate 100 Widgets that display their index in the List
children: new List.generate(100, (index) {
return new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
verticalDirection: VerticalDirection.down,
children: <Widget>[
new Center(
child: new Image(
image: new NetworkImage('https://github.com/flutter/website/blob/master/_includes/code/layout/lakes/images/lake.jpg?raw=true')
)
),
new Expanded(child: new Text("apple2")), new Expanded(child: new Text(
'Item $index',
style: Theme.of(context).textTheme.headline,
)),new Expanded(child: new Center(child: new Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[new Text("+",style: new TextStyle(fontSize: 24.0),),new Text("1"),new Text("-")])))]
);
}),
),
),
)
);
}
}
And this is my output.
How to set column height?
When i'm trying to add new view, it's showing this error "Another exception was thrown: A RenderFlex overflowed by 21 pixels on the bottom."
Put this instead of
childAspectRatio:1.0 to childAspectRatio: (itemWidth / itemHeight)
var size = MediaQuery.of(context).size;
final double itemHeight = (size.height) / 2;
final double itemWidth = size.width / 2;
It works fine in my code to set height and width of Gridview
You might try this:
GridView.count(
crossAxisCount: 2,
childAspectRatio: MediaQuery.of(context).size.height / 400,
children: <Widget>[...]
);
Try this
childAspectRatio: mediaQueryData.size.height / 1000,
where
MediaQueryData mediaQueryData = MediaQuery.of(context);
I saw this code somewhere and looks ok to me.
Maintain
childAspectRatio: with MediaQuery.of(context).size.height/600
if this didint work change 600 with diffrent but less numbers.
[Screenshot][https://i.stack.imgur.com/h28C2.png]1
This is my code:
final screenWidth = MediaQuery.of(context).size.width/3;
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: new Container(
color: Colors.white70,
padding: EdgeInsets.all(5.0),
child: new GridView.count(
childAspectRatio: screenWidth/180.0,
crossAxisCount: 3,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
children: _buildFirdTitles(35),
),
),
);
If you use GridView.builder
Try this, use gridDelegate section to custom items height
Edit the parameter childAspectRatio
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
// width / height: fixed for *all* items
childAspectRatio: 0.75,
)
class ItemCardGridView extends StatelessWidget {
const ItemCardGridView(
{Key? key,
required this.crossAxisCount,
required this.padding,
required this.items})
// we plan to use this with 1 or 2 columns only
: assert(crossAxisCount == 1 || crossAxisCount == 2),
super(key: key);
final int crossAxisCount;
final EdgeInsets padding;
// list representing the data for all items
final List<ItemCardData> items;
#override
Widget build(BuildContext context) {
return GridView.builder(
padding: padding,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: crossAxisCount,
// width / height: fixed for *all* items
childAspectRatio: 0.75,
),
// return a custom ItemCard
itemBuilder: (context, i) => ItemCard(data: items[i]),
itemCount: items.length,
);
}
}