connection problem between flutter and mysql - mysql

I'm having a problem in flutter...
I'm trying to access my database and I get this error:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Connection refused and changed IP addresses to my IP with 10.0.2.2:8000/api and with 127.0.0.1:8000/api.
Enter to give phpmyadmin to authorize the entry of IP.
with using Flutter laravel Php.
auth_services
class AuthServices {
static Future<http.Response> register(
String name, String email, String password) async {
Map data = {
"name": name,
"email": email,
"password": password,
};
var body = json.encode(data);
var url = Uri.parse(baseURL + '/auth/register');
http.Response response = await http.post(
url,
headers: headers,
body: body,
);
print(response.body);
return response;
}
register_screen
createAccountPressed() async {
bool emailValid = RegExp(
r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+#[a-zA-Z0-9]+\.[a-zA-Z]+")
.hasMatch(_email);
if (emailValid) {
http.Response response =
await AuthServices.register(_name, _email, _password);
Map responseMap = jsonDecode(response.body);
if (response.statusCode == 200) {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => const HomeScreen(),
));
} else {
errorSnackBar(context, responseMap.values.first[0]);
}
} else {
errorSnackBar(context, 'email not valid');
}
}
globals.dart
import 'package:flutter/material.dart';
const String baseURL = "http://192.168.100.4:8000/api/"; //emulator localhost
const Map<String, String> headers = {"Content-Type": "application/json"};
errorSnackBar(BuildContext context, String text) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
backgroundColor: Colors.red,
content: Text(text),
duration: const Duration(seconds: 1),
));
}

Related

Exception caught by image resource service ═ HTTP request failed, statusCode: 403,

I picked an image from my gallery, then use this image as in my http body parameter , I believe it sending the image in string format thats why its showing this error.How can I display this image in my App ?
I tried to implement with Multipart but didn't came up with any solution, so I stick to this base64 format
void filePicker() async {
final File? selectedImage =
await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
fileContent = image!.readAsBytesSync();
fileContentBase64 = base64.encode(fileContent);
print(fileContentBase64.substring(0, 100));
});
}
Then in my API function use this image with other parameters
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = await http.post(
Uri.parse(
"http://medbo.digitalicon.in/json/SaveCustomTestBooking"),
body: ({
'VisitDate': _selectedDate,
'EncUserId': EncUserId,
'UserFile': fileContentBase64 , // here
'Description': testTextController.text
}));
if (response.statusCode == 200) {
print("Correct");
print(response.body);
jsonResponse = json.decode(response.body.toString());
print(jsonResponse);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DieticianAfterDateSelectPage(
rresponse:
DieticianEncBookingIdModel.fromJson(jsonResponse),
)));
} else {
// ScaffoldMessenger.of(context)
// .showSnackBar(SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
}
}

How to navigate to the next Material page after getting Successful API response using Multipart request as Http body parameter?

I believe response.statusCode == 200 from my Api because its printing Uploaded! How can I store my API response in a variable (Lets say "jsonResponse") so that I can pass it to my new MaterialPage DieticianAfterDateSelectPage?
The Error:
The method '[]' was called on null.
Receiver: null
Tried calling: []("Status")
The relevant error-causing widget was
MaterialApp
lib\main.dart:19
//
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var postUri = Uri.parse("http://mkklklklklktBooking");
var request = http.MultipartRequest('POST',postUri);
request.fields['VisitDate'] = '_selectedDate';
request.fields['EncUserId'] = 'EncUserId';
request.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
request.send().then((response){
if (response.statusCode == 200) {
print("Uploaded!"); //From here.............
Navigator.push(context, MaterialPageRoute(builder: (context) => DieticianAfterDateSelectPage(rresponse:DieticianEncBookingIdModel.fromJson(jsonResponse),)));
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Somthing went wrong")));
throw Exception("Faild to fetch");
}
}
);}
My variable image contain my gallery image after method call.
final ImagePicker _picker = ImagePicker();
File? image;
var fileContent;
var fileContentBase64;
Function to get image from gallery
void filePicker() async {
final File? selectedImage =
await ImagePicker.pickImage(source: ImageSource.gallery);
print(selectedImage!.path);
setState(() {
image = selectedImage;
fileContent = image!.readAsBytesSync();
fileContentBase64 = base64.encode(fileContent);
});
}
It's not very clear how to help. I can see that you are passing a value to DieticianAfterDateSelectPage, and your error message. But you are asking how to store the value in a variable!
What you probably need is to understand the error message. You are getting it because you are calling the [] operator on null. You need to check how that's happening, and check the line number 19 in your main.dart as in the error message.
This is how I print my Multipart request body
Future<void> SaveCustomTestBooking() async {
var jsonResponse;
if (EncUserId.isNotEmpty) {
var response = http.MultipartRequest('POST',Uri.parse("http://myApiTestBooking"));
response.fields['VisitDate'] = _selectedDate;
response.fields['EncUserId'] = EncUserId;
response.fields['Description'] = testTextController.text;
response.files.add(new http.MultipartFile.fromBytes(
"UserFile", File(image!.path).readAsBytesSync(),
filename:"Image.jpg",
contentType: MediaType('image', 'jpg')));
response.send().then((response) async {
if (response.statusCode == 200){
isApiCallProcess = false;
final respBody = await response.stream.bytesToString();// this is how we print body for Multipart request
jsonResponse = json.decode(respBody.toString());
print(respBody);
print("Uploaded!");
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text("Booked"),
backgroundColor: Color(0xFF00b3a4),
));
// Navigator.push(context,new MaterialPageRoute( builder: (context) =>new MyTestReqDetailsPage(),));
Navigator.push(context,new MaterialPageRoute( builder: (context) =>new Home2(),));
}
});
}
}

Flutter Registration with API

I successfully can login with my API connection also can display the data in my app.
I follow the same method for the registration to send data in API So that I can login.
But the registration is not happening, although it didn't show any error. My SnackBar showing You are already registered . But When I try to login with the data which I provided in registration form, its showing user not found( Obvious reason registration process didn't perform). Is there any problem with my API MODEL?
Here is my Parameters
{
"Email":"qwer#gmail.com",
"Mobile":"1237891",
"Password":"9991",
"RetypePassword":"9991"
}
And here is the Json response
{
"Status": "1",
"Message": "You are registered successfully",
"UserData": {
"Name": "qwer#gmail.com",
"EncUserId": "IS0QOCrLby8Ft1kbkzn/mg=="
}
}
After that I created a registration form, when user click the Register button it's run my API function registrationOfuser()
Future <void> registrationOfuser(String email, contact, pass,conpass) async{
var jsonResponse ;
Map data = {
'Email': email,
'Mobile': contact,
'Password': pass,
'RetypePassword': conpass,
};
print(data);
String body = json.encode(data);
var url = 'http://myurl/home/djkjkfjkjfwkjfkwjkjfkjwjfkwjfkwf';
var response = await http.post(
url,
body: body,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
);
print(response.body);
print(response.statusCode);
if (response.statusCode == 200) {
jsonResponse = json.decode(response.body.toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content:Text(" ${jsonResponse['Message']}"))) ;
//Or put here your next screen using Navigator.push() method
print('success');
} else {
print('error');
}
}
And here is my MODEL
class RegistrationApiResponse {
RegistrationApiResponse({
required this.status,
required this.message,
required this.userData,
});
String status;
String message;
//UserData userData;
UserData? userData;
factory RegistrationApiResponse.fromJson(Map<String, dynamic> json) => RegistrationApiResponse(
status: json["Status"],
message: json["Message"],
userData: json["UserData"] == null? null:UserData.fromJson(json["UserData"] as Map<String, dynamic>),
}
class UserData {
UserData({
required this.name,
required this.encUserId,
});
String name;
String encUserId;
factory UserData.fromJson(Map<String, dynamic> json) => UserData(
name: json["Name"],
encUserId: json["EncUserId"],
);
}
Try to below code help:
Create TextEditingController
final TextEditingController email = new TextEditingController();
final TextEditingController contact = new TextEditingController();
final TextEditingController password = new TextEditingController();
final TextEditingController conpassword = new TextEditingController();
Create one function for registration
register(String email, contact, pass,conpass) async {
Map data = {
'Email': email,
'Mobile': contact,
'Password': pass,
'RetypePassword': conpass,
};
print(data);
String body = json.encode(data);
var url = 'Your url here';
var response = await http.post(
url,
body: body,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*"
},
);
print(response.body);
print(response.statusCode);
if (response.statusCode == 200) {
//Or put here your next screen using Navigator.push() method
print('success');
} else {
print('error');
}
}
Create Button
ElevatedButton(
child:Text('Register'),
onPressed:(){
register(email.text, contact.text, password.text, conpassword.text);
},
),
You need to get text from controller. Do as follows:
body:({
'Email':emailController.text,
'Mobile':phoneController.text,
'Password':passwordController.text,
'RetypePassword':rePasswordController.text,
}));
class ApiService {
callloginapi(
var email,
) async {
LoginReg? userModel;
Response response = await post(
Uri.parse('http://13.127.138.139/api/Login_Register_User'),
body: {
'mobile': email,
});
var jsonResponse = jsonDecode(response.body.toString());
userModel = LoginReg.fromJson(jsonResponse);
print(jsonResponse['token']);
var flag = jsonResponse['data']['flag'];
log('==========flag ===========$flag');
//return userModel;
var message = jsonResponse['message'];
if (response.statusCode == 200) {
if (flag == 'true') {
Get.offAllNamed(PageRoutes.home);
// t
emailController.clear();
print('$message');
// moveToHome(context);
} else {
// server error
print('Not Register');
}
}
}}

How to return a Future http function as boolean so that it can be used for furthur activity flow based on result of http response

This is a code for an edit user information http post, the response message will return if the edit is success or not. I want this function to be able to return a boolean so that the user interface class will be able to know if that post is success or not. In this following code, it returns Future which is unable to be put in if(bool) function. This EditCustomerPost class is called by the user interface class.
Is there anyway to return the result of this http post back to the user interface class (widgets class)? I want to return the result as 'bool success'.
Thank you for your help!
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import './loginPost.dart';
import './loginPage.dart';
import './userInfoPage2.dart';
class EditCustomerPost {
String jsonString;
String reMsg;
Map<String, dynamic> reMsgMap;
bool success = false;
BuildContext context;
String token;
String editWhat;
EditCustomerPost({
this.jsonString,
this.reMsg,
this.reMsgMap,
this.context,
this.token,
});
void showDialog1(String msg, bool success) {
// flutter defined function
String title = "Completed";
if (!success) {
title = 'Error';
}
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text(title),
content: new Text(msg),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
void showDialog2() {
// flutter defined function
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Access time expired"),
content: new Text("Please Login again"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("OK"),
onPressed: () {
Navigator.of(context).pop();
Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginPage()),
);
},
),
],
);
},
);
}
// testcodepostrequest
Future<bool> makePostEditRequest(String editWhat) async {
// set up POST request arguments
String url;
if (editWhat == 'name') {
url = 'http://firstcarestartup.appspot.com/customer/editName';
} else if (editWhat == 'email') {
url = 'http://firstcarestartup.appspot.com/customer/editEmail';
} else if (editWhat == 'phoneNum') {
url = 'http://firstcarestartup.appspot.com/customer/editPhoneNum';
} else if (editWhat == 'profilePicture'){
url = 'http://firstcarestartup.appspot.com/customer/editProfilePicture';
}
Map<String, String> headers = {
"Content-type": "application/json",
"Authorization": "Bearer " + token
};
print('==========HTTP POST FOR EDIT PROFILE==========\n');
print('json post edit header= ' + headers.toString());
print('json post edit request= ' + jsonString);
print('json string length: '+jsonString.length.toString());
print('url: '+url);
// make POST request
http.Response response =
await http.post(url, headers: headers, body: jsonString);
// check the status code for the result
// int statusCode = response.statusCode;
// this API passes back the id of the new item added to the body
reMsgMap = jsonDecode(response.body);
if (reMsgMap["error"] != null) {
reMsg = reMsgMap["error"];
success = false;
if (reMsg == "jwt expired") {
showDialog2();
} else {
print("error: " + reMsg);
}
} else if (reMsgMap["msg"] != null) {
reMsg = reMsgMap["msg"];
success = true;
print(reMsgMap.toString());
}
if (success) {
showDialog1(reMsg, success);
}
return success;
}
}
You can get the value returned by makePostEditRequest(...) when its future is resolved. This is done with await inside async block. For usage example see how elsewhere in your code variable response receives the value from http.post(...) call when its future is resolved.

How to save api fetched data into local database using sqflite in flutter?

I am developing an app where I need to maintain an add to cart session. I need to store the items in the local DB and retrieve the data from the local DB in another screen when the add to cart button is clicked. I have the data from the API in a list but I am not getting how to save those data in the database. Please help me solve the problem. Thank you
//This is the screen from wherein a button click I need to save the data to the local database.
home.dart
ClipRRect(
borderRadius:
BorderRadius.only(
bottomLeft:
Radius.circular(5.0),
bottomRight:
Radius.circular(5.0),
),
child: Container(
decoration: BoxDecoration(
border: Border(
right: BorderSide(
color: Colors.black12,
),
left: BorderSide(
color: Colors.black12,
),
bottom: BorderSide(
color: Colors.black12,
),
)),
height: 40.0,
width: 200.0,
child: ActionChip(
label: Text(
"ADD TO CART",
style: TextStyle(
fontSize: 16.0),
),
pressElevation: 0.0,
avatar: Icon(
Icons
.add_shopping_cart,
size: 20.0,
color: Color(
0xFFD1A155,
),
),
backgroundColor:
Colors.transparent,
onPressed: () async {
await DBProvider.db
.newClient(
clientList(
index));
}),
),
),
//This is how i am fetching the data from the api
List<FeaturedModel> myAllDatas = [];
List<FeaturedItemsModel> myItems = [];
Future getDatas() async {
String basicAuth = 'Basic ' +
base64.encode(
utf8.encode('${GlobalVar.consumerKey}:${GlobalVar.secretKey}'));
var response = await http
.get("${GlobalVar.url}wp-json/wc/v3/products?featured=1", headers: {
'Authorization': basicAuth,
'Accept': 'application/json',
});
if (response.statusCode == 200) {
String responseBody = response.body;
var jsonBody = json.decode(responseBody);
for (var data in jsonBody) {
myAllDatas.add(new FeaturedModel(
data['id'], data['name'], data['price'], data['average_rating']));
for (var items in jsonBody) {
myItems.add(new FeaturedItemsModel(items['images'][0]['src']));
}
}
setState(() {});
} else {
print(response.statusCode);
print(response.body);
}
}
model class
import 'dart:convert';
Client clientFromJson(String str) {
final jsonData = json.decode(str);
return Client.fromMap(jsonData);
}
String clientToJson(Client data) {
final dyn = data.toMap();
return json.encode(dyn);
}
class Client {
int id;
String name;
String price;
String category;
String image;
Client({this.id, this.name, this.price, this.category, this.image});
factory Client.fromMap(Map<String, dynamic> json) => new Client(
id: json["id"],
name: json["name"],
price: json["price"],
category: json["category"],
image: json["image"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"price": price,
"category": category,
"image": image
};
}
dbhelper class
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:restaurant_app/models/cartModel.dart';
import 'package:sqflite/sqflite.dart';
class DBProvider {
DBProvider._();
static final DBProvider db = DBProvider._();
Database _database;
Future<Database> get database async {
if (_database != null) return _database;
// if _database is null we instantiate it
_database = await initDB();
return _database;
}
initDB() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, "TestDB.db");
return await openDatabase(path, version: 1, onOpen: (db) {},
onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE Client ("
"id INTEGER PRIMARY KEY,"
"name TEXT,"
"price TEXT,"
"category TEXT,"
"image TEXT,"
")");
});
}
newClient(Client newClient) async {
final db = await database;
//get the biggest id in the table
var table = await db.rawQuery("SELECT MAX(id)+1 as id FROM Client");
int id = table.first["id"];
//insert to the table using the new id
var raw = await db.rawInsert(
"INSERT Into Client (id,first_name,last_name,blocked)"
" VALUES (?,?,?,?)",
[id, newClient.name, newClient.price,
newClient.category,newClient.image]);
return raw;
}
updateClient(Client newClient) async {
final db = await database;
var res = await db.update("Client", newClient.toMap(),
where: "id = ?", whereArgs: [newClient.id]);
return res;
}
getClient(int id) async {
final db = await database;
var res = await db.query("Client", where: "id = ?", whereArgs: [id]);
return res.isNotEmpty ? Client.fromMap(res.first) : null;
}
Future<List<Client>> getAllClients() async {
final db = await database;
var res = await db.query("Client");
List<Client> list =
res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
return list;
}
deleteClient(int id) async {
final db = await database;
return db.delete("Client", where: "id = ?", whereArgs: [id]);
}
deleteAll() async {
final db = await database;
db.rawDelete("Delete * from Client");
}
}
Could you provide more details on what's not working in your implementation? The documentation in sqflite includes example for helpers that you can use.
Since you're mapping the json data into an Object, this helper snippet from the page should help map Objects in the database.
Future<Todo> insert(Todo todo) async {
todo.id = await db.insert(tableTodo, todo.toMap());
return todo;
}