Fit the whole Screen with two dynamic Widgets - flutter

Within a Column I have two Widgets: TableCalendar and a Container that contains a ListView.builder. Both have dynamic sizes.
I want my Container to fill the remaining size of the screen that is left from the calendar.
I thought that I could regulate this wrapping both Widgets with the Expanded Widget, but that only leads to an error.
The following assertion was thrown during performLayout(): RenderFlex
children have non-zero flex but incoming height constraints are
unbounded.
Here is my code:
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TableCalendar(
events: _events, //fixme: here is the problem
initialCalendarFormat: CalendarFormat.twoWeeks,
calendarController: _controller,
calendarStyle: CalendarStyle(),
headerStyle: HeaderStyle(
centerHeaderTitle: true,
formatButtonDecoration: BoxDecoration(
color: Colors.pinkAccent.shade100,
borderRadius: BorderRadius.circular(20.0),
),
formatButtonShowsNext: false,
),
startingDayOfWeek: StartingDayOfWeek.monday,
onDaySelected: (date, events) {
setState(() {
_listOfShiftsPerGivenDay = events;
});
},
builders: CalendarBuilders(
selectedDayBuilder: (context, date, events) => Container(
alignment: Alignment.center,
margin: EdgeInsets.all(4.0),
color: Colors.pink,
// decoration: BoxDecoration(),
child: Text(
date.day.toString(),
),
),
todayDayBuilder: (context, date, events) => Container(
alignment: Alignment.center,
margin: EdgeInsets.all(4.0),
color: Colors.teal.shade100,
child: Text(
date.day.toString(),
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 18.0),
),
),
markersBuilder: (context, date, events, holidays) {
final children = <Widget>[];
if (events.isNotEmpty) {
children.add(
Positioned(
right: 1,
bottom: 1,
child: _buildEventsMarker(date, events),
),
);
}
return children;
}),
),
Container(
//fixme: the hight needs to be variable
height: 200.0,
child: ListView.builder(
itemCount: _listOfShiftsPerGivenDay.length,
itemBuilder: (context, index) => Container(
width: MediaQuery.of(context).size.width,
padding:
EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: _events[_controller.selectedDay][index],
// ),
),
),
)
],
),

What is the parent of the main Column at the beginning? Is it another Column?
If that is the case, then try wrapping the Column at the beginning with Expanded, that will force a height constraint to its children, then you can use Expanded on Container.
child: Expanded(
child: Column(
children: <Widget>[
TableCalendar();
Expanded(
child: Container()
)
])
I have written an article on Medium on why this might happen, if you want to know more.

What if you wrap your ListView() in an Expanded?
child: Column(
children: <Widget>[
TableCalendar();
Expanded(
child: ListView.builder()
)
])

Related

Flutter: Make all screen scrollable with GridView.builder inside

In my home screen my app shows carousel first then a vertical list of challenges cards retrieved from Cloud Firestore using GridView.builder as follows:
GridView.builder(
scrollDirection: Axis.vertical,
itemCount: _challenges.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 1,
childAspectRatio: MediaQuery.of(context).size.width /
(MediaQuery.of(context).size.height / 4),
),
itemBuilder: (context, index) {
return InkWell(
onTap: () {
if (_challenges[index]["isLocked"] == "true") {
showLockedDialog();
} else {
checkParticipation(index);
if (checkPart == true) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) =>
ChallengeDetails(_challenges[index])));
}
checkPart = true;
}
},
child: Stack(
children: [
Center(
child: ClipRRect(
borderRadius: BorderRadius.circular(15),
child: Image(
image: NetworkImage(_challenges[index]["image-path"]),
fit: BoxFit.cover,
height: 150,
width: 350,
opacity: _challenges[index]["isLocked"] == "true"
? AlwaysStoppedAnimation(.4)
: null,
),
),
),
Center(
child: Text(
"${_challenges[index]["name"]}\n",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold),
),
),
Center(
child: Text(
"\n${_challenges[index]["date"]}",
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold),
textDirection: TextDirection.ltr,
)),
Center(
child: SizedBox(
height: 130,
width: 130,
child: _challenges[index]["isLocked"] == "true"
? Image.asset("assets/lock-icon.jpg")
: null,
),
)
],
),
);
});
Everything retrieving fine and it is rendered in my home_screen as follows:
body: Column(
children: [
AdsBanner(),
SizedBox(
height: 30,
),
Padding(
padding: const EdgeInsets.only(right: 8, left: 8, bottom: 5),
child: Row(
children: [
Text(
AppLocalizations.of(context)!.challenges + " ",
style: TextStyle(fontSize: 20),
),
Text(
AppLocalizations.of(context)!.clickToParticipate,
style: TextStyle(fontSize: 15),
)
],
),
),
Expanded(child: ChallengeCard()),
],
),
The problem is that only the GridView area is scrolling and what am seeking for is to scroll the whole screen with the GridView area, I was trying to use the CustomScrollView() but its not working properly.
I'll be thankful for any help.
First in your GridView.builder add these:
GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
...
)
then in your home_screen wrap your column with SingleChildScrollView:
SingleChildScrollView(
child: Column(
children: [
AdsBanner(),
SizedBox(
height: 30,
),
Padding(
...
),
),
You can provide physics: NeverScrollableScrollPhysics() on GridView to disable scroll effect. If you want scrollable as secondary widget use primary: false, to have Full Page scrollable, you can use body:SingleChildScrollView(..) or better using body:CustomScrollView(..)

it's possible to make listview in expand and fill parent without overflow?

it's possible to make listview in expand and fill the container without overflow the container, and shrink when listview is short of content without declare manual min or max height?
Code
Flexible(
fit: FlexFit.loose,
child: Container(
padding: EdgeInsets.symmetric(vertical: 20, horizontal: 10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(kBoxRadius),
boxShadow: [kBoxShadow]),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
DText(
"Aug 2021",
size: 12,
weight: FontWeight.bold,
),
SizedBox(height: 10),
Row(
children: dates,
),
SizedBox(height: 15),
Container(
height: 1,
color: Color(0xFFE7E7E7),
),
Container(
constraints:
BoxConstraints(minHeight: 0, maxHeight: 600),
child: ListView.separated(
shrinkWrap: true,
itemBuilder: (context, index) {
return DText("Asd");
},
separatorBuilder: (_, __) {
return SizedBox(height: 10);
},
itemCount: 20,
),
)
],
),
),
)
Expectation
when the content is big
because i set manually max height.
Yes, it is possible using shrinkWrap: true. The code will be something like below,
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(),
body: Center(
child: Container(
color: Colors.red,
child: ListView(
shrinkWrap: true,
children: <Widget>[
ListTile(title: Text('Apple')),
ListTile(title: Text('Orange')),
ListTile(title: Text('Banana')),
],
),
),
),
),
);
}
}

How to arrange the items correctly in flutter

I try to make design of page of display comment. I need make page design is as follows: list at up and then Text Field at the bottom.So user will can see all comment and send new comment.
Something like photo:
but I have same problem with display.
This is my code:I make it like that now but now I can see list just without text field at the bottom
#override
Widget build(BuildContext context) {
return FutureBuilder<List<Flowerdata>>(
future: fetchFlowers(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Center(
child: CircularProgressIndicator()
);
return ListView(
children: snapshot.data
.map((data) => Column(children: <Widget>[
GestureDetector(
onTap: ()=>{
getItemAndNavigate(data.id, context)
},
child: Row(
children: [
Container(
width: 100,
height: 100,
margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child:
Image.network(data.flowerImageURL,
width: 200, height: 100, fit: BoxFit.cover,))),
Flexible(child:
Text(data.flowerName,
style: TextStyle(fontSize: 18))
),
]),),
Divider(color: Colors.black),
],))
.toList(),
);
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
controller: naameController,
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter Your Name Here'),
)
);
},
);
}
How can I arrange the items correctly?
First, your Container widget is unreachable, you should fix it then you can wrap your widgets with Column and wrap ListView with Expanded widget after giving height to Container. It will fix your problem.
But i have some suggestions about ListView. Why you did not use ListView.separated? If you use separated method you can delete map and your Divider.
Also when i looked your design, your list items looks like a card. You can use Card widget beside of GestureDetector.
I hope this will help you, if not i will glad to help you.
Edit: Here is sample code based on your question and my answer;
Column(
children: [
Expanded(
child: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int i) {
InkWell(
onTap: () => getItemAndNavigate(snapshot.data[i].id, context),
child: Card(
child: Row(
children: <Widget>[
Container(
width: 100,
height: 100,
margin: EdgeInsets.fromLTRB(10, 0, 10, 0),
child: ClipRRect(
borderRadius: BorderRadius.circular(8.0),
child: Image.network(snapshot.data[i].flowerImageURL,
width: 200, height: 100, fit: BoxFit.cover,),
),
),
Flexible(
child: Text(
snapshot.data[i].flowerName,
style: TextStyle(fontSize: 18),
),
),
]
),
),
);
},
),
),
Container(
width: 280,
padding: EdgeInsets.all(10.0),
child: TextField(
autocorrect: true,
decoration: InputDecoration(hintText: 'Enter Your Name Here'),
),
),
],
),
You are placing the TextField in the position after returning ListView, which make it dead code. You can add it at the end of your ListView children list or place a Stack outside to place both the ListView and TextField inside.

Refresh ListView.builder On Button Click in Flutter

I am using the below code, where I have a ListView that had a switch.
I want to implement something like when I click on the RaisedButton - it will reload the ListView and all the values of switch.value should be changed to either true or false.
The user can either change the value of the switch from items in the ListView or from the button click.
I do not have an idea on how I should change the value or all the switches in the ListView.
return Column(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width / 2,
height: 100,
padding: EdgeInsets.all(20),
child: RaisedButton(
onPressed: () {
},
child: Text(
BTN_START_TRIP,
style: new TextStyle(
fontSize: 20.0,
),
),
textColor: buttonFontColor,
color: buttonColor,
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(15.0))
),
),
Expanded(
child: ListView.builder(
padding: EdgeInsets.all(3.0),
// Let the ListView know how many items it needs to build.
itemCount: snapshot.data.results.length,
// Provide a builder function. This is where the magic happens.
// Convert each item into a widget based on the type of item it is.
itemBuilder: (context, index){
return Container(
height: 120,
child: Card(
elevation: 10,
child: InkWell(
splashColor: Colors.blue.withAlpha(30),
onTap: () {
print(snapshot.data.results[index].original_title);
},
child: Container(
height: 120,
child: Row(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(20, 0, 5, 0),
width: MediaQuery.of(context).size.width -90,
child: Align(
alignment: Alignment.topLeft,
child: Text(snapshot.data.results[index].original_title,
textAlign: TextAlign.left,
style: TextStyle(fontSize: defaultTitleFontsize, color: defaultFontColor),
maxLines: 5),
),
),
Container(
padding: EdgeInsets.fromLTRB(20, 0, 5, 0),
child: Align(
alignment: Alignment.topLeft,
child: Text(snapshot.data.results[index].original_language,textAlign: TextAlign.left,style: TextStyle(fontSize: defaultsubTitleFontsize, color: defaultFontColor)),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Container(
child: Switch(
value: false,
onChanged: (value){
setState(() {
print(value);
});
}
),
),
],
),
]
),
),
),
),
);
},
),
)
],
);
You'll need to have a variable to decide if the switch should be on or off. And during a certain event (click of button e.g) set the variable to appropriate value & re-trigger the build (re-painting of the UI) by calling setState. You'll need to have the above logic part of a stateful widget to accomplish that.

Dynamic height of listview builder item

I am unable to set the dynamic size to my list item of list view builder, every time it shows blank screen and when I specify a constant size it works.
I tried by using column by setting mainAxisSize=minimum and by using container as we know container wraps the child height but nothing works
listItem (GuideLines news) =>Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[Container(
decoration: BoxDecoration(image: new DecorationImage(image: AdvancedNetworkImage(
"${news.featured_image}",
useDiskCache: true,
cacheRule: CacheRule(maxAge: const Duration(days: 7)),
),fit: BoxFit.cover)),
margin: EdgeInsets.only(bottom: 10.0),
child: ListTile(
onTap: (){
print(news.web_link);
Navigator.push(context, MaterialPageRoute(builder: (context) => NewsDetailsPage(news)));
},
title: new Container(
margin: EdgeInsets.only(left: 30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: new Text("${DateFormat("E, d MMM y").format(CommonService.dateFormat(news.publish_date.toString()))}", style: TextStyle(fontFamily: 'SF-Display-Regular' ,fontSize: 13.0 ,color: Colors.white),),
),
SizedBox(height: 13.0),
new Flexible(
child: new Container( width: MediaQuery.of(context).size.width *0.45,
child: Padding(
padding: const EdgeInsets.only(bottom: 20.0),
child: new Text("${news.title}" ,maxLines: 3, overflow: TextOverflow.ellipsis, style: TextStyle(fontFamily: 'SF-Display-Semibold' ,fontSize: 22.0 ,color: Colors.white),),
)
),
)
],
)),
trailing: Padding(
padding: const EdgeInsets.only(right: 20),
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[Icon(Icons.arrow_forward_ios, color: Colors.white),SizedBox(width: 8,)],
),
),
),
)],
);
Just add these two properties of shrinkWrap and physics to make the height of list dynamic
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(), //Optional
itemCount: size,
itemBuilder: (context, position) {}
),
The problem with your code is, that you used a Flexible widget in a Column. A Flexible widget expands to the remaining space of the Column or Row. However, this only works if you have restricted the size of the Column or Row widget. Because otherwise, the size of the element in the Column would expand to infinity as the remaining space is not restricted and therefore also infinity.
When using Flexible or Expanded widgets you always need to restrict their parent size, else you get this error:
RenderFlex children have non-zero flex but incoming height constraints
are unbounded. When a column is in a parent that does not provide a
finite height constraint, for example if it is in a vertical
scrollable, it will try to shrink-wrap its children along the vertical
axis. Setting a flex on a child (e.g. using Expanded) indicates that
the child is to expand to fill the remaining space in the vertical
direction.
The solution and some cleanup of your code:
Widget listItem(GuideLines news) {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AdvancedNetworkImage(
"${news.featured_image}",
useDiskCache: true,
cacheRule: CacheRule(maxAge: const Duration(days: 7)),
),
fit: BoxFit.cover),
),
margin: EdgeInsets.only(bottom: 10.0),
child: ListTile(
onTap: () {
print(news.web_link);
Navigator.push(context, MaterialPageRoute(builder: (context) => NewsDetailsPage(news)));
},
title: Container(
margin: EdgeInsets.only(left: 30.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 20.0, bottom: 13.0),
child: Text(
"${DateFormat("E, d MMM y").format(CommonService.dateFormat(news.publish_date.toString()))}",
style: TextStyle(fontFamily: 'SF-Display-Regular', fontSize: 13.0, color: Colors.white),
),
),
Container(
width: MediaQuery.of(context).size.width * 0.45,
padding: const EdgeInsets.only(bottom: 20.0),
child: new Text(
"${news.title}",
maxLines: 3,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontFamily: 'SF-Display-Semibold', fontSize: 22.0, color: Colors.white),
),
)
],
),
),
trailing: Padding(
padding: const EdgeInsets.only(right: 28),
child: Icon(Icons.arrow_forward_ios, color: Colors.white),
),
),
);
}
In your specific case, this Flexible widget was redundant anyway.