ReorderbleList with Draggable Widgets does not work - flutter

I have a ReorderdableList with 5 Widgets and each of them is Draggable.
The Draggable Widget works great, but it seems that this makes the onReorder function not work.
This is my ReorderableListView:
return Scaffold(
body: ReorderableListView(
onReorder: ((oldIndex, newIndex) {
print('onReorder');
}),
onReorderStart: (index) => print('reorder start'),
scrollDirection: Axis.horizontal,
children: [
for (final card in handCards)
HandCard(key: ValueKey(card), card, player, handOwner),
],
),
);
Each Handcard returns a Draggable Widget. Is there a way to make sure both still work?
Handcard Widget:
class HandCard extends ConsumerStatefulWidget {
HandCard(this.card, this.player, this.handOwner, {Key? key})
: super(key: key);
String handOwner;
dynamic card;
Player player;
#override
_HandCardState createState() => _HandCardState();
}
class _HandCardState extends ConsumerState<HandCard> {
#override
void initState() {
isVisibled = true;
// TODO: implement initState
super.initState();
print(isVisibled);
}
void setVisible() {
setState(() {
isVisibled = true;
});
}
late bool isVisibled;
#override
Widget build(BuildContext context) {
var handCardPickProvider =
ref.watch(handCardHighlightProvider(widget.card).notifier);
var handCardPick = ref.watch(handCardHighlightProvider(widget.card));
var gameStateProvider = ref.watch(GameStateProvider);
var handSize = ref.watch(handSizeProvider(widget.handOwner).state);
return Draggable<HandCard>(
onDragStarted: () {
// change state of current cards in hand
handSize.state = handSize.state - 1;
},
onDragEnd: (details) {
handSize.state = handSize.state + 1;
},
onDragCompleted: () {
setState(() {
isVisibled = true;
});
},
data: widget,
childWhenDragging: SizedBox.shrink(),
feedback: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(widget.card.imageLink),
fit: BoxFit.fill,
),
),
width: 100,
height: 150,
child: Stack(children: [
(widget.card is CharacterCard)
? Positioned(
right: 0,
left: 60,
child: Container(
color: Colors.white,
width: 40,
height: 13,
child: Center(
child: Text(
widget.card.power.toString(),
style: TextStyle(
color: Colors.black,
fontSize: 10,
fontWeight: FontWeight.bold),
),
),
),
)
: const SizedBox.shrink(),
Positioned(
left: 2,
child: Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Center(
child: Text(
widget.card.cost.toString(),
style: TextStyle(color: Colors.white, fontSize: 12),
)),
))
]),
),
child: (isVisibled)
? InkWell(
onTap: () {
print('click');
// If it is the counter move and the card has a counter effect we can use it
if (gameStateProvider.gameSession!.moves.length != 0) {
Move currentMove = gameStateProvider.gameSession!
.moves[gameStateProvider.gameSession!.atMove - 1];
print(currentMove.moveType);
// Handle on counter effect
if (currentMove.moveType == 'on counter effect' &&
currentMove.toPlayer.id == widget.player.id) {
handCardPickProvider.highlightCard(widget.card);
}
}
},
child: Container(
margin: EdgeInsets.all(1),
decoration: BoxDecoration(
boxShadow: [
(handCardPick)
? BoxShadow(
color: Colors.white,
spreadRadius: 1,
blurRadius: 10)
: BoxShadow(
color: Colors.white,
spreadRadius: 0,
blurRadius: 0),
],
image: DecorationImage(
image: AssetImage(widget.card.imageLink),
fit: BoxFit.fill,
),
),
width: 100,
height: 150,
child: Stack(children: [
(widget.card is CharacterCard)
? Positioned(
right: 0,
left: 60,
child: Container(
color: Colors.white,
width: 40,
height: 13,
child: Center(
child: Text(
widget.card.power.toString(),
style: TextStyle(
color: Colors.black,
fontSize: 10,
fontWeight: FontWeight.bold),
),
),
),
)
: const SizedBox.shrink(),
Positioned(
left: 2,
child: Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: Colors.red,
shape: BoxShape.circle,
),
child: Center(
child: Text(
widget.card.cost.toString(),
style: TextStyle(color: Colors.white, fontSize: 12),
)),
))
]),
),
)
: SizedBox.shrink(),
);
}
}

Related

How to access context and setstate outside build method in Flutter

How to access context and setstate outside build method in Flutter?
To make the app responsive I need context.
I get error "Undefined name 'context'.
Try correcting the name to one that is defined, or defining the name."
When I write context here:-
class Portfolio extends StatefulWidget {
final BuildContext context1;
const Portfolio({
required this.context1,
Key? key,
}) : super(key: key);
#override
State<Portfolio> createState() => _PortfolioState();
}
DragAndDropList buildList(CardsList list) => DragAndDropList(
header: Padding(
padding: EdgeInsets.only(
left: 15.0,
top: 10,
bottom: 10,
right: 15,
),
child: Row(
children: [
Text(
list.header,
style: TextStyle(
color: Color(0xFF100F32),
fontWeight: FontWeight.w700,
fontSize: responsiveWidth(14, context),
),
),
Spacer(),
Icon(
Icons.more_horiz,
color: Color(0xFF364766),
size: 20,
),
],
),
),
children: list.cards
.map(
(item) => DragAndDropItem(
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 8.0),
child: Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.all(10),
child: Text(item.text),
),
),
),
),
)
.toList(),
footer: Padding(
padding: EdgeInsets.only(left: 10.0, bottom: 10),
child: addCard == false
? OPopupTrigger(
triggerWidget: Row(
children: [
Icon(
Icons.add,
color: Color(0xFF80899D),
),
Text(
'Add a card',
style: TextStyle(
color: Color(0xFF80899D),
fontSize: 12,
),
),
],
),
barrierDismissible: true,
popupHeader: SizedBox(),
popupContent: Container(
height: 100,
width: 100,
color: Colors.red,
child: Row(
children: [
Text('Hehehe'),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(Icons.cancel),
),
],
),
),
)
: Column(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.only(left: 10, top: 10, bottom: 25),
child: TextField(
onChanged: (newText) {
list.textField = newText;
},
maxLines: null,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
hintText: 'Enter a title for this card...',
hintStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
labelStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
),
),
style: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
),
),
SizedBox(
height: 20,
),
Row(
children: [
GestureDetector(
onTap: () {
list.cards.add(
Cards(text: list.textField, position: 1),
);
print(list.textField);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF026AA7),
borderRadius: BorderRadius.circular(5),
),
height: 30,
width: 80,
child: Center(
child: Text(
'Add card',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
),
),
GestureDetector(
onTap: () {
addCard = false;
},
child: Icon(
Icons.close,
color: Color(0xFF80899D),
size: 24,
),
),
],
),
],
),
),
);
class _PortfolioState extends State<Portfolio> {
#override
void initState() {
// TODO: implement initState
lists = widgets.map(buildList).toList();
}
late List<DragAndDropList> lists;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
Full code file:-
import 'package:expandable_reorderable_list/expandable_reorderable_list.dart';
import 'package:flutter/material.dart';
import 'package:o_popup/o_popup.dart';
import 'package:project_submission/responsive.dart';
import 'drag_and_drop_list.dart';
void main() {
runApp(const MyApp());
}
class CardsList {
final String header;
final List<Cards> cards;
String textField;
CardsList({
required this.header,
required this.cards,
this.textField = '',
});
}
class Cards {
final String text;
final int position;
const Cards({
required this.text,
required this.position,
});
}
List<CardsList> widgets = [
CardsList(
header: 'To-do',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header2',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header3',
textField: '',
cards: [
Cards(
text:
'Trello Tip: Card labels! What do they mean? (Click for more info)',
position: 1),
Cards(text: 'Project "Teamwork Dream Work" Launch Timeline', position: 2),
Cards(text: 'Stakeholders', position: 3),
],
),
CardsList(
header: 'header4',
textField: '',
cards: [
Cards(text: 'Hello1', position: 1),
Cards(text: 'Hello2', position: 2),
Cards(text: 'Hello3', position: 3),
],
),
];
bool addCard = false;
bool greyArea = false;
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: Wait());
}
}
class Wait extends StatefulWidget {
const Wait({Key? key}) : super(key: key);
#override
State<Wait> createState() => _WaitState();
}
class _WaitState extends State<Wait> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Portfolio(
context1: context,
)));
},
child: Text('Wait'),
);
}
}
class Portfolio extends StatefulWidget {
final BuildContext context1;
const Portfolio({
required this.context1,
Key? key,
}) : super(key: key);
#override
State<Portfolio> createState() => _PortfolioState();
}
DragAndDropList buildList(CardsList list) => DragAndDropList(
header: Padding(
padding: EdgeInsets.only(
left: 15.0,
top: 10,
bottom: 10,
right: 15,
),
child: Row(
children: [
Text(
list.header,
style: TextStyle(
color: Color(0xFF100F32),
fontWeight: FontWeight.w700,
fontSize: responsiveWidth(14, context),
),
),
Spacer(),
Icon(
Icons.more_horiz,
color: Color(0xFF364766),
size: 20,
),
],
),
),
children: list.cards
.map(
(item) => DragAndDropItem(
child: Center(
child: Padding(
padding: EdgeInsets.only(top: 8.0),
child: Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.all(10),
child: Text(item.text),
),
),
),
),
)
.toList(),
footer: Padding(
padding: EdgeInsets.only(left: 10.0, bottom: 10),
child: addCard == false
? OPopupTrigger(
triggerWidget: Row(
children: [
Icon(
Icons.add,
color: Color(0xFF80899D),
),
Text(
'Add a card',
style: TextStyle(
color: Color(0xFF80899D),
fontSize: 12,
),
),
],
),
barrierDismissible: true,
popupHeader: SizedBox(),
popupContent: Container(
height: 100,
width: 100,
color: Colors.red,
child: Row(
children: [
Text('Hehehe'),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(Icons.cancel),
),
],
),
),
)
: Column(
children: [
Container(
width: 280,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(5),
),
padding: EdgeInsets.only(left: 10, top: 10, bottom: 25),
child: TextField(
onChanged: (newText) {
list.textField = newText;
},
maxLines: null,
decoration: InputDecoration(
isDense: true,
contentPadding: EdgeInsets.zero,
hintText: 'Enter a title for this card...',
hintStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
labelStyle: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
border: OutlineInputBorder(
borderSide: BorderSide.none,
),
),
style: TextStyle(
color: Color(0xFF838EA0),
fontSize: 12,
),
),
),
SizedBox(
height: 20,
),
Row(
children: [
GestureDetector(
onTap: () {
list.cards.add(
Cards(text: list.textField, position: 1),
);
print(list.textField);
},
child: Container(
decoration: BoxDecoration(
color: Color(0xFF026AA7),
borderRadius: BorderRadius.circular(5),
),
height: 30,
width: 80,
child: Center(
child: Text(
'Add card',
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
),
),
GestureDetector(
onTap: () {
addCard = false;
},
child: Icon(
Icons.close,
color: Color(0xFF80899D),
size: 24,
),
),
],
),
],
),
),
);
class _PortfolioState extends State<Portfolio> {
#override
void initState() {
// TODO: implement initState
lists = widgets.map(buildList).toList();
}
late List<DragAndDropList> lists;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Stack(
children: [
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
Color(0xFF2B1B81),
Color(0xFFDD499D),
],
),
),
),
Text(
'Project Management',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 20,
),
),
Padding(
padding: EdgeInsets.only(
left: 10,
top: 30,
),
child: DragAndDropLists(
listWidth: 300,
axis: Axis.horizontal,
listPadding: EdgeInsets.only(right: 10),
itemDragOnLongPress: false,
children: lists,
onItemReorder: onItemReorder,
onListReorder: onListReorder,
),
),
// Row(
// children: [
// DragTarget(
// onAccept: (data) {
// setState(() {
// widgets.add(data);
// widgets.remove(data);
// });
// },
// onWillAccept: (data) {
// setState(() {
// greyArea = true;
// });
// return true;
// },
// onLeave: (data) {
// setState(() {
// greyArea = false;
// widgets
// .sort((a, b) => a['position'].compareTo(b['price']));
// });
// },
// builder: (context, _, __) => SizedBox(
// height: MediaQuery.of(context).size.height,
// child: Column(
// children: [
// Padding(
// padding: EdgeInsets.only(left: 30.0, top: 30),
// child: Container(
// width: 300,
// decoration: BoxDecoration(
// color: Color(0xFFEBECF0),
// borderRadius: BorderRadius.circular(6),
// ),
// child: Column(
// children: [
// Text(
// 'Project Resources',
// style: TextStyle(
// color: Color(0xFF5D6C83),
// fontWeight: FontWeight.w600,
// fontSize: 12),
// ),
// for (var wid in widgets)
// Column(
// children: [
// Padding(
// padding: EdgeInsets.all(8.0),
// child: Draggable(
// child: Container(
// decoration: BoxDecoration(
// color: Colors.green,
// ),
// child: Text(wid['text']),
// height: 100,
// width: 100,
// ),
// data: wid,
// feedback: Container(
// color: Colors.red,
// height: 100,
// width: 100,
// ),
// childWhenDragging: SizedBox(),
// ),
// ),
// DragTarget(
// onAccept: (data) {
// setState(() {
// widgets.add({
// 'text': data['text'],
// 'position': 1
// });
// widgets.remove({
// 'text': data['text'],
// 'position': data['position']
// });
// });
// },
// onWillAccept: (data) {
// setState(() {
// greyArea = true;
// });
// return true;
// },
// onLeave: (data) {
// setState(() {
// greyArea = false;
// });
// },
// builder: (context, _, __) {
// print(_);
// return SizedBox();
// },
// ),
// ],
// ),
// greyArea == true
// ? Container(
// color: Colors.grey,
// height: 20,
// width: 100,
// )
// : SizedBox(),
// SizedBox(
// height: 8,
// ),
// ],
// ),
// ),
// ),
// ],
// ),
// ),
// ),
// ],
// ),
],
),
),
);
}
void onItemReorder(
int oldItemIndex,
int oldListIndex,
int newItemIndex,
int newListIndex,
) {
setState(() {
final oldListItems = lists[oldListIndex].children;
final newListItems = lists[newListIndex].children;
final movedItem = oldListItems.removeAt(oldItemIndex);
newListItems.insert(newItemIndex, movedItem);
});
print(lists);
}
void onListReorder(
int oldListIndex,
int newListIndex,
) {
setState(() {
final movedList = lists.removeAt(oldListIndex);
lists.insert(newListIndex, movedList);
});
}
}

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,....);
}

how to make this table scrollable to bottom

i am beginner in flutter , i wrote a code with a leagueboard table from api , after i executed i found that my table is not scrolling , the scroll appears only on the top but no scrolling to bottom
here what i have tried:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:http/http.dart' as http;
class LeagueBoard extends StatefulWidget {
#override
_LeagueBoardState createState() => _LeagueBoardState();
}
class _LeagueBoardState extends State<LeagueBoard> {
List<Club> clubs = [];
getTable() async {
http.Response response = await http.get(
'http://api.football-data.org/v2/competitions/PL/standings',
headers: {'X-Auth-Token': '86014f6025ae430dba078acc94bb2647'});
String body = response.body;
Map data = jsonDecode(body);
List table = data['standings'][0]['table'];
// for (var team in table) {
// clubs.add(Club(team['team']['crestUrl'].toString(), team['position'].toString(),team['points'].toString(),team['points'].toString(),team['playedGames'].toString(),team['won'].toString(),
// team['draw'].toString(),team['lost'].toString(),team['goalsFor'],team['goalsAgainst']));
// print(team);
// }
// for (var team in table) {
// clubs.add(Club(team['team']['crestUrl'].toString(), team['position'].toString(),team['points'].toString(),team['points'].toString(),team['playedGames'].toString(),team['won'].toString(),
// team['draw'].toString(),team['lost'].toString(),team['goalsFor'],team['goalsAgainst']));
// print(team);
// }
// for (var team in clubs) {
// debugPrint(team.toString());
// }
setState(() {
for (var team in table) {
clubs.add(Club(team['team']['name'],team['team']['crestUrl'], team['position'].toString(),team['points'].toString(),team['playedGames'].toString(),team['won'].toString(),
team['draw'].toString(),team['lost'].toString(),team['goalsFor'],team['goalsAgainst']));
print("hello");
}
});
}
// List<Club> clubs = [ Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),
// Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),
// Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),
// Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),
// Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),
// Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),
// Club("Manchester City","https://upload.wikimedia.org/wikipedia/fr/thumb/b/ba/Logo_Manchester_City_2016.svg/1200px-Logo_Manchester_City_2016.svg.png","1","77","17","15","1","1",25,5),
// Club("Chelsea","https://upload.wikimedia.org/wikipedia/fr/thumb/5/51/Logo_Chelsea.svg/768px-Logo_Chelsea.svg.png","2","70","17","13","2","3",19,8),];
#override
void initState() {
super.initState();
getTable();
}
#override
Widget build(BuildContext context) {
return clubs == null
? Container(
color: Colors.white,
child: Center(
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(
Color(0xFFe70066),
),
),
),
)
: Scaffold(
appBar: AppBar(
title: Text("LeagueBoard"),
backgroundColor: Colors.blue[300],
elevation: 0.0,
),
body: SingleChildScrollView(
child: Column(
children: [
TopRow(),
ListView.builder(
shrinkWrap: true,
// physics: NeverScrollableScrollPhysics(),
itemCount: clubs.length,
itemBuilder: (context, index) {
return TableRow(index: index, clubs:clubs);
},
),
],
),
),
);
}
}
class TopRow extends StatelessWidget {
const TopRow({
Key key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
TextStyle textStyle = TextStyle(fontSize: 11, fontWeight: FontWeight.bold);
TextStyle textStyle2 = TextStyle(fontSize: 13);
return Container(
child: Row(
children: [
Container(
alignment: Alignment.center,
width: 30,
height: 30,
child: Text('#'),
),
SizedBox(width: 20),
Container(alignment: Alignment.center, child: Text('Team')),
Spacer(),
Container(
width: 28,
child: Text('MP', style: textStyle),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text('W', style: textStyle),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text('D', style: textStyle),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text('L', style: textStyle),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text('GD', style: textStyle),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text('Pts', style: textStyle),
),
SizedBox(
width: 5,
),
Container(
width: 5,
height: 20,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.grey[800],
),
padding: EdgeInsets.fromLTRB(10, 5, 2, 5),
),
],
),
);
}
}
class TableRow extends StatelessWidget {
final int index;
final List<Club> clubs;
const TableRow({
this.index,
this.clubs,
Key key,
}) : super(key: key);
/////////////////////////////////////////////////////////////////////linkwell
////////////////////////////////////////////////////////////////////
#override
Widget build(BuildContext context) {
TextStyle textStyle = TextStyle(fontSize: 11, fontWeight: FontWeight.bold);
TextStyle textStyle2 = TextStyle(fontSize: 13, fontWeight: FontWeight.bold);
return Container(
width: double.infinity,
height: 40,
decoration: BoxDecoration(
border: Border.all(color: Colors.black38, width: 0.2),
color: index == 0 ? Colors.yellow[100] : Colors.purpleAccent[20],
),
child: Row(
children: [
Container(//iinkwell
alignment: Alignment.center,
width: 30,
height: 40,
color: index < 2
? Colors.blue
: index == 2
? Colors.red[400]
: index > 11
? Colors.red[800]
: Colors.grey[700],
child: Text(
(index + 1).toString(),
style: TextStyle(color: Colors.white),
),
),
SizedBox(width: 20),
Row(children: [
SvgPicture.network(clubs[index].image,
width: 24.0, height: 24.0,
),
SizedBox(width: 5.0),
clubs[index].name.length > 11
? Text(clubs[index].name
.toString()
.substring(0, 11) +
'...')
: Text(clubs[index].name.toString(), style: textStyle2),
],),
Spacer(),
Container(
width: 28,
child: Text(clubs[index].matches, style: textStyle2),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text(clubs[index].wins, style: textStyle2),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text(clubs[index].draws, style: textStyle2),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text(clubs[index].loss, style: textStyle2),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text((clubs[index].goals - clubs[index].goalsIn).toString(), style: textStyle2),
),
SizedBox(
width: 5,
),
Container(
width: 28,
child: Text(clubs[index].points, style: textStyle2),
),
SizedBox(
width: 5,
),
Container(
width: 5,
height: 20,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.grey[600],
),
padding: EdgeInsets.fromLTRB(10, 5, 2, 5),
),
],
),
);
}
}
class Club {
String name;
String image;
String rank;
String points;
String matches;
String wins;
String loss;
String draws;
int goals;
int goalsIn;
Club(this.name,this.image,this.rank,this.points, this.matches,this.wins,this.loss,this.draws,this.goals,this.goalsIn);
}
I am trying to make my table scrolling because i can not see all of the teams that came from becand due to non scrolling reasons
You are using ListView inside SingleChildScrollView. So set that ListView as non-primary.
primary: false
Change at this point in your code
ListView.builder(
shrinkWrap: true,
primary: false,
// physics: NeverScrollableScrollPhysics(),
itemCount: clubs.length,
itemBuilder: (context, index) {
return TableRow(index: index, clubs:clubs);
},
),

Data is not showing correct in Tabbar from firebase realtime flutter

I am having an issue getting data from the firebase realtime database in the tab bar view. Data showing in Tabbar view from real-time database flutter .. but last tab data same showing in all tabs. All the tab bar views data are different but it is showing data of one tab in all tabs. I think it overwrites previous data with data we got at last tab.
Screen Shot1
Screen Shot 2
loadsubcategories() {
ref = FirebaseDatabase.instance;
ref.reference().child('Categories').child(id).child("Subcategories")
// .onValue
// .listen((event) {
// var snapshot = event.snapshot;
.once()
.then((DataSnapshot snapshot){
if(snapshot.value != null){
var keys = snapshot.value.keys;
var value = snapshot.value;
//listtab = new List();
listtab.clear();
for (var key in keys) {
print(key);
TabNews data = TabNews(
value[key]['subcategory'],
0,
value[key]['id'],
);
listtab.add(data);
}
} else {
print("chal Chutti kr");
}
// setState(() {
//
// });
setState(() {
// _controller = TabController( length: listtab.length, initialIndex: 0);
// _controller.addListener(_handleTabSelection);
});
}
);
}
tabbarviewdata(String subcategoryid) {
print("fajasl"+id);
cardref = FirebaseDatabase.instance;
cardref.reference().child('Categories').child(id).child("Subcategories").child(subcategoryid).child("Personalities")
// .onValue
// .listen((event) {
// var snapshot = event.snapshot;
.once()
.then((DataSnapshot snapshot){
if(snapshot.value != null){
var keys = snapshot.value.keys;
var value = snapshot.value;
// cardlist= new List();
cardlist.clear();
for (var key in keys) {
// print(key);
CardList data = CardList(
value[key]['image'],
value[key]['name'],
value[key]['designation'],
value[key]['subscribeCount'],
"",
false,
value[key]['id'],
);
cardlist.add(data);
// print(data.designation);
}
}
else {
print("No Data");
}
}
);
return
ListView.builder(
itemCount: 1,
itemBuilder: (context, i) {
return Column(
children: [
for (int i = 0; i < cardlist.length; i++)
Padding(
padding: EdgeInsets.only(
left: MediaQuery.of(context).size.width / 70,
right: MediaQuery.of(context).size.width / 30),
child: GestureDetector(
onTap: () {
dialogDisplay(context, i);
// displaysnaplist(context, i);
},
child: Container(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
elevation: 0,
child: Row(
//mainAxisAlignment: MainAxisAlignment.spaceBetween,
// crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(
top: ScreenUtil().setHeight(40),
left: ScreenUtil().setHeight(40),
bottom: ScreenUtil().setHeight(40),
),
child: Container(
height: ScreenUtil().setHeight(250),
width: ScreenUtil().setHeight(250),
child: Text(""),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
image: DecorationImage(
// scale: 20,
image: NetworkImage(
cardlist[i].image,
),
fit: BoxFit.cover,
// fit: BoxFit.fitWidth
),
),
),
),
SizedBox(
width: ScreenUtil().setWidth(50),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(
top: MediaQuery
.of(context)
.size
.height /
28),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
cardlist[i].name,
style: TextStyle(
decoration: TextDecoration.none,
fontFamily: 'roboto',
fontWeight: FontWeight.w600,
color: Colors.black,
),
),
SizedBox(
height:
MediaQuery
.of(context)
.size
.height /
120,
),
Text(
cardlist[i].designation,
style: TextStyle(
decoration: TextDecoration.none,
fontFamily: 'roboto',
fontSize: 10,
color: Colors.blue,
),
),
SizedBox(
height:
MediaQuery
.of(context)
.size
.height /
120,
),
Row(
children: [
Text(
cardlist[i].subscribeCount.toString(),
style: TextStyle(
decoration: TextDecoration.none,
fontFamily: 'roboto',
color: Colors.grey[700],
fontSize: 10,
),
),
SizedBox(
width: MediaQuery
.of(context)
.size
.width /
100,
),
Text(
'Subscribed',
style: TextStyle(
decoration: TextDecoration.none,
fontFamily: 'roboto',
color: Colors.grey[700],
fontSize: 10),
),
],
),
],
),
),
),
Padding(
padding: EdgeInsets.only(
top: ScreenUtil().setHeight(120),
right: ScreenUtil().setHeight(50),
),
child: Column(
children: [
Visibility(
visible: cardlist[i].show ?? true,
child: RaisedButton(
elevation: 0,
// minWidth: 100,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
10.0),
),
color: Color(0xffF8D4D3),
child: Text(
cardlist[i].newstype,
style: TextStyle(
color: Color(0xffB53B38),
fontSize: 10),
),
onPressed: () {
dialogDisplay(context, i);
}),
),
],
),
)
],
),
),
),
),
),
],
);
});
// }
// );
}

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)
),
),
)