Buttons center their children when they are placed in a ListView.builder widget - flutter

Why do buttons in Flutter tend to align their children to the centre when they are placed in list views?
For example:
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index){
return MaterialButton(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello"),
],
));
}
),
);
}
}
This would result in ten hellos spaced evenly by the default height of the button, but they would be centered; even though I used the CrossAxisAlignment.start property in a column.
Here is the image:
But when I replace the MaterialButton with a Container they are aligned to the start to the column as wanted.
When I just remove the ListView.Builder I get 'hello' aligned to the start.
The same thing happens with the rest of the buttons.
Is there a way to make buttons in list views not have centered children inside them?
Edit: the example was fixed by #Harry but it didn't fix my exact code
here is my code: I try to created a list of widgets outside and use a function to add my list items into that list and return a list view through the ActivitiesList widget
import 'package:flutter/material.dart';
import 'package:list_them_out/models/activities.dart';
import 'package:provider/provider.dart';
class ActivitiesList extends StatefulWidget {
#override
_ActivitiesListState createState() => _ActivitiesListState();
}
double conBorderRadius = 30;
class _ActivitiesListState extends State<ActivitiesList> {
List<Widget> itemData = [];
void getData(context) {
double cardHeight = MediaQuery.of(context).size.height * 0.3;
double cardWidth = MediaQuery.of(context).size.width * 0.97;
final activities = Provider.of<List<Activity>>(context);
activities == null
// ignore: unnecessary_statements
? null
: setState(() {
itemData = [];
});
activities == null
// ignore: unnecessary_statements
? null
: setState(() {
activities.forEach((element) {
itemData.add(Padding(
padding: EdgeInsets.symmetric(horizontal: 10),
child: Container(
width: cardWidth,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(conBorderRadius),
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Colors.lightGreen[300],
Colors.lightBlue[300],
]
),
boxShadow: [
BoxShadow(
color: Colors.grey[600],
offset: Offset(4.0, 4.0),
blurRadius: 15,
spreadRadius: 1),
BoxShadow(
color: Colors.white,
offset: Offset(-4.0, -4.0),
blurRadius: 15,
spreadRadius: 1),
]),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(conBorderRadius),
child: MaterialButton(
splashColor: HSLColor.fromColor(Colors.green).toColor(),
onPressed: () {},
child: Align(
alignment: Alignment.centerLeft,
child: Container(
child: Padding(
padding: EdgeInsets.only(top: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: cardWidth * 0.61,
child: Text(
element.name,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: Colors.grey[600],
fontSize: 25,
fontWeight: FontWeight.w500,
letterSpacing: 1,
),
),
),
Padding(
padding: EdgeInsets.only(top: cardHeight * 0.09, left: cardWidth * 0.03),
child: Container(
width: cardWidth * 0.48,
child: RichText(
maxLines: 2,
overflow: TextOverflow.ellipsis,
text: TextSpan(children: [
TextSpan(
text: "Start: ",
style: TextStyle(
color: Colors.grey[800],
fontSize: 20,
fontWeight: FontWeight.w400,
letterSpacing: 1),
),
TextSpan(
text: element.time,
style: TextStyle(
color: Colors.black87,
fontWeight: FontWeight.w300,
fontSize: 20,
))
]),
),
),
),
SizedBox(height: cardHeight * 0.06,),
Row(
children: [
IconButton(icon: Icon(Icons.comment),
onPressed: () => null,
color: Colors.grey[600],
),
Padding(
padding: EdgeInsets.only(bottom: 5),
child: Text("Comments", style: TextStyle(color: Colors.grey[600], fontSize: 20, fontWeight: FontWeight.w300, letterSpacing: 1),),
)
],
)
],
),
),),
),
),
),
Positioned(
right: 0,
bottom: 0,
top: 0,
child: ClipPath(
clipper: MyClip(radius: conBorderRadius),
child: Container(
height: cardHeight,
width: cardWidth * 0.45,
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: <Color>[
Colors.grey[300],
Colors.lightBlue[100].withOpacity(0.5)
])),
),
),
),
Positioned(
right: cardWidth * 0.05,
bottom: 20,
child: Container(
child: Text("Hello"),
),
)
],
)),
));
});
});
}
#override
Widget build(BuildContext context) {
double listHeight = MediaQuery.of(context).size.height * 0.86;
double listWidth = MediaQuery.of(context).size.width * 0.97;
getData(context);
return ClipRRect(
borderRadius: BorderRadius.only(
topRight: Radius.circular(50), topLeft: Radius.circular(50)),
child: Container(
height: listHeight,
width: listWidth,
child: ListView.builder(
itemCount: itemData.length,
itemBuilder: (context, index) {
return Padding(
padding: EdgeInsets.only(bottom: 30),
child: itemData[index],
);
}),
));
}
}
``

Try using the Align widget. Just wrap the column with an align widget and have the alignment parameter be alignment.centerLeft.
import 'package:flutter/material.dart';
class Test extends StatefulWidget {
#override
_TestState createState() => _TestState();
}
class _TestState extends State<Test> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: 10,
itemBuilder: (context, index){
return MaterialButton(
child: Align(
child:Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Hello"),
],
),
alignment: Alignment.centerLeft,
)
);
}
),
);
}
}

Related

i cant update itemcount

hey why is my itemcount not working i have 6 rows in my database but when i run the code it show me only one row and the other rows not showing it
this is my code:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class my_ads extends StatefulWidget {
const my_ads({Key? key}) : super(key: key);
#override
State<my_ads> createState() => _my_adsState();
}
List list = [];
int select_item = 0;
class _my_adsState extends State<my_ads> {
#override
Future ReadData() async {
var url = "https://***.***.***.**/getData.php";
var res = await http.get(Uri.parse(url));
if (res.statusCode == 200) {
var red = jsonDecode(res.body);
setState(() {
list.addAll(red);
});
print(list);
}
}
#override
void initState() {
super.initState();
GetData();
}
GetData() async {
await ReadData();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: list.length,
itemBuilder: ((cts, i) {
return Container(
height: 800,
child: ListView(
children: [
Container(
margin: EdgeInsets.only(left: 70, right: 60),
height: 54.0,
width: 224.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xffF4AC47), width: 5),
color: Color(0xff42A9D2),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: new Center(
child: new Text(
"MyAds",
style: TextStyle(
fontSize: 25,
color: Color(0xff072A52),
fontFamily: 'Cairo'),
textAlign: TextAlign.center,
),
//end logo
)),
),
///start Section
Container(
margin: EdgeInsets.only(left: 10, right: 10, top: 10),
height: 180.0,
width: 430.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Color(0xff42A9D2), width: 5),
borderRadius: BorderRadius.circular(8)),
child: new Container(
child: Row(
children: [
Expanded(
child: Image(
image: AssetImage("assets/book.jpg"),
)),
Container(
margin: EdgeInsets.only(
left: 110, top: 30, right: 13),
child: Column(
children: [
Text(
"test",
style: TextStyle(
fontSize: 20, color: Colors.black87),
),
SizedBox(
height: 20,
),
Row(
children: [
Text("test2"),
Icon(Icons.perm_identity_rounded)
],
),
SizedBox(
height: 5,
),
Row(
children: [
Text("}"),
Column(
children: [Icon(Icons.store)],
)
],
),
],
),
)
],
)
//end logo
)),
),
],
),
);
})));
}
}
i tried to change ListView to ListTile but the design will be detroyed becuse i need to make the same design to other pages but my problem is with itemcount its not making any changes ! please if you have any ideas with my problem give me ansewrs

How do i correctly position these items horizontally in flutter to avoid overflow?

I have a list of items that are responsible for a tab bar design, i want to make all the sizedboxes display at a go and not overflow horizontally.
I will give my code for better clarification.
This is what i could come up with after over an hour of tussle:
And this is what i am expecting
I will give my code snippets of the view below.
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
class JobsHeaderWidget extends StatefulWidget {
const JobsHeaderWidget({
Key key,
}) : super(key: key);
#override
State<JobsHeaderWidget> createState() => _JobsHeaderWidgetState();
}
class _JobsHeaderWidgetState extends State<JobsHeaderWidget> {
List<String> items = [
"All",
"Critical",
"Open",
"Closed",
"Overdue",
];
int current = 0;
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(left: 10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Jobs',
style: GoogleFonts.poppins(
color: Colors.black, fontSize: 18, fontWeight: FontWeight.w600),
),
Row(
children: [
Text(
'View Insights ',
style: GoogleFonts.poppins(
color: Color(0xff3498DB),
fontSize: 12,
fontWeight: FontWeight.w500),
),
Icon(
Icons.arrow_forward_ios,
color: Color(0xff3498DB),
size: 12,
),
],
),
filterJobs()
],
),
);
}
Widget filterJobs() {
return Container(
width: double.infinity,
child: Column(
children: [
/// CUSTOM TABBAR
SizedBox(
width: double.infinity,
height: 60,
child: ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: items.length,
scrollDirection: Axis.horizontal,
itemBuilder: (ctx, index) {
return Column(
children: [
GestureDetector(
onTap: () {
setState(() {
current = index;
});
},
child: AnimatedContainer(
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(5),
decoration: BoxDecoration(
color: current == index
? Color(0xff34495E)
: Color(0xffF5F5F5),
borderRadius: BorderRadius.circular(11),
),
child: Center(
child: Padding(
padding: const EdgeInsets.only(
left: 10.0, right: 10.0, top: 5, bottom: 5),
child: Text(
items[index],
style: GoogleFonts.poppins(
fontSize: 10,
fontWeight: FontWeight.w500,
color: current == index
? Colors.white
: Colors.grey),
),
),
),
),
),
],
);
}),
),
// Builder(
// builder: (context) {
// switch (current) {
// case 0:
// return AllNotificationItemsView();
// case 1:
// return JobsNotificationItemsView();
// case 2:
// return MessagesNotificationItemsView();
// case 3:
// return CustomersNotificationItemsView();
// default:
// return SizedBox.shrink();
// }
// },
// )
],
),
);
}
}
The reason for overflow is List View Builder. Remove it and add a Row widget instead. Iterate the list item in it and you will get your desired output.
Full Code : -
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image',
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const JobsHeaderWidget(),
);
}
}
class JobsHeaderWidget extends StatefulWidget {
const JobsHeaderWidget({super.key});
#override
State<JobsHeaderWidget> createState() => _JobsHeaderWidgetState();
}
class _JobsHeaderWidgetState extends State<JobsHeaderWidget> {
List<String> items = [
"All",
"Critical",
"Open",
"Closed",
"Overdue",
];
int current = 0;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
body: Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10, top: 5),
child: Align(
alignment: Alignment.topCenter,
child: Container(
constraints: const BoxConstraints(maxWidth: 610, maxHeight: 100),
alignment: Alignment.center,
width: double.infinity,
child: IntrinsicWidth(
child: FittedBox(
fit: BoxFit.fitWidth,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
for (int i = 0; i < items.length; i++) ...[
GestureDetector(
onTap: () {
setState(() {
current = i;
});
},
child: AnimatedContainer(
height: 40,
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 5, bottom: 5),
decoration: BoxDecoration(
color: current == i
? const Color(0xff34495E)
: const Color(0xffF5F5F5),
borderRadius: BorderRadius.circular(11),
),
child: Center(
child: Text(
items[i],
style: GoogleFonts.poppins(
fontSize: 19,
fontWeight: FontWeight.w500,
color: current == i
? Colors.white
: Colors.grey),
),
),
),
),
]
],
),
),
),
),
),
),
);
}
}
Output : -
Hey there for making the appbar not overflowing, you must use expanded widget. try to wrap your gestureDetector or whatever widget that you create for making the design for each listview child like this
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
current = i;
});
},
child: AnimatedContainer(
height: 40,
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.only(
left: 15.0, right: 15.0, top: 5, bottom: 5),
decoration: BoxDecoration(
color: current == i
? const Color(0xff34495E)
: const Color(0xffF5F5F5),
borderRadius: BorderRadius.circular(11),
),
child: Center(
child: Text(
items[i],
style: GoogleFonts.poppins(
fontSize: 12,
fontWeight: FontWeight.w500,
color: current == i ? Colors.white : Colors.grey),
),
),
),
),
),
as you can see when you doing this the design will look like this
the text inside of the design would gone because of overflowing issue, you can change the text widget into this widget https://pub.dev/packages/auto_size_text
this is the snipet
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.only(left: 5.0, right: 5, top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
for (int i = 0; i < items.length; i++) ...[
Expanded(
child: GestureDetector(
onTap: () {
setState(() {
current = i;
});
},
child: AnimatedContainer(
height: 40,
duration: const Duration(milliseconds: 300),
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.only(
left: 5.0, right: 5.0, top: 5, bottom: 5),
decoration: BoxDecoration(
color: current == i
? const Color(0xff34495E)
: const Color(0xffF5F5F5),
borderRadius: BorderRadius.circular(11),
),
child: Center(
child: AutoSizeText(
items[i],
maxLines: 1,
style: GoogleFonts.poppins(
fontSize: 12,
fontWeight: FontWeight.w500,
color:
current == i ? Colors.white : Colors.grey),
),
),
),
),
),
]
],
),
),
));
but surely the text would be some of big and some of small look like this, and this is the result

How to fetch data (Text) from Website in Flutter / dart?

So, I'm pretty new on Flutter (just about a week) and dart but I hope this Question is not toooooo stupid:
I'm trying to create an App for an existing Website (a forum). I dont want to use the flutter WebView, because I want to create an comepletly new Interface (The Website is not optimized for mobile View, that's why I'm builing this App).
The (german) Forum:
https://www.porsche-914.com/forum
I want to fetch the single forum topics as well as the posts itself including username, title and date and then map the text to a custom widget to display it. The Widget Part is no problem, it's already done but I cant figure out how to fetch that data from the website and how to store it.
I don't know, hope you can help me...
Thanks a lot for the taken time.
How the mapping should work:
fetched[index].title, fetched[index].text
Center(
child: NeumorphismPost(
title: fetched[index].title,
titleColor: Theme.of(context).cardColor,
textColor: Theme.of(context).cardColor,
text: fetched[index].text,
width: 370,
onTap: () {
_popupPage(context,
title: fetched[index].title,
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Text(
fetched[index].text,
style: TextStyle(
color: Theme.of(context).cardColor,
fontSize: 18),
),
),
);
},
),
),
This is my custom Widget:
import 'package:flutter/material.dart';
class NeumorphismPost extends StatefulWidget {
final double width;
final double height;
final double borderRadius;
final String title;
final String text;
final Color titleColor;
final Color textColor;
final double titleSize;
final double textSize;
final Function onTap;
NeumorphismPost({
this.width = 185,
this.height = 185,
this.title = "Title",
this.text = "",
this.borderRadius = 20,
this.titleColor = const Color(0xFF424242),
this.textColor = const Color(0xFF424242),
this.titleSize = 22,
this.textSize = 18,
required this.onTap,
});
#override
State<NeumorphismPost> createState() => _NeumorphismPostState();
}
class _NeumorphismPostState extends State<NeumorphismPost> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
direction: Axis.vertical,
children: [
SingleChildScrollView(
child: SizedBox(
height: widget.height,
width: widget.width,
child: GestureDetector(
onTap: () {},
child: Scaffold(
backgroundColor: Colors.transparent,
body: SizedBox(
height: widget.height,
width: widget.width,
child: Center(
child: Container(
height: widget.height,
width: widget.width,
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
borderRadius:
BorderRadius.circular(widget.borderRadius),
boxShadow: [
BoxShadow(
color: Theme.of(context).hintColor,
offset: const Offset(5, 5),
blurRadius: 15,
spreadRadius: 1,
),
BoxShadow(
color: Theme.of(context).backgroundColor,
offset: Offset(-5, -5),
blurRadius: 15,
spreadRadius: 1,
)
],
),
child: Wrap(
direction: Axis.horizontal,
children: [
SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: <Widget>[
Wrap(
direction: Axis.horizontal,
children: [
SizedBox(
height: widget.height / 3,
child: Wrap(
children: [
Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets
.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.title,
textAlign:
TextAlign.center,
overflow:
TextOverflow.fade,
style: TextStyle(
fontSize:
widget.titleSize,
fontWeight:
FontWeight.bold,
color:
widget.titleColor,
),
),
),
],
),
],
),
),
],
),
Wrap(
direction: Axis.horizontal,
children: [
GestureDetector(
onTap: () {
widget.onTap();
},
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 5),
child: SizedBox(
height: widget.height / 1.38,
child: Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.text,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: widget.textSize,
fontWeight:
FontWeight.normal,
color: widget.textColor,
),
),
),
),
),
),
],
),
],
),
),
),
],
),
),
),
),
),
),
),
),
],
),
);
}
}
From my point of view, you want to create a scraper. I checked the target website (https://www.porsche-914.com/forum), it can be scraped without any special technique (they don't have many Ajax calls (you may test by using Postman)). So it is a possible task. My suggestion flow is:
Load the raw HTML using any technique (http, dio, inappwebview ...)
Parse it using BeautifulSoup (https://pub.dev/packages/beautiful_soup_dart) (or any parser; it is just my favorite parser.)
Map it to your existing model.
Here is some example code. Hope it helps:
import 'package:http/http.dart' as http;
import 'package:beautiful_soup_dart/beautiful_soup.dart';
class TestParse {
excuteSample() async {
var url = Uri.parse('https://www.porsche-914.com/forum');
var response = await http.get(url);
BeautifulSoup bs = BeautifulSoup(response.body);
final allHeaderName = bs.findAll('td', attrs: {'class': 'oben'});
allHeaderName.forEach((element) {
print('the header: ${element.text}');
});
}
}
Here is the result:
The final result you need is a long story and long code. Hope this will give you a starting point.
UPDATE: I added the full demo code, using your requested code:
import 'package:beautiful_soup_dart/beautiful_soup.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(const MaterialApp(home: MyApp()));
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final testparse = TestParse();
List<String> yourModelPleaseReplaceThis = [];
#override
void initState() {
super.initState();
excuteRequestAndParse();
}
excuteRequestAndParse() async {
final result =
await testparse.excuteSample(); //[1] i guess you missing this await
setState(() {
yourModelPleaseReplaceThis = result;
});
}
#override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (context, index) {
return Center(
child: NeumorphismPost(
title: yourModelPleaseReplaceThis[index],
titleColor: Theme.of(context).cardColor,
textColor: Theme.of(context).cardColor,
text: yourModelPleaseReplaceThis[index],
width: 370,
onTap: () {
//THIS CODE BELOW IS YOUR CODE....
},
),
);
},
itemCount: yourModelPleaseReplaceThis.length,
);
}
}
// BELOW IS TESTING CODE....
class TestParse {
Future<List<String>> excuteSample() async {
var url = Uri.parse('https://www.porsche-914.com/forum');
var response = await http.get(url);
BeautifulSoup bs = BeautifulSoup(response.body);
final allHeaderName = bs.findAll('td', attrs: {'class': 'oben'});
allHeaderName.forEach((element) {
print('the header: ${element.text}');
});
return Future.value(allHeaderName.map((e) => e.text).toList());
}
}
class NeumorphismPost extends StatefulWidget {
final double width;
final double height;
final double borderRadius;
final String title;
final String text;
final Color titleColor;
final Color textColor;
final double titleSize;
final double textSize;
final Function onTap;
NeumorphismPost({
this.width = 185,
this.height = 185,
this.title = "Title",
this.text = "",
this.borderRadius = 20,
this.titleColor = const Color(0xFF424242),
this.textColor = const Color(0xFF424242),
this.titleSize = 22,
this.textSize = 18,
required this.onTap,
});
#override
State<NeumorphismPost> createState() => _NeumorphismPostState();
}
class _NeumorphismPostState extends State<NeumorphismPost> {
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
direction: Axis.vertical,
children: [
SingleChildScrollView(
child: SizedBox(
height: widget.height,
width: widget.width,
child: GestureDetector(
onTap: () {},
child: Scaffold(
backgroundColor: Colors.transparent,
body: SizedBox(
height: widget.height,
width: widget.width,
child: Center(
child: Container(
height: widget.height,
width: widget.width,
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
borderRadius:
BorderRadius.circular(widget.borderRadius),
boxShadow: [
BoxShadow(
color: Theme.of(context).hintColor,
offset: const Offset(5, 5),
blurRadius: 15,
spreadRadius: 1,
),
BoxShadow(
color: Theme.of(context).backgroundColor,
offset: Offset(-5, -5),
blurRadius: 15,
spreadRadius: 1,
)
],
),
child: Wrap(
direction: Axis.horizontal,
children: [
SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.spaceEvenly,
children: <Widget>[
Wrap(
direction: Axis.horizontal,
children: [
SizedBox(
height: widget.height / 3,
child: Wrap(
children: [
Column(
mainAxisAlignment:
MainAxisAlignment.start,
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets
.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.title,
textAlign:
TextAlign.center,
overflow:
TextOverflow.fade,
style: TextStyle(
fontSize:
widget.titleSize,
fontWeight:
FontWeight.bold,
color:
widget.titleColor,
),
),
),
],
),
],
),
),
],
),
Wrap(
direction: Axis.horizontal,
children: [
GestureDetector(
onTap: () {
widget.onTap();
},
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 5),
child: SizedBox(
height: widget.height / 1.38,
child: Padding(
padding:
const EdgeInsets.symmetric(
horizontal: 15,
vertical: 15),
child: Text(
widget.text,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: widget.textSize,
fontWeight:
FontWeight.normal,
color: widget.textColor,
),
),
),
),
),
),
],
),
],
),
),
),
],
),
),
),
),
),
),
),
),
],
),
);
}
}
This is the result:
Please note:
This list I created is for sample, so it is just a list of Strings. You should create a complete Model.

Flutter : Use function from another file in widget

I'm using flutter and i'm completely a newbie with this framework. I'm trying to use the visibility widget to show and hide a Row.
I'm trying to use this widget when I declare the variable bool _isVisible = false in a stateful or stateless widget, but I have a problem when I want to show and hide the row() through a widget from another dart file. I don't know how to do it. To solve this problem i'm trying to create a dart file for create a function and variable bool _isVisible = false; so that all widgets can access but I am unable to use the bool variable and the function of this dart file in my widgets.
in this picture: ontap in the green circle i want the pink color all the row() with the rating and the button to be hidden.
A screenshot of the issue from my application
P.S: sorry for my english
This is the widget( AnimeMovieDialog ) with the rating section that i want to be hidden (or show) when user tap on the CardAnimeMovie widget.
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Tutorial by Woolha.com',
home: AnimeMovieDialog(),
debugShowCheckedModeBanner: false,
);
}
}
class AnimeMovieDialog extends StatefulWidget {
#override
_AnimeMovieDialogState createState() => _AnimeMovieDialogState();
}
class _AnimeMovieDialogState extends State<AnimeMovieDialog> {
double _rating = 1;
double count = 1;
bool _isVisible = true;
void _change() {
setState(() {
_isVisible = !_isVisible;
print("tap succes");
});
}
void _close() {
setState(() {
_isVisible = false;
});
}
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return SafeArea(
child: Visibility(
visible: _isVisible,
child: Stack(children: [
Container(
width: width,
height: height,
decoration: BoxDecoration(color: Color(0xffffff).withOpacity(0.6)),
),
Center(
child: SingleChildScrollView(
child: Container(
width: width / 1.05,
height: height / 1.2,
decoration: BoxDecoration(color: Color(0xff212529)),
child: Column(
children: [
Row(
children: [
Container(
width: width / 1.05,
height: 60,
decoration: BoxDecoration(color: Color(0xff212529)),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding:
const EdgeInsets.fromLTRB(4.0, 5, 35, 0),
child: GestureDetector(
onTap: () {
_close();
},
child: Container(
width: 65,
height: 45,
color: Colors.blue,
child: Icon(Icons.clear,
color: Colors.white)),
),
),
Container(
width: width / 2,
height: height / 2,
child: TextField(
cursorColor: Colors.orange,
style: TextStyle(
color: Colors.white,
),
maxLines: 1,
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white)),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.orange)),
border: UnderlineInputBorder(
borderSide: BorderSide(
color: Colors.white)),
hintText: 'Rechercher',
hintStyle:
TextStyle(color: Colors.white),
)),
),
Padding(
padding:
const EdgeInsets.fromLTRB(15, 0, 8, 0),
child: Container(
child: Icon(Icons.search,
color: Colors.white)),
)
],
),
)
],
),
Row(
children: [
Container(
width: width / 1.05,
height: height / 1.5,
child: ListView(
children: [
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie(),
CardAnimeMovie()
],
),
)
],
),
Row(children: [
Column(
children: [
Container(
width: width / 2,
height: height / 11.25,
color: null,
child: Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
25, 0, 0, 0),
child: GFRating(
onChanged: (value) {
setState(() {
_rating = value;
});
},
value: _rating,
size: 25,
color: Colors.orange,
borderColor: Colors.orange,
),
)
],
)),
],
),
Padding(
padding: const EdgeInsets.fromLTRB(35, 0, 8, 0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
width: width / 3,
height: height / 18,
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25.0),
topRight: Radius.circular(25.0),
bottomLeft: Radius.circular(25.0),
bottomRight: Radius.circular(25.0))),
child: TextButton(
style: TextButton.styleFrom(
primary: Colors.blue,
onSurface: Colors.red,
),
onPressed: null,
child: Text('Noter',
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 17)),
),
),
],
),
)
])
],
)),
),
),
]),
),
);
}
}
This is the movie resume (green in the picture)
class CardAnimeMovie extends StatefulWidget {
#override
_CardAnimeMovieState createState() => _CardAnimeMovieState();
}
class _CardAnimeMovieState extends State<CardAnimeMovie> {
// bool _visible = false;
// void ratechange() {
// setState(() {
// _visible = !_visible;
// });
// }
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Padding(
padding: const EdgeInsets.all(2.0),
child: GestureDetector(
onTap: () {
ratechange();
},
child: Container(
width: width / 5,
height: height / 3.2,
decoration: BoxDecoration(color: Color(0xff272824)),
child: Row(
children: [
Column(children: [
Container(
width: width / 2.1,
height: height / 3.2,
child: Image.network(
'https://image.noelshack.com/fichiers/2014/31/1406628082-btlbdfqiyaasamj.jpg',
fit: BoxFit.cover,
),
)
]),
Column(children: [
Container(
width: width / 2.15,
height: height / 3.2,
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(color: Colors.white, width: 0.5),
),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(15, 5, 0, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
children: [
Text(
'Titre : oeuvre',
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 18,
),
)
],
),
SizedBox(
height: 0.5,
),
Row(
children: [
Text(
'Auteur : XXXX',
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 18,
),
)
],
),
SizedBox(height: 7),
Row(
children: [
Container(
width: width / 2.5,
height: height / 5,
child: Text(
"Résume : Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,",
style: TextStyle(
color: Colors.white,
fontFamily: 'DBIcons',
fontSize: 18,
),
),
)
],
)
],
),
),
)
])
],
)),
),
);
}
}
You can give function to another dart file and with this you can invoke function in another dart file.
For example:
class AnotherWidget extends StatelessWidget{
final Function myFunction;
AnotherWidget ({this.myFunction});
#override
Widget build(BuildContext context) {
return FlatButton(onPressed: myFunction,....);
}

trying to add to bag and to update prices and cups

I am trying to do this test TODOs: but i have been have issuses pls help: i am trying to Uncomment the _confirmOrderModalBottomSheet() method to show summary of order, Uncomment the setState() function to clear the price and cups, and Change the 'price' to 0 when this button is clicked Increment the _cupsCounter when 'Add to Bag' button is clicked, and to Call setState((){}) method to update both price and cups counter when 'Add to Bag' button is clicked
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Coffee Test',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Colors.white,
),
home: MyHomePage(title: 'Coffee Test'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedPosition = -1;
String _coffeePrice ="0";
int _cupsCounter =0;
int price = 0;
String _currency ="₦";
static const String coffeeCup ="images/coffee_cup_size.png";
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0,
title: FlatButton(
onPressed: (){
//TODO: Uncomment the _confirmOrderModalBottomSheet() method to show summary of order
//_confirmOrderModalBottomSheet(totalPrice: "$_currency$price", numOfCups: "x $_cupsCounter");
},
child: Text("Buy Now",style: TextStyle(color: Colors.black87),),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18.0), side: BorderSide(color: Colors.blue))
),
actions: [
InkWell(
onTap: () {
//TODO: Uncomment the setState() function to clear the price and cups
//TODO: Change the 'price' to 0 when this button is clicked
setState(() {
this.price = -1;
this._cupsCounter = 0;
});
Icon(Icons.clear);
}),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Container(
height: double.maxFinite,
alignment: Alignment.center,
child: Text("$_cupsCounter Cups = $_currency$price.00", style: TextStyle(fontSize: 18),),
),
)
],
),
body: Padding(padding: EdgeInsets.all(20), child: _mainBody(),) // This trailing comma makes auto-formatting nicer for build methods.
);
}
Widget _mainBody(){
return SingleChildScrollView(
child: Container(
height: double.maxFinite,
width: double.maxFinite,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
flex: 0,
child: Stack(
children: [
Container(
width: double.maxFinite,
height: 250,
margin: EdgeInsets.only(left: 50, right: 50, bottom: 50, top: 60),
decoration: BoxDecoration(borderRadius:
BorderRadius.all(Radius.circular(180)),
color: Color.fromRGBO(239, 235, 233, 100)),
),
Container(
alignment: Alignment.center,
width: double.maxFinite,
height: 350,
child: Image.asset("images/cup_of_coffee.png", height: 300,),
)
],
)),
Padding(padding: EdgeInsets.all(10),),
Expanded(flex: 0,child: Text("Caffè Americano",
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 30),)),
Padding(padding: EdgeInsets.all(6),),
Expanded(flex: 0, child: Text("Select the cup size you want and we will deliver it to you in less than 48hours",
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 14, color: Colors.black45,),
textAlign: TextAlign.start,),
),
Container(
margin: EdgeInsets.only(top: 30, left: 20),
height: 55,
width: double.maxFinite,
alignment: Alignment.center,
child:Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
RichText(text: TextSpan(
text: _currency,
style: TextStyle(fontWeight: FontWeight.bold,
fontSize: 25, color: Colors.black87),
children: [
TextSpan(text: _coffeePrice, style: TextStyle(fontSize: 50, fontWeight: FontWeight.bold))
]
),),
Padding(
padding: EdgeInsets.only(right: 15),
),
ListView.builder(itemBuilder: (context, index){
return InkWell(
child: _coffeeSizeButton(_selectedPosition == index,
index ==0? "S" : index ==1? "M": "L"),
onTap: (){
setState(() {
this._coffeePrice= index ==0? "300" : index ==1? "600": "900";
_selectedPosition = index;
});
},
);
}, scrollDirection: Axis.horizontal,
itemCount: 3, shrinkWrap: true,),
],),
),
Container(
margin: EdgeInsets.only(top: 30),
padding: EdgeInsets.all(10),
width: double.maxFinite,
height: 70,
child: FlatButton(onPressed: (){
//TODO: Currently _cupsCounter only show 1 when this button is clicked.
// TODO: Increment the _cupsCounter when 'Add to Bag' button is clicked'
//TODO: Call setState((){}) method to update both price and cups counter when 'Add to Bag' button is clicked
this._cupsCounter = 1;
this.price += int.parse(_coffeePrice);
}, child: Center(child: Text("Add to Bag",
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),)
,),
color: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)
),
),
)
],
),
),
);
}
Widget _coffeeSizeButton(bool isSelected, String coffeeSize){
return Stack(
children: [
Container(alignment: Alignment.center, width: 55,
child: Text(coffeeSize, style: TextStyle(fontSize: 10, fontWeight: FontWeight.bold,
color: isSelected? Colors.blue: Colors.black45),),),
new Container(
margin: EdgeInsets.only(right: 10),
child: Image.asset(coffeeCup, width:50, color: isSelected ? Colors.blue: Colors.black45,),
decoration: BoxDecoration(border: Border(top: BorderSide(color: isSelected? Colors.blue: Colors.black45,
width: isSelected? 2: 1), left: BorderSide(color: isSelected? Colors.blue: Colors.black45,
width: isSelected? 2: 1), bottom: BorderSide(color: isSelected? Colors.blue: Colors.black45,
width: isSelected? 2: 1), right: BorderSide(color: isSelected ?Colors.blue: Colors.black45 ,
width: isSelected? 2: 1)), borderRadius: BorderRadius.all(Radius.circular(5))),
)
],
);
}
void _confirmOrderModalBottomSheet({String totalPrice, String numOfCups}){
showModalBottomSheet(
context: context,
builder: (builder){
return new Container(
height: 150.0,
color: Colors.transparent, //could change this to Color(0xFF737373),
//so you don't have to change MaterialApp canvasColor
child: new Container(
padding: EdgeInsets.all(10),
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.only(
topLeft: const Radius.circular(10.0),
topRight: const Radius.circular(10.0))),
child: Column(
children: [
Container(
child: Text("Confirm Order",
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18),),
alignment: Alignment.center, height: 30, decoration: BoxDecoration(
), ),
_getEstimate(totalPrice, numOfCups)
],
)),
);
}
);
}
Widget _getEstimate(String totalPrice, String numOfCups){
return Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Image.asset("images/cup_of_coffee.png", height: 70, width: 50,),
Padding(padding: EdgeInsets.all(10)),
Text(numOfCups, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),),
Padding(padding: EdgeInsets.all(10)),
Text(totalPrice, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),)
],
);
}
}
You're setting 1 to your _cupsCounter instead of adding one to it.
When updating your values, putting the operation i.e _cupsCounter += 1; in setState will update the state of your widget which makes values change in your widgets.
setState((){
_cupsCounter += 1; // make it +=1 instead of =1.
price += int.parse(_coffeePrice);
});
Also you can use setState by putting it after your operation which will update the state of your widget after the operation is done.
_cupsCounter += 1; // make it +=1 instead of =1.
price += int.parse(_coffeePrice);
setState((){});
Full code should look like this.
Container(
margin: EdgeInsets.only(top: 30),
padding: EdgeInsets.all(10),
width: double.maxFinite,
height: 70,
child: FlatButton(onPressed: (){
// Currently _cupsCounter only show 1 when this button is clicked.
// Increment the _cupsCounter when 'Add to Bag' button is clicked'
// Call setState((){}) method to update both price and cups counter when 'Add to Bag' button is clicked
setState((){
_cupsCounter += 1; // make it +=1 instead of =1.
price += int.parse(_coffeePrice);
}); // call setState like this
}, child: Center(child: Text("Add to Bag",
style: TextStyle(fontWeight: FontWeight.bold, color: Colors.white),)
,),
color: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)
),
),
)