hive condition if id exist - flutter

i use this code putData but it shown repeat, i want to show my data from database to hive.box,i just want: if there is same id or exist, it cannot store to hive.box database.if not same or exist it wil store to databse hive.box.
this is getdata from mysql database
Future getAllData() async {
await openBox();
String url = "http://dhoido.com/sttt/tes/viewHive.php";
try{
var response = await http.get(Uri.parse(url));
var _jsonDecode = jsonDecode(response.body);
// setState(() {
// var resBody = json.decode(response.body);
// list = resBody;
// });
// box.clear();
// if (box.get('id').exists ) {
await putData(_jsonDecode) as List;
// }
} catch (SocketException) {
print(SocketException);
}
Future putData(data) async {
for(var d in data) {
d = TodoModel(
id: d['id'],
title: d['title'],
detail: d['detail'],
isCompleted: false
);
if(d != box.values.toList()){
box.add(d);
}
else{
box.clear();
}
}

Related

Sqflite get locked on bulk insertion even after using transaction object and batch

I am new to flutter and I am doing bulk insertion in sqflite database. I have tried using both transaction and batch objects but my issue still remains there and database gets locked.
Here is what i am doing.
Future<List<ShopsModel>> fetchShops() async{
int count = 0;
List<ShopsModel> shopsList = [];
int id = 0;
String date = "";
List<SyncDataModel> syncList = await DatabaseHelper.instance.getSyncDataHistory();
syncList.forEach((element) {
id = element.SyncID!;
date = element.ShopSyncDate == null ? "" : element.ShopSyncDate!;
});
//Info.startProgress();
String response = await ApiServices.getMethodApi("${ApiUrls.IMPORT_SHOPS}?date=$date");
if(response.isEmpty || response == null){
return shopsList;
}
var shopsApiResponse = shopsApiResponseFromJson(response);
if(shopsApiResponse.data != null){
shopsApiResponse.data!.forEach((element) async{
await insertShops(element);
count++;
if(count == 1){
syncList.length == 0 ? await DatabaseHelper.instance.insertSyncDataHistory(
SyncDataModel(
ShopSyncDate: DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()),
LastSyncDate: DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now())
)) :
await DatabaseHelper.instance.updateShopSyncDate(
DateFormat('yyyy-MM-dd HH:mm:ss').format(DateTime.now()), id);
}
});
}
return shopsList;
}
Future insertShops(ShopsModel row) async{
var shopsRow = await DatabaseHelper.instance.getShopByShopId(row.shopID!);
if(shopsRow.IsModify == 0 || shopsRow.IsModify == null) {
var result = await DatabaseHelper.instance.deleteImportedShops(
row.shopID!, DateFormat('yyyy-MM-dd HH:mm:ss').format(
DateTime.parse(row.updatedOn!)));
if (result > 0) {
print('Shop has been deleted');
}
await DatabaseHelper.instance.insertShops(
ShopsModel(
shopID: row.shopID,
shopName: row.shopName,
shopCode: row.shopCode,
contactPerson: row.contactPerson,
contactNo: row.contactNo,
nTNNO: row.nTNNO,
regionID: row.regionID,
areaID: row.areaID,
salePersonID: row.salePersonID,
createdByID: row.createdByID,
updatedByID: row.updatedByID,
systemNotes: row.systemNotes,
remarks: row.remarks,
description: row.description,
entryDate: DateFormat('yyyy-MM-dd HH:mm:ss').format(
DateTime.parse(row.entryDate!)),
branchID: row.branchID,
longitiude: row.longitiude,
latitiude: row.latitiude,
googleAddress: row.googleAddress,
createdOn: DateFormat('yyyy-MM-dd HH:mm:ss').format(
DateTime.parse(row.createdOn!)),
updatedOn: DateFormat('yyyy-MM-dd HH:mm:ss').format(
DateTime.parse(row.updatedOn!)),
tradeChannelID: row.tradeChannelID,
route: row.route,
vPO: row.vPO,
sEO: row.sEO,
imageUrl: row.imageUrl,
IsModify: 0
)
);
}
}
// Below are my Database methods
Future<int> deleteImportedShops(int shopID, String updatedDate) async{
Database db = await instance.database;
return await db.delete("$shopsTable", where: 'ShopID = ? AND UpdatedOn <= ?', whereArgs: [shopID, updatedDate]);
}
Future<void> insertShops(ShopsModel shopsRow) async{
Database db = await instance.database;
await db.transaction((txn) async {
var batch = txn.batch();
batch.insert("$shopsTable", shopsRow.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
await batch.commit();
});
}
Future<void> insertSyncDataHistory(SyncDataModel row) async{
Database db = await instance.database;
await db.transaction((txn) async {
var batch = txn.batch();
batch.insert("$syncDataTable", row.toJson(), conflictAlgorithm: ConflictAlgorithm.replace);
await batch.commit();
});
}
Future<void> updateShopSyncDate(String? pDate, int id) async{
Database db = await instance.database;
await db.transaction((txn) async {
var batch = txn.batch();
batch.rawUpdate("UPDATE SyncDataHistory SET ShopSyncDate = ?, LastSyncDate = ? WHERE SyncID = ?", [pDate, pDate, id]);
await batch.commit();
});
}
Here are the details what I am getting as an output.
Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction object for database operations during a transaction
Please help me out. Any help would be appreciated.

Flutter: How to send multiple images using for loop

I am using http package to perform multipart request.I am trying to upload multiple images using for loop but I am not getting any idea how to do it following is my postman response in the below image you can see 2 fields one is attribute and another one is image here I want to loop only adhar and pan inside attributes after sending "mobileno":"4567654","role":"p","userstatus":"D", to database
following is my multipart request code
Future<void> insertCategory(String category, BuildContext context) async {
var flutterFunctions =
Provider.of<FlutterFunctions>(context, listen: false);
var data = {"mobileno":"4567654","role":"p","userstatus":"D","adhar":"adhar","pan":"pan"};
var url = PurohitApi().baseUrl + PurohitApi().insertcategory;
Map<String, String> obj = {"attributes": json.encode(data).toString()};
try {
loading();
final client = RetryClient(
http.Client(),
retries: 4,
when: (reponse) {
return reponse.statusCode == 401 ? true : false;
},
onRetry: (request, response, retryCount) async {
if (retryCount == 0 && response?.statusCode == 401) {
var accesstoken = await Provider.of<Auth>(context, listen: false)
.restoreAccessToken();
request.headers['Authorization'] = accesstoken;
print(accesstoken);
}
},
);
var response = await http.MultipartRequest('Post', Uri.parse(url))
..files.add(await http.MultipartFile.fromPath(
"imagefile", flutterFunctions.imageFile!.path,
contentType: MediaType("image", "jpg")))
..headers['Authorization'] = token!
..fields.addAll(obj);
final send = await client.send(response);
final res = await http.Response.fromStream(send);
var messages = json.decode(res.body);
loading();
print(messages);
} catch (e) {
print(e);
}
}
Future<Object> addUserImages(List<XFile> files, String userID, String token) async {
try {
var url = Uri.parse(API_BASE_URL + addUserImagesUrl);
var request = http.MultipartRequest("POST", url);
request.headers['Authorization'] = "Bearer ${StaticServices.userBaseModel!.token!.token}";
for (var i = 0; i < files.length; i++) {
String fileName = DateTime.now().microsecondsSinceEpoch.toString().characters.takeLast(7).toString();
var pic = http.MultipartFile.fromBytes("files", await File(files[i].path).readAsBytes(), filename: '${userID}_${i}_$fileName', contentType: MediaType("image", files[i].mimeType ?? "png"));
//add multipart to request
request.files.add(pic);
}
var response = await request.send();
var responseData = await response.stream.toBytes();
var responseString = String.fromCharCodes(responseData);
if (response.statusCode == 200) {
return Success(response: Images.fromJson(jsonDecode(responseString)));
}
return Failure(
errorMessage: responseString,
);
} on HttpException {
return Failure(errorMessage: "No Internet Connection");
} on FormatException {
return Failure(errorMessage: "Invalid Format");
} on SocketException {
return Failure(errorMessage: "No Internet Connection");
} catch (e) {
return Failure(errorMessage: "Invalid Error");
}
}

Display percent value while function being excected in flutter

I have this function here it gets data from API and stores the data locally and I want to display a percent value like 20% ..... 100% in the splash screen while this function is being executed how can I do that?
_getCleaningDate(
{required AppGetCleaningDateEvent event,
required Emitter<AppState> emit}) async {
userDataModel = await SQLService.getUserData();
if (userDataModel == null) {
print('No User Data');
}
if (userDataModel != null) {
try {
emit(AppGetCleaningDateLoadingState());
propertiesModel = null;
offlineProperties = null;
bool hasNetwork = await Services.hasNetwork();
this.hasNetwork = hasNetwork;
if (hasNetwork) {
propertiesModel = await Services.getCleaningDate(
token: userDataModel!.token!,
cleanday: AvadaTheme.formateCleaningDate(event.dateTime));
await _syncAllData(event: AppSyncAllDataEvent(), emit: emit);
offlineProperties = await SQLService.getProperties(
AvadaTheme.formateCleaningDateFromStored(event.dateTime));
emit(AppGetCleaningDateSuccessState());
} else {
offlineProperties = await SQLService.getProperties(
AvadaTheme.formateCleaningDateFromStored(event.dateTime));
emit(AppGetCleaningDateSuccessState());
}
} on DioError catch (error) {
emit(AppGetCleaningDateErrorState(error.message));
}
}
}

How to merge two schemas in mongodb

I have a post schema and user schema and I want to merge them together. I waant to know how to do it. So far I have this code but I keep returning promises. When I add then after the .map, I get no result. Any help would be appreciated
let posts = await Post.find();
console.log(posts);
let test = await posts.map(async(post) => {
const creator = await User.findOne({token: post.creator});
var username = null;
if(creator){
username = creator.username;
}
return {...post._doc, username: username};
});
return posts;
you can use q and async module
const q = require("q");
const async = require("async");
async function mainFunction() {
try {
let posts = await Post.find();
let result = await getUser(posts);
console.log(result)
} catch (error) {
console.error(error);
return { error: error };
}
}
async function getUser (posts) {
let defer = q.defer;
let test = [];
async.eachSeries(posts,async (post) => {// like loop
try {
let creator = await User.findOne({ token: post.creator });
var username = null;
if (creator) {
username = creator.username;
}
test.push({ ...post._doc, username: username });
} catch (error) {
console.log(error);
}
},() => {//callback
console.log("finish loop");
defer.resolve(test); // when finished loop return result
}
);
return defer.promise;
};

A value of type can't be returned from method because it has a return type of

List<String> getData() async {
var response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
print(data);
var temperature = jsonDecode(data)['main']['temp'];
var condition = jsonDecode(data)['weather'][0]['id'];
var city_name = jsonDecode(data)['name'];
return [temperature, condition, city_name];
} else {
print(response.statusCode);
}
}
}
I get a strange error saying that I can't return List<String> because is expecting List<String> to be returned.
Since the function get data is is async it should return Future<List<String>> example is as follows:
Future<List<String>> getData() async {
var response = await http.get(url);
if (response.statusCode == 200) {
String data = response.body;
print(data);
var temperature = jsonDecode(data)['main']['temp'];
var condition = jsonDecode(data)['weather'][0]['id'];
var city_name = jsonDecode(data)['name'];
return <String>[temperature, condition, city_name];
} else {
print(response.statusCode);
}
}
Also your are decoding 3 times unnecessarily, you can do it once keep it in var and use for further usage, example as follows:
String data = response.body;
var decodedData = jsonDecode(data);
var temperature = decodedData['main']['temp'];
var condition = decodedData['weather'][0]['id'];
var city_name = decodedData['name'];
As a generalization, when you get this error in an async function:
A value of type x can't be returned from method because it has a
return type of x
The message seems weird, but it could mean that you are missing a Future<> return type.
So add Future<> to your method return type:
Example:
List<String> getValues() async
{
List<String> list = await getJson();
return list;
}
Change to:
Future<List<String>> getValues() async
{
List<String> list = await getJson();
return list;
}