Related
In below code at the end of the code I have created one widget but when I am passing doc to the widget its breaking the code by opening box.dart and errors_patch.dart files I couldn't get where I am making mistake.In list view builder i have checked for length of file.
First I have to show icon and when tapped on Icon it should open the dialogue box with image inside it
class PanDetails extends StatefulWidget {
const PanDetails({Key? key}) : super(key: key);
#override
State<PanDetails> createState() => _PanDetailsState();
}
class _PanDetailsState extends State<PanDetails> {
TextEditingController panController = TextEditingController();
List<File?>? panDetailsImages;
List panfiles = \[\];
#override
void initState() {
init();
super.initState();
}
Future init() async {
dynamic companyId = getIt<SharedPreferences>().getString('companyId');
//final docs = DioClient().KycDetails(companyId);
dynamic responseData = await getIt<DioClient>().KycDetails(companyId);
final details = responseData\['data'\];
Pan pandetails = Pan.fromJson(details\['pan'\]);
setState(() {
List<String> panfiles = pandetails.files;
this.panfiles = panfiles;
});
print('panfiles...))))))))))))${panfiles\[0\].toString()}');
}
#override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
double maxHeight = constraints.maxHeight;
double maxWidth = constraints.maxWidth;
double h1p = maxHeight * 0.01;
double h10p = maxHeight * 0.1;
double w10p = maxWidth * 0.1;
double w1p = maxWidth * 0.01;
return SafeArea(
child: Scaffold(
backgroundColor: Colours.black,
appBar: AppBar(
elevation: 0,
automaticallyImplyLeading: false,
toolbarHeight: h10p * .9,
flexibleSpace: AppbarWidget()),
body: Container(
width: maxWidth,
decoration: const BoxDecoration(
color: Colours.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
)),
child: ListView(children: \[
InkWell(
onTap: () {
Navigator.pop(context);
},
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: w1p * 3, vertical: h1p * 3),
child: Row(
children: \[
SvgPicture.asset("assets/images/arrowLeft.svg"),
SizedBox(
width: w10p * .3,
),
const Text(
"PAN Details",
style: TextStyles.leadingText,
),
\],
),
),
),
Padding(
padding: EdgeInsets.only(
left: w1p * 6, right: w1p * 6, top: h1p * 3),
child: Container(
decoration: BoxDecoration(
boxShadow: \[
BoxShadow(
color: Color(0x26000000),
offset: Offset(0, 1),
blurRadius: 1,
spreadRadius: 0)
\],
color: Colours.paleGrey,
),
child: TextFormField(
controller: panController,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
horizontal: w1p * 6, vertical: h1p * .5),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
fillColor: Colours.paleGrey,
hintText: "PAN Number",
hintStyle: TextStyles.textStyle120,
)),
),
),
SizedBox(
height: h1p * 3,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: \[
DocumentUploading(
maxWidth: maxWidth,
maxHeight: maxHeight,
onFileSelection: (files) {
panDetailsImages = files;
setState(() {});
},
),
SizedBox(
width: 40,
height: 50,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: panfiles.length,
itemBuilder: (context, index) {
final doc = panfiles\[index\];
// print(doc);
return GestureDetector(
child: imageDialog(doc.toString()));
},
),
//_checkController();
)
\],
),
InkWell(
onTap: () async {
Map<String, dynamic> panDetails =
await getIt<KycManager>().storePanCardDetails(
panController.text,
filePath:
panDetailsImages?.first?.path ?? "");
Fluttertoast.showToast(msg: panDetails\['msg'\]);
// ScaffoldMessenger.of(context).showSnackBar(SnackBar(
// behavior: SnackBarBehavior.floating,
// content: Text(
// panDetails\['msg'\],
// style: const TextStyle(color: Colors.green),
// )));
if (panDetails\['error'\] == false) {
Navigator.pop(context);
}
},
child: Submitbutton(
maxWidth: maxWidth,
maxHeight: maxHeight,
isKyc: true,
content: "Save & Continue",
))
\]))));
});
}
}
Widget imageDialog(path) {
return Dialog(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: \[
Container(
width: 220,
height: 200,
child: Image.network(
'$path',
fit: BoxFit.cover,
),
),
\],
),[![enter image description here][1]][1]
);
}
Below is my code where two containers used one is for uploading front image another one is for uploading back image.Whenever I uploads any one front or back image another container changes its position and comes little down. I wants to avoid that another container is changing its position and wants to remain another container on its place even if other container changes
Card(
elevation: 5,
child: Column(
children: [
Row(
children: [
InkWell(
// onTap: () => ({
// }),
onTap: () async {
// List<File?>? fileSelection =
// await getIt<KycManager>().selectFile(widget.flag);
// print('=====>File uploaded====>${fileSelection}');
// if (fileSelection?.isEmpty == true ||
// fileSelection == null) {
// Fluttertoast.showToast(msg: "Please select file");
// return;
// }
// setState(() {
// img = fileSelection[0];
// imgpath = '${img?.path}'; //error
// });
// ScaffoldMessenger.of(context).showSnackBar(SnackBar(
// behavior: SnackBarBehavior.floating,
// content: Text(
// fileSelection != null
// ? "Uploaded images ${fileSelection.first}"
// : "",
// style: TextStyle(
// color: fileSelection != null
// ? Colors.green
// : Colors.red),
// )));
// widget.onFileSelection(fileSelection);
FilePickerResult? fileResult = (await FilePicker
.platform
.pickFiles(allowMultiple: false));
String? path = fileResult != null
? fileResult.files.isNotEmpty
? fileResult.files[0].path
: ""
: "";
final File selectFront = File(path as String);
// print(selectFront.readAsBytesSync());
setState(() {
this.frontImage = selectFront;
this.img1 = path.toString();
});
print("front img........$path");
},
child: Column(
children: [
Padding(
padding: EdgeInsets.only(
left: w1p * 6,
right: w1p * 6,
top: h1p * 1),
child: Container(
height: h1p * 6,
width: w10p * 4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Colours.disabledText,
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: w1p * 2,
vertical: h1p * 2),
child: Row(children: [
InkWell(
onTap: () async {
// File? file = File("");
// String filePath = "";
XFile? fileResult =
await ImagePicker()
.pickImage(
source: ImageSource
.camera);
String? path = fileResult !=
null
? fileResult.path.isNotEmpty
? fileResult.path
: ""
: "";
final File selectFront =
File(path as String);
setState(() {
this.frontImage = selectFront;
this.img1 = path.toString();
});
},
child: Container(
child: Center(
child: SvgPicture.asset(
"assets/images/kycImages/camera.svg",
height: h1p * 4),
),
),
),
Text(
'Upload Front Image',
style: TextStyles.textStyle121,
),
]))),
),
this.frontImage != null
? showImage(img1)
: SizedBox()
],
)),
InkWell(
onTap: () async {
FilePickerResult? fileResult = (await FilePicker
.platform
.pickFiles(allowMultiple: false));
String? path = fileResult != null
? fileResult.files.isNotEmpty
? fileResult.files[0].path
: ""
: "";
final File selectBack = File(path as String);
setState(() {
this.backImage = selectBack;
this.img2 = path.toString();
});
},
child: Padding(
padding: EdgeInsets.only(
left: w1p * 2, right: w1p * 3, top: h1p * 1),
child: Column(
children: [
Container(
height: h1p * 6,
width: w10p * 4,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Colours.disabledText,
),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: w1p * 2,
vertical: h1p * 2),
child: Row(children: [
InkWell(
onTap: () async {
XFile? fileResult =
await ImagePicker().pickImage(
source:
ImageSource.camera);
String? path = fileResult != null
? fileResult.path.isNotEmpty
? fileResult.path
: ""
: "";
final File selectBack =
File(path as String);
setState(() {
this.backImage = selectBack;
this.img2 = path.toString();
});
},
child: Container(
child: SvgPicture.asset(
"assets/images/kycImages/camera.svg",
height: h1p * 4,
),
),
),
// ),
Text(
'Upload Back Image',
style: TextStyles.textStyle121,
),
])),
),
this.backImage != null
? showImage(img2)
: SizedBox()
],
),
)),
],
),
Padding(
padding: EdgeInsets.only(
left: w1p * 3,
right: w1p * 6,
),
child: SizedBox(
width: maxWidth,
height: 50,
child: ListView.separated(
separatorBuilder: (context, index) => SizedBox(
width: 220,
),
scrollDirection: Axis.horizontal,
itemCount: imgfiles.length,
itemBuilder: (context, index) {
String doc = imgfiles[index];
print('the whole filepath >>>>>>>>$doc');
List doc1 = doc.split("?");
List doc2 = doc1[0].split(".");
List fpath = doc2;
print('doc1.>>>>>>>>$doc1');
print('fpath.>>>>>>>>$fpath');
final fp = doc2.last;
String filepath = fp.toString();
print('filepath.>>>>>>>>$filepath');
Future<File?> downloadFile(
String url, String name) async {
final appStorage =
await getApplicationDocumentsDirectory();
final file = File('${appStorage.path}/$name');
try {
final response = await Dio().get(url,
options: Options(
responseType: ResponseType.bytes,
followRedirects: false,
receiveTimeout: 0));
final raf = file.openSync(mode: FileMode.write);
raf.writeFromSync(response.data);
await raf.close();
return file;
} catch (e) {
return null;
}
}
Future openFile(
{required String url, String? filename}) async {
final file = await downloadFile(url, filename!);
if (file == null) return;
print(
'path for pdf file++++++++++++ ${file.path}');
OpenFile.open(file.path);
}
// filepath != 'pdf'
// ?
if (filepath != 'pdf') {
print('object++++====');
return GestureDetector(
onTap: () {
showDialog(
context: context,
builder: (context) {
return Dialog(
child: SizedBox(
width: maxWidth * 5,
height: maxHeight * 0.5,
child: Image.network(
// ignore: unnecessary_string_interpolations
'$doc',
fit: BoxFit.cover,
),
),
);
});
},
child: Padding(
padding: EdgeInsets.only(
left: w1p * 6, right: w1p * 6),
child: imageDialog(doc),
));
} else {
return GestureDetector(
onTap: () {
openFile(
url: doc, filename: 'adhaarcard.pdf');
},
child: Padding(
padding: EdgeInsets.only(
left: w1p * 6,
// right: w1p * 6,
),
child: imageDialog(doc),
));
}
},
),
//_checkController();
),
),
Row(
children: [
Padding(
padding: EdgeInsets.only(
left: w1p * 6,
right: w1p * 6,
top: h1p * 2,
bottom: h1p),
child: Align(
alignment: Alignment.topLeft,
child: TextButton(
onPressed: () async {
print(
"aadharfront--${frontImage} backImg --- ${backImage}");
Map<String, dynamic> aadhaar =
await getIt<KycManager>().adhaarDetails(
companyId, frontImage!, backImage!);
setState(() {
this.onPressed == 1;
});
String adharmsg = aadhaar.toString();
String adhaarmsg = adharmsg.substring(4);
Fluttertoast.showToast(
msg: adhaarmsg,
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 3,
backgroundColor:
Color.fromARGB(255, 253, 153, 33),
textColor: Colors.white,
fontSize: 12.0);
},
child: Text(
'CAPTURED',
style: TextStyle(color: Colors.black),
),
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll(
Color.fromARGB(255, 253, 153, 33),
),
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
side: BorderSide(
width: 1,
color: Color.fromARGB(255, 150, 146, 146),
),
))),
),
),
),
SizedBox(
width: maxWidth * 0.1,
),
onPressed == 1
? Padding(
padding: EdgeInsets.only(
left: w1p * 0.03,
right: w1p * 1,
top: h1p * 1),
child: adhaarDetails(),
)
: const SizedBox()
],
),
],
),
),
I think this is happening because you didn't use any constraints.
1st approach you can try.
Align Row Items By using mainAxisAlignment.start
2nd approach can be
Give constraint to The Row (use this approach if above approach not works)
I have my flutter app connected to my firebase proyect and im having trouble logging in, since with my code im not being able to read the collection i created
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({Key? key}) : super(key: key);
#override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
TextEditingController idController = TextEditingController();
TextEditingController passController = TextEditingController();
double screenHeight = 0;
double screenWidth = 0;
Color primary = const Color(0xffeef444c);
late SharedPreferences sharedPreferences;
get HomeScreen => null;
#override
Widget build(BuildContext context) {
final bool isKeyboardVisible =
KeyboardVisibilityProvider.isKeyboardVisible(context);
screenHeight = MediaQuery.of(context).size.height;
screenWidth = MediaQuery.of(context).size.width;
return Scaffold(
resizeToAvoidBottomInset: false,
body: Column(
children: [
isKeyboardVisible
? SizedBox(
height: screenHeight / 16,
)
: Container(
height: screenHeight / 2.5,
width: screenWidth,
decoration: BoxDecoration(
color: primary,
borderRadius: const BorderRadius.only(
bottomRight: Radius.circular(70),
),
),
child: Center(
child: Icon(
Icons.person,
color: Colors.white,
size: screenWidth / 5,
),
),
),
Container(
margin: EdgeInsets.only(
top: screenHeight / 15,
bottom: screenHeight / 20,
),
child: Text(
"Login",
style: TextStyle(
fontSize: screenWidth / 18,
fontFamily: "NexaBold",
),
),
),
Container(
alignment: Alignment.centerLeft,
margin: EdgeInsets.symmetric(
horizontal: screenWidth / 12,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
fieldTitle("Employee ID"),
customField("Enter your employee id", idController, false),
fieldTitle("Password"),
customField("Enter your password", passController, true),
GestureDetector(
onTap: () async {
FocusScope.of(context).unfocus();
String id = idController.text.trim();
String password = passController.text.trim();
if (id.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Employee id is still empty!"),
));
} else if (password.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text("Password is still empty!"),
));
} else {
QuerySnapshot snap = await FirebaseFirestore.instance
.collection("Employee")
.where('id', isEqualTo: id)
.get();
try {
if (password == snap.docs[0]['password']) {
sharedPreferences =
await SharedPreferences.getInstance();
sharedPreferences
.setString('employeeId', id)
.then((_) {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => HomeScreen));
});
} else {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text("Password is not correct!"),
));
}
} catch (e) {
String error = " ";
if (e.toString() ==
"RangeError (index): Invalid value: Valid value range is empty: 0") {
setState(() {
error = "Employee id does not exist!";
});
} else {
setState(() {
error = "Error occurred!";
});
}
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text(error),
));
}
}
},
child: Container(
height: 60,
width: screenWidth,
margin: EdgeInsets.only(top: screenHeight / 40),
decoration: BoxDecoration(
color: primary,
borderRadius: const BorderRadius.all(Radius.circular(30)),
),
child: Center(
child: Text(
"LOGIN",
style: TextStyle(
fontFamily: "NexaBold",
fontSize: screenWidth / 26,
color: Colors.white,
letterSpacing: 2,
),
),
),
),
)
],
),
),
],
),
);
}
Widget fieldTitle(String title) {
return Container(
margin: const EdgeInsets.only(bottom: 12),
child: Text(
title,
style: TextStyle(
fontSize: screenWidth / 26,
fontFamily: "NexaBold",
),
),
);
}
Widget customField(
String hint, TextEditingController controller, bool obscure) {
return Container(
width: screenWidth,
margin: EdgeInsets.only(bottom: 12),
decoration: const BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(12)),
boxShadow: [
BoxShadow(
color: Colors.black26,
blurRadius: 10,
offset: Offset(2, 2),
),
],
),
child: Row(
children: [
Container(
width: screenWidth / 6,
child: Icon(
Icons.person,
color: primary,
size: screenWidth / 15,
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(right: screenWidth / 12),
child: TextFormField(
controller: controller,
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
contentPadding: EdgeInsets.symmetric(
vertical: screenHeight / 35,
),
border: InputBorder.none,
hintText: hint,
),
maxLines: 1,
obscureText: obscure,
),
),
)
],
),
);
}
}
i have a collection called "Employee" with 2 parameters being "id" and "password". Please help and thanks in advance. im getting this error
if (e.toString() == > "RangeError (index): Invalid value: Valid value range is empty: 0") { setState(() { error = "Employee id does not exist!"; > });
which i think it means Im not being able to read the specific Collection, tried enabling internet connection in Android manifest but still not working`
Issue:
I am trying to add items to wishlist and cart on pressing relevant icons of an instrument item card. However, when I tap on them, neither are they getting added to the global lists of wishList and cartList, nor are the wishList and cart icons changing colors to red and blue respectively.
Below are my codes for the relevant .dart files.
home_welcome_screen.dart - The screen which hosts the instrument item cards in a horizontal ListView:
import 'package:flutter/material.dart';
import 'package:musicart/screens/instrument_detail.dart';
import 'package:musicart/screens/wishlist_screen.dart';
import 'package:musicart/widgets/animated_bottom_bar.dart';
import 'package:musicart/widgets/brand_logo_card.dart';
import 'package:musicart/widgets/instrument_card.dart';
import 'package:musicart/widgets/search_widget.dart';
import 'package:musicart/widgets/text_label.dart';
import '../global_variables/global_variables.dart';
import 'package:carousel_slider/carousel_slider.dart';
class HomeWelcomeScreen extends StatefulWidget {
const HomeWelcomeScreen({Key? key}) : super(key: key);
#override
State<HomeWelcomeScreen> createState() => _HomeWelcomeScreenState();
}
class _HomeWelcomeScreenState extends State<HomeWelcomeScreen> {
final TextEditingController _searchBoxController = TextEditingController();
final String _hintText = "Search instruments...";
int _currentIndex = 0;
int _currentCarouselIndex = 0;
#override
Widget build(BuildContext context) {
double? screenWidth = MediaQuery.of(context).size.width;
double? screenHeight = MediaQuery.of(context).size.height;
List<Widget> indicators(imagesLength, currentIndex) {
return List<Widget>.generate(imagesLength, (index) {
return Container(
margin: EdgeInsets.symmetric(
vertical: screenHeight * 0.01,
horizontal: 2,
),
width: currentIndex == index ? 15 : 10,
height: 3,
decoration: BoxDecoration(
color: currentIndex == index ? Colors.black87 : Colors.grey,
borderRadius: const BorderRadius.all(
Radius.circular(2),
),
),
);
});
}
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(top: screenHeight * 0.02),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025, right: screenWidth * 0.19),
child: Image(
image: const AssetImage("../assets/images/logo.png"),
height: 40,
width: screenWidth * 0.25,
),
),
Padding(
padding: EdgeInsets.only(right: screenWidth * 0.025),
child: SearchWidget(
width: screenWidth * 0.3,
onChanged: (p0) {},
searchController: _searchBoxController,
onTap: () {},
hintText: _hintText,
),
),
Padding(
padding: EdgeInsets.only(right: screenWidth * 0.025),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
WishListScreen(mywishList: wishList[0])));
},
child: const Icon(
Icons.favorite_outline_rounded,
color: Colors.black87,
size: 40,
),
),
),
Padding(
padding: EdgeInsets.only(right: screenWidth * 0.025),
child: InkWell(
onTap: () {},
child: const Icon(
Icons.shopping_cart_outlined,
color: Colors.black87,
size: 40,
),
),
),
],
),
Padding(
padding: EdgeInsets.only(top: screenHeight * 0.015),
),
SizedBox(
width: screenWidth,
height: screenHeight,
child: Column(
children: [
Expanded(
child: ListView(
children: [
// Padding(
// padding: EdgeInsets.only(top: screenHeight * 0.01)),
CarouselSlider(
items: carouselImageList.map<Widget>((i) {
return Builder(
builder: (BuildContext context) {
return Container(
width: screenWidth * 0.95,
decoration: BoxDecoration(
image:
DecorationImage(image: NetworkImage(i)),
),
);
},
);
}).toList(),
options: CarouselOptions(
height: screenHeight * 0.25,
aspectRatio: 16 / 9,
autoPlay: true,
autoPlayInterval: const Duration(seconds: 5),
initialPage: 0,
viewportFraction: 1,
onPageChanged: (index, timed) {
setState(() {
_currentCarouselIndex = index;
});
}),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: indicators(
carouselImageList.length, _currentCarouselIndex),
),
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025,
top: screenHeight * 0.005,
),
child: TextLabel(
width: screenWidth * 0.15,
labelText: "Top Brands",
),
),
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025,
top: screenWidth * 0.025),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: screenWidth * 0.025),
child: SizedBox(
height: screenHeight * 0.1,
child: Row(
children: [
Expanded(
child: ListView.builder(
itemCount: brandLogos.length,
scrollDirection: Axis.horizontal,
//shrinkWrap: true,
physics:
const AlwaysScrollableScrollPhysics(),
itemBuilder:
(BuildContext context, int index) {
return BrandLogoCard(
width: screenWidth * 0.33,
height: screenHeight * 0.18,
brandImageUrl: brandLogos[index]
["img-url"],
paddingRight: screenWidth * 0.015);
},
),
),
],
),
),
),
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025,
top: screenWidth * 0.025),
),
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025,
),
child: TextLabel(
width: screenWidth * 0.21,
labelText: "Trending Guitars",
),
),
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025,
top: screenWidth * 0.025),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: screenWidth * 0.025),
child: SizedBox(
height: screenHeight * 0.28,
child: Row(
children: [
Expanded(
child: ListView.builder(
itemCount: instruments.length,
scrollDirection: Axis.horizontal,
//shrinkWrap: true,
physics:
const AlwaysScrollableScrollPhysics(),
itemBuilder:
(BuildContext context, int index) {
return InstrumentCard(
width: screenWidth * 0.4,
height: screenHeight * 0.37,
instrumentImageUrl: instruments[index]
["img-url"],
instrumentName: instruments[index]
["name"],
instrumentMrp:
"₹${instruments[index]["mrp"].toString()}",
instrumentPrice:
"₹${instruments[index]["price"].toString()}",
paddingRight: screenHeight * 0.015,
innerHorizontalSymmetricPadding:
screenWidth * 0.025,
innerVerticalSymmetricPadding:
screenHeight * 0.005,
instrumentDiscount:
"${(((1 - (instruments[index]["price"] / instruments[index]["mrp"])) * 100).round()).toString()}% off",
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
InstrumentDetail(
instrument: instruments[
index])));
},
onWishTap: () {
if (wishList
.contains(instruments[index])) {
setState(() {
wishList.remove(instruments[index]);
});
} else {
setState(() {
wishList.add(instruments[index]);
});
}
},
onCartTap: () {
if (cartList
.contains(instruments[index])) {
setState(() {
cartList.remove(instruments[index]);
});
} else {
setState(() {
cartList.add(instruments[index]);
});
}
},
isWishlisted: (wishList
.contains(instruments[index]))
? true
: false,
isCarted: (cartList
.contains(instruments[index]))
? true
: false,
);
},
),
),
],
),
),
),
Padding(
padding: EdgeInsets.only(
left: screenWidth * 0.025,
top: screenWidth * 0.025),
),
],
),
),
],
),
),
],
),
}
}
instrument_card.dart - The widget for the instrument item displayed on the HomeWelcomeScreen
import 'package:flutter/material.dart';
import 'package:musicart/global_variables/global_variables.dart';
class InstrumentCard extends StatefulWidget {
const InstrumentCard({
Key? key,
required this.width,
required this.height,
required this.instrumentImageUrl,
required this.instrumentName,
required this.instrumentMrp,
required this.instrumentPrice,
required this.paddingRight,
required this.innerHorizontalSymmetricPadding,
required this.innerVerticalSymmetricPadding,
required this.instrumentDiscount,
required this.onTap,
required this.onWishTap,
required this.onCartTap,
required this.isWishlisted,
required this.isCarted,
}) : super(key: key);
final double width;
final double height;
final String instrumentImageUrl;
final String instrumentName;
final String instrumentMrp;
final String instrumentPrice;
final double paddingRight;
final double innerHorizontalSymmetricPadding;
final double innerVerticalSymmetricPadding;
final String instrumentDiscount;
final VoidCallback onTap;
final VoidCallback onWishTap;
final VoidCallback onCartTap;
final bool isWishlisted;
final bool isCarted;
#override
State<InstrumentCard> createState() => _InstrumentCardState();
}
class _InstrumentCardState extends State<InstrumentCard> {
bool isWishlisted = false;
bool isCarted = false;
#override
void initState() {
super.initState();
isWishlisted = widget.isWishlisted;
isCarted = widget.isCarted;
}
#override
Widget build(BuildContext context) {
return InkWell(
onTap: widget.onTap,
child: Padding(
padding: EdgeInsets.only(right: widget.paddingRight),
child: Stack(
children: [
Container(
width: widget.width,
height: widget.height,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey,
width: 0.5,
),
borderRadius: const BorderRadius.all(
Radius.circular(10),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: widget.width,
height: widget.height * 0.5,
decoration: BoxDecoration(
image: DecorationImage(
image: NetworkImage(widget.instrumentImageUrl),
fit: BoxFit.fill,
),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10),
topRight: Radius.circular(10),
),
border: Border.all(color: Colors.grey, width: 0.015),
),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: widget.innerHorizontalSymmetricPadding,
vertical: widget.innerVerticalSymmetricPadding,
),
child: Text(
widget.instrumentName,
style: globalTextStyle.copyWith(
color: Colors.black87,
fontSize: 14,
fontWeight: FontWeight.bold),
),
),
Row(
children: [
Padding(
padding: EdgeInsets.only(left: widget.width * 0.07)),
Text(
widget.instrumentPrice,
style: globalTextStyle.copyWith(
color: Colors.green.shade900,
fontWeight: FontWeight.bold,
fontSize: 14,
),
),
Padding(
padding: EdgeInsets.only(left: widget.width * 0.07)),
Text(
widget.instrumentMrp,
style: globalTextStyle.copyWith(
color: Colors.grey,
fontSize: 12,
decoration: TextDecoration.lineThrough,
),
),
],
),
Padding(padding: EdgeInsets.only(top: widget.height * 0.025)),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
width: widget.width / 2,
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: Colors.grey, width: 0.2),
right: BorderSide(color: Colors.grey, width: 0.2),
),
),
child: InkWell(
onTap: () {
// setState(() {
// isWishlisted = !isWishlisted;
// });
widget.onWishTap;
},
child: Padding(
padding: EdgeInsets.symmetric(
vertical: widget.height * 0.0125),
child: (isWishlisted)
? Icon(
Icons.favorite_rounded,
color: Colors.red.shade900,
)
: const Icon(
Icons.favorite_border_rounded,
color: Colors.black87,
),
),
),
),
Container(
width: widget.width / 2,
decoration: const BoxDecoration(
border: Border(
top: BorderSide(color: Colors.grey, width: 0.2),
right: BorderSide(color: Colors.grey, width: 0.2),
),
),
child: InkWell(
onTap: () {
// setState(() {
// isCarted = !isCarted;
// });
widget.onCartTap;
},
child: Padding(
padding: EdgeInsets.symmetric(
vertical: widget.height * 0.0125),
child: (isCarted)
? Icon(Icons.shopping_cart_rounded,
color: Colors.blue.shade900)
: const Icon(
Icons.shopping_cart_outlined,
color: Colors.black87,
),
),
),
),
],
),
],
),
),
Positioned(
right: 0,
top: widget.height * 0.075,
child: Container(
width: widget.width * 0.25,
height: widget.height * 0.07,
decoration: BoxDecoration(
color: Colors.green.shade900,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(5),
bottomLeft: Radius.circular(5),
),
),
child: Padding(
padding: EdgeInsets.only(
left: widget.width * 0.04,
top: widget.height * 0.016,
),
child: Text(
widget.instrumentDiscount,
style: globalTextStyle.copyWith(
color: Colors.white70,
fontSize: 10,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
),
),
);
}
}
global_variables.dart - a Dart file that contains the list of map elements of instrument items and also has empty lists declared for wishList and cartList where I intend to add/remove instrument items based on tapping the instrument item cards on the HomeWelcomeScreen
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../widgets/animated_bottom_bar.dart';
TextStyle globalTextStyle = GoogleFonts.lato();
const _inactiveColor = Colors.grey;
const _activeColor = Colors.white70;
List<Map<String, dynamic>> brandLogos = [
{
"brand": "fender",
"img-url":
"https://png.pngitem.com/pimgs/s/159-1597814_fender-guitar-hd-png-download.png",
},
{
"brand": "yamaha",
"img-url":
"https://www.motoroids.com/wp-content/uploads/2011/03/Yamaha-logo.jpg",
},
{
"brand": "ibanez",
"img-url":
"https://s0.bukalapak.com/img/57118379431/large/IBANEZ_GUITAR_sticker_logo_ibanez_gitar_stiker_murah_8cm.jpg",
},
{
"brand": "gibson",
"img-url":
"https://i.etsystatic.com/34531699/r/il/cd1ba7/3800299077/il_340x270.3800299077_1e91.jpg",
},
{
"brand": "tama",
"img-url": "https://www.vector-logo.net/logo_preview/eps/t/Tama.png",
},
];
List<Map<String, dynamic>> instruments = [
{
"instrument": "Guitar",
"name": "Fender Stratocaster",
"brand": "Fender",
"mrp": 62000,
"price": 58900,
"rating": 4.7,
"reviews": 11,
"img-url":
"https://cdn.shopify.com/s/files/1/0657/6821/products/FEN-0144522500_grande.jpg?v=1639964521",
},
{
"instrument": "Guitar",
"name": "Squier Bullet Strat",
"brand": "Fender",
"mrp": 17280,
"price": 11900,
"rating": 4.5,
"reviews": 188,
"img-url":
"https://cdn.shopify.com/s/files/1/0657/6821/products/SQUIERBULLETSTRAT_0934fec6-212d-4e8e-84d2-27c52f31c427_large.jpg?v=1653118647",
},
{
"instrument": "Guitar",
"name": "Les Paul Studio LT",
"brand": "Epiphone",
"mrp": 29999,
"price": 24604,
"rating": 4.4,
"reviews": 11,
"img-url":
"https://cdn.shopify.com/s/files/1/0657/6821/products/SQUIERBULLETSTRAT_0934fec6-212d-4e8e-84d2-27c52f31c427_large.jpg?v=1653118647",
},
{
"instrument": "Guitar",
"name": "KX 100 HT",
"brand": "Cort",
"mrp": 21542,
"price": 17176,
"rating": 5.0,
"reviews": 2,
"img-url":
"https://cdn.shopify.com/s/files/1/0657/6821/products/io_large.jpg?v=1640775516",
},
{
"instrument": "Guitar",
"name": "Jet-1",
"brand": "Aria",
"mrp": 15174,
"price": 14416,
"rating": 4.0,
"reviews": 1,
"img-url":
"https://cdn.shopify.com/s/files/1/0657/6821/products/ARI-JET1BK_large.jpg?v=1639700162",
},
];
List<Map<String, dynamic>> wishList = [];
List<Map<String, dynamic>> cartList = [];
My logic so far: I have tried calling VoidCallBack functions which when the relevant UI is tapped on will set the state in which the specific instrument card item will be added/removed from the wishlist or cart lists. Also, I have got two boolean propetries of the InstrumentCard, one each for isWishlisted and isCarted whose values will be toggled betwen true and false based on whether the specific instrument item is present or absent in the wishlist or cart. Their boolean values will be used for rendering the relvant icons (added - red/blue or empty - outlined) for the wishlist and cart.
Request: What is wrong with my logic and how will I add/remove items to the wishlist and cart?
Screenshot for reference:
To call a method inside tap you need to use (). Do it like
onTap: () {
setState(() {
isCarted = !isCarted;
});
widget.onCartTap(); //this
When I upgrade image_picker to image_picker: ^0.8.3+2 then I get some error as below :
The method 'readAsBytesSync' isn't defined for the type 'XFile'.
Try correcting the name to the name of an existing method, or defining a method named 'readAsBytesSync'.
in code
Img.Image image = Img.decodeImage(pickedImage.readAsBytesSync());
Please help to resolve this problem.
Thank you for your help.
full my code are :
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_vector_icons/flutter_vector_icons.dart';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'package:image/image.dart' as Img;
import 'dart:math' as Math;
import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:async/async.dart';
class ProfileScreen extends StatefulWidget {
#override
_ProfileScreenState createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
XFile pickedImage;
ImagePicker _imagePicker = ImagePicker();
File _imageUpload;
String fileName;
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Stack(
fit: StackFit.expand,
children: [
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromRGBO(4, 9, 35, 1),
Color.fromRGBO(39, 105, 171, 1),
],
begin: FractionalOffset.bottomCenter,
end: FractionalOffset.topCenter,
),
),
),
Scaffold(
backgroundColor: Colors.transparent,
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 40),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(
AntDesign.arrowleft,
color: Colors.white,
),
Icon(
AntDesign.logout,
color: Colors.white,
),
],
),
SizedBox(
height: 10,
),
Text(
'My Profile',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontSize: 30,
fontFamily: 'Nisebuschgardens',
),
),
SizedBox(
height: 10,
),
Container(
height: height * 0.43,
child: LayoutBuilder(
builder: (context, constraints) {
double innerHeight = constraints.maxHeight;
double innerWidth = constraints.maxWidth;
return Stack(
fit: StackFit.expand,
children: [
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
height: innerHeight * 0.72,
width: innerWidth,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
child: Column(
children: [
SizedBox(
height: 85,
),
Text(
'I Nyoman Gunartha',
style: TextStyle(
color: Color.fromRGBO(39, 105, 171, 1),
fontFamily: 'Nunito',
fontSize: 25,
),
),
Text(
'NoPeg : 210026',
style: TextStyle(
color: Color.fromRGBO(39, 105, 171, 1),
fontFamily: 'Nunito',
fontSize: 20,
),
),
SizedBox(
height: 10,
),
],
),
),
),
Positioned(
top: 110,
right: 20,
child: Icon(
AntDesign.setting,
color: Colors.grey[700],
size: 30,
),
),
Positioned(
top: 0,
left: 0,
right: 0,
child: Center(
child: Container(
width: 150,
height: 150,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular (100.0),
),
child: pickedImage != null
? Container(
height: 200,
width: 200,
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(100.0),
image: DecorationImage(
image: FileImage(
File(pickedImage.path)),
fit: BoxFit.cover,
),
),
)
: Text('no image'),
),
),
),
],
);
},
),
),
SizedBox(
height: 20,
),
Container(
height: height * 0.3,
width: width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: Colors.white,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 15),
child: Column(
children: [
SizedBox(
height: 20,
),
Text(
'Change Profile',
style: TextStyle(
color: Color.fromRGBO(39, 105, 171, 1),
fontSize: 20,
fontFamily: 'Nunito',
),
),
Divider(
thickness: 2.5,
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
child: Text('Select Image'),
onPressed: () {
_selectImage();
}),
SizedBox(
width: 25,
),
ElevatedButton(
child: Text('Upload'),
onPressed: () {
upload(imageFile: pickedImage);
}),
],
),
],
),
),
)
],
),
),
),
)
],
);
}
void _selectImage() async {
try {
final checkDataImage =
// await _imagePicker.pickImage(source: ImageSource.gallery);
await _imagePicker.pickImage(source: ImageSource.camera);
if (checkDataImage != null) {
print(checkDataImage.name);
print(checkDataImage.path);
setState(() {
pickedImage = checkDataImage;
});
}
} catch (err) {
print(err);
pickedImage = null;
}
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
Img.Image image = Img.decodeImage(pickedImage.readAsBytesSync());
// Img.Image image = Img.decodeImage(pickedImage.readAsBytes());
Img.Image smallerImg = Img.copyResize(image, width: 500);
int rand = new Math.Random().nextInt(999999999);
var compressImg = new File('$path/image_$rand.jpg')
..writeAsBytesSync(Img.encodeJpg(smallerImg, quality: 90));
setState(() {
if (!mounted) return;
_imageUpload = compressImg;
});
}
upload({File imageFile}) async {
// var stream = new http.ByteStream(imageFile.openRead());
// stream.cast();
var stream = http.ByteStream(imageFile.openRead())..cast();
var length = await imageFile.length();
var multipartFile = http.MultipartFile('image', stream, length,
filename: basename(imageFile.path));
var uri = Uri.parse(urlAPI + "upload-image.php");
var request = new http.MultipartRequest("POST", uri);
request.files.add(multipartFile);
try {
var response = await request.send();
if (response.statusCode == 200) {
var responseString = await response.stream.bytesToString();
print(responseString);
}
} catch (e) {
print('Network issue: ' + e.toString());
}
}
}
You should use the readAsBytes method, which return a Future:
Img.Image image = Img.decodeImage(await pickedImage.readAsBytes());
just use List<int> imageBytes = await image.readAsBytes();