setState() is not updating the Text() widget in flutter - flutter

I'm trying to build an app that is like a calculator but it has some additional buttons that automaticly sets a number to displayedNumber. I tried the setState() for setting the number but the Text() widget is not updating.
This is what I tried:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Home(),
));
}
class Home extends StatefulWidget {
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
String name = 'Amir Mahdi Abravesh';
String phoneNumber = '+989920250829';
double input = 0.00;
double displayedNumber = 0.0;
String inputST = '\$' + '$displayedNumber';
void displayingDigits(){
if(displayedNumber == 0.0){
displayedNumber += input;
} else {
displayedNumber = displayedNumber * 10;
displayedNumber += input;
}
}
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Center(
child: Text(
'Send Money to',
style: TextStyle(
color: Colors.black,
// fontFamily: 'SF Pro',
fontWeight: FontWeight.bold,
),
),
),
centerTitle: true,
backgroundColor: Colors.white,
// shadowColor: Color.fromARGB(197, 192, 192, 192),
elevation: 0,
),
body: Column(
children: <Widget>[
SizedBox(height: 10,),
Expanded(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundImage: AssetImage('assets/AMA25 trs.png'),
backgroundColor: Colors.black,
radius: 30,
),
SizedBox(height: 5,),
Text(
'$name',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
SizedBox(height: 5,),
Text(
'$phoneNumber',
style: TextStyle(
color: Colors.grey,
),
),
],
),
),
),
Expanded(
child: Container(
padding: EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
'$displayedNumber',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
Divider(
height: 30,
color: Colors.grey[700],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () {
setState(() {
displayedNumber = 50.0;
// inputST = '\$' + '$displayedNumber';
});
},
child: Container(
padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
),
child: Text(
'\$50',
style: TextStyle(
color: Colors.grey,
// fontSize: 18,
),
),
),
),
],
),
),
),
],
),
);
}
}
You can ignore the inputST that I commented. That's just for showing a $ before the displayedNumber.
I want this button to set 50 to the displayedNumber and update the number on the screen.

Here you go . You just needed to move variables after State
// ignore_for_file: prefer_interpolation_to_compose_strings
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Home(),
));
}
class Home extends StatefulWidget {
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
String name = 'Amir Mahdi Abravesh';
String phoneNumber = '+989920250829';
double input = 0.00;
double displayedNumber = 0.0;
#override
Widget build(BuildContext context) {
void displayingDigits() {
if (displayedNumber == 0.0) {
displayedNumber += input;
} else {
displayedNumber = displayedNumber * 10;
displayedNumber += input;
}
}
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Center(
child: Text(
'Send Money to',
style: TextStyle(
color: Colors.black,
// fontFamily: 'SF Pro',
fontWeight: FontWeight.bold,
),
),
),
centerTitle: true,
backgroundColor: Colors.white,
// shadowColor: Color.fromARGB(197, 192, 192, 192),
elevation: 0,
),
body: Column(
children: <Widget>[
SizedBox(
height: 10,
),
Expanded(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircleAvatar(
backgroundImage: AssetImage('assets/AMA25 trs.png'),
backgroundColor: Colors.black,
radius: 30,
),
SizedBox(
height: 5,
),
Text(
'$name',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
SizedBox(
height: 5,
),
Text(
'$phoneNumber',
style: TextStyle(
color: Colors.grey,
),
),
],
),
),
),
Expanded(
child: Container(
padding: EdgeInsets.all(30),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Text(
'$displayedNumber',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
Divider(
height: 30,
color: Colors.grey[700],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () {
setState(() {
displayedNumber = 50.0;
// inputST = '\$' + '$displayedNumber';
});
},
child: Container(
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 15),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(15),
),
child: Text(
'\$50',
style: TextStyle(
color: Colors.grey,
// fontSize: 18,
),
),
),
),
],
),
]),
),
)
],
),
);
}
}

Because you have define double displayedNumber = 0.0; inside build().
Define double displayedNumber = 0.0; outside the build().
class _HomeState extends State<Home> {
double displayedNumber = 0.0; // Initialize here
#override
Widget build(BuildContext context) {}}

Related

How to make Container height dynamic to fit ListView but to certain max height Flutter

I am trying to show ListView in a custom dialog window. What I want to make dialog box height dynamic according to ListView content but to certain max height. If the ListView content reaches specific height it should me scrollable.
This is my code:
class PeekTableDialog extends StatefulWidget {
Order order;
PeekTableDialog({required this.order});
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return PeekTableDialogState();
}
}
class PeekTableDialogState extends State<PeekTableDialog> {
final ScrollController controller = ScrollController();
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
void initState() {
super.initState();
}
Widget getExtras(Food fooditem) {
List<String> extras = [];
for (var extra in fooditem.extras) {
if (fooditem.extras.last == extra) {
extras.add(extra.name);
} else {
extras.add(extra.name + ', ');
}
}
return Wrap(
runSpacing: 2,
spacing: 2,
children: List.generate(
extras.length,
(index) {
return Text(
extras[index].toString(),
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.normal,
fontStyle: FontStyle.italic,
),
);
},
),
);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
return SizedBox(
width: MediaQuery.of(context).size.width * 0.50,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: double.infinity,
color: Colors.grey[400],
padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
alignment: Alignment.center,
child: Row(
children: [
Expanded(
child: Container(
alignment: Alignment.center,
child: Text(
widget.order.table!.name,
style: AppTextStyles().style2,
),
),
),
IconButton(
onPressed: () {
Navigator.of(context).pop();
},
padding: EdgeInsets.zero,
icon: Icon(
Icons.close,
color: Colors.white,
size: 35,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
alignment: Alignment.center,
child: Text(
'\$' + widget.order.total,
style: TextStyle(
color: Colors.grey[800],
fontSize: 35,
fontWeight: FontWeight.w400,
),
),
),
SizedBox(
height: 15,
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 10),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
child: Text(
'Qty',
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(
width: 10,
),
Expanded(
flex: 2,
child: Text(
'Item',
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(
width: 10,
),
Expanded(
child: Container(
child: Text(
'Price',
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.w700,
),
),
),
),
const SizedBox(
width: 10,
),
Expanded(
child: Container(
child: Text(
'Disc.',
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.w700,
),
),
),
),
],
),
const Divider(
color: Colors.grey,
height: 1.5,
),
const SizedBox(
height: 10,
),
Container(
padding: EdgeInsets.only(bottom: 30),
child: Scrollbar(
isAlwaysShown: true,
controller: controller,
thickness: 12,
showTrackOnHover: true,
child: ListView.separated(
itemCount: widget.order.cartItems.length,
controller: controller,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Container(
child: Row(
children: [
Expanded(
child: Container(
alignment: Alignment.centerLeft,
child: Text(
widget.order.cartItems[index].cartCount
.toString(),
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
),
),
const SizedBox(
width: 10,
),
Expanded(
flex: 2,
child: Container(
alignment: Alignment.centerLeft,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(
widget.order.cartItems[index].name,
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
const SizedBox(
height: 5,
),
getExtras(widget.order.cartItems[index]),
],
),
),
),
const SizedBox(
width: 10,
),
Expanded(
child: Container(
alignment: Alignment.centerLeft,
child: Text(
'\$' +
widget.order.cartItems[index].totalPrice
.toStringAsFixed(2),
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
),
),
const SizedBox(
width: 10,
),
Expanded(
child: Container(
alignment: Alignment.centerLeft,
child: Text(
'\$' +
widget
.order.cartItems[index].newDiscPrice
.toStringAsFixed(2),
style: TextStyle(
color: Colors.grey[700],
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
),
),
],
),
);
},
separatorBuilder: (context, index) {
return const SizedBox(height: 3);
},
),
),
),
],
),
),
],
),
);
}
}
Anyone help me please with this small issue.
Thanks in advance.
Well, It's pretty easy. All you have to do is to create a class like this :
class ExpandableText extends StatefulWidget {
ExpandableText(this.text, this.isLongText, {Key? key}) : super(key: key);
final String text;
bool isExpanded = false;
final bool isLongText;
#override
_ExpandableTextState createState() => _ExpandableTextState();
}
class _ExpandableTextState extends State<ExpandableText>
with TickerProviderStateMixin<ExpandableText> {
#override
void initState() {
if (widget.isLongText) {
setState(() {
widget.isExpanded = false;
});
} else {
widget.isExpanded = true;
}
super.initState();
}
#override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
AnimatedSize(
vsync: this,
duration: const Duration(milliseconds: 500),
child: ConstrainedBox(
constraints: widget.isExpanded
? const BoxConstraints(maxHeight: 250.0)
: const BoxConstraints(
maxHeight: 60.0,
),
child: SingleChildScrollView(
child: Text(
widget.text,
overflow: TextOverflow.fade,
),
),
),
),
widget.isExpanded
? ConstrainedBox(constraints: const BoxConstraints())
: TextButton(
style: const ButtonStyle(alignment: Alignment.topRight),
child: const Text(
'Expand..'
),
onPressed: () => setState(() => widget.isExpanded = true),
),
],
);
}
}
Just play with the maxHeight according to your needs. Call this class like this (inside your dialog window) :
ExpandableText(
dataToBeShown,
dataToBeShown.length > 250 ? true : false,
),

How to make dynamic listview in tabbar

I want to make here Listing of cicrleavater, and in that cicleavter size issue width not getting more than 20 ! i want to make listing like instagram stories...and each tap i want show same pages but data differnt and current circle avater border need to show yello color....! how to do that i show you my screen size issue top whre cicleavter size issue i want make dyanamic listview and show on border when i tapped on it it
class FolderPageTabBAr extends StatefulWidget {
#override
_FolderPageTabBArState createState() => _FolderPageTabBArState();
}
class _FolderPageTabBArState extends State<FolderPageTabBAr> {
List<Widget> pages = [
CampaignFolder(),
ShelfScreen(),
CampaignFolder(),
ShelfScreen(),
];
double Redius = 40.0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: pages.length,
initialIndex: 0,
child: Scaffold(
body: Stack(
children: <Widget>[
TabBarView(
children: pages,
),
Container(
margin: EdgeInsets.only(top: 110,left: 1),
child: SizedBox(
height: 80,
width: 500,
child: TabBar(
tabs: [
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child:Text(
'ALL',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 12.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
radius: 22,
backgroundImage: NetworkImage(Globals.PhotographerProf),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
Globals.Buisnessname,
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 11.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Family",
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 10.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(Globals.PhotographerProf),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child:Text(
"Album",
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 9.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
],
unselectedLabelColor: Colors.orange,
labelColor: Colors.deepOrange,
indicatorColor: Colors.transparent,
),
)
),
],
),
),
);
}
}
To create multiple (dynamic) views that look similar use List View Builder
FULL Example:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyClass {
final String url;
final int id;
MyClass(this.url, this.id);
}
class Foo extends StatefulWidget {
#override
State<StatefulWidget> createState() => FooState();
}
class FooState extends State<Foo> {
int selectedIndex = 0;
List<MyClass> items = [
MyClass('https://picsum.photos/250?image=9', 1),
MyClass('https://picsum.photos/250?image=10', 5),
MyClass('https://picsum.photos/250?image=11', 33)
];
#override
Widget build(BuildContext context) {
print("build");
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
height: 90,
child: ListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
itemCount: items.length,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () {
setState(() {
selectedIndex = index;
});
},
child: getAvatarView(items[index], index == selectedIndex),
);
},
),
),
Text(
"here is my page for id ${items[selectedIndex].id}",
style: TextStyle(backgroundColor: Colors.black, color: Colors.red),
),
],
),
);
}
Widget getAvatarView(MyClass item, bool isSelected) {
return Container(
margin: isSelected ? const EdgeInsets.all(5.0) : null,
decoration: BoxDecoration(
border: isSelected ? Border.all(color: Colors.yellow) : null),
child: Column(
children: <Widget>[
CircleAvatar(
backgroundImage: NetworkImage(item.url),
radius: 22,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'ALL',
overflow: TextOverflow.ellipsis,
style: new TextStyle(
fontSize: 12.0,
fontFamily: 'Roboto',
color: new Color(0xFF212121),
fontWeight: FontWeight.bold,
),
),
)
],
),
);
}
}
To pass multiple attributes in an item (callback function, url for img,...) use a List of Custom classes.

Change Background Color and Text Color of a button onPressed and set back to default when unPressed Flutter

I am new to flutter. I have two buttons in a row and I want to change the colour and the text of the first button when it is pressed to something else and if the second button is pressed the first button should go back to the default colour and the second button should go to the new colour. Is there any way I can achieve this by indexing?
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: 150,
width: MediaQuery.of(context).size.width * 0.45,
child: RaisedButton(
color: primaryColor,
onPressed: () {},
child: Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Column(
children: [
Text('Stunning Solo', style: TextStyle(fontSize: 15,color: Colors.white)),
Text('Current Plan', style: TextStyle(fontSize: 12,color: Colors.white)),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text("\$$dollars3",style: TextStyle(fontSize: 20,color: Colors.white)),
),
Text(
"Free forever",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 13,
color: whiteColor),
),
],
),
),
),
),
SizedBox(height: 20),
SizedBox(
height: 150,
width: MediaQuery.of(context).size.width * 0.45,
child: RaisedButton(
color: primaryColor,
onPressed:
() {},
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 20.0),
child: Text('Startup Pack', style: TextStyle(fontSize: 15,color: Colors.white)),
),
Text('Introductory Offer', style: TextStyle(fontSize: 12,color: Colors.white)),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
"\$$dollars",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
decoration: TextDecoration.lineThrough),
),
SizedBox(width: 5),
Text(
"\$$dollars2",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: whiteColor),
),
]),
You can use ToggleButton for this.
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<bool> buttonsState = [
true,
false
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: ToggleButtons(
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
color: Colors.blue,
fillColor: Colors.blue,
isSelected: buttonsState,
children: <Widget>[
Padding(
padding: EdgeInsets.only(
left: 8,
right:8,
),
child: Text(
"Free forever", style: _getTextStyle(0),
textAlign: TextAlign.center,
),
),
Padding(
padding: EdgeInsets.only(
left: 8,
right: 8,
),
child: Text(
"Startup Pack", style: _getTextStyle(1),
textAlign: TextAlign.center,
),
),
],
onPressed: _updateButtonState,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
),
),
);
}
_updateButtonState(int index) {
setState(() {
for (int buttonIndex = 0; buttonIndex < buttonsState.length; buttonIndex++) {
if (buttonIndex == index) {
buttonsState[buttonIndex] = true;
} else {
buttonsState[buttonIndex] = false;
}
}
});
}
TextStyle _getTextStyle(int index) {
return buttonsState[index]
? TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.white) : TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: Colors.blue);
}
}
You can just use TextButton since it provides state type. It is also the replacement of FlatButton.
Example if you want to change foregroundColor which are text or icon color:
TextButton(
onPressed: onPressed,
child: Text("label"),
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
} else if (states.contains(MaterialState.selected)) {
return pressedColor;
} else if (states.contains(MaterialState.error)) {
return redPrimary;
} else if (states.contains(MaterialState.disabled)) {
return darkSecondary;
}
return darkSecondary;
},
),
...
),
);

Flutter how give a gap between containers in SliverChildBuilderDelegate

I am using SliverAppBar in my app which is working fine but problem is in list of container its not increasing gap between list
[
My code
import 'package:flutter/material.dart';
class ClaimsScreen extends StatefulWidget {
#override
_ClaimsScreenState createState() => _ClaimsScreenState();
}
class _ClaimsScreenState extends State<ClaimsScreen> {
final List _claims = [
{
'av': '27,000',
'cv': '25,000',
'cqno': '3442121',
'status': 'CLAIM PAYMENT PRCESSED',
'cno': '00651211',
},
{
'av': '29,000',
'cv': '25,000',
'cqno': '3442121',
'status': 'CLAIM PAYMENT PRCESSED',
'cno': '00651211',
},
];
#override
Widget build(BuildContext context) {
double statusBarHeight = MediaQuery.of(context).padding.top;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Expanded(
child: Container(
child: new CustomScrollView(
scrollDirection: Axis.vertical,
slivers: <Widget>[
new SliverAppBar(
backgroundColor: Colors.white,
expandedHeight: statusBarHeight * 5,
flexibleSpace: new FlexibleSpaceBar(
title: const Text(
'Claims',
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 20,
color: Color(0xff00AEF0),
fontWeight: FontWeight.bold),
),
),
),
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
sliver: new SliverFixedExtentList(
itemExtent: 150.0,
delegate: new SliverChildBuilderDelegate(
(builder, index) => BenefitList(index),
childCount: _claims.length),
)),
],
),
),
);
}
Widget BenefitList(int index) {
double statusBarHeight = MediaQuery.of(context).padding.top;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Container(
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 30,
child: Container(
child: Padding(
padding: const EdgeInsets.only(right: 10, left: 10, top: 10),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text(
'Approved Value : ',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Text(
_claims[index]['av'],
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff00AEF0)),
),
],
),
SizedBox(height: height* 0.005,),
Row(
children: <Widget>[
Text(
'Claim Value : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['cv'],
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff00AEF0)),
),
],
),
SizedBox(height: height* 0.005,),
Row(
children: <Widget>[
Text(
'Claim No : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['cno'],
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff00AEF0)),
),
],
),
Row(
children: <Widget>[
Text(
'Cheque Number : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['cqno'],
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff00AEF0)),
),
],
),
SizedBox(height: height* 0.005,),
Row(
children: <Widget>[
Text(
'Status : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['status'],
style: TextStyle(
fontWeight: FontWeight.bold, color: Color(0xff00AEF0)),
)
],
)
],
),
),
),
),
);
}
}
I try to increase the number if itemExtent but it's just increasing the height of card not increasing the gap. I just need to add some gap between each card so when they increase it will automatically show some gap between them. Also, I try to add margin in Container but its also not working
By default SliverFixedExtentList has no gaps between its items. Consider using SliverList instead. Also FYI the new keyword is optional and does not need to be used.
You can copy paste run full code below
You can use Padding and EdgeInsets.only(top: 30)
return Padding(
padding: EdgeInsets.only(top: 30),
child: Container(
child: Card(
working demo
full code
import 'package:flutter/material.dart';
class ClaimsScreen extends StatefulWidget {
#override
_ClaimsScreenState createState() => _ClaimsScreenState();
}
class _ClaimsScreenState extends State<ClaimsScreen> {
final List _claims = [
{
'av': '27,000',
'cv': '25,000',
'cqno': '3442121',
'status': 'CLAIM PAYMENT PRCESSED',
'cno': '00651211',
},
{
'av': '29,000',
'cv': '25,000',
'cqno': '3442121',
'status': 'CLAIM PAYMENT PRCESSED',
'cno': '00651211',
},
];
#override
Widget build(BuildContext context) {
double statusBarHeight = MediaQuery.of(context).padding.top;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Expanded(
child: Container(
child: new CustomScrollView(
scrollDirection: Axis.vertical,
slivers: <Widget>[
new SliverAppBar(
backgroundColor: Colors.white,
expandedHeight: statusBarHeight * 5,
flexibleSpace: new FlexibleSpaceBar(
title: const Text(
'Claims',
textAlign: TextAlign.left,
style: TextStyle(
fontSize: 20,
color: Color(0xff00AEF0),
fontWeight: FontWeight.bold),
),
),
),
new SliverPadding(
padding: const EdgeInsets.symmetric(vertical: 20.0),
sliver: new SliverFixedExtentList(
itemExtent: 150.0,
delegate: new SliverChildBuilderDelegate(
(builder, index) => BenefitList(index),
childCount: _claims.length),
)),
],
),
),
);
}
Widget BenefitList(int index) {
double statusBarHeight = MediaQuery.of(context).padding.top;
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Padding(
padding: EdgeInsets.only(top: 30),
child: Container(
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
elevation: 30,
child: Container(
child: Padding(
padding: const EdgeInsets.only(right: 10, left: 10, top: 10),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text(
'Approved Value : ',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
Text(
_claims[index]['av'],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color(0xff00AEF0)),
),
],
),
SizedBox(
height: height * 0.005,
),
Row(
children: <Widget>[
Text(
'Claim Value : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['cv'],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color(0xff00AEF0)),
),
],
),
SizedBox(
height: height * 0.005,
),
Row(
children: <Widget>[
Text(
'Claim No : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['cno'],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color(0xff00AEF0)),
),
],
),
Row(
children: <Widget>[
Text(
'Cheque Number : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['cqno'],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color(0xff00AEF0)),
),
],
),
SizedBox(
height: height * 0.005,
),
Row(
children: <Widget>[
Text(
'Status : ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Text(
_claims[index]['status'],
style: TextStyle(
fontWeight: FontWeight.bold,
color: Color(0xff00AEF0)),
)
],
)
],
),
),
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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 _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ClaimsScreen(),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Flutter: Updating UI from outside of a StatefulWidget

I am new to flutter, and working on a shopping cart project. i don't know how exatly i am suppose to ask this question but, here is what i wanted.
I am trying to update my UI when the cart item and prices changes, which means to display sum amount of products from ListView (Stateful widget) to main OrderPage Stateful widget. I know about setState() method, but i think i should use some callback methods here, dont know exactly.
I have explained in short in Image - see below img
What i have done: when user modify cart products, I have saved the value (price/product/count) in to constant value , i calculate the value and save in constant value, and later use that const var in Main widget (Main Ui), which does update when i close and reopen the page, but could not able to update when button pressed (product +/-buttons)
What i want to do is,
Update my total value when +/- buttons are pressed.
Here is my full code:
class cartConstant{
static int packageCount;
static List<int> list;
}
class OrderPage extends StatefulWidget {
#override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
int data = 3;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(
color: Colors.black54, //change your color here
),
backgroundColor: Colors.white,
elevation: 1,
title: Text("Your order Summery",style: TextStyle(color: Colors.black54),),
centerTitle: true,
),
body: Container(
child:
FutureBuilder(
builder: (context, snapshot){
// var datas = snapshot.data;
return
ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: data,
itemBuilder: (BuildContext context, int index){
// Cart cart = datas[index];
return CartListView();
},
padding: EdgeInsets.symmetric(horizontal: 10.0),
scrollDirection: Axis.vertical,
);
},
),
),
bottomNavigationBar: _buildTotalContainer(),
);
}
Widget _buildTotalContainer() {
return Container(
height: 220.0,
padding: EdgeInsets.only(
left: 10.0,
right: 10.0,
),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 15,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Discount",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"0.0",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 10.0,
),
Divider(
height: 2.0,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Cart Total",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SignInPage()));
},
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(35.0),
),
child: Center(
child: Text(
"Proceed To Checkout",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
SizedBox(
height: 20.0,
),
],
),
);
}
}
class CartListView extends StatefulWidget {
#override
_CartListViewState createState() => _CartListViewState();
}
class _CartListViewState extends State<CartListView> {
int _counter = 1;
int getPrice(int i,int priceC){
cartConstant.packageCount = i*priceC;
return cartConstant.packageCount;
}
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFD3D3D3), width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: (){
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
},
child: Icon(Icons.add, color: Color(0xFFD3D3D3))),
Text(
"$_counter",
style: TextStyle(fontSize: 18.0, color: Colors.grey),
),
InkWell(
onTap:(){
setState(() {
_counter--;
if (_counter < 2) {
_counter = 1;
}
});
},
child: Icon(Icons.remove, color: Color(0xFFD3D3D3))),
],
),
),
),
SizedBox(
width: 20.0,
),
Container(
height: 70.0,
width: 70.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/food.jpg"),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(35.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 5.0,
offset: Offset(0.0, 2.0))
]),
),
SizedBox(
width: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Employee Package",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 5.0),
SizedBox(height: 5.0),
Container(
height: 25.0,
width: 120.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
children: <Widget>[
Text("Price",
style: TextStyle(
color: Color(0xFFD3D3D3),
fontWeight: FontWeight.bold)),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {},
child: Text(
getPrice(_counter, 2000).toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
width: 10.0,
),
],
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {
},
child: Icon(
Icons.cancel,
color: Colors.grey,
),
),
],
),
),
);
}
}
you can also check from my cart screen shot below:
You can copy paste run full code below
You can use callback refresh() and pass callback to CartListView
code snippet
class _OrderPageState extends State<OrderPage> {
int data = 3;
void refresh() {
setState(() {});
}
...
itemBuilder: (BuildContext context, int index) {
// Cart cart = datas[index];
return CartListView(refresh);
},
...
class CartListView extends StatefulWidget {
VoidCallback callback;
CartListView(this.callback);
...
InkWell(
onTap: () {
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
widget.callback();
},
working demo
full code
import 'package:flutter/material.dart';
class cartConstant {
static int packageCount;
static List<int> list;
}
class OrderPage extends StatefulWidget {
#override
_OrderPageState createState() => _OrderPageState();
}
class _OrderPageState extends State<OrderPage> {
int data = 3;
void refresh() {
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
automaticallyImplyLeading: true,
iconTheme: IconThemeData(
color: Colors.black54, //change your color here
),
backgroundColor: Colors.white,
elevation: 1,
title: Text(
"Your order Summery",
style: TextStyle(color: Colors.black54),
),
centerTitle: true,
),
body: Container(
child: FutureBuilder(
builder: (context, snapshot) {
// var datas = snapshot.data;
return ListView.builder(
physics: ClampingScrollPhysics(),
shrinkWrap: true,
itemCount: data,
itemBuilder: (BuildContext context, int index) {
// Cart cart = datas[index];
return CartListView(refresh);
},
padding: EdgeInsets.symmetric(horizontal: 10.0),
scrollDirection: Axis.vertical,
);
},
),
),
bottomNavigationBar: _buildTotalContainer(),
);
}
Widget _buildTotalContainer() {
return Container(
height: 220.0,
padding: EdgeInsets.only(
left: 10.0,
right: 10.0,
),
child: Column(
children: <Widget>[
SizedBox(
height: 10.0,
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Subtotal",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
cartConstant.packageCount.toString(),
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
),
SizedBox(
height: 15,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Discount",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"0.0",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 10.0,
),
Divider(
height: 2.0,
),
SizedBox(
height: 20.0,
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Cart Total",
style: TextStyle(
color: Color(0xFF9BA7C6),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
Text(
"8000",
style: TextStyle(
color: Color(0xFF6C6D6D),
fontSize: 16.0,
fontWeight: FontWeight.bold),
),
],
),
SizedBox(
height: 20.0,
),
GestureDetector(
onTap: () {
// Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context) => SignInPage()));
},
child: Container(
height: 50.0,
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(35.0),
),
child: Center(
child: Text(
"Proceed To Checkout",
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
),
SizedBox(
height: 20.0,
),
],
),
);
}
}
class CartListView extends StatefulWidget {
VoidCallback callback;
CartListView(this.callback);
#override
_CartListViewState createState() => _CartListViewState();
}
class _CartListViewState extends State<CartListView> {
int _counter = 1;
int getPrice(int i, int priceC) {
cartConstant.packageCount = i * priceC;
return cartConstant.packageCount;
}
#override
Widget build(BuildContext context) {
return Card(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: Row(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xFFD3D3D3), width: 2.0),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: () {
setState(() {
_counter++;
if (_counter > 20) {
_counter = 20;
}
});
widget.callback();
},
child: Icon(Icons.add, color: Color(0xFFD3D3D3))),
Text(
"$_counter",
style: TextStyle(fontSize: 18.0, color: Colors.grey),
),
InkWell(
onTap: () {
setState(() {
_counter--;
if (_counter < 2) {
_counter = 1;
}
});
widget.callback();
},
child: Icon(Icons.remove, color: Color(0xFFD3D3D3))),
],
),
),
),
SizedBox(
width: 20.0,
),
Container(
height: 70.0,
width: 70.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/food.jpg"),
fit: BoxFit.cover),
borderRadius: BorderRadius.circular(35.0),
boxShadow: [
BoxShadow(
color: Colors.black54,
blurRadius: 5.0,
offset: Offset(0.0, 2.0))
]),
),
SizedBox(
width: 20.0,
),
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Employee Package",
style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 5.0),
SizedBox(height: 5.0),
Container(
height: 25.0,
width: 120.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Row(
children: <Widget>[
Text("Price",
style: TextStyle(
color: Color(0xFFD3D3D3),
fontWeight: FontWeight.bold)),
SizedBox(
width: 5.0,
),
InkWell(
onTap: () {},
child: Text(
getPrice(_counter, 2000).toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.red,
),
),
),
SizedBox(
width: 10.0,
),
],
),
],
),
),
],
),
Spacer(),
GestureDetector(
onTap: () {},
child: Icon(
Icons.cancel,
color: Colors.grey,
),
),
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: OrderPage(),
);
}
}
When the button is tapped, you just need to update the Subtotal amount and cart total.
Step 1 : Replace the harcoded value by a variable. So, something like :
Row(
children: <Widget>[
Text(
"Subtotal",
style: ...
),
Text(
"$subTotal",
style: ....
),
],
),
Step 2 : Now, add a code to calcualte subTotal and cartTotal. You already have code which increments and decrements the variable _counter. You just need to tweak that part like :
setState( (){
_counter++;
// So, the quantity is increased. Just get the price of current item and add in the sub total.
subTotal += priceC;
cartTotal = subTotal - discount;
} );