Flutter: How to center text with dynamic length? - flutter

Hello I have created a custom appbar where the title of appbar will come from API which can any of the length so How can I center it.
code of custom appbar,
class CustomAppBar extends PreferredSize {
final String title;
final double height;
CustomAppBar({
#required this.title,
this.height = kToolbarHeight,
});
#override
Size get preferredSize => Size.fromHeight(height);
#override
Widget build(BuildContext context) {
final headline6 = Theme.of(context).textTheme.headline6;
return Container(
width: double.infinity,
height: 99,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppColors.veryDarkBlue,
AppColors.blueWhale,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
stops: [
0.3,0.8
],
),
),
padding: EdgeInsets.only(
top: 27,
left: 19,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
InkWell(
child: Icon(
Icons.arrow_back_ios_rounded,
color: Colors.white,
size: 20.sdpHeight,
),
onTap: () => Navigator.pop(context),
),
Expanded(
child: Center(
child: Text(
title, //<--- I want to align this
style: headline6.copyWith(
color: Colors.white,
fontSize: 16,
),
),
),
),
],
)
);
}
}
how it looks,
in second screen shot it has little more gap on left then it should be so How I can fix it?

add something to take up the space from right just as your icon
children: [
InkWell(
child: Icon(
Icons.arrow_back_ios_rounded,
color: Colors.white,
size: 20.sdpHeight,
),
onTap: () => Navigator.pop(context),
),
Expanded(
child: Center(
child: Text(
title, //<--- I want to align this
style: headline6.copyWith(
color: Colors.white,
fontSize: 16,
),
),
),
),
SizedBox(width:40.0),
],

Related

Error: The method 'raisedButton' isn't defined for the class '_PomodoroState'

I'm currently doing a flutter tutorial in android studio and I have this issue,
I tried to create a class, tried to become it a variable, but no luck, also I named a file “raised_button.dart” and use the stful widget to see if it works but it doesn't work
This is my code:
import 'package:flutter/material.dart';
import 'package:percent_indicator/circular_percent_indicator.dart';
import 'dart:async';
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: Pomodoro(),
));
class Pomodoro extends StatefulWidget {
const Pomodoro({Key? key}) : super(key: key);
#override
State<Pomodoro> createState() => _PomodoroState();
}
class _PomodoroState extends State<Pomodoro> {
double percent = 0;
static int TimeInMinut = 240;
int TimeInSec = TimeInMinut * 60;
late Timer timer;
_StartTimer(){
TimeInMinut = 240;
int Time = TimeInMinut *60;
double SecPercent = (Time/100);
timer = Timer.periodic(Duration(seconds:1), (timer) {
setState((){
if(Time > 0){
Time--;
if(Time % 60 ==0){
TimeInMinut --;
}if(Time % SecPercent == 0){
if(percent <1){
percent += 0.01;
}else{
percent = 1;
}
}
}else{
percent = 0;
TimeInMinut = 240;
timer.cancel();
}
});
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.orangeAccent, Colors.redAccent],
begin: FractionalOffset(0.5,1)
)
),
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 25.0),
child: Text(
"Pomodoro Clock",
style: TextStyle(
color: Colors.white,
fontSize: 40.0
),
),
),
Expanded(
child: CircularPercentIndicator(
percent: percent,
animation: true,
animateFromLastPercent: true,
radius: 150.0,
lineWidth: 20.0,
progressColor: Colors.white,
center: Text(
"$TimeInMinut",
style: TextStyle(
color: Colors.white,
fontSize: 80.0
),
),
),
),
SizedBox(height: 10.0,),
Expanded(
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(topRight: Radius.circular(30.0),topLeft: Radius.circular(30.0))
),
child: Padding(
padding: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
child: Column(
children: <Widget>[
Expanded(
child: Row(
children: <Widget>[
Expanded(
child: Column(
children: <Widget>[
Text(
"Focus Time",
style: TextStyle(
fontSize: 20.0,
),
),
SizedBox(height: 10.0,),
Text(
"240",
style: TextStyle(
fontSize: 50.0
),
),
]
),
),
Expanded(
child: Column(
children: <Widget>[
Text(
"Pause Time",
style: TextStyle(
fontSize: 20.0,
),
),
SizedBox(height: 10.0,),
Text(
"20",
style: TextStyle(
fontSize: 50.0
),
),
]
),
)
],
)
),
Padding(
padding: EdgeInsets.symmetric(vertical: 28.0),
child: raisedButton(
onPressed: _StartTimer,
color: Colors.redAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0),
),
child: Padding(
padding: EdgeInsets.all(20.0),
child: Text("Start focusing",
style: TextStyle(
color: Colors.white,
fontSize: 22.0
),
),
)
),
)
],
)
),
),
),
],
),
),
),
);
}
}
and this what is shows on terminal
lib/main.dart:151:38: Error: The method 'raisedButton' isn't defined for the class '_PomodoroState'.
- '_PomodoroState' is from 'package:pomodoris/main.dart' ('lib/main.dart').
Try correcting the name to the name of an existing method, or defining a method named 'raisedButton'.
child: raisedButton(
What should I do in that particular case?
Thank you in advance.
Capitalize the R. It's RaisedButton, not raisedButton.
However, RaisedButton is depricated. Instead of
raisedButton(
onPressed: _StartTimer,
color: Colors.redAccent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0),
),
child: Padding(
you want to use ElevatedButton. You also need to move your styling to the new style property, where you pass the color etc. into ElevatedButton.styleFrom() constructor.
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100.0),
),
),
onPressed: _StartTimer,
child: Padding(
However...
This look is also depricated according to the Material Guidelines that Flutter follows. See how to make buttons look nice and modern here: https://material.io/components/buttons
All of the names are also the names of the widgets in Flutter. If you get stuck there, feel free to ask again!
**RaisedButton is deprecated on the Latest flutter version. You can replace RaisedButton with ElevatedButton **
ElevatedButton(
child: Text('ElevatedButton'))
RaisedButton is no longer use by Flutter new versions
instead you can use an Elevated button
ElevatedButton(
onPressed: () {
print('login clicked');
},
child: Text(
'Login',
style: TextStyle(fontSize: 18.0, fontFamily: "Brand Bold"),
))

Tabs RenderFlex overflowed by 20 pixels on the bottom

I'm new in flutter and I'm trying to resolve this issue.
Updated My Code
After setting width and height of container, I'm getting this output now
Desirable output
TabsContainer.dart
class TabsContainer extends StatelessWidget {
final String image, tittle;
const TabsContainer({Key? key, required this.image, required this.tittle})
: super(key: key);
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.asset(
image,
fit: BoxFit.cover,
height: 46,
width: 46,
),
),
const SizedBox(
height: 10,
),
Text(
tittle,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.black),
)
],
);
}
}
categorypage.dart
List<Tab> tabs = [
const Tab(
height: 50,
child: TabsContainer(
image: 'assets/images/g.png', tittle: 'Social Media'),
),
const Tab(
height: 50,
child: TabsContainer(
image: 'assets/images/g.png', tittle: 'Interior Design')),
];
List<Widget> tabsContent = [
const SocialMedia(),
];
#override
Widget build(BuildContext context) {
return SafeArea(
child: DefaultTabController(
length: tabs.length,
child: Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.arrow_back_ios_rounded,
size: 30, color: AppColors.fIconsAndTextColor),
),
actions: [
IconButton(
onPressed: () {},
icon: const Icon(Icons.notifications,
size: 30, color: AppColors.fIconsAndTextColor),
)
],
elevation: 0.0,
backgroundColor: Colors.transparent),
backgroundColor: AppColors.fBackgroundColor,
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Column(
children: [
const Align(
alignment: Alignment.centerLeft,
child: Text(
'Category',
style: TextStyle(fontFamily: "ROCK"),
)),
const SizedBox(height: 10),
TabBar(
automaticIndicatorColorAdjustment: false,
indicatorColor: Colors.transparent,
isScrollable: true,
tabs: tabs),
const SizedBox(height: 10),
Expanded(
child: TabBarView(
physics: const NeverScrollableScrollPhysics(),
children: tabsContent),
),
],
),
),
),
),
);
}
}
try this :
class TabsContainer extends StatelessWidget {
final String image, tittle;
const TabsContainer({Key? key, required this.image, required this.tittle})
: super(key: key);
#override
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: Colors.white,
),
child: Image.asset(image),
),
Text(
tittle,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.black),
)
],
);
}
}
Tab: the default height is 72.0 pixels. Without an icon, the height is 46.0 pixels.
We need to provide our custom height in this case. And for decoration, use ClipRRect for on image.
class TabsContainer extends StatelessWidget {
final String image, tittle;
const TabsContainer({Key? key, required this.image, required this.tittle})
: super(key: key);
#override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.asset(
image,
fit: BoxFit.cover,
// as for Desirable output, both height and width will be same
height: 50,
width: 50,
),
),
const SizedBox(
height: 10,
), // you can use padding here
Text(
tittle,
textAlign: TextAlign.center,
style: const TextStyle(color: Colors.black),
)
],
);
}
}
And tabs will be like
List<Tab> tabs = [
const Tab(
height: 50 +
10 +
24, // image height + padding/space + 24 for font, better will be getting text size from theme
child: TabsContainer(
image: ...
),
I will also encourage you to check icon and text property for this case. The image size is ok up to 46, if you increase the size, you need to provide Tab(height:) to fix the overflow. You can use unselectedLabelStyle and labelStyle for text on TabBar.
In this case tabs will be
List<Tab> tabs = [
Tab(
text: 'Social Media',
icon: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.asset(
'assets/images/image01.png',
fit: BoxFit.cover,
// as for Desirable output, both height and width will be same
height: 46,
width: 46,
),
),
),
Tab(
text: 'Interior Design',
icon: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Image.asset(
'assets/images/image02.png',
fit: BoxFit.fitHeight,
// as for Desirable output, both height and width will be same
height: 46,
width: 46,
),
),
),
];

Flutter positioned widget cuts off content

I'm attempting to create a notification widget with a number overlay.
I've followed the code here to make the widget.
Using this code (not specifying a position), produces the following widget:
Widget iconWidget() {
return Stack(
children: <Widget>[
Center(
child: Container(
child: Icon(
icon,
color: color,
),
)),
Positioned(
child: CircleAvatar(
child: Text('$count',
style: TextStyle(fontSize: 12, color: Colors.white)),
backgroundColor: count == 0 ? Colors.grey : Colors.black,
),
)
],
);
}
However, as soon as I specify a position (right: 0), my widget gets gut off:
Widget iconWidget() {
return Stack(
children: <Widget>[
Center(
child: Container(
child: Icon(
icon,
color: color,
),
)),
Positioned(
right: 0,
child: CircleAvatar(
child: Text('$count',
style: TextStyle(fontSize: 12, color: Colors.white)),
backgroundColor: count == 0 ? Colors.grey : Colors.black,
),
)
],
);
}
My widget is being created as an icon within a tab controller:
Tab(
icon: IconWithCount(
icon: FlutterIcons.heartbeat_faw5s,
color: Colors.red,
count: 5)
.iconWidget(),
),
Full class creating the widget:
class IconWithCount {
final IconData icon;
final int count;
final Color color;
IconWithCount({
this.icon,
this.count,
this.color,
});
Widget iconWidget() {
return Stack(
children: <Widget>[
Center(
child: Container(
child: Icon(
icon,
color: color,
),
)),
Positioned(
right: 0,
child: CircleAvatar(
child: Text('$count',
style: TextStyle(fontSize: 12, color: Colors.white)),
backgroundColor: count == 0 ? Colors.grey : Colors.black,
),
)
],
);
}
}
overflow is Deprecated. Use this:
Stack(
clipBehavior: Clip.none, // <---
children: [],
)
Inside the stack , just add this
overflow: Overflow.visible,

adding ListView.builder

I'm trying to make the displayAccoutList() scrollable.
I've tried to use ListView but it didn't work. I'm thinking to use ListView.builder but I don't know how to create data for accountItems()
enter code here`import 'package:flutter/material.dart';
import 'app_drawer.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Accounts',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Account(),
);
}
}
class Account extends StatefulWidget {
#override
_AccountState createState() => _AccountState();
}
class _AccountState extends State<Account> {
Card topArea() =>
Card(
margin: EdgeInsets.all(10.0),
elevation: 1.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(50.0))),
child: Container(
decoration: BoxDecoration(
gradient: RadialGradient(
colors: [Color(0xFFFF5722), Color(0xFFFF5722)])),
padding: EdgeInsets.all(5.0),
// color: Color(0xFF015FFF),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.white,
),
onPressed: () {},
),
Text("Savings",
style: TextStyle(color: Colors.white, fontSize: 20.0)),
IconButton(
icon: Icon(
Icons.arrow_forward,
color: Colors.white,
),
onPressed: () {},
)
],
),
Center(
child: Padding(
padding: EdgeInsets.all(5.0),
child: Text(r"£ " "100,943.33",
style: TextStyle(color: Colors.white, fontSize: 24.0)),
),
),
SizedBox(height: 35.0),
],
)),
);
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: AppDrawer(),
appBar: AppBar(
iconTheme: IconThemeData(
color: Colors.grey, //change your color here
),
backgroundColor: Colors.white,
elevation: 0.0,
title: Text(
"Accounts",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.search,
color: Colors.grey,
),
onPressed: () {},
)
],
),
body: Container(
color: Colors.white,
child: Column(
children: <Widget>[
topArea(),
SizedBox(
height: 40.0,
child: Icon(Icons.refresh,
size: 35.0,
color: Color(0xFFFF5722),
),
),
displayAccoutList()
],
),
),
bottomNavigationBar: BottomAppBar(
elevation: 0.0,
child: Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
FlatButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 30.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
color: Color(0xFFFF5722),
// borderSide: BorderSide(color: Color(0xFF015FFF), width: 1.0),
onPressed: () {},
child: Text("ACTIVITY"),
),
OutlineButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 28.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
borderSide: BorderSide(color: Color(0xFFFF5722), width: 1.0),
onPressed: () {},
child: Text("STATEMENTS"),
),
OutlineButton(
padding:
EdgeInsets.symmetric(vertical: 12.0, horizontal: 28.0),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0.0)),
borderSide: BorderSide(color: Color(0xFFFF5722), width: 1.0),
onPressed: () {},
child: Text("DETAILS"),
)
],
),
),
)
);
}
}
Container accountItems(String item, String charge, String dateString,
String type,
{Color oddColour = Colors.white}) =>
Container(
decoration: BoxDecoration(color: oddColour),
padding:
EdgeInsets.only(top: 20.0, bottom: 20.0, left: 5.0, right: 5.0),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(item, style: TextStyle(fontSize: 16.0)),
Text(charge, style: TextStyle(fontSize: 16.0))
],
),
SizedBox(
height: 10.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(dateString,
style: TextStyle(color: Colors.grey, fontSize: 14.0)),
Text(type, style: TextStyle(color: Colors.grey, fontSize: 14.0))
],
),
],
),
);
displayAccoutList() {
return Container(
margin: EdgeInsets.all(15.0),
child: Column(
children: <Widget>[
accountItems("M KING", r"+ £ 4,946.00", "15-07-19", "Credit",
oddColour: const Color(0xFFF7F7F9)),
accountItems(
"Gordon Street Tenants", r"+ £ 5,428.00", "15-07-19", "Credit"),
accountItems("Amazon EU", r"+ £ 746.00", "15-07-19", "Credit",
oddColour: const Color(0xFFF7F7F9)),
accountItems(
"Floww LTD", r"+ £ 5,526.00", "15-07-19", "Credit"),
accountItems(
"KLM", r"- £ 2,500.00", "10-07-19", "Payment",
oddColour: const Color(0xFFF7F7F9)),
],
),
);
`
The other page app_drawer.dart
`
import 'package:flutter/material.dart';
class AppDrawer extends StatefulWidget {
#override
_AppDrawerState createState() => _AppDrawerState();
}
class _AppDrawerState extends State<AppDrawer> {
#override
Widget build(BuildContext context) {
return SizedBox(
width: 160.0,
child: Drawer(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 50.0),
child: FlatButton.icon(
icon: Icon(
Icons.arrow_back,
color: Colors.grey,
),
onPressed: null,
label: Text("Back",
style: TextStyle(
fontWeight: FontWeight.w400,
fontSize: 16.0,
color: Colors.black)),
color: Colors.black,
),
),
buildMenuItem(Icons.account_balance, "ACCOUNTS",
opacity: 1.0, color: Color(0xFFFF6E40)),
Divider(),
buildMenuItem(Icons.compare_arrows, "TRANSFER"),
Divider(),
buildMenuItem(Icons.receipt, "STATEMENTS"),
Divider(),
buildMenuItem(Icons.attach_money, "PAYMENTS"),
Divider(),
buildMenuItem(Icons.sentiment_satisfied, "INVESTMENTS"),
Divider(),
buildMenuItem(Icons.phone, "SUPPORT"),
Divider()
],
),
),
);
}
Opacity buildMenuItem(IconData icon, String title,
{double opacity = 0.3, Color color = Colors.black}) {
return Opacity(
opacity: opacity,
child: Center(
child: Column(
children: <Widget>[
SizedBox(
height: 20.0,
),
Icon(
icon,
size: 50.0,
color: color,
),
SizedBox(
height: 10.0,
),
Text(title,
style: TextStyle(
fontWeight: FontWeight.w500, fontSize: 14.0, color: color)),
SizedBox(
height: 10.0,
),
],
),
),
);
}
}
`
To able to scroll through the section and have unlimited amount of transaction
I think this is what you are going for.
In this snippet, I defined Language as a class with attributes language and rating.
Then I created a list of languages in the stateless widget TheList.
Finally, I used the listView.builder to map the list for its length and display text that shows the attributes of the languages.
Let me know if you have any questions!
import 'package:flutter/material.dart';
class Language {
const Language({this.language,this.rating});
final String language;
final String rating;
}
class TheList extends StatelessWidget {
// Builder methods rely on a set of data, such as a list.
final List<Language> _languages = [
const Language(language: "flutter", rating: "amazing"),
const Language(language: "javascript", rating: "stellar"),
const Language(language: "java", rating: "sucks"),
];
// First, make your build method like normal.
// Instead of returning Widgets, return a method that returns widgets.
// Don't forget to pass in the context!
#override
Widget build(BuildContext context) {
return _buildList(context);
}
// A builder method almost always returns a ListView.
// A ListView is a widget similar to Column or Row.
// It knows whether it needs to be scrollable or not.
// It has a constructor called builder, which it knows will
// work with a List.
ListView _buildList(context) {
return ListView.builder(
// Must have an item count equal to the number of items!
itemCount: _languages.length,
// A callback that will return a widget.
itemBuilder: (context, index) {
// In our case, a Language and its rating for each language in the list.
return Text(_languages[index].language + ": " + _languages[index].rating);
},
);
}
}

add a method ontap() in my listview in flutter

for adding a method ontap() in my listview with a custom class that I made for it look of a tile
i tried adding ontap(): but don't recognized it says
here is the code
class _MenuCard extends StatelessWidget {
final String headImageAssetPath;
final IconData icon;
final Color iconBackgroundColor;
final String title;
final String subtitle;
final int heartCount;
_MenuCard({
this.headImageAssetPath,
this.icon,
this.iconBackgroundColor,
this.title,
this.subtitle,
this.heartCount,
});
#override
Widget build(BuildContext context) {
return new Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
child: new Card(
elevation: 10.0,
child: new Column(
children: [
new Image.asset(
headImageAssetPath,
width: double.infinity,
height: 100.0,
fit: BoxFit.cover,
),
new Row(
children: [
new Padding(
padding: const EdgeInsets.all(15.0),
child: new Container(
padding: const EdgeInsets.all(10.0),
decoration: new BoxDecoration(
color: iconBackgroundColor,
borderRadius: new BorderRadius.all(const Radius.circular(15.0)),
),
child: new Icon(
icon,
color: Colors.white,
),
),
),
new Expanded(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Text(
title,
style: const TextStyle(
fontSize: 25.0,
fontFamily: 'mermaid',
),
),
new Text(
subtitle,
style: const TextStyle(
fontSize: 16.0,
fontFamily: 'bebas-neue',
letterSpacing: 1.0,
color: const Color(0xFFAAAAAA),
),
),
],
),
),
new Container(
width: 2.0,
height: 70.0,
decoration: new BoxDecoration(
gradient: new LinearGradient(
colors: [
Colors.white,
Colors.white,
const Color(0xFFAAAAAA),
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
),
new Padding(
padding: const EdgeInsets.only(left: 15.0, right: 15.0),
child: new Column(
children: [
new Icon(
Icons.favorite_border,
color: Colors.red,
),
new Text(
'$heartCount',
),
],
),
),
],
),
],
),
),
);
}
}
this code is of class that I use to build my listview in the scaffold of the stateless widget.
and here is how I am building my listview after returning scaffold in body:
the code is below
body: new ListView(
children: [
new _MenuCard(
headImageAssetPath: 'images/img.png',
icon: Icons.fastfood,
iconBackgroundColor: Colors.orange,
title: 'il domacca',
subtitle: "78 5TH AVENUE, NEW YORK",
heartCount: 84
),
new _MenuCard(
headImageAssetPath: 'images/img.png',
icon: Icons.local_dining,
iconBackgroundColor: Colors.red,
title: 'Mc Grady',
subtitle: "79 5TH AVENUE, NEW YORK",
heartCount: 84
),
new _MenuCard(
headImageAssetPath: 'images/img.png',
icon: Icons.fastfood,
iconBackgroundColor: Colors.purpleAccent,
title: 'Sugar & Spice',
subtitle: "80 5TH AVENUE, NEW YORK",
heartCount: 84
),
]
),
You can wrap you custom list item widget inside a GestureDetector which has an onTap callback method you can specify.
Example -
class _MenuCard extends StatelessWidget {
final String headImageAssetPath;
final IconData icon;
final Color iconBackgroundColor;
final String title;
final String subtitle;
final int heartCount;
final VoidCallback onTapCallback; //Add this custom onTap method
_MenuCard({
this.headImageAssetPath,
this.icon,
this.iconBackgroundColor,
this.title,
this.subtitle,
this.heartCount,
this.onTapCallback,
});
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTapCallback,
child: new Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
child: //Rest of your code
),
);
}
}
And inside ListView you can specify your custom onTapCallback.
body: new ListView(
children: [
new _MenuCard(
headImageAssetPath: 'images/img.png',
icon: Icons.fastfood,
iconBackgroundColor: Colors.orange,
title: 'il domacca',
subtitle: "78 5TH AVENUE, NEW YORK",
heartCount: 84,
onTapCallback: () {
// Your onTap code goes here
}
),
// Rest of your code
]
)
Besides onTap, the GestureDetector widget also has a lot of other user event callbacks. You can find out more about them here.
Also, the same functionality can also be achieved with the help of the InkWell widget, you will just need to replace GestureDetector with InkWell and the rest of the code will remain same. Documentation for the widget can be found here.
Hope this helps!