Flutter : Persist Data - flutter

I am building an online shop. I have a counter[-]0[+] next to every product on the home page. I am able to add and remove products to the cart but when I switch to a different screen, my counter on the home page is reset back to 0. I would like to keep that data persistent. what would be the best way to achieve this?
cart_counter.dart
import 'package:flutter/material.dart';
import '../providers/cart.dart';
import 'package:provider/provider.dart';
import '../providers/products.dart';
class CartCounter extends StatefulWidget {
const CartCounter({Key? key}) : super(key: key);
#override
_CartCounterState createState() => _CartCounterState();
}
class _CartCounterState extends State<CartCounter> {
int numOfItems = 0;
#override
Widget build(BuildContext context) {
final product = Provider.of<Product>(context, listen: false);
final cart = Provider.of<Cart>(context, listen: false);
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CounterButton(
icon: Icons.remove,
onPress: () {
if (numOfItems > 0) {
setState(() {
numOfItems--;
});
cart.removeSingleItem(product.id);
}
},
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 13.0),
child: Text(
numOfItems.toString(),
style: const TextStyle(
fontSize: 20.0,
),
),
),
CounterButton(
icon: Icons.add,
onPress: () {
setState(() {
numOfItems++;
cart.addItem(
product.id,
product.price,
product.title,
);
});
},
),
],
);
}
}
class CounterButton extends StatelessWidget {
final IconData icon;
final void Function() onPress;
const CounterButton({
Key? key,
required this.icon,
required this.onPress,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return SizedBox(
width: 60.0,
height: 45.0,
child: OutlinedButton(
style: OutlinedButton.styleFrom(
elevation: 2,
backgroundColor: Theme.of(context).primaryColor,
primary: Theme.of(context).primaryColor,
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
onPressed: onPress,
child: Icon(
icon,
color: Colors.white,
size: 30.0,
),
),
);
}
}
product_item.dart
import 'package:flutter/material.dart';
import 'cart_counter.dart';
class ProductItem extends StatelessWidget {
final String id;
final String title;
final double price;
final String image;
const ProductItem(this.id, this.title, this.price, this.image, {Key? key})
: super(key: key);
#override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
child: Card(
elevation: 2.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
child: Column(
children: [
Row(
children: [
Container(
height: 50,
width: 70.0,
decoration: BoxDecoration(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(20.0),
bottomRight: Radius.circular(20.0),
),
color: Theme.of(context).primaryColor,
),
child: Center(
child: Text(
title,
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
color: Colors.white,
),
),
),
),
],
),
Image.asset(image),
const SizedBox(
height: 10.0,
),
Text(
price.toStringAsFixed(2),
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.0,
),
),
const SizedBox(
height: 10.0,
),
const CartCounter(),
const SizedBox(
height: 20.0,
),
],
),
),
);
}
}

Use Shared Preferences or Secure Storage to store the values.
See this answer to a similar question.

Related

How to add a TextButton inside ProfileListItem in flutter

how i create a text button inside profile list item?
please check the code and help to create a text button i edited previous code because 2 person said that they need to see my ProfileListItem
i tried to add a TextButton inside ProfileListItem but i can't. here is my code how i create a text
button inside profile list item?
Expanded(
child: ListView(
children: const <Widget>[
ProfileListItem(
icon: LineAwesomeIcons.lock,
text: 'Privacy',
hasNavigation: true,
),
class ProfileListItem extends StatelessWidget {
final IconData icon;
final text;
final bool hasNavigation;
const ProfileListItem({
Key? key,
required this.icon,
this.text,
required this.hasNavigation,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: kSpacingUnit.w * 5.5,
margin: EdgeInsets.symmetric(horizontal: kSpacingUnit.w * 4)
.copyWith(bottom: kSpacingUnit.w * 2),
padding: EdgeInsets.symmetric(horizontal: kSpacingUnit.w * 2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(kSpacingUnit.w * 3),
//color: Theme.of(context).backgroundColor,
color: AppColors.deep_orange,
),
child: Row(children: <Widget>[
Icon(
this.icon,
size: kSpacingUnit.w * 2.5,
),
SizedBox(width: kSpacingUnit.w * 2.5),
Text(
this.text,
style: kTitleTextStyle.copyWith(fontWeight: FontWeight.w500),
),
Row(
children: <Widget>[
Icon(
this.icon,
size: kSpacingUnit.w * 2.5,
),
SizedBox(width: kSpacingUnit.w * 2.5),
Text(
this.text,
style: kTitleTextStyle.copyWith(fontWeight: FontWeight.w500),
),
],
),
]));
}
}
Please try the below code :
class ProfileListItem extends StatelessWidget {
final IconData icon;
final String? text;
final bool hasNavigation;
const ProfileListItem({
Key? key,
required this.icon,
this.text,
required this.hasNavigation,
}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container(
height: 10.h,
// margin:
// EdgeInsets.symmetric(horizontal: 10.w * 4).copyWith(bottom: 10 * 2),
// padding: EdgeInsets.symmetric(horizontal: 10.w * 2),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10 * 3),
//color: Theme.of(context).backgroundColor,
color: Colors.deepOrange,
),
child: Row(children: [
TextButton(
onPressed: () {},
child: Text(
text ?? "",
style: const TextStyle(fontSize: 12),
),
),
Expanded(
child: TextButton(
onPressed: () {},
child: Row(
children: <Widget>[
Icon(
icon,
size: 20,
color: Colors.white,
),
Text(
text ?? "",
style: const TextStyle(
fontSize: 12,
color: Colors.white,
),
),
],
),
),
),
]));
}
}
For more detail see here : https://api.flutter.dev/flutter/material/TextButton-class.html

Add labels, title or texts to side navigation bar menu items on Flutter

With the following code, I create the structure for the Navigation Bar items on Flutter, and all of it works fine, but I can't make the 'text', 'labels', or 'titles' to be visible right next to the font awesome icons. Some of the parameters, which are the ones commented on, don't work either. Is there any functional way to do so?
Widget build(BuildContext context) {
return Container(
height: 350.0,
child: Column(
children: [
NavBarItem(
active: selected[0],
fontAwesomeIcons: FontAwesomeIcons.user,
text: 'sdfg',
touched: () {
setState(() {
select(0);
});
},
),
NavBarItem(
text: 'dfgdfg',
active: selected[1],
fontAwesomeIcons: FontAwesomeIcons.user,
touched: () {
setState(() {
select(1);
});
},
),
NavBarItem(
text: 'sdfgsdf',
active: selected[2],
fontAwesomeIcons: FontAwesomeIcons.user,
touched: () {
setState(() {
select(2);
});
},
),
NavBarItem(
text: 'ertdsf',
active: selected[3],
fontAwesomeIcons: FontAwesomeIcons.user,
touched: () {
setState(() {
select(3);
});
},
),
],
),
);
}
}
class NavBarItem extends StatefulWidget {
final IconData fontAwesomeIcons;
final Function touched;
final bool active;
final color = Colors.white;
final hoverColor = Colors.green;
// final String title;
// final Text title;
NavBarItem(
{
// required this.title,
required this.active,
required this.fontAwesomeIcons,
required this.touched,
required String text
// required String label
});
#override
_NavBarItemState createState() => _NavBarItemState();
}
class _NavBarItemState extends State<NavBarItem> {
#override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
widget.touched();
},
splashColor: Colors.white,
hoverColor: Colors.white12,
child: Container(
padding: EdgeInsets.symmetric(vertical: 3.0),
child: Row(
children: [
Container(
height: 60.0,
width: 80.0,
child: Row(
children: [
AnimatedContainer(
duration: Duration(milliseconds: 475),
height: 35.0,
width: 5.0,
decoration: BoxDecoration(
color:
widget.active ? Colors.white : Colors.transparent,
borderRadius: BorderRadius.only(
topRight: Radius.circular(10.0),
bottomRight: Radius.circular(10.0))),
),
Padding(
padding: EdgeInsets.only(left: 30.0),
child: Icon(
widget.fontAwesomeIcons,
color: widget.active ? Colors.white : Colors.white54,
size: 20.0,
),
),
],
),
)
],
),
),
),
);
}
}
Not sure what exactly you are looking for, but I don't see you adding Text widget in the row. And adding the width to container will hide other widgets.
class NavBarItem extends StatefulWidget {
final IconData fontAwesomeIcons;
final Function touched;
final bool active;
final color = Colors.white;
final hoverColor = Colors.green;
final String text;
NavBarItem(
{
required this.active,
required this.fontAwesomeIcons,
required this.touched,
required this.text
});
#override
_NavBarItemState createState() => _NavBarItemState();
}
class _NavBarItemState extends State<NavBarItem> {
#override
Widget build(BuildContext context) {
return Material(
color: Colors.transparent,
child: InkWell(
onTap: () {
widget.touched();
},
splashColor: Colors.white,
hoverColor: Colors.white12,
child: Container(
height: 60,
padding: const EdgeInsets.symmetric(vertical: 3.0),
alignment: Alignment.centerLeft,
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: [
AnimatedContainer(
duration: const Duration(milliseconds: 475),
height: 35.0,
width: 5.0,
decoration: BoxDecoration(
color:
widget.active ? Colors.white : Colors.transparent,
borderRadius: const BorderRadius.only(
topRight: Radius.circular(10.0),
bottomRight: Radius.circular(10.0))),
),
Padding(
padding: const EdgeInsets.only(left: 30.0),
child: Icon(
widget.fontAwesomeIcons,
color: widget.active ? Colors.white : Colors.white54,
size: 20.0,
),
),
const SizedBox(width: 16),
Text(widget.text),
],
),
),
),
);
}
}

How to achieve animated search app bar in flutter?

I want to achieve the animated search app bar: https://drive.google.com/file/d/1BnykuOZExHusxIRgareKmdaPM6RlswYe/view?usp=sharing
I tried to use a stack and an animated container, to achieve it. however, it was giving renderflex error.
I would like to know if anyone has other suggestions to achieve it.
Following is the code for the custom appbar and search widget:
AppBar:
class CustomHomeAppBar extends ConsumerStatefulWidget with PreferredSizeWidget {
#override
final Size preferredSize;
CustomHomeAppBar({Key? key, required this.title})
: preferredSize = const Size.fromHeight(60.0),
super(key: key);
final String title;
#override
ConsumerState<ConsumerStatefulWidget> createState() =>
_CustomHomeAppBarState();
}
class _CustomHomeAppBarState extends ConsumerState<CustomHomeAppBar> {
#override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
elevation: 0,
title: Stack(children: [
Row(
mainAxisSize: MainAxisSize.min,
children: [
InkWell(
onTap: () {},
child: const CircleAvatar(
radius: 18,
backgroundColor: Colors.teal,
child: CircleAvatar(
backgroundImage: NetworkImage(
"https://images.unsplash.com/photo-1494790108377-be9c29b29330?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=687&q=80"),
radius: 28,
),
),
),
const SizedBox(
width: 10,
),
Text(
widget.title,
style:
const TextStyle(fontWeight: FontWeight.w400, fontSize: 22),
),
],
),
Positioned(right: 0, child: AnimatedSearchBar())
]));
}
}
search widget:
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
class AnimatedSearchBar extends StatefulWidget {
const AnimatedSearchBar({Key? key}) : super(key: key);
#override
State<AnimatedSearchBar> createState() => _AnimatedSearchBarState();
}
class _AnimatedSearchBarState extends State<AnimatedSearchBar> {
bool _folded = true;
#override
Widget build(BuildContext context) {
return AnimatedContainer(
duration: const Duration(milliseconds: 400),
width: _folded ? 24 : MediaQuery.of(context).size.width - 16,
// height: 56,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(32),
color: Colors.white,
),
child: Row(children: [
Expanded(
child: Container(
// padding: const EdgeInsets.only(left: 16),
decoration:
BoxDecoration(color: Color.fromARGB(255, 212, 207, 207)),
child: !_folded
? const TextField(
decoration: InputDecoration(
hintText: 'Search',
hintStyle: TextStyle(color: Colors.blue),
border: InputBorder.none))
: null,
),
),
AnimatedContainer(
duration: const Duration(milliseconds: 400),
child: InkWell(
onTap: () {
print("clicks");
setState(() {
_folded = !_folded;
});
},
// child: Padding(
// padding: const EdgeInsets.all(16.0),
child: Icon(
_folded ? Icons.search : Icons.close,
color: Colors.blue[900],
),
),
),
// )
]),
);
}
}
It results in the following appbar:
search with stack

Change TabbarView in Flutter When pressed button from another class and also need to make swipe-able

Hey I m new in flutter now m stuck with the tab bar I have four files (Class), the first one is the parent file and the other three files(Class) are the child.
Now I want to change tabbarview when I clicked the button from the child class.
I also shared my sample code please help me.
This is My Parent Class
class AddItemTab extends StatefulWidget {
const AddItemTab({Key? key}) : super(key: key);
#override
_AddItemTabState createState() => _AddItemTabState();
}
class _AddItemTabState extends State<AddItemTab> {
final List<Widget> _fragments = [
const ProductPurchase(),
const ProtectionProduct(),
const RoomProduct()
];
int _page = 0;
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
backgroundColor: MyColor.backgroundColor,
body: Padding(
padding: const EdgeInsets.only(
top: 50.0, right: 20.0, left: 20.0, bottom: 20.0),
child: Container(
child: Column(
children: [
Row(
children: [
Align(
alignment: Alignment.centerLeft,
child: IconButton(
padding: EdgeInsets.zero,
constraints: BoxConstraints(),
onPressed: () {
Navigator.of(context).pop();
},
icon: const Icon(Icons.arrow_back_ios),
),
),
Text("Back"),
],
),
SizedBox(
height: 15,
),
const Align(
alignment: Alignment.centerLeft,
child: Text(
'Add an item',
style: TextStyle(
color: Colors.black,
fontSize: 34,
fontFamily: 'Inter',
fontWeight: FontWeight.w700,
),
)),
const SizedBox(
height: 15,
),
Container(
height: 55,
width: double.infinity,
child: const TabBar(
indicator: BoxDecoration(
color: MyColor.buttonColor,
borderRadius: BorderRadius.all(
Radius.circular(5),
),
),
indicatorWeight: 5,
indicatorPadding: EdgeInsets.only(top:50),
// controller: _tabController,
labelColor: Colors.black,
tabs: [
Tab(
child: Text(
"Purchase",
textAlign: TextAlign.center,
),
),
Tab(
text: 'Protection',
),
Tab(
text: 'Room',
),
],
),
),
const SizedBox(height: 20),
Expanded(
child: TabBarView(
children: [
_fragments[0],
_fragments[1],
_fragments[2],
],
))
],
),
),
)),
);
}
}
This is My Child Class
class ProductPurchase extends StatefulWidget {
const ProductPurchase({Key? key}) : super(key: key);
#override
_ProductPurchaseState createState() => _ProductPurchaseState();
}
class _ProductPurchaseState extends State<ProductPurchase> {
final List<Widget> _fragments = [
const ProtectionProduct(),
];
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: MyColor.backgroundColor,
body: Stack(
children: [
Padding(
padding: EdgeInsets.only(bottom: 50),
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
elevation: 5,
),
onPressed: () {
// Navigator.of(context).push(MaterialPageRoute(
// builder: (context) => ProductView()));
// _fragments[0];
},
child: Ink(
decoration: BoxDecoration(
color: MyColor.buttonColor,
borderRadius: BorderRadius.circular(10)),
child: Container(
width: 250,
padding: const EdgeInsets.all(15),
constraints: const BoxConstraints(minWidth: 88.0),
child: const Text('Go To Next Tabbar View',
textAlign: TextAlign.center,`enter code here`
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
),
),
],
),
);
}
}
You need to use TabController for this , while you already have tab Bar and tab Bar view, you can do it like
class _AddItemTabState extends State<AddItemTab>
with SingleTickerProviderStateMixin {
final List<Widget> _fragments = [
.....
];
late final TabController controller = TabController(length: 3, vsync: this);
#override
Widget build(BuildContext context) {
........
child: TabBar(
controller: controller,
......
Expanded(
child: TabBarView(
controller: controller,
And to move n index, here 2
onPressed: () {
controller.animateTo(2);
},
To call from different widget using callback method
class ProductPurchase extends StatefulWidget {
final VoidCallback callback;
const ProductPurchase({Key? key, required this.callback}) : super(key: key);
.....
onPressed: (){
widget.callback();
},
Once you used this widget, provide
ProductPurchase(callback: (){
controller.animateTo(2);
},);
class ProductPurchase extends StatefulWidget {
final VoidCallback callback;
const ProductPurchase({Key? key, required this.callback}) : super(key: key);
#override
_ProductPurchaseState createState() => _ProductPurchaseState();
}
class _ProductPurchaseState extends State<ProductPurchase> {
#override
Widget build(BuildContext context) {
return Scaffold(
// backgroundColor: MyColor.backgroundColor,
body: Stack(
children: [
Padding(
padding: EdgeInsets.only(bottom: 50),
child: Align(
alignment: Alignment.bottomCenter,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
padding: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
elevation: 5,
),
onPressed: () {
widget.callback(); //this
},
child: Ink(
decoration: BoxDecoration(
color: MyColor.buttonColor,
borderRadius: BorderRadius.circular(10)),
child: Container(
width: 250,
padding: const EdgeInsets.all(15),
constraints: const BoxConstraints(minWidth: 88.0),
child: const Text('Go To Next Tabbar View',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white)),
),
),
),
),
),
],
),
);
}
}
And fragments
late final List<Widget> _fragments = [
ProductPurchase(
callback: () {
controller.animateTo(3);
},
),
Container(color: Colors.cyanAccent, child: Stack(children: [Text("fsA")])),
Text("2A")
];
More about TabBar

Creating a custom Flutter DropDown button as a separate widget

I am working on a Flutter project, which has multiple dropdown buttons on different pages. I have created a custom dropdown button and it's working fine. But when I try to make it a separate widget (to use in other pages) in a file having some errors. below is the code I tried.
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
#override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
List<Activities> _activities = [
Activities(id: 1, icon: Icons.place, title: 'Travel'),
Activities(id: 2, icon: Icons.food_bank, title: 'Eat'),
];
List<DropdownMenuItem<Activities>> activityListDropDownItems = [];
Activities selectedActivity;
int selectedActivityId = 0;
String selectedActivityTitle = '';
IconData selectedActivityIcon = Icons.addchart;
List<DropdownMenuItem<Activities>> buildActivityList(List activities) {
List<DropdownMenuItem<Activities>> items = [];
for (Activities activity in activities) {
items.add(
DropdownMenuItem(
value: activity,
child: Row(
children: [
Text(
'${activity.title}',
style: TextStyle(
color: Colors.red,
),
),
],
),
),
);
}
return items;
}
onChangeActivityListDropDownItem(Activities selected) {
setState(() {
selectedActivity = selected;
selectedActivityId = selected.id;
selectedActivityTitle = selected.title;
selectedActivityIcon = selected.icon;
});
}
#override
void initState() {
activityListDropDownItems = buildActivityList(_activities);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Custom DropDown'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('$selectedActivityTitle'),
SizedBox(height: 10.0),
Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.grey,
width: 0.3,
),
borderRadius: BorderRadius.all(
Radius.circular(
30.0,
),
),
),
child: Row(
children: [
SizedBox(width: 10.0),
Icon(
selectedActivityIcon,
color: Colors.red.withOpacity(0.7),
),
SizedBox(width: 10.0),
Expanded(
child: DropdownButton(
hint: Text(
'Activity',
style: TextStyle(),
),
isExpanded: true,
value: selectedActivity,
items: activityListDropDownItems,
onChanged: onChangeActivityListDropDownItem,
underline: Container(),
),
)
],
),
),
SizedBox(height: 20.0),
//MyDropDown(
// value: selectedActivity,
// items: activityListDropDownItems,
// onChanged: onChangeActivityListDropDownItem,
//),
],
),
),
);
}
}
class MyDropDown extends StatelessWidget {
final List<DropdownMenuItem> items;
final IconData icon;
final dynamic value;
final String hintText;
final ValueChanged onChanged;
const MyDropDown(
{Key key,
#required this.items,
this.icon,
this.value,
this.hintText,
this.onChanged})
: super(key: key);
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 10.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Colors.grey,
width: 0.3,
),
borderRadius: BorderRadius.all(
Radius.circular(
30.0,
),
),
),
child: Row(
children: [
SizedBox(width: 10.0),
Icon(
icon,
color: Colors.red.withOpacity(0.7),
),
SizedBox(width: 10.0),
Expanded(
child: DropdownButton(
hint: Text(
hintText,
style: TextStyle(),
),
isExpanded: true,
value: value,
items: items,
onChanged: onChanged,
underline: Container(),
),
)
],
),
);
}
}
class Activities {
final int id;
final IconData icon;
final String title;
Activities({#required this.id, #required this.icon, #required this.title});
}
when I use the MyDropDown shown an error. How to pass value and onChanged to DropdownButton?
MyDropDown(
value: selectedActivity,
items: activityListDropDownItems,
onChanged: onChangeActivityListDropDownItem,
),
Your value expects a datetype dynamic while your passing Activities
class MyDropDown<T> extends StatelessWidget {
final T value;
const MyDropDown({Key key, this.value}) : super(key: key);
#override
Widget build(BuildContext context) {
return Container();
}
}
Declare Object type
MyDropDown<Activies>(
value: selectedActivity,
items: activityListDropDownItems,
onChanged: onChangeActivityListDropDownItem,
),