How do I put a ListView under a scaffold with padding? - flutter

I am quite new to flutter and I've been trying to set up a profile page for my app but it seems like I don't quite understand how these flutter widgets come together, I apologize if my question is quite dumb but I've been googling and failing at getting this to work. So basically I have a scaffold which holds a container thats supposed to display profile info (email, name, etc.), under it I'd like to place a listview, but flutter has been boggling my mind, I can't seem to understand how layouts work together, here is my code. When I try to do buildPage(), I get an error that the scaffold has infinite size, using buildBox() alone works. I'm not sure how to go about this. Any Help is appreciated
import 'package:flutter/material.dart';
class ProfileBox extends StatefulWidget {
final String userEmail;
const ProfileBox(this.userEmail);
#override
_ProfileBoxState createState() => _ProfileBoxState();
}
class _ProfileBoxState extends State<ProfileBox> {
#override
Widget build(BuildContext context) {
return _buildPage();
}
Widget _buildBox(){
return Scaffold(
body: Align(
alignment: Alignment.topCenter,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Container(
margin: const EdgeInsets.only(top: 20.0),
decoration: BoxDecoration(
color: Color(0xFF8185E2), border: Border.all(
color: Color(0xFF8185E2),
),
borderRadius: BorderRadius.all(Radius.circular(20))
),
height: constraints.maxHeight / 2.5,
width: MediaQuery.of(context).size.width - (MediaQuery.of(context).size.width * 5)/100,
child: Center(
child: Text(
widget.userEmail,
textAlign: TextAlign.center,
),
),
);
},
),
),
);
}
Widget _buildPage()
{
return Column(children: <Widget>[
_buildBox(),
_buildList(),
],);
}
Widget _buildList()
{
return ListView(
children: <Widget>[
ListTile(
title: Text('Sun'),
),
ListTile(
title: Text('Moon'),
),
ListTile(
title: Text('Star'),
),
],
);
}
}

I just modified your code with Scaffold put the top Widget before the SafeArea, Please check the below code of it.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class HomeScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return _HomeScreen();
}
}
class _HomeScreen extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return _buildPage();
}
Widget _buildPage() {
return SafeArea(
top: true,
child: Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
margin: const EdgeInsets.only(top: 20.0),
decoration: BoxDecoration(
color: Color(0xFF8185E2),
border: Border.all(
color: Color(0xFF8185E2),
),
borderRadius: BorderRadius.all(Radius.circular(20))),
height: MediaQuery.of(context).size.height / 2.5,
width: MediaQuery.of(context).size.width -
(MediaQuery.of(context).size.width * 5) / 100,
child: Center(
child: Text(
"YOUR_EMAIL",
textAlign: TextAlign.center,
),
),
),
Expanded(
child: _buildList(),
)
],
),
),
);
Column(
children: <Widget>[
// _buildBox(),
_buildList(),
],
);
}
Widget _buildList() {
return ListView(
children: <Widget>[
ListTile(
title: Text('Sun'),
),
ListTile(
title: Text('Moon'),
),
ListTile(
title: Text('Star'),
),
],
);
}
}
And output of the program as follow

Scaffold Widget should be a top Widget that contains the Column widget and all children Widget. I think you can start learning how to layout Widget in Flutter in order to understand more the way how Widget works, and the good place can be: https://flutter.dev/docs/development/ui/layout#lay-out-a-widget
Coming back to your question, you can just fix a bit to make it work:
class _ProfileBoxState extends State<ProfileBox> {
#override
Widget build(BuildContext context) {
return _buildPage();
}
Widget _buildBox() {
return Align(
alignment: Alignment.topCenter,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Container(
margin: const EdgeInsets.only(top: 20.0),
decoration: BoxDecoration(
color: Color(0xFF8185E2),
border: Border.all(
color: Color(0xFF8185E2),
),
borderRadius: BorderRadius.all(Radius.circular(20))),
height: constraints.maxHeight / 2.5,
width: MediaQuery.of(context).size.width -
(MediaQuery.of(context).size.width * 5) / 100,
child: Center(
child: Text(
widget.userEmail,
textAlign: TextAlign.center,
),
),
);
},
),
);
}
Widget _buildPage() {
return Scaffold(
body: Column(
children: <Widget>[
_buildBox(),
_buildList(),
],
),
);
}
Widget _buildList() {
return ListView(
children: <Widget>[
ListTile(
title: Text('Sun'),
),
ListTile(
title: Text('Moon'),
),
ListTile(
title: Text('Star'),
),
],
);
}
}

Related

How to make responsive svg -flutter

What is the best way to get a responsive svg image, I thought about using MediaQuery, but probably not quite it will fit for every screen.
I used Stack and Positioned because I have more things to lay on one screen that will overlap.
I want to make responsive this:
class Shape extends StatelessWidget {
static Route route() {
return MaterialPageRoute<void>(builder: (_) => Shape());
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
leading: IconButton(
icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
onPressed: () => Navigator.of(context).pop(),
),
),
body: _profilePage(context),
);
}
Widget _profilePage(BuildContext context) {
return SafeArea(
child: Align(
child: Center(
child: Stack(children: <Widget>[
Positioned(
width: MediaQuery.of(context).size.width * 1,
height: MediaQuery.of(context).size.height,
top: MediaQuery.of(context).size.width * 0.4,
child: _curved(context),
),
]),
),
),
);
// });
}
Widget _curved(BuildContext context) {
return SvgPicture.asset(
'assets/images/shape_curved.svg',
color:Colors.green,
allowDrawingOutsideViewBox: true,
);}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(children: [
Flexible(
flex: 2,
child: Container(
color: Colors.yellow,
child: Container(
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(80.0),
))),
),
),
Flexible(
child: Container(
color: Colors.green,
child: Container(
decoration: BoxDecoration(
color: Colors.yellow,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(80.0),
))),
),
),
]),
);
}
}

VerticalCardPager not taking full width

When using the VerticalCardPager on a page on its own, it works with no problems.
However, when using it beneath other widgets, the cards shrink in size. I have tried wrapping within a SingleChildScrollView to extend the page but this does not work with the Expanded/Flexible widget.
HomeScreen
import 'package:club2_app/widgets/vertical_card.dart';
import 'package:flutter/material.dart';
import '../widgets/news_card.dart';
import '../constants.dart';
import '../widgets/app_bar.dart';
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(),
body: SafeArea(
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(left: 10, top: 15),
child: Text(
"News",
style: TextStyle(
color: kPrimaryLightColor,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
),
],
), // 'News'
NewsCard(),
Row(
children: [
Padding(
padding: EdgeInsets.only(left: 10.0),
child: Text(
'Posts',
style: TextStyle(
color: kPrimaryLightColor,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
),
],
), // 'Posts'
Expanded(
child: Container(
padding: EdgeInsets.all(5.0),
width: double.infinity,
child: VerticalCard(),
),
)
],
),
),
);
}
}
VerticalCardWidget
import 'package:flutter/material.dart';
import 'package:vertical_card_pager/vertical_card_pager.dart';
class VerticalCard extends StatefulWidget {
#override
_VerticalCardState createState() => _VerticalCardState();
}
final List<String> titles = [
"How to Manage Injuries",
"Is Football Getting Faster?",
"Improving Match Fitness",
"Expected Goals: The Over and Under Achievers",
];
final List<Widget> images = [
Hero(
tag: "News 1",
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Container(
width: double.infinity,
child: Image.asset(
"assets/images/Mbappe.jpeg",
fit: BoxFit.cover,
),
),
),
),
Hero(
tag: "News 2",
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset(
"assets/images/Mbappe.jpeg",
fit: BoxFit.cover,
),
),
),
Hero(
tag: "News 3",
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset(
"assets/images/Mbappe.jpeg",
fit: BoxFit.cover,
),
),
),
Hero(
tag: "News 4",
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset(
"assets/images/Mbappe.jpeg",
fit: BoxFit.cover,
),
),
),
];
class _VerticalCardState extends State<VerticalCard> {
#override
Widget build(BuildContext context) {
return VerticalCardPager(
titles: titles,
images: images,
onPageChanged: (page) {
// print(page);
},
);
}
}
I'm afraid it is a limitation of the VerticalCardPager.
The width and height of the cards inside a VerticalCardPager are defined based on the maxHeight of the Parent Widget:
double getWidth(maxHeight, i) {
double cardMaxWidth = maxHeight / 2;
return cardMaxWidth - 60 * (i - 2).abs();
}
double getHeight(maxHeight, i) {
double cardMaxHeight = maxHeight / 2;
if (i == 2) {
return cardMaxHeight;
} else if (i == 0 || i == 4) {
return cardMaxHeight - cardMaxHeight * (4 / 5) - 10;
} else
return cardMaxHeight - cardMaxHeight * (4 / 5);
}
}
For i == 2, the middle Card, the width and height are both equal to maxHeight / 2.
So, if you want the Cards to have a different aspect ratio and fill the width of the screen, you will have to modify the code of the VerticalCardPager.
However, if you want to keep the same aspect ratio and expand out of the screen. You can use a SingleChildScrollView as you mentioned. Here you go:
class _HomeScreenState extends State<HomeScreen> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Vertical Pager')),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
[...]
SizedBox(
height: MediaQuery.of(context).size.height,
child: Container(
padding: EdgeInsets.all(5.0),
width: double.infinity,
child: VerticalCard(),
),
)
],
),
),
),
);
}
}
However, the scrolling behavior might be a little bit chaotic, or even impossible on some devices.
try to wrap Your column into container and set its width to "double.infinity"

I am not able to make my app scrollble, despite of having SingleChildScrollView in Flutter

In my app, i have used BlogTile and CategoryTile widgets (which were made by myself) and I am using them in Contaniers/Columns. When I used SingleChildScrollView with CategoryTile, and made axis as horizontal, it was working fine. But as soon as i use it for BlogTile, it doen't work. I am not able to scroll in my app vertically. But when i try to scroll vertically by clicking on the part between CategoryTile and BlogTile, it works. But when i try to scroll by clicking from anyb other section of it, it doesn't work. Please someone help me
Check this code -
import 'package:flutter/material.dart';
import 'package:news_app/helper/data.dart';
import 'package:news_app/helper/news.dart';
import 'package:news_app/models/article_model.dart';
import 'package:news_app/models/category_models.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<CategoryModel> categories = new List<CategoryModel>();
List<ArticleModel> articles = new List<ArticleModel>();
bool loading = true;
#override
void initState() {
// TODO: implement initState
super.initState();
categories = getCategories();
getNews();
}
getNews() async {
News newsClass = News();
await newsClass.getNews();
articles = newsClass.news;
setState(() {
loading = false;
print('Done');
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Flutter',
style: TextStyle(
color: Colors.black,
),
),
Text(
'News',
style: TextStyle(
color: Colors.blue,
),
),
],
),
//elevation: 2.0,
),
body: loading
? Center(
child: Container(
child: CircularProgressIndicator(),
),
)
: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: SingleChildScrollView(
child: Container(
padding: EdgeInsets.only(top: 10.0),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
///Categories
Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
height: 70.0,
child: ListView.builder(
itemCount: categories.length,
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemBuilder: (context, index) {
return CategoryTile(
imageUrl: categories[index].imageUrl,
categoryName: categories[index].categoryName,
);
},
),
),
SizedBox(
height: 30.0,
),
///Blogs
SingleChildScrollView(
child: Container(
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: articles.length,
itemBuilder: (context, index) {
return BlogTile(
imageUrl: articles[index].urlToImage,
title: articles[index].title,
desc: articles[index].description,
);
},
),
),
),
],
),
),
),
),
),
),
);
}
}
class CategoryTile extends StatelessWidget {
final imageUrl, categoryName;
CategoryTile({this.imageUrl, this.categoryName});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {},
child: Container(
margin: EdgeInsets.only(right: 16.0),
child: Stack(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(6.0),
child: Image.network(
imageUrl,
width: 120.0,
height: 160.0,
fit: BoxFit.cover,
),
),
Container(
alignment: Alignment.center,
width: 120.0,
height: 160.0,
decoration: BoxDecoration(
color: Colors.black26,
borderRadius: BorderRadius.circular(6.0)),
child: Text(
categoryName,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w500,
fontSize: 14.0,
),
),
),
],
),
),
);
}
}
class BlogTile extends StatelessWidget {
final String imageUrl, title, desc;
BlogTile(
{#required this.imageUrl, #required this.desc, #required this.title});
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Image.network(imageUrl),
Text(title),
Text(desc),
],
),
);
}
}
I think the issue here is that you're giving unbounded height and width to some of the ScrollViews.
First off, don't use multiple scrolling widgets nested inside one another. But if you want to do that, try wrapping each of your scrollview within a Container like this:
SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
height: 50.0,
width: 50.0,
child: SingleChildScrollView(
child: ...,
),
),
),
What I'd also suggest is that instead of using a SingleChildScrollView, use a ListView widget. It works almost the same and you can put multiple children inside it. A simple ListView() will work. Don't use ListView.builder or any other aggregate function.

Items in ListView get it's height

I'm trying to create a horizontal list view with some card.
I want the list view to have height X and the cards to have height Y, I don't know why but the cards are getting the height of the list view.
This is what I have:
class FinanceApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Container(
color: Color(0x180000),
child: Column(
children: <Widget>[
Header(),
SizedBox(
height: 20,
),
Expanded(
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(32.0),
topRight: Radius.circular(32.0),
),
),
child: Column(
children: <Widget>[
Container(
height: 250,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
CustomCard(),
CustomCard(),
],
),
),
],
),
),
),
],
),
),
),
);
}
}
EDIT: The only thing that kinda works for me, Is to wrap the card container in another container, use padding to get the size I want, but it does not seem like a great solution.
Check this out:
import 'package:flutter/material.dart';
class StackOverFlow extends StatefulWidget {
#override
_StackOverFlowState createState() => _StackOverFlowState();
}
class _StackOverFlowState extends State<StackOverFlow> {
#override
Widget build(BuildContext context) {
return Scaffold(
body:
Center(
child: Container(
color: Colors.blue,
height: 200.0,
width: double.infinity,
child: ListView.builder(
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.all(16.0),
itemCount: 100,
itemBuilder: _buildItem,
),
),
),
);
}
Widget _buildItem (BuildContext context, int index) {
return Center(
child: Card(
child: Text(index.toString()),
),
);
}
}
And for giving children same size consider wrapping the cards with a Container:
Widget _buildItem (BuildContext context, int index) {
return Center(
child: Container(
height: 100.0,
width: 100.0,
child: Card(
child: Center(child: Text(index.toString())),
),
),
);
}

Flutter's Flexible Behavior

I want the blue to be full.
But it only spreads up to half.
https://i.stack.imgur.com/UQsiB.png
class TestScene extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
fit: FlexFit.loose,
child: Container(
color: Colors.red,
child: const Text('1'),
),
),
Flexible(
fit: FlexFit.loose,
child: Container(
color: Colors.blue,
child: const Text('1234567890123456789012345678901234567890'),
),
),
],
),
);
}
}
The reverse will also fail.
https://i.stack.imgur.com/rf00I.png
In both cases, it's nice.
https://i.stack.imgur.com/21ORb.png
This is a way ! (To take remain space)
String one='1',two='1234567890123456789012345678901234567890';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
backgroundColor:Colors.white,
body: Row(
mainAxisSize:MainAxisSize.max,
children: <Widget>[
one.length>=two.length ?
Expanded(
child: Container(
color: Colors.red,
child: Text(one),
),
):Container(
color: Colors.red,
child: Text(one),
),
two.length>=one.length ?
Expanded(
child: Container(
color: Colors.blue,
child: Text(two),
),
):Container(
color: Colors.blue,
child: Text(two),
),
],
),
);
}
Or to maintain equal size with colors simply use Expanded in both widgets
Wrap the one that you want to fill the space by Expanded. If you want both red and blue to fill the row, wrap both of them with Expanded and give them their own ratio with the flex property
class TestScene extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Row(
children: <Widget>[
Container(
color: Colors.red,
child: const Text('1'),
),
Expanded(
child: Container(
color: Colors.blue,
child: const Text('1234567890123456789012345678901234567890'),
),
),
],
),
);
}
}