How to solve flutter page is not showing properly - flutter

I am currently working on an E-Commerce app. I have made my Homepage which shows the available products and a HomeDetailPage which shows the details of a single product when a user clicks on a particular product. Now the problem is my entire app is working finely in my Pixel-5 Emulator but the HomeDetailPage is not Working in my actual device when I install the app in my personal phone. I am currently using Samsung A50 as my actual device I dont understand what is wrong in this code
Here is the Code For Homepage:-
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_application_1/pages/homedetal.dart';
import 'package:flutter_application_1/products.dart';
class Homepage extends StatefulWidget {
const Homepage({Key? key}) : super(key: key);
#override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
getdata() async {
var catalogdata = await rootBundle.loadString("assets/files/products.json");
var catalogjson = await jsonDecode(catalogdata);
var productdata = catalogjson["products"];
ProductsModel.productlist =
List.from(productdata).map<Item>((item) => Item.fromMap(item)).toList();
setState(() {});
}
#override
void initState() {
// TODO: implement initState
getdata();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
// key: ProductsModel.scaffoldKey,
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(right: 32.0, left: 32.0, top: 32.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
'TonyShop',
style: TextStyle(
fontSize: 45,
color: Colors.deepPurple,
fontWeight: FontWeight.bold),
),
IconButton(
onPressed: () {
Navigator.pushNamed(context, "/login");
},
icon: Icon(
Icons.arrow_forward,
color: Colors.deepPurple,
))
],
),
),
Padding(
padding:
const EdgeInsets.only(right: 32.0, left: 32.0, bottom: 32.0),
child: Text(
'Trending products',
style: TextStyle(
fontSize: 20,
color: Colors.deepPurple,
fontWeight: FontWeight.bold),
),
),
// SizedBox(
// height: 20,
// ),
Expanded(
child: ListView.builder(
shrinkWrap: true,
physics: AlwaysScrollableScrollPhysics(),
itemCount: ProductsModel.productlist.length,
itemBuilder: (context, index) {
final catalog = ProductsModel.productlist[index];
return Material(
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
HomeDetailPage(singleitem: catalog),
));
},
child:
Itemwidget(item: ProductsModel.productlist[index])),
);
},
),
)
],
),
));
}
}
class Itemwidget extends StatefulWidget {
final Item item;
const Itemwidget({
Key? key,
required this.item,
}) : super(key: key);
#override
State<Itemwidget> createState() => _ItemwidgetState();
}
class _ItemwidgetState extends State<Itemwidget> {
#override
Widget build(BuildContext context) {
return Material(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
color: Color.fromARGB(255, 255, 255, 255),
borderRadius: BorderRadius.all(Radius.circular(20.0))),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Container(
height: 120,
width: 120,
child: Hero(
tag: Key(widget.item.id.toString()),
child: Image.network(widget.item.image)),
),
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Container(
width: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.item.name,
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold),
),
Container(
child: Text(
widget.item.desc,
style: TextStyle(
fontSize: 12, fontWeight: FontWeight.normal),
),
width: 150,
),
SizedBox(
height: 10,
),
ButtonBar(
buttonPadding: EdgeInsets.all(0.0),
alignment: MainAxisAlignment.spaceBetween,
children: [
Text(
widget.item.price.toString(),
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => HomeDetailPage(
singleitem: widget.item)));
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Color.fromRGBO(
0,
0,
0,
1,
)),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(16.0)))),
child: Text(
"Buy",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
)
],
)
],
),
),
)
],
),
),
),
),
);
}
}
And Here is my Code for HomeDetailPage:-
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_application_1/pages/home.dart';
import 'package:flutter_application_1/products.dart';
class HomeDetailPage extends StatefulWidget {
const HomeDetailPage({
Key? key,
required this.singleitem,
}) : super(key: key);
final Item singleitem;
#override
State<HomeDetailPage> createState() => _HomeDetailPageState();
}
class _HomeDetailPageState extends State<HomeDetailPage> {
Future<bool> _previousroute() {
// important trick to handle backbutton press;
return Future(() => Navigator.canPop(context));
}
#override
Widget build(BuildContext context) {
// Variables for getting the height and width of the screen
double h = MediaQuery.of(context).size.height;
double w = MediaQuery.of(context).size.width;
return WillPopScope(
onWillPop: () => _previousroute(),
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
shadowColor: Colors.white,
elevation: 0,
leading: IconButton(
icon: Icon(Icons.arrow_back_ios),
color: Colors.black,
onPressed: () {
Navigator.pop(context);
},
)),
// key: ProductsModel.scaffoldKey,
body: Container(
height: h,
child: Flexible(
fit: FlexFit.tight,
child: SingleChildScrollView(
padding: EdgeInsets.all(0.0),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ClipPath(
clipper: Clipper(),
child: Container(
decoration: BoxDecoration(
color: Color.fromARGB(255, 240, 240, 245),
),
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Hero(
tag: Key(widget.singleitem.id.toString()),
child: Image.network(widget.singleitem.image)),
),
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
widget.singleitem.name,
style: TextStyle(
color: Colors.black,
fontSize: 30,
fontWeight: FontWeight.bold),
),
],
),
),
Padding(
padding: const EdgeInsets.all(16.0),
child: Text(
widget.singleitem.desc,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.normal),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(left: 4.0, right: 4.0),
child: Container(
width: w,
// box decoration does not work with button
// decoration: BoxDecoration(
// borderRadius: BorderRadius.circular(32.0)),
child: ElevatedButton(
onPressed: () {
showDialog(
context: context,
builder: (context) {
return Container(
child: AlertDialog(
actions: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Your Order Is On The Way",
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold),
),
),
Row(
mainAxisAlignment:
MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
onPressed: () {
// Used to create ok button
Navigator.of(context).pop();
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(
Color.fromRGBO(
0,
0,
0,
1,
)),
shape: MaterialStateProperty
.all(RoundedRectangleBorder(
borderRadius:
BorderRadius
.circular(
16.0)))),
child: Text(
"Ok",
style: TextStyle(
fontSize: 20,
fontWeight:
FontWeight.bold),
),
),
)
],
)
],
));
});
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Color.fromRGBO(
0,
0,
0,
1,
)),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16.0),
))),
child: Text(
"Buy",
style: TextStyle(
color: Colors.white,
fontSize: 25,
fontWeight: FontWeight.bold),
),
),
),
),
)
],
),
),
),
),
),
);
}
}
class Clipper extends CustomClipper<Path> {
#override
Path getClip(Size size) {
// TODO: implement getClip
var path = new Path();
// fixed or unchanged points of the container
path.lineTo(0, 0);
path.lineTo(size.width, 0);
path.lineTo(size.width, size.height - 20);
path.quadraticBezierTo(
//point creating the curve radius
size.width / 2,
size.height + 20,
// starting point of the curve
0,
size.height - 20);
return path;
}
#override
bool shouldReclip(covariant CustomClipper<Path> oldClipper) {
// TODO: implement shouldReclip
return false;
}
}
Here is my Products model class
import 'package:flutter/material.dart';
class ProductsModel {
static List productlist = [];
static final GlobalKey<ScaffoldState> scaffoldKey =
GlobalKey<ScaffoldState>();
}
class Item {
late final int id;
late final String name;
late final String desc;
late final int price;
late final String color;
late final String image;
Item({
required this.id,
required this.name,
required this.desc,
required this.price,
required this.color,
required this.image,
});
factory Item.fromMap(map) {
return Item(
id: map["id"],
name: map["name"],
desc: map["desc"],
price: map["price"],
color: map["color"],
image: map["image"]);
}
}
In case that if you want to try this yourself Here is my dummy product.json file code for you:-
{
"products": [
{
"id": 1,
"name": "iPhone 12 Pro",
"desc": "Apple iPhone 12th generation",
"price": 999,
"color": "#33505a",
"image": "https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/iphone-12-pro-blue-hero?wid=940&hei=1112&fmt=png-alpha&qlt=80&.v=1604021661000"
},
{
"id": 2,
"name": "Pixel 5",
"desc": "Google Pixel phone 5th generation",
"price": 699,
"color": "#00ac51",
"image": "https://www.telstra.com.au/content/dam/tcom/lego/2020/plans-devices/mobiles/google-pixel-5/shared-google-pixel-5-black-05-900x1200.png"
},
{
"id": 3,
"name": "M1 Macbook Air",
"desc": "Apple Macbook air with apple silicon",
"price": 1099,
"color": "#e0bfae",
"image": "https://support.apple.com/library/APPLE/APPLECARE_ALLGEOS/SP825/macbookair.png"
},
{
"id": 4,
"name": "Playstation 5",
"desc": "Sony Playstation 5th generation",
"price": 500,
"color": "#544ee4",
"image": "https://i1.wp.com/freepngimages.com/wp-content/uploads/2020/07/Playstation-5-games-console-transparent-background-png-image.png?fit=1000%2C1000"
},
{
"id": 5,
"name": "Airpods Pro",
"desc": "Apple Aipods Pro 1st generation",
"price": 200,
"color": "#e3e4e9",
"image": "https://crdms.images.consumerreports.org/c_lfill,w_598/prod/products/cr/models/400116-wireless-portable-headphones-apple-airpods-pro-10009323.png"
},
{
"id": 6,
"name": "iPad Pro",
"desc": "Apple iPad Pro 2020 edition",
"price": 799,
"color": "#f73984",
"image": "https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/ipad-pro-12-select-wifi-silver-202003_FMT_WHH?wid=940&hei=1112&fmt=png-alpha&qlt=80&.v=1583551131102"
},
{
"id": 7,
"name": "Galaxy S21 Ultra",
"desc": "Samsung Galaxy S21 Ultra 2021 edition",
"price": 1299,
"color": "#1c1c1c",
"image": "https://lh3.googleusercontent.com/qRQPjHrhRVIs-xnfNSyiPXOH2vH97ylMacgbTKebqJtRfNH3LlYo8pN-5igsLDWUH62tGl5zNpTsl5xd8SprzGmXoCEmWFOi2-2cQVGS-r3PaRXHt62DmJHq-jrYX0UQvWZ9BA=s800-c"
},
{
"id": 8,
"name": "Galaxy S21",
"desc": "Samsung Galaxy S21 2021 edition",
"price": 899,
"color": "#7c95eb",
"image": "https://images.samsung.com/is/image/samsung/p6pim/za/galaxy-s21/gallery/za-clear-cover-galaxy-s21-5g-ef-qg991ttegww-363168624?$720_576_PNG$"
}
]
}
In my emulator it looks like this Emulator Image
In my Device it looks like this Device Image

It's because of expanded widget in HomeDetailsScreen, you can use Flexible instead of expanded like that:
Flexible(
fit: FlexFit.tight,
child: ...,
);

Related

use variables of one class in another class Flutter

# cartmodel
`class CartModel extends ChangeNotifier {
// list of items on sale
final List _shopItems = const [
// [ itemName, itemPrice, imagePath, color ]
["Avocado", "4", "assets/images/avocado.png", Colors.green],
["Banana", "2", "assets/images/banana.png", Colors.yellow],
["pollo", "12", "assets/images/chicken.png", Colors.brown],
["acqua", "1", "assets/images/water.png", Colors.blue],
["mela", "3", "assets/images/mela.png", Colors.red],
["broccoli", "3", "assets/images/broccoli.png", Colors.brown],
];
final List _faidate = const [
["Avocado", "14000", "assets/images/avocado.png", Colors.orange],
["Banana", "2", "assets/images/banana.png", Colors.blueGrey],
["pollo", "12", "assets/images/chicken.png", Colors.red],
["acqua", "1", "assets/images/water.png", Colors.blue],
];
// list of cart items
final List _cartItems = [];
get faidate => _faidate;
get cartItems => _cartItems;
get shopItems => _shopItems;
// add item to cart
void addItemToCart(int index) {
_cartItems.add(_shopItems[index]);
notifyListeners();
}
// remove item from cart
void removeItemFromCart(int index) {
_cartItems.removeAt(index);
notifyListeners();
}
// calculate total price
String calculateTotal() {
double totalPrice = 0;
for (int i = 0; i < cartItems.length; i++) {
totalPrice += double.parse(cartItems[i][1].toString());
}
return totalPrice.toStringAsFixed(2);
}
}`
cartpage
`class CartPage extends StatelessWidget {
CartPage({
Key? key,
}) : super(key: key);
#override
Widget build(BuildContext context) {
Device.screenType == ScreenType.tablet;
return Container(
width: 100.w,
height: 90.5.h,
child: Container(
width: 100.w,
height: 20.5.h,
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
iconTheme: IconThemeData(
color: Colors.grey[800],
),
),
body: Consumer<CartModel>(
builder: (context, value, child) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Let's order fresh items for you
Padding(
padding: EdgeInsets.symmetric(horizontal: 24.0),
child: Text(
"Cart",
style: GoogleFonts.notoSerif(
fontSize: 36,
fontWeight: FontWeight.bold,
),
),
),
// list view of cart
Expanded(
child: Padding(
padding: const EdgeInsets.all(12.0),
child: ListView.builder(
itemCount: (value.cartItems.length),
padding: EdgeInsets.all(12),
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(12.0),
child: Container(
decoration: BoxDecoration(
color: Colors.grey[200],
borderRadius: BorderRadius.circular(8)),
child: ListTile(
leading: Image.asset(
value.cartItems[index][2],
height: 36,
),
title: Text(
value.cartItems[index][0],
style: const TextStyle(fontSize: 18),
),
subtitle: Text(
'\points ' + value.cartItems[index][1],
style: const TextStyle(fontSize: 12),
),
trailing: IconButton(
icon: const Icon(Icons.cancel),
onPressed: () => Provider.of<CartModel>(
context,
listen: false)
.removeItemFromCart(index),
),
),
),
);
},
),
),
),
// total amount + pay now
Padding(
padding: const EdgeInsets.all(25.0),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.blueGrey[900]),
padding: const EdgeInsets.all(24),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'total price',
style: TextStyle(color: Colors.green[200]),
),
const SizedBox(height: 8),
// total price
Text(
'\Points ${value.calculateTotal()}',
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
// pay now
Container(
),
padding: const EdgeInsets.all(1),
child: Row(
children: [
ElevatedButton(
onPressed: () {},
child: const Text('order now')),
],
),
),
],
),
),
)
],
);
},
),
),
),
);
}
}
`
# points page
`class points extends StatefulWidget {
points({Key? key,}) :super(key: key);
_pointsState createState() => _pointsState();
}
class _pointsState extends State<points> {
int _points = 0;
#override
void initState() {
super.initState();
_loadPunti();
}
_loadPunti() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_points = (prefs.getInt('points') ?? 0);
});
}
_savePunti() async {
await FirebaseFirestore.instance.collection('xxxx').add({
'Points': _points,
});
}
other code...
hi all, I was looking for a solution for this test of a flutter shopping app and I'm having problems in being able to use the "points" variable in the cart page to be able to confirm a purchase on the "onpressed" in the cartpage, I also attached the cartmodel like this to be able to verify. Thank you all

Display TickMark widget depending on String and boolean value in Dart

Need to display icon with checkmark based on a String value that comes dynamically.
Like
this image is its pending show first widget with tick and rest are blank.
if delivered show with tick and the rest are blank.
Facing problems in creating logic using enums.
Currently, it displays the icons on button clicks
based on four constants which is fine with the widget CheckStatus.
Need to make in a way based on a boolean check if it's true and pending that pending tick widget displayed
and similar with other values.
Here is the complete code for it currently.
import 'package:dotted_border/dotted_border.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:matab/models/order.dart';
import 'package:matab/ui/general_widgets/check_status.dart';
import 'package:matab/ui/pages/styles.dart';
import '../../general_widgets/custom_gradient_button.dart';
class TrackOrder extends StatefulWidget {
const TrackOrder({Key? key, required this.order}) : super(key: key);
final Order order;
#override
State<TrackOrder> createState() => _TrackOrderState();
}
enum Status { Pending, Confirmed, Shipped, Received }
class _TrackOrderState extends State<TrackOrder> {
static const darkGreyColor = Colors.grey;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Center(child: Text('Track Order')),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => Get.back(),
),
),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(height: 50),
Text(
"Order ID:" + widget.order.orderID,
style: const TextStyle(
color: darkGreyColor,
fontSize: 18,
fontWeight: FontWeight.bold),
),
const SizedBox(height: 50),
const Text('Sat, 12 Mar 2022',
style: TextStyle(
color: darkGreyColor,
fontSize: 18,
fontWeight: FontWeight.bold)),
const SizedBox(
height: 15,
),
Container(
margin: const EdgeInsets.fromLTRB(15, 0, 0, 0),
child: const Text('Estimated Time: 07 Days',
style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold)),
),
const SizedBox(height: 30),
SizedBox(
width: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
OrderStatusBar(title: widget.order.orderStatus, status: true),
dottedLine(),
OrderStatusBar(
title: widget.order.orderStatus, status: false),
dottedLine(),
OrderStatusBar(
title: widget.order.orderStatus, status: false),
dottedLine(),
OrderStatusBar(
title: widget.order.orderStatus, status: false),
],
),
),
const SizedBox(
height: 40,
),
Container(
margin: const EdgeInsets.fromLTRB(15, 0, 0, 0),
child: const Text('Shipping Address',
style: TextStyle(fontSize: 23, fontWeight: FontWeight.bold)),
),
Center(
child: Text(widget.order.deliveryAddress.address,
style: const TextStyle(
color: Colors.grey,
fontSize: 18,
fontWeight: FontWeight.bold)),
),
Center(
child: Padding(
padding: const EdgeInsets.all(
50.0,
),
child: CustomGradientButton(
buttonText: "Track Order".tr, buttonFunction: () => {}),
),
),
Center(
child: Padding(
padding: const EdgeInsets.only(top: 18.0),
child: GestureDetector(
child: Text(
'Back to Home'.tr,
style: TextStyle(
color: mainColor,
fontSize: 23,
fontWeight: FontWeight.bold),
),
onTap: () => {
Get.off(CheckStatus(
order: widget.order,
))
},
),
),
)
],
),
),
);
}
}
class OrderStatusBar extends StatefulWidget {
const OrderStatusBar({Key? key, required this.title, required this.status})
: super(key: key);
final String title;
final bool status;
#override
State<OrderStatusBar> createState() => _OrderStatusBarState();
}
class _OrderStatusBarState extends State<OrderStatusBar> {
#override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.rtl,
child: Row(
children: [
widget.status ? dottedCircleWithCheckMark() : dottedCircle(),
const SizedBox(width: 30),
Text(
widget.title.tr,
style: TextStyle(
fontSize: 20,
fontWeight: widget.status ? FontWeight.bold : null,
),
),
],
),
);
}
}
const size = 25.0;
const strokeWidth = 1.0;
const checkedColor = Color.fromRGBO(232, 113, 65, 1);
Widget dottedLine() {
return Directionality(
textDirection: TextDirection.rtl,
child: Align(
alignment: Alignment.topRight,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 0, size / 2, 0),
child: const Padding(
padding: EdgeInsets.only(left: 27 / 2),
child: SizedBox(
height: size,
child: DottedLine(
dashColor: Colors.black,
direction: Axis.vertical,
lineLength: size,
lineThickness: strokeWidth,
dashLength: 5,
dashGapLength: 5,
),
),
),
),
),
);
}
dottedCircle() {
return DottedBorder(
borderType: BorderType.Circle,
dashPattern: const [5, 5],
child: Container(
height: size,
width: size,
decoration: const BoxDecoration(shape: BoxShape.circle),
));
}
dottedCircleWithCheckMark() {
return Container(
height: size + strokeWidth * 2,
width: size + strokeWidth * 2,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: checkedColor,
),
child: const Icon(
Icons.check,
color: Colors.white,
size: size / 4 * 3,
),
);
}
// ignore_for_file: constant_identifier_names
class CheckStatus extends StatefulWidget {
const CheckStatus({Key? key, required this.order}) : super(key: key);
final Order order;
#override
State<CheckStatus> createState() => _CheckStatusState();
}
class _CheckStatusState extends State<CheckStatus> {
int selectedItemIndex = 0;
var pending = Status.Pending;
List<bool> orderStatus = [true,true,true,false];
#override
void initState() {
// TODO: implement initState
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
for (int i = 0; i < Status.values.length; i++)
ElevatedButton(
onPressed: () {
selectedItemIndex = i;
setState(() {});
},
child: Text("Order Status ${Status.values[i]}"),
),
Row(
children: [
for (int i = 0; i <= selectedItemIndex; i++)
Container(
height: size + strokeWidth * 2,
width: size + strokeWidth * 2,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: checkedColor,
),
child: const Icon(
Icons.check,
color: Colors.white,
size: size / 4 * 3,
),
),
ElevatedButton(onPressed: () {}, child: Text("Back"))
],
)
],
),
);
}
}

I have made Grid View in Flutter now how can I make option as selectable and push selected option to firebase database

[Grid View in flutter][1]
[1]: https://i.stack.imgur.com/Xj1CO.jpg
I have to make a grid view in the flutter where users can see options they can select. But I am getting errors in selecting the option and sending the selected option to the firebase database. This is the code where I have made gridview and set the option which user can select it but I am facing problem in option selection and sending selected option to firebase database.
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
const SizedBox(
height: 20,
),
const Text(
"What are you trying to improve on?",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
color: Color.fromARGB(255, 57, 57, 57),
),
),
const SizedBox(
height: 15,
),
const Text(
"Tell us more about your goal. Select maximum four from below.",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.w400,
color: Color.fromARGB(255, 184, 184, 184),
),
),
const SizedBox(
height: 12.0,
),
const Padding(
padding: EdgeInsets.all(24.0),
child: GridB(),
),
ElevatedButton(
onPressed: () {},
style: ElevatedButton.styleFrom(
minimumSize: Size(350.0, 50.0),
textStyle:
TextStyle(fontSize: 17, fontWeight: FontWeight.w700)),
child: const Text("Next"),
)
],
),
),
),
);
}
}
class GridB extends StatefulWidget {
const GridB({Key? key}) : super(key: key);
#override
State<GridB> createState() => _GridBState();
}
class _GridBState extends State<GridB> {
final List<Map<String, dynamic>> gridMap = [
{
"title": "Negotiation",
},
{
"title": "Influencing Others",
},
{
"title": "Managing Up",
},
{
"title": "First-time Manager",
},
{
"title": "Time Management",
},
{
"title": "Prioritization",
},
{
"title": "Communication",
},
{
"title": "Crucial Conversation",
},
{
"title": "Engagement at work",
},
{
"title": "Stackeholder satisfaction",
}
];
#override
Widget build(BuildContext context) {
return GridView.builder(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10.0,
mainAxisSpacing: 10.0,
childAspectRatio: 2,
),
itemCount: gridMap.length,
itemBuilder: (_, index) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(
16.0,
),
color: const Color.fromARGB(255, 231, 231, 231),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"${gridMap.elementAt(index)['title']}",
style: Theme.of(context).textTheme.subtitle1!.merge(
const TextStyle(
color: Color.fromARGB(255, 90, 89, 89),
fontFamily: "Open Sans",
fontSize: 16,
fontWeight: FontWeight.w400,
),
),
),
],
),
),
],
),
);
},
);
}
}

How to change the background color of an item in a list when using the function List.generate in flutter

function description: when an item is clicked, change the background color of this item 。
I defined the variable color in the List.generate function and used the setState function in onTapDown to modify this value, but it has no effect. what should I do?
my code is as follows
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class Homepage extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Homepage> {
final titles = ["AAA", "BBB", "CCC", "DDD"];
final subtitles = [
"我去,额度这么高?",
"XX,你上次给我兑换的烤箱还不错哦",
"抱歉,我觉得我们不是很合适",
"邻居你好,你家的租户最近有点吵"
];
final date = ["昨天 18:08", "星期二", "7月21日", "7月19日"];
final avatar = [
"WechatIMG325.jpeg",
"WechatIMG326.jpeg",
"WechatIMG327.jpeg",
"WechatIMG328.jpeg"
];
// final icons = [Icons.ac_unit, Icons.access_alarm, Icons.access_time];
#override
Widget build(BuildContext context) {
return Column(
children: [
...List.generate(titles.length, (index) {
var color = Colors.white;
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails details) {
setState(() {
color = Colors.grey;
});
debugPrint("presed GestureDetector");
},
onTapUp: (TapUpDetails details) {
setState(() {
color = Colors.white;
});
debugPrint("presed GestureDetector");
},
child: Container(
color: color,
margin: const EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Row(children: [
SizedBox(
width: 50,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: Image.asset("assets/images/${avatar[index]}",
height: 50, width: 50),
),
),
),
//const SizedBox(width: 10),
IntrinsicWidth(
child: Container(
margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
titles[index],
style: const TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.w300,
),
),
const SizedBox(height: 5),
Text(
subtitles[index],
style: const TextStyle(
fontSize: 15,
color: Colors.black54,
fontWeight: FontWeight.w300,
),
),
],
),
),
),
]),
),
);
}),
],
);
}
}
try this code will help you to start in OOP and make model to data in your app and you can add any thing to class like Icon ....
class FakeData {
final String title, subTitle, avatar, data;
bool onTapDown;
FakeData(
{required this.title,
this.onTapDown = false,
required this.subTitle,
required this.avatar,
required this.data});
}
this class collect data app and state for all item
class HomeState extends State<Homepage> {
final fakeData = [
FakeData(
title: 'AAA',
subTitle: '我去,额度这么高?',
avatar: "WechatIMG325.jpeg",
data: "昨天 18:08",
),
FakeData(
title: 'BBB',
subTitle: "XX,你上次给我兑换的烤箱还不错哦",
avatar: "WechatIMG326.jpeg",
data: "星期二",
),
FakeData(
title: 'CCC',
subTitle: "抱歉,我觉得我们不是很合适",
avatar: "WechatIMG327.jpeg",
data: "7月21日",
),
FakeData(
title: 'DDD',
subTitle: "邻居你好,你家的租户最近有点吵",
avatar: "WechatIMG328.jpeg",
data: "7月19日",
),
];
// final icons = [Icons.ac_unit, Icons.access_alarm, Icons.access_time];
#override
Widget build(BuildContext context) {
return Column(
children: [
...List.generate(fakeData.length, (index) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails details) {
setState(() {
fakeData[index].onTapDown = !fakeData[index].onTapDown;
});
debugPrint("presed GestureDetector");
},
onTapUp: (TapUpDetails details) {
setState(() {
fakeData[index].onTapDown = !fakeData[index].onTapDown;
});
debugPrint("presed GestureDetector");
},
child: Container(
color: fakeData[index].onTapDown ? Colors.grey : Colors.white,
margin: const EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Row(children: [
SizedBox(
width: 50,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: Image.asset(
"assets/images/${fakeData[index].avatar}",
height: 50,
width: 50),
),
),
),
//const SizedBox(width: 10),
IntrinsicWidth(
child: Container(
margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
fakeData[index].title,
style: const TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.w300,
),
),
const SizedBox(height: 5),
Text(
fakeData[index].subTitle,
style: const TextStyle(
fontSize: 15,
color: Colors.black54,
fontWeight: FontWeight.w300,
),
),
],
),
),
),
]),
),
);
}),
],
);
}
}
The variable color needs to be outside the build method of the State, this code will reset the color to Colors.white on each build.
import 'package:flutter/material.dart';
class Homepage extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Homepage> {
final titles = ["AAA", "BBB", "CCC", "DDD"];
final subtitles = [
"我去,额度这么高?",
"XX,你上次给我兑换的烤箱还不错哦",
"抱歉,我觉得我们不是很合适",
"邻居你好,你家的租户最近有点吵"
];
final date = ["昨天 18:08", "星期二", "7月21日", "7月19日"];
final avatar = [
"WechatIMG325.jpeg",
"WechatIMG326.jpeg",
"WechatIMG327.jpeg",
"WechatIMG328.jpeg"
];
var color = Colors.white;
// final icons = [Icons.ac_unit, Icons.access_alarm, Icons.access_time];
#override
Widget build(BuildContext context) {
return Column(
children: [
...List.generate(titles.length, (index) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails details) {
setState(() {
color = Colors.grey;
});
debugPrint("presed GestureDetector");
},
onTapUp: (TapUpDetails details) {
setState(() {
color = Colors.white;
});
debugPrint("presed GestureDetector");
},
child: Container(
color: color,
margin: const EdgeInsets.fromLTRB(10, 0, 10, 0),
child: Row(children: [
SizedBox(
width: 50,
child: Container(
margin: const EdgeInsets.fromLTRB(0, 10, 0, 10),
child: ClipRRect(
borderRadius: BorderRadius.circular(5.0),
child: Image.asset("assets/images/${avatar[index]}",
height: 50, width: 50),
),
),
),
//const SizedBox(width: 10),
IntrinsicWidth(
child: Container(
margin: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
titles[index],
style: const TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: FontWeight.w300,
),
),
const SizedBox(height: 5),
Text(
subtitles[index],
style: const TextStyle(
fontSize: 15,
color: Colors.black54,
fontWeight: FontWeight.w300,
),
),
],
),
),
),
]),
),
);
}),
],
);
}
}
The code above should work as our state is extracted outside of the build method and it would update correctly with each setState.

Change the color of options and show different widgets by taping on them in flutter?

I am using flutter. I want to change the color of a particular option when I tap on it, not all the options at the same time. When we press an option its color changes and it shows different widgets below it(like tab bar). The code is attached below. I am glad if someone helps. ..
import 'package:flutter/material.dart';
class cards extends StatelessWidget {
const cards({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Cards"),
),
body: Padding(
padding: const EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
optionCards("A", "assets/icons/recycle.png", context),
optionCards("B", "assets/icons/tools.png", context),
optionCards("C", "assets/icons/file.png", context),
],
),
),
);
}
Widget optionCards(
String text,
String assetImage,
BuildContext context,
) {
return Container(
width: 100,
height: 100,
decoration: const ShapeDecoration(
color: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5),
),
),
),
child: SingleChildScrollView(
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(top: 13),
child: IconButton(
onPressed: null,
icon: Icon(Icons.file_copy),
),
),
Text(
text,
style: const TextStyle(
fontSize: 14,
fontFamily: 'CeraPro',
color: Color.fromRGBO(0, 0, 0, 1),
),
)
],
),
),
);
}
}
Maintain state for holding selected Tab.
Your code is updated with Tab bar Feasibility.
Updated Code:
import 'package:flutter/material.dart';
class Card extends StatefulWidget {
const Card({Key? key}) : super(key: key);
#override
State<Card> createState() => _CardState();
}
class _CardState extends State<Card> {
String selectedCard = '1';
#override
Widget build(BuildContext context) {
final List<dynamic> tabOptionsList = [
{"id": "1", "text": "A options"},
{"id": "2", "text": "B options"},
{"id": "3", "text": "C options"}
];
final selectedTabValue = tabOptionsList
.where((element) => element['id'] == selectedCard)
.toList()[0]['text'];
print(selectedTabValue);
return Scaffold(
appBar: AppBar(
title: const Text("Cards"),
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
optionCards("A", "assets/icons/recycle.png", context, "1"),
optionCards("B", "assets/icons/tools.png", context, "2"),
optionCards("C", "assets/icons/file.png", context, "3"),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
selectedTabValue,
style: const TextStyle(color: Colors.red),
),
),
],
),
);
}
Widget optionCards(
String text, String assetImage, BuildContext context, String cardId) {
return GestureDetector(
onTap: () {
setState(() {
selectedCard = cardId;
});
},
child: Container(
width: 100,
height: 100,
decoration: ShapeDecoration(
color: cardId == selectedCard ? Colors.green : Colors.grey,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(5),
),
),
),
child: SingleChildScrollView(
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(top: 13),
child: IconButton(
onPressed: null,
icon: Icon(Icons.file_copy),
),
),
Text(
text,
style: const TextStyle(
fontSize: 14,
fontFamily: 'CeraPro',
color: Color.fromRGBO(0, 0, 0, 1),
),
)
],
),
),
),
);
}
}