Need to accomodate gridView in my flutter - flutter

Im building an app that shows diets and also have a search bar to look for the diets.
I cant manage accomodate the search bar correctly like outside the gridviewer. heres the code of my view and how it actually looks. I dont want to be like another card
body: Container(
child: GridView.builder(
padding: EdgeInsets.all(15),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount: dietsForDisplay.length + 1,
itemBuilder: (BuildContext context, int index) {
if (diets.length == 0) {
return Container(
child: Padding(
padding: const EdgeInsets.all(60.0),
child: Text(
"No existen Dietas registradas por la nutriĆ³loga.",
style: TextStyle(
color: Color(0xFF002D53),
fontFamily: 'Montserrat',
fontSize: 25,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
),
);
} else {
return index == 0
? _searchBar()
: _listItem(
context,
index - 1,
);
}
}),
));
}
and the code for the searchBar and listItem are Cards

Wrap your material app inside a Safe Area Widget
https://api.flutter.dev/flutter/widgets/SafeArea-class.html

I would suggest you to wrap your Scaffold widget with SafeArea so that your appbar won't get obstructed due to the notch. If you would want to add a search bar in your Scaffold's body, I would suggest using a Column to place your search bar on the top and your GridView.builder() on the bottom. Here is how it looks like after my suggestions:
SafeArea(
child:Scaffold(
body: Column(
children: <Widget>[
//Search Bar here
Expanded(
child: //GridView.builder() here
);
],
),
),
);
*If you want that page to be scrollable then replace Column with ListView

Related

Create a bidirectional infinite ListView.builder in Flutter

I mean in both axis, horizontal and vertical.
I tried nesting two ListView.builder but they don't scroll together as I would like.
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: Drawer(),
appBar: AppBar(),
body: Container(
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemBuilder: (context, x) {
return Container(
height: 50,
width: 50,
child: ListView.builder(
itemBuilder: (context, y) {
return Container(
height: 100, child: Text("${y.toString()}"));
},
),
);
}),
));
}
}
Possible solutions I have in mind:
Make the ListView.builders scroll together. But I think that solution may not be efficient performance wise, since flutter still treating each column as an individual scroller
Create a finite ListView.builder and rebuild it as necessary to make the illusion it is infinite. But that may add unnecessary complexity to the project.
Add NeverScrollableScrollPhysics on vertical axis and perform the scroll with another Widget. I failed attempting that. That method just worked for me if the list is finite.
Is there any widget appropriated to that application that I could be maybe missing?
Is there any other better approach to create something like that?
Two dimensional scrolling is supported by DataTable (try the Flutter Gallery "Data tables" demo) and Table. Maybe try building a schedule widget based on on of those.
You can use wrap DataTable inside two SingleChildScrollView widgets to achieve bidirectional scrolling..
By using something like this
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: DataTable(
dataRowHeight: 50,
dividerThickness: 5,
horizontalMargin: 15,
columnSpacing: 13,
showBottomBorder: true,
headingRowColor: MaterialStateProperty.all<Color>(
Colors.blueGrey[100]),
columns: [
DataColumn(
label: Text(
"Module Name",
style: TextStyle(
// fontStyle: FontStyle.italic,
fontWeight: FontWeight.w600,
fontSize: 14,
color: Theme.of(context).highlightColor,
),
),
numeric: false,
),
],
rows: data
.map((details) => DataRow(
cells: [
DataCell(
Text(
details.name,
),
),
//list of cells: remenber the number of DataColumn and DataCell should be same
],
))
.toList()),
),
);
To fetch data from internet you can wrap the first SingleChildScrollView with FutureBuilder
PS: here data is list of modules data fetch from internet,
just for example I have added only one DataColumn you can add as needed

how to align listview items top left?

i am trying to align list view items at the top left, but it aligns them in the center. I tried this with another widget, it works fine, but with the listview, it doesn't.
here is my code
Container(
height: height * 30,
// color: Colors.grey[400],
alignment: Alignment.topLeft,
child: ListView.builder(
itemBuilder: (context, i) => ReviewItem(
review: book.reviews[i]['review'],
date: book.reviews[i]['date'],
),
itemCount: book.reviews.length,
),
),
this is the review item
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
timeago.format(DateTime.parse(date)),
style: Theme.of(context).textTheme.headline4.copyWith(
fontSize: width * kFont12Ratio, color: Colors.grey[500]),
),
SizedBox(height: height * 0.5),
Text(review),
Divider(),
],
);
Thanks in advance
By default, ListView will automatically pad the list's scrollable extremities to avoid partial obstructions indicated by MediaQuery's padding. In other words, if you put a widget before the ListView, you should wrap the ListView with a MediaQuery.removePadding widget (with removeTop: true). Like so:
MediaQuery.removePadding(
context: context,
removeTop: true,
child: ListView.builder(...),
);
I achieved that by adding padding inside the listview builder
padding: EdgeInsets.only(top: 0),
You can use padding instead
Or use Stack with Position (top:0,left:0)
Or use Align( )

Making a 2x2 grid in Flutter

I'm trying to create a 2x2 grid for displaying some info in cards. Disclaimer: I'm totally new to Dart and Flutter, so expect a lot of ignorance on the topic here.
These cards should have a fixed size, have an image, display some text... and be positioned from left to right, from top to bottom.
First, I tried to use the Flex widget, but it seems to only work horizontally or vertically. Therefore, my only solution was to use two Flexes, but only showing the second when the amount of elements is higher than 2 (which would only use one row).
Then, I tried using GridView, but it doesn't work in any possible way. It doesn't matter which example from the Internet I copy and paste to begin testing: they just won't show up in the screen unless they're the only thing that is shown in the app, with no other widget whatsoever. I still don't understand why that happens.
This is my current code:
First widgets in "home_page.dart":
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 30)),
Text(
'App test',
style: TextStyle(fontSize: 24),
),
EventsList(key: new Key('test')),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
The "EventList" part is a widget that should represent the grid functionality I explained before. This class gets some info from a service (which currently just sends some hardcoded info from a Future), and paints the given widgets ("Card" items, basically) into the EventList view:
class _EventsListState extends State<EventsList> {
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Event>>(
future: new EventsService().getEventsForCoords(),
builder: (context, AsyncSnapshot<List<Event>> snapshot) {
if (snapshot.hasData) {
return Padding(
padding: EdgeInsets.only(left: 20, right: 20),
child: Flex(
direction: Axis.horizontal,
verticalDirection: VerticalDirection.down,
mainAxisAlignment: MainAxisAlignment.center,
children: generateProximityEventCards(snapshot.data),
));
} else {
return CircularProgressIndicator();
}
});
}
List<Card> generateProximityEventCards(List<Event> eventList) {
// Load Events from API
print(eventList);
// Render each card
return eventList.map((Event ev) {
return Card(
child: Padding(
padding: EdgeInsets.only(bottom: 15),
child: Column(
children: <Widget>[
Image(
fit: BoxFit.cover,
image: ev.imageUrl,
height: 100,
width: 150,
),
Padding(
child: Text(ev.name),
padding: EdgeInsets.only(left: 10, right: 10),
),
Padding(
child: Text(ev.address),
padding: EdgeInsets.only(left: 10, right: 10),
),
],
),
));
}).toList();
}
}
This is how it currently looks:
As I said before, I understand that the Flex widget can't really get that 2x2 grid look that I'm looking for, which would be something like this (done with Paint):
So, some questions:
How can I get a grid like that working? Have in mind that I want to have more stuff below that, so it cannot be an "infinite" grid, nor a full window grid.
Is it possible to perform some scrolling to the right in the container of that grid? So in case there are more than 4 elements, I can get to the other ones just scrolling with the finger to the right.
As you can see in the first image, the second example is bigger than the first. How to limit the Card's size?
Thank you a lot for your help!
The reason the gridview was not working is because you need to set the shrinkWrap property of theGridView to true, to make it take up as little space as possible. (by default, scrollable widgets like gridview and listview take up as much vertical space as possible, which gives you an error if you put that inside a column widget)
Try using the scrollable GridView.count widget like this and setting shrinkWrap to true:
...
GridView.count(
primary: false,
padding: /* You can add padding: */ You can add padding const EdgeInsets.all(20),
crossAxisCount: /* This makes it 2x2: */ 2,
shrinkWrap: true,
children: generateProximityEventCards(snapshot.data),
...
Is this what you exactly want?
do let me know so that I can update the code for you
import 'package:flutter/material.dart';
class List extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
title: Text('Inicio', style: TextStyle(color: Colors.black, fontSize: 18.0),),
),
body: GridView.count(
shrinkWrap: true,
crossAxisCount: 2,
children: List.generate(
50,//this is the total number of cards
(index){
return Container(
child: Card(
color: Colors.blue,
),
);
}
),
),
);
}
}

How to make a container 'lighten' on hold / on tap in Flutter?

I am trying to create an app with a scroll view and the objects are clickable like the google news app. Can anyone answer how to animate the container to have a white glow on holding the tile?
Here is the list view builder I have for the app
Container(
padding: EdgeInsets.only(top: 16),
child: ListView.builder(
physics: ClampingScrollPhysics(),
itemCount: article.length,
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemBuilder: (context, index) {
return news_tile(
imageurl: article[index].urlToimage,
news_title: article[index].title,
news_desc: article[index].description,
web_url: article[index].url
);
}),
)
and this is the contents of the tile which the list view builder calls
class news_tile extends StatelessWidget {
String imageurl, news_title, news_desc,web_url;
news_tile({this.imageurl, this.news_title, this.news_desc,this.web_url});
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
Navigator.push(context, MaterialPageRoute(
builder: (context) => article_view(
web_url: web_url,
)
));
},
child: Container(
margin: EdgeInsets.only(bottom: 16),
child: Column(
children: <Widget>[
ClipRRect(borderRadius: BorderRadius.circular(6), child: Image.network(imageurl)),
SizedBox(
height: 8,
),
Text(news_title, style: TextStyle(fontSize: 17,fontWeight: FontWeight.w600)),
SizedBox(
height: 8,
),
Text(news_desc, style: TextStyle(color: Colors.black54))
],
),
),
);
}
}
You could go with the InkWell Widget. It provides a tapping/holding color effect similar to that. Have a look at the official docs here:
https://api.flutter.dev/flutter/material/InkWell-class.html
Note that you need a Material Widget as an ancestor of your InkWell, but the docs explain that more.
Hope it works for you!
Edit: Sorry, since you are working with a Container, Ink is also important for you:
https://api.flutter.dev/flutter/material/Ink-class.html
Check the docs section "The ink splashes aren't visible!" for why that is.

Flutter GridView.builder is Generating Unwanted Extra Space

I am trying to display a row of buttons. Since the number of buttons depends on the number of elements in a List, I have to use GridView.builder to dynamically create the right amount of buttons. Unfortunately it seems that GridView.builder is taking up alot of unnecessary space. Anyone know what is wrong here?
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// Dice buttons
Flexible(
child: GridView.builder(
itemCount: dices.length,
gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: dices.length,
),
itemBuilder: (BuildContext context, int index) {
return new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ButtonTheme(
minWidth: 50.0,
height: 50.0,
child: RaisedButton(
child: Text(
dices[index].toString(),
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
color: usedDices[index] || !expectNum
? Colors.grey
: Colors.black,
onPressed: () {
if (!usedDices[index] && expectNum) {
setState(() {
numUsed[turn] = dices[index].toString();
numUsedIndex[turn] = index;
});
expectNum = false;
usedDices[index] = true;
}
},
),
),
]);
})),
Link to Pic: https://drive.google.com/file/d/1_Jr4rz9GJ-D8-Xjxs2w8Sn8lOdnBBqTc/view?usp=sharing
As you can see are lots of unnecessary space here and it seems to be the reuslt of GridView.builder
That space is the result of Flexible, which fills the available space. You will see that if you replace it with a Container and give it a height, it won't produce that much space below.
Just had this problem, top SliverPadding is set to 20.0 by default. Looking at docs I see:
/// By default, [ListView] will automatically pad the list's scrollable
/// extremities to avoid partial obstructions indicated by [MediaQuery]'s
/// padding. To avoid this behavior, override with a zero [padding] property.
So,
GridView.builder(
// shrinkWrap: true,
padding: EdgeInsets.zero,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisSpacing: 1,
mainAxisSpacing: 1,
crossAxisCount: 3,
),
itemBuilder: (context, index) {
return Container(
color: Colors.black,
);
},
itemCount: 10,
),
or
If you put a widget before the ListView, you should wrap the ListView with a
MediaQuery.removePadding widget (with removeTop: true)