Related
I am currently working on an E-commerce Application, I am facing a little problem in getting the Total Cart Value.
I have implemented a counter and when I press the "+" button the counter value increments but the cartTotal does not get incremented. But when I navigate back and then again come back to the cart page the value gets incremented. So I want to fix this, I want real-time updation of CartTotal.
NOTE: The cart total is coming from API I do not have to do any calculations for getting the cart value
Code for Gettin Cart Details from API
Future<CartDetailsModel?> getCartDetailsData() async {
if (_isNetworkAvail) {
var getData = await apiBaseHelper.getAPICall(getCartDataApi, {});
return CartDetailsModel.fromJson(getData);
} else {
setState(() {
_isNetworkAvail = false;
});
}
return null;
}
Scaffold Code
Scaffold(
resizeToAvoidBottomInset: false,
appBar: getAppBar(context, 'checkout'),
drawer: const CustomNavigationDrawer(),
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: FutureBuilder<CartDetailsModel?>(
future: getCartDetailsData(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Text(
"No items in Cart",
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
),
);
}
if (snapshot.connectionState == ConnectionState.waiting) {
return Container();
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
IconButton(
onPressed: () {
Navigator.of(context).pop(true);
},
icon: const Icon(Icons.arrow_back),
color: Colors.black,
),
const Text(
'Checkout',
style: TextStyle(
fontSize: 22, fontWeight: FontWeight.w600),
),
],
),
]),
cardsList(snapshot),
orderDetails(snapshot),
addDiscountBtn(),
nextBtn(),
],
);
},
)),
),
);
Code of the Widget where I want realTime updation (Wrapped with FutureBuilder, tried with StreamBuilder too but still not worked)
Widget orderDetails(AsyncSnapshot<CartDetailsModel?> snapshot) {
return Card(
shape: RoundedRectangleBorder(
//<-- SEE HERE
side: const BorderSide(
color: colors.primary,
),
borderRadius: BorderRadius.circular(10.0),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Summary',
style: TextStyle(
color: Color(0xff131523),
fontSize: 14,
fontWeight: FontWeight.w500),
),
const SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
RichText(
text: TextSpan(
children: <TextSpan>[
const TextSpan(
text: 'Price',
style: TextStyle(
color: Color(0xff131523),
fontSize: 14,
fontWeight: FontWeight.w600),
),
TextSpan(
text:
' (${snapshot.data?.data?.products?.items?.length.toString()} items)',
style: const TextStyle(
color: Color(0xff131523),
fontSize: 14,
fontWeight: FontWeight.w600),
),
],
),
),
Text(
'${snapshot.data?.data?.cart?.totalAmount}',
style: const TextStyle(
color: Color(0xff131523),
fontSize: 14,
fontWeight: FontWeight.w600),
)
],
),
const SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Delivery Charges',
style: TextStyle(
color: Color(0xffB0B0B0),
fontSize: 14,
fontWeight: FontWeight.w600),
),
Text(
deliveryCharges.toString(),
style: const TextStyle(
color: Color(0xffB0B0B0),
fontSize: 14,
),
)
],
),
const SizedBox(
height: 15,
),
const Divider(
thickness: 1,
),
const SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Total Price',
style: TextStyle(
color: Color(0xffA7A7A7),
fontSize: 14,
fontWeight: FontWeight.w600),
),
Text(
snapshot.data!.data!.cart!.totalAmount.toString(),
style: const TextStyle(
color: colors.primary,
fontSize: 14,
fontWeight: FontWeight.w500),
)
],
),
const SizedBox(
height: 15,
),
const Divider(
thickness: 1,
),
const SizedBox(
height: 15,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Total CBM',
style: TextStyle(
color: Color(0xffB0B0B0),
fontSize: 14,
fontWeight: FontWeight.w600),
),
Text(
'${snapshot.data?.data?.cart?.totalCbm}',
style: const TextStyle(
color: Color(0xffB0B0B0),
fontSize: 14,
fontWeight: FontWeight.w500),
)
],
),
const SizedBox(
height: 20,
),
],
),
),
);
}
hey guys i have some error in this code whin i open this page it show this error
this error
i know becuse the table there is no data in the table but i want to escape this error how i do it?
i tried everything in the code but nothing work i tried to put inNotEmpty but when i tried to add data in the table still nothing show
this is my code:
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class sections_KSU extends StatefulWidget {
#override
State<sections_KSU> createState() => _sections_KSUState();
}
List<String> disciplines = [
'الهندسة',
'العلوم الطبيعية',
'العلوم الاجتماعية',
'العلوم الإنسانية',
'العلوم الإدارية',
'التربية',
'الطب والعلوم الصحية',
'القانون',
'الفن والتصميم',
'الزراعة والدراسات البيئية',
];
List list = [];
class _sections_KSUState extends State<sections_KSU> {
get controller => null;
var pr1;
Future ReadData() async {
var url = "https://***.***.***.**/getksu.php";
var res = await http.get(Uri.parse(url));
if (res.statusCode == 200) {
var red = jsonDecode(res.body);
setState(() {
list = red;
});
} else {
Text("No ads right now");
}
}
#override
void initState() {
super.initState();
GetData();
}
GetData() async {
await ReadData();
}
Widget build(BuildContext context) {
return Scaffold(
body:SafeArea(
child: Column(
children: [
Container(
margin: EdgeInsets.only(left: 70, right: 60),
height: 56.0,
width: 245.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Color(0xffF4AC47), width: 5),
color: Color(0xff42A9D2),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: new Center(
child: new Text(
"جامعة الملك سعود",
style: TextStyle(
fontSize: 25,
color: Color(0xff072A52),
fontFamily: 'Cairo'),
textAlign: TextAlign.center,
),
///end logo
)),
),
SizedBox(
height: 35,
),
///Search
Container(
width: 390,
height: 69,
decoration: BoxDecoration(
border: Border.all(color: Color(0xff072A52), width: 5),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(15),
bottomRight: Radius.circular(15),
topLeft: Radius.circular(15),
topRight: Radius.circular(15))),
child: Column(
children: [
Container(
child: (TextField(
controller: controller,
decoration: InputDecoration(
prefixIcon: const Icon(Icons.search),
hintText: 'Search',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5))),
)),
),
],
)),
///search end
SizedBox(
height: 10,
),
/// icon filter
Row(
children: [
TextButton(onPressed: (){dd();}, child:dd())
],
),
/// icon filter end
///start Section
///
Expanded(
child: ListView.builder(
itemCount:list.length,
itemBuilder: ((cts, i) {
return Column(
children: [
Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
height: 160.0,
child: Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.blueGrey, width:2),
borderRadius: BorderRadius.circular(8)),
child:TextButton(///
onPressed: (){},
child:Container(
child: Column(
children: [
Row(
children: [
const Expanded(
flex: 3,
child: Image(
image: AssetImage("assets/book.jpg"),height:130,
),
),
Expanded(
flex: 9,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"${list[i]["book_name"]}",
style: TextStyle(
fontSize: 25, color: Colors.green),
),
const SizedBox(height: 65),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text("${list[i]["collage"]}",style:TextStyle(fontSize:16)),SizedBox(width:10,),
const Icon(Icons.perm_identity_rounded,color:Colors.teal,),
SizedBox(width:60,),
Text("${list[i]["loc"]}",style:TextStyle(fontSize:15),),SizedBox(width:10,),
const Icon(Icons.person_pin_circle,color:Colors.teal,),SizedBox(width: 10,)
],
),
],
),
)
],
),
],
),
),
)
),
),
const SizedBox(height: 26),
],
);
}),
),
),
],
),
)
);
}
}
///flter
class dd extends StatefulWidget {
const dd({Key? key}) : super(key: key);
#override
State<dd> createState() => _ddState();
}
class _ddState extends State<dd> {
List<String> disciplines = [
'الهندسة',
'العلوم الطبيعية',
'العلوم الاجتماعية',
'العلوم الإنسانية',
'العلوم الإدارية',
'التربية',
'الطب والعلوم الصحية',
'القانون',
'الفن والتصميم',
'الزراعة والدراسات البيئية',
];
get TitleName => "التخصصات";
///يطبع التخصص المختار
set UnaverNAME(String UnaverNAME) {print(UnaverNAME);}
set selectItem(String selectItem) {}
#override
Widget build(BuildContext context) {
return SizedBox(
width: 168,height:60,
child: Padding(
padding: const EdgeInsets.only(left:8),
child: Center(
child: DropdownButtonFormField<String>(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(40),
borderSide: BorderSide(color: Color(0xff072A52), width: 2),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(40),
borderSide: BorderSide(width: 2, color: Color(0xff072A52)))),
hint: Center(
child: Text(
" $TitleName",
// " اسم الجامعة",
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 16,
color: Color.fromRGBO(244, 172, 71, 1)),
)),
// value: selectItem,
items: disciplines
.map((item) => DropdownMenuItem(
value: item,
child: Text(item,
style: TextStyle(
fontSize: 12,
color: Color.fromRGBO(244, 172, 71, 1),
fontWeight: FontWeight.w900))))
.toList(),
onChanged: (value) {
setState(() {
selectItem = value!;
UnaverNAME = value;
});
},
),
),
),
);
}
}
and this is my php code:
<?php
include("config.php");
$sql = "SELECT book_name,loc,com,spe,collage FROM ads where collage = 'جامعة الملك سعود' ";
$res = $connect->query($sql);
if ($res >= 1) {
while($row = $res -> fetch_assoc()) {
$data[]=$row;
}
echo json_encode($data);
} else {
echo json_encode("sorry this is no ads know");
}
$mysqli_connect-> close();
?>
Hey guys I have a problem when I press the insert ad I want the info about the book insert into the table but it shows me this error:
E/flutter ( 3974): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'TextEditingController' is not a subtype of type 'String' in type cast
I want if I press the button after I press the button insert the info into the table and I tried to make everything in the connection and the insert-ads.php nothing works
this is my code:
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert';
// ignore: library_prefixes
class uploudd extends StatefulWidget {
const uploudd({key});
#override
State<uploudd> createState() => _uplouddState();
}
class _uplouddState extends State<uploudd> {
File? _imagepath;
String? _imageName;
String? _imageData;
var UnaverNAME;
var CollegeName;
var districts1;
TextEditingController NameBook = TextEditingController();
TextEditingController Email = TextEditingController();
TextEditingController PhoNamber = TextEditingController();
TextEditingController NotAds = TextEditingController();
SizedBox TextF(var name, var exampel, var inText) {
return SizedBox(
width: 175,
child: TextField(
keyboardType: TextInputType.emailAddress,
controller: inText,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
labelText: " $name ",
labelStyle: TextStyle(
fontSize: 15,
color: Color(0xffF4AC47),
fontWeight: FontWeight.w700),
hintText: " $exampel ",
suffix: Icon(
Icons.person,
size: 20,
color: Colors.white,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Color(0xff072A52),
width: 4,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff072A52), width: 4),
)),
),
);
}
Padding TextForm(var name, var exampel, var inText) {
return Padding(
padding: const EdgeInsets.all(13.0),
child: TextField(
maxLines: 5,
keyboardType: TextInputType.emailAddress,
controller: inText,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
labelText: " $name ",
labelStyle: TextStyle(
fontSize: 35,
color: Color(0xffF4AC47),
fontWeight: FontWeight.w700),
hintText: " $exampel ",
suffix: Icon(
Icons.person,
size: 20,
color: Colors.white,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(15),
borderSide: BorderSide(
color: Color(0xff42A9D2),
width: 4,
)),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff42A9D2), width: 4),
)),
),
);
}
List<String> universities = [
"جامعة الملك سعود",
"جامعة الأميرة نورة ",
"جامعة الإمام ",
"جامعة الفيصل",
"جامعة الفيصلية",
"جامعة اليمامة",
"جامعة عفت",
"جامعة الفيصلية",
"الكلية التقنية"
];
SizedBox districtsINRiadh(
String TitleName,
var nameCo,
) {
String selectItem = '$TitleName';
return SizedBox(
width: 186,
child: Center(
child: DropdownButtonFormField<String>(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff072A52), width: 4),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(
width: 4,
color: Color(0xff072A52),
))),
hint: Center(
child: Text(
" $TitleName ",
// " collage name",
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 15,
color: Color(0xffF4AC47)),
)),
// value: selectItem,
items: districtsInRiyadh
.map((item) => DropdownMenuItem(
value: item,
child: Text(item,
style:
TextStyle(fontSize: 20, color: Color(0xffF4AC47)))))
.toList(),
onChanged: (value) {
setState(() {
// var finalname;
selectItem = value!;
districts1 = value;
// print(CollegeName);
});
},
),
),
);
}
SizedBox Universities(
String TitleName,
var nameCo,
) {
String selectItem = '$TitleName';
return SizedBox(
width: 186,
child: Center(
child: DropdownButtonFormField<String>(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff072A52), width: 4),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(
width: 4,
color: Color(0xff072A52),
))),
hint: Center(
child: Text(
" $TitleName ",
// " collage name",
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 15,
color: Color(0xffF4AC47)),
)),
// value: selectItem,
items: universities
.map((item) => DropdownMenuItem(
value: item,
child: Text(item,
style:
TextStyle(fontSize: 20, color: Color(0xffF4AC47)))))
.toList(),
onChanged: (value) {
setState(() {
// var finalname;
selectItem = value!;
CollegeName = value;
// print(CollegeName);
});
},
),
),
);
}
List<String> districtsInRiyadh = [
"العزيزية",
"الفاروق",
"الحمراء",
"المنصورة",
"النهضة",
"القويعية",
"الربوة",
"الروضة",
"الشفاء",
"اليرموك",
"الرياض الجديدة",
"الشهداء",
"الزهراء",
"الجزيرة",
"الملك عبد الله",
"الفيحاء",
"النهضة ",
"العليا",
"المطار القديم",
"السليمانية",
"الثمامة",
"الورود",
"الياسمين"
];
List<String> disciplines = [
'الهندسة',
'العلوم الطبيعية',
'العلوم الاجتماعية',
'العلوم الإنسانية',
'العلوم الإدارية',
'التربية',
'الطب والعلوم الصحية',
'القانون',
'الفن والتصميم',
'الزراعة والدراسات البيئية',
];
SizedBox SectionName(
String TitleName,
var nameUnaverNAME,
) {
String selectItem = '$TitleName';
return SizedBox(
width: 186,
child: Center(
child: DropdownButtonFormField<String>(
decoration: InputDecoration(
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: Color(0xff072A52), width: 4),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(width: 4, color: Color(0xff072A52)))),
hint: Center(
child: Text(
" $TitleName ",
// " collage name",
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 20,
color: Color(0xffF4AC47)),
)),
// value: selectItem,
items: disciplines
.map((item) => DropdownMenuItem(
value: item,
child: Text(item,
style: TextStyle(
fontSize: 12,
color: Color(0xffF4AC47),
fontWeight: FontWeight.w900))))
.toList(),
onChanged: (value) {
setState(() {
selectItem = value!;
UnaverNAME = value;
});
},
),
),
);
}
//------------This is get path images----------------
final ImagePicker imagePicker = ImagePicker();
Future<void> getimages() async {
final XFile? getimage =
await imagePicker.pickImage(source: ImageSource.gallery);
//if (getimage == null) return;
setState(() {
//print(File(getimage.path));
_imagepath = File(getimage!.path);
_imageName = getimage.path.split('/').last;
_imageData = base64Encode(_imagepath!.readAsBytesSync());
print(_imagepath);
print(_imageName);
print(_imageData);
});
}
//--------------This is method is add images--------------------
Future<void> upload() async {
try {
var url = "http://111111/php_file/UploadImage.php";
var res = await http.post(Uri.parse(url), body: {
"data": _imageData,
"name": _imageName,
});
var response = jsonDecode(res.body);
if (response['success'] == "true") {
print("uploudd");
} else
print("no images");
} catch (e) {
print(e);
}
// if (_imagepath == null) return;
// String imageCode = base64Encode(_imagepath!.readAsBytesSync());
// String id = _imagepath!.path.split('/').last;
// var response = await http.post(Uri.parse(url), body: {
// "id": id,
// "imageCode": imageCode,
// });
// var res = jsonDecode(response.body);
// if (res['suvvess'] == "true") {
// print("uploudd");
// } else
// print("no images");
}
Future InsertAdd() async {
String TheUrl = "https://***.***.***.**/insert-ads.php";
var rep = await http.post(Uri.parse(TheUrl), headers: {
"Accept": "application/json"
}, body: {
"book_name": NameBook,
"phone2": PhoNamber,
});
var respb = json.decode(rep.body);
print(respb);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Center(
child: Column(
children: [
Container(
margin: EdgeInsets.only(right: 60, left: 70),
height: 54.0,
width: 224.0,
child: Container(
decoration: BoxDecoration(
border:
Border.all(color: Color(0xffF4AC47), width: 3),
color: Color(0xff42A9D2),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(40),
bottomRight: Radius.circular(40))),
child: const Center(
child: Text(
" insert ad",
style: TextStyle(
fontSize: 30,
color: Color(0xff072A52),
fontWeight: FontWeight.w700),
textAlign: TextAlign.center,
),
)),
),
SizedBox(
height: 30,
),
Row(
children: [
SizedBox(
width: 304,
),
Container(
child: Text(
" images",
style:
TextStyle(color: Color(0xffF4AC47), fontSize: 25),
),
decoration: BoxDecoration(
color: Color(0xff072A52),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
bottomLeft: Radius.circular(60),
)),
),
],
),
Column(
children: [
Row(
children: [
Container(
height: 70,
width: 392,
child: Row(
children: [
SizedBox(
width: 208,
),
Container(
height: 60,
width: 60,
child: _imagepath == null
? Text('not here in images')
: Image.file(_imagepath!),
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
bottomLeft: Radius.circular(60),
)),
),
SizedBox(
width: 40,
),
Container(
child: IconButton(
onPressed: getimages,
icon: Icon(Icons.add),
color: Colors.black,
iconSize: 60,
),
),
],
),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
color: Color(0xff42A9D2),
width: 2,
),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(60),
bottomLeft: Radius.circular(60),
)),
),
],
),
],
),
SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Universities(" collage name", UnaverNAME),
SizedBox(
width: 15,
),
TextF(' book name ', 'prog101', NameBook),
// SectionName(' spe', CollegeName),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
SectionName(' spe', CollegeName),
SizedBox(
width: 15,
),
TextF(' phone number ', ' 0555511111', PhoNamber),
],
),
),
SizedBox(
height: 15,
),
districtsINRiadh('districts', districts1),
TextForm(
' comments in ads ',
'book for programing and for collage',
NotAds),
SizedBox(
height: 30,
),
ConstrainedBox(
constraints: BoxConstraints.tightFor(width: 385, height: 70),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Color(0xff072A52),
shape: BeveledRectangleBorder(
borderRadius:
BorderRadiusDirectional.circular(4))),
onPressed: () {
InsertAdd();
setState(() {
print(UnaverNAME);
print(CollegeName);
print(districts1);
print(NameBook.text.toString());
print(NotAds.text.toString());
print(PhoNamber.text);
// print(pass.text.toString());
//final Name = TextEditingController();
});
// Navigator.of(context).push(
// MaterialPageRoute(
// builder: (context) => welcome(
// paswordd: pasword.text, uernamee: name.text)
// )
// );
},
child: Text(
"insert ad",
style: TextStyle(
color: Color(0xffF4AC47),
fontSize: 30,
fontWeight: FontWeight.w500),
)),
),
// Container(
// child: ElevatedButton(
// child: Text('uplod'),
// onPressed: getimages,
// ),
// ),
// Center(
// child: _imagepath == null
// ? Text('not here in images')
// : Image.file(_imagepath!),
// ),
// Container(
// child: _imagepath == null
// ? Text('not images is here')
// : ElevatedButton(
// child: Text('print'),
// onPressed: upload,
// ),
// ),
//Image(image:Image.asset('name'));
],
),
),
),
),
);
}
}
this is my php code:
<?
require('config.php');
// insert a new ad
$book_name = $_POST['book_name'];
$phone = $_POST['phone2'];
$sql = "INSERT INTO ads (`book_name`,`phone2`)VALUE ('$book_name','$phone')";
$statement = $connect -> prepare($sql);
$statement -> execute();
echo json_encode("done add");
?>
You have to use textController's text property to find the text. You have already done it at several places but missed while making the request.
Future InsertAdd() async {
String TheUrl = "https://***.***.***.**/insert-ads.php";
var rep = await http.post(Uri.parse(TheUrl), headers: {
"Accept": "application/json"
}, body: {
"book_name": NameBook.text.toString(),
"phone2": PhoNamber.text.toString(),
});
var respb = json.decode(rep.body);
print(respb);
}
I have a problem with this error for a long time and I really don't know how to solve it. I saw from various sources that there should be a problem with JSON decoding, but I have done it according to the instructions several times and the problem did not arise there. The error is as follows:
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: FormatException: Unexpected character (at character 1)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www....
^
#0 _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
#1 _ChunkedJsonParser.parseNumber (dart:convert-patch/convert_patch.dart:1250:9)
#2 _ChunkedJsonParser.parse (dart:convert-patch/convert_patch.dart:915:22)
#3 _parseJson (dart:convert-patch/convert_patch.dart:35:10)
#4 JsonDecoder.convert (dart:convert/json.dart:612:36)
#5 JsonCodec.decode (dart:convert/json.dart:216:41)
#6 _RegisterState.register (package:projectbicycle/example/register.dart:25:21)
<asynchronous suspension>
register.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:projectbicycle/dashboard.dart';
import 'package:projectbicycle/main.dart';
class Register extends StatefulWidget {
const Register({Key? key}) : super(key: key);
#override
_RegisterState createState() => _RegisterState();
}
class _RegisterState extends State<Register> {
TextEditingController user = TextEditingController();
TextEditingController pass = TextEditingController();
Future register() async {
var url = Uri.http("95.105.178.9", '/api_bike/register.php', {'q': '{http}'});
var response = await http.post(url, body: {
"username": user.text.toString(),
"password": pass.text.toString()
});
var data = json.decode(response.body);
if (data == "Error") {
Fluttertoast.showToast(
backgroundColor: Colors.orange,
textColor: Colors.white,
msg: 'User already exit!',
toastLength: Toast.LENGTH_SHORT,
);
} else {
Fluttertoast.showToast(
backgroundColor: Colors.green,
textColor: Colors.white,
msg: 'Registration Successful',
toastLength: Toast.LENGTH_SHORT,
);
Navigator.push(context,
MaterialPageRoute(
builder: (context) => DashBoard(),
),
);
}
}
bool isPasswordVisible = false;
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Container(
height: double.infinity,
width: double.infinity,
alignment: Alignment.center,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.teal.shade200, Colors.purple.shade900])),
child: SingleChildScrollView(
child: Column(
children: [
Align(
alignment: Alignment.topRight,
child: Container(
height: 100,
width: 300,
decoration: const BoxDecoration(
gradient:
LinearGradient(colors: [Colors.red, Colors.yellow]),
boxShadow: [
BoxShadow(
blurRadius: 4,
spreadRadius: 3,
color: Colors.black12)
],
borderRadius: BorderRadius.only(
topLeft: Radius.circular(200),
bottomRight: Radius.circular(200))),
child: Padding(
padding: const EdgeInsets.only(bottom: 35, left: 65),
child: Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const Text(
'Let\'s',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.white,
shadows: [
Shadow(
color: Colors.black45,
offset: Offset(1, 1),
blurRadius: 5)
]),
),
Text(
' Register',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
color: Colors.pink.shade600,
shadows: const [
Shadow(
color: Colors.black45,
offset: Offset(1, 1),
blurRadius: 5)
]),
),
],
),
),
),
),
const SizedBox(
height: 40,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30)
.copyWith(bottom: 10),
child: TextField(
controller: user,
style: const TextStyle(color: Colors.white, fontSize: 14.5),
decoration: InputDecoration(
prefixIconConstraints:
const BoxConstraints(minWidth: 45),
prefixIcon: const Icon(
Icons.alternate_email_outlined,
color: Colors.white70,
size: 22,
),
border: InputBorder.none,
hintText: 'Enter Username',
hintStyle: const TextStyle(
color: Colors.white60, fontSize: 14.5),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(100).copyWith(
bottomRight: const Radius.circular(0)),
borderSide:
const BorderSide(color: Colors.white38)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(100).copyWith(
bottomRight: const Radius.circular(0)),
borderSide:
const BorderSide(color: Colors.white70))),
),
),
const SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 30)
.copyWith(bottom: 10),
child: TextField(
controller: pass,
style: const TextStyle(color: Colors.white, fontSize: 14.5),
obscureText: isPasswordVisible ? false : true,
decoration: InputDecoration(
prefixIconConstraints:
const BoxConstraints(minWidth: 45),
prefixIcon: const Icon(
Icons.lock,
color: Colors.white70,
size: 22,
),
suffixIconConstraints:
const BoxConstraints(minWidth: 45, maxWidth: 46),
suffixIcon: GestureDetector(
onTap: () {
setState(() {
isPasswordVisible = !isPasswordVisible;
});
},
child: Icon(
isPasswordVisible
? Icons.visibility
: Icons.visibility_off,
color: Colors.white70,
size: 22,
),
),
border: InputBorder.none,
hintText: 'Enter Password',
hintStyle: const TextStyle(
color: Colors.white60, fontSize: 14.5),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(100).copyWith(
bottomRight: const Radius.circular(0)),
borderSide:
const BorderSide(color: Colors.white38)),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(100).copyWith(
bottomRight: const Radius.circular(0)),
borderSide:
const BorderSide(color: Colors.white70))),
),
),
const SizedBox(
height: 50,
),
GestureDetector(
onTap: () {
register();
},
child: Container(
height: 53,
width: double.infinity,
margin: const EdgeInsets.symmetric(horizontal: 30),
alignment: Alignment.center,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
blurRadius: 4,
color: Colors.black12.withOpacity(.2),
offset: const Offset(2, 2))
],
borderRadius: BorderRadius.circular(100)
.copyWith(bottomRight: const Radius.circular(0)),
gradient: LinearGradient(colors: [
Colors.purple.shade600,
Colors.amber.shade900
])),
child: Text('Signup',
style: TextStyle(
color: Colors.white.withOpacity(.8),
fontSize: 15,
fontWeight: FontWeight.bold)),
),
),
const SizedBox(
height: 50,
),
const Text('Already have an account?',
style: TextStyle(color: Colors.white70, fontSize: 13)),
const SizedBox(
height: 20,
),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const MyHomePage()),
);
},
child: Container(
height: 53,
width: double.infinity,
margin: const EdgeInsets.symmetric(horizontal: 30),
alignment: Alignment.center,
decoration: BoxDecoration(
border: Border.all(color: Colors.white60),
borderRadius: BorderRadius.circular(100)
.copyWith(bottomRight: const Radius.circular(0)),
),
child: Text('Login',
style: TextStyle(
color: Colors.white.withOpacity(.8),
fontSize: 15,
fontWeight: FontWeight.bold)),
),
),
const SizedBox(
height: 20,
)
],
),
),
),
),
);
}
}
register.php
<?php
$db = mysqli_connect('localhost','root','','userdata');
if(!$db)
{
echo "Database connection failed";
}
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT username FROM users WHERE username = '".$username."'";
$result = mysqli_query($db,$sql);
$count = mysqli_num_rows($result);
if($count == 1){
echo json_encode("Error");
}else{
$insert = "INSERT INTO users(username,password) VALUES ('".$username."','".$password."')";
$query = mysqli_query($db,$insert);
if($query){
echo json_encode("Success");
}
}
?>
I will be very grateful for any help, as I said, I know that there should obviously be a problem in decoding, but I really don't know where and how to fix it
I've tried different variations of decoding and several direct instructions, the one mentioned is a YouTube tutorial where it works. and it doesn't show any error.
Hi guys I'm new in flutter. Please help me to solve by problem
I want to create a display using parse json on php url result And defined the result on final blockBustorDealList.
I am looking for a solution for this code.
I've provided the entire code below.
I just want a result like
final blockBustorDealList = [
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC56049_thumbnail.webp?v=20220602014017',
'title': 'Trick R Treat Ultimate Sam',
'offer': 'RMB 54.90'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC61901_thumbnail.webp?v=20220602014017',
'title': 'Blockbustor Deals On TVs',
'offer': 'From ₹5,499'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC54206_thumbnail.webp?v=20220602014017',
'title': 'Asian, Kraasa & more',
'offer': 'Min. 55% Off'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC54226_thumbnail.webp?v=20220602014017',
'title': 'Puma, FILA & more',
'offer': 'Min. 60% Off'
}
];
using the result of http://192.168.1.4/flutter/get_products.php url
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
// My Own Imports
import 'package:go_kart/pages/category/top_offers.dart';
import 'package:http/http.dart' as http;
class BlockBusterDeals extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: Column(
children: <Widget>[
// TopImage(),
OfferGrid(),
],
),
);
}
}
final blockBustorDealList = [
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC56049_thumbnail.webp?v=20220602014017',
'title': 'Trick R Treat Ultimate Sam',
'offer': 'RMB 54.90'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC61901_thumbnail.webp?v=20220602014017',
'title': 'Blockbustor Deals On TVs',
'offer': 'From ₹5,499'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC54206_thumbnail.webp?v=20220602014017',
'title': 'Asian, Kraasa & more',
'offer': 'Min. 55% Off'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC54226_thumbnail.webp?v=20220602014017',
'title': 'Puma, FILA & more',
'offer': 'Min. 60% Off'
}
];
class OfferGrid extends StatelessWidget {
// var url = "http://192.168.1.4/flutter/get_products.php";
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
InkWell getStructuredGridCell(blockBustorDeal) {
final item = blockBustorDeal;
return InkWell(
child: Container(
margin: EdgeInsets.all(2.0),
decoration: BoxDecoration(
color: Color.fromARGB(255, 15, 13, 13),
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: <Widget>[
Container(
margin: const EdgeInsets.only(top: 10.0, bottom: 10.0),
height: 170.0,
child: Image.network(
item['image'],
fit: BoxFit.fitWidth,
),
),
Container(
// alignment: Alignment.center,
child: Column(
children: <Widget>[
Text(
'${item['title']}',
style: TextStyle(fontSize: 12.0, color: Colors.white),
),
Text(
'${item['offer']}',
style: TextStyle(
color: const Color(0xFF67A86B), fontSize: 16.0),
),
],
),
),
],
),
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => TopOffers(title: '${item['title']}')),
);
},
);
}
return Column(
children: <Widget>[
SizedBox(
width: width,
height: 479.0,
child: Stack(
children: <Widget>[
Container(
width: width,
height: 460.0,
decoration: BoxDecoration(
color: Colors.transparent,
),
),
Container(
decoration: BoxDecoration(
color: Colors.transparent,
borderRadius: BorderRadius.circular(5.0),
),
padding: EdgeInsets.only(top: 5.0, right: 5.0, left: 5.0),
width: width - 20.0,
margin: EdgeInsets.only(right: 10.0, left: 10.0, top: 10.0),
child: GridView.count(
primary: false,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
crossAxisCount: 2,
childAspectRatio: ((width) / 500),
children: List.generate(blockBustorDealList.length, (index) {
return getStructuredGridCell(blockBustorDealList[index]);
}),
),
),
],
),
),
],
);
}
}
version: 1.0.0+1
sdk: ">=2.7.0 <3.0.0"
Try below code.
Your JSON string :
List blockBustorDealList = [
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC56049_thumbnail.webp?v=20220602014017',
'title': 'Trick R Treat Ultimate Sam',
'offer': 'RMB 54.90'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC61901_thumbnail.webp?v=20220602014017',
'title': 'Blockbustor Deals On TVs',
'offer': 'From ₹5,499'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC54206_thumbnail.webp?v=20220602014017',
'title': 'Asian, Kraasa & more',
'offer': 'Min. 55% Off'
},
{
'image':
'https://is.simplify.cool/component/admin/upload_img/demo/backend/files/thumbnail/NEC54226_thumbnail.webp?v=20220602014017',
'title': 'Puma, FILA & more',
'offer': 'Min. 60% Off'
}
];
Your Widget:
GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: blockBustorDealList.length,
itemBuilder: (BuildContext context, int index) {
return Card(
elevation: 5,
shadowColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
20,
),
),
margin: EdgeInsets.all(5),
child: Container(
height: 300,
width: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(
10,
),
topRight: Radius.circular(
10,
),
),
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
blockBustorDealList[index]['image'],
),
),
),
),
),
Container(
height: 2,
color: Colors.black,
),
Container(
height: 80,
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20.0),
bottomRight: Radius.circular(20.0),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
blockBustorDealList[index]['title'],
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
SizedBox(
height: 5,
),
Text(
blockBustorDealList[index]['offer'],
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 12,
),
),
],
),
),
],
),
),
);
},
),
Your Result Screen:
Updated Answer
Add http: ^0.13.4 dependency/package in your pubspec.yaml file, refer http
Import below libraries in your code:
import 'package:http/http.dart' as http;
import 'dart:convert';
Your API Call function:
Future<List<dynamic>> getJobsData() async {
String url = 'https://is.simplify.cool/flutter/products.php';
var response = await http.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
});
return json.decode(response.body);
}
Your Widget:
FutureBuilder<List<dynamic>>(
future: getJobsData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: GridView.builder(
shrinkWrap: true,//add this line
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
var title = snapshot.data[index]['title'];
var image = snapshot.data[index]['image'];
var offer = snapshot.data[index]['offer'];
return Card(
elevation: 5,
shadowColor: Colors.grey,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
20,
),
),
margin: EdgeInsets.all(5),
child: Container(
height: 300,
width: 200,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(
10,
),
topRight: Radius.circular(
10,
),
),
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(
image,
),
),
),
),
),
Container(
height: 2,
color: Colors.black,
),
Container(
height: 80,
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(20.0),
bottomRight: Radius.circular(20.0),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
fontSize: 15,
),
),
SizedBox(
height: 5,
),
Text(
offer,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
fontSize: 12,
),
),
],
),
),
],
),
),
);
},
),
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
Result screen: