Remove a row by key on Google Sheet with gsheets package - flutter

This is an example code, here i find the row by key. I need something like this, but that delete a row if i know the key. (I don't know the index)
import 'package:gsheets/gsheets.dart';
...
Future deleteUser() async {
final gsheets = GSheets(_credentials);
final ss = await gsheets.spreadsheet(_spreadsheetId);
var sheet = ss.worksheetByTitle('game');
row = await sheet.values.rowByKey("key");
}
Thank you!

I resolved with this:
void deleteUser() async {
final gsheets = GSheets(_credentials);
final ss = await gsheets.spreadsheet(_spreadsheetId);
var sheet = ss.worksheetByTitle('game');
final lista = await sheet.values.allRows();
for(var i=0; i<lista.length; i++){
var riga=lista[i];
if (riga[0] == dati[0]){ //dati[0] contain the key
sheet.deleteRow(i+1);
break;
}
}
}

Related

How to Save List in SharedPreferences in Flutter

Hello all at first I want to mention that I've tried a lot of solutions here but it didn't work for me.
I bring the list from the database through the following code:
var listCat = [];
Future getdata() async {
apiURL = '***************.php';
var response = await http.post(Uri.parse(apiURL));
var responsebody = jsonDecode(response.body);
if (responsebody.length >0){
for (int i = 0; i < responsebody.length; i++) {
listCat.add(responsebody[i]['name']+ ':' + responsebody[i]['image'].toString());
}
return responsebody;
}else{
}
}
As is obvious in the code above I am trying to get the name and image and this is not a problem right now I want to store this listCat in SharedPreferences until I recall it from all pages of the app
I have the following class to save SharedPreferences:
class APIPreferences {
static SharedPreferences ? _preferences;
static const _keyMuinCat = 'MuinCat';
static Future init() async => _preferences = await SharedPreferences.getInstance();
static Future setMuinCat(String MuinCat) async => await _preferences!.setString(_keyMuinCat, MuinCat);
static String? getMuinCat() => _preferences!.getString(_keyMuinCat);
}
Then I save what I need to save by the following line:
APIPreferences.setMuinCat(listCat.toString());
Then I can bring pre-stored data from any location where I need it through the following code:
CatList = APIPreferences.getMuinCat() ?? '';
I tried to do the following thing now to save the list in the first code above:
var listCat = [];
Future getdata() async {
apiURL = '***************.php';
var response = await http.post(Uri.parse(apiURL));
var responsebody = jsonDecode(response.body);
if (responsebody.length >0){
for (int i = 0; i < responsebody.length; i++) {
listCat.add(responsebody[i]['name']+ ':' + responsebody[i]['image'].toString());
APIPreferences.setMuinCat(listCat.toString());
}
return responsebody;
}else{
}
}
But it didn't work. I don't really know how to deal with it.
How can I save it and then bring it to use with ListView.
instead of:
_preferences!.setString(_keyMuinCat, "some string");
use:
_preferences!.setStringList(_keyMuinCat, ["some", "strings", "in", "list"]);
So in your code, the setMuinCat method needs to be:
static Future setMuinCat(List<String> muinCat) async => await _preferences!.setStringList(_keyMuinCat, muinCat);
and then you call it like this:
APIPreferences.setMuinCat((listCat as List).map((v) => v.toString()).toList());
To save the list in shared preferences you need to pass as jsonEncode(yourList data) and when you will fecth the shared list you will again jsonDecode(your list)
await prefs.setString('YOUR KEY', json.encode(YOURMAP()));

for-loop should wait for future

I have a list of userIDs and I want to get a value from the database for each user and write it to a new list. But the for loop doesn't wait for the future and throws the error "Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0"
List userIDs = ["gsdgsgsgda32", "gwerszhgda7h", "fsdgz675ehds"];
Future <dynamic> getList() async {
List items=[];
for (var i = 0; i < userIDs.length; i++) {
items[i] = await getUserItems(userIDs[i]);
}
return items;
}
Future <String?> getUserItems(String? _userID) async {
String? userItem=" ";
final FirebaseApp testApp = Firebase.app();
final FirebaseDatabase database = FirebaseDatabase.instanceFor(app: testApp);
database.ref().child('users').child(_userID!).once().then((pdata) {
userItem = pdata.snapshot.child('item').value as String?;
});
return userItem;
}
This is not problem with future. List items is empty so when you call items[0] = 3; there is no items[0] and you get RangeError. Proper way to add element to list is call items.add(3)
So your code should look like this:
List userIDs = ["gsdgsgsgda32", "gwerszhgda7h", "fsdgz675ehds"];
Future <dynamic> getList() async {
List items=[];
for (var i = 0; i < userIDs.length; i++) {
final item = await getUserItems(userIDs[i]);
items.add(item);
}
return items;
}
Future <String?> getUserItems(String? _userID) async {
String? userItem=" ";
final FirebaseApp testApp = Firebase.app();
final FirebaseDatabase database = FirebaseDatabase.instanceFor(app: testApp);
database.ref().child('users').child(_userID!).once().then((pdata) {
userItem = pdata.snapshot.child('item').value as String?;
});
return userItem;
}
By using .then you are telling dart to continue running and come back when the Future completes.
Instead you should use await inside getUserItems.
You have to fiddle around a bit but here's a suggestion to start with:
Future <String?> getUserItems(String? _userID) async {
String? userItem=" ";
final FirebaseApp testApp = Firebase.app();
final FirebaseDatabase database = FirebaseDatabase.instanceFor(app: testApp);
userItem = (await database.ref().child('users').child(_userID!).once()).snapshot.child('item').value as String?
return userItem;
}
Also using String? for userItem and setting it to " " is a bit of an anti pattern. Since you allow it to be nullable i'd suggest having it as null writing your logic around that.
Try to use it like this
Future <dynamic> getList() async {
List items=[];
userIDs.forEach((item) async {
items.add(await getUserItems(item));
});
return items;
}

flutter sqflite+getx use group_button to filter the array from database and render GridView.builder

I am using flutter desktop development. Use the group button filter to read data from the database and render it to GridView.builder().
At present, I can't realize the filtering function when I read the data sheet from the database[enter image description here][1]
I am using getx
final selected = 'table_operation'.obs;
final items = ['table_operation', 'merge_table', 'turn_table'];
final SqliteHelper _sqliteHelper = SqliteHelper();
final areas = [].obs;
final selectedAreaType = 0.obs;
final tables = [].obs;
// final filterTables = [].obs;
var areaModel;
final areaId = 0.obs;
void setSelected(value) {
selected.value = value;
}
void setSelectArea(int value) {
selectedAreaType.value = value;
areaModel = areas[selectedAreaType.value];
areaId.value = areaModel.id;
}
#override
onInit() {
getAreaList();
getTableList();
super.onInit();
}
Future<List<AreaModel>> getAreaList() async {
List<Map<String, dynamic>> results = await _sqliteHelper.queryObject('area');
List<AreaModel> areaList = [];
for (var r in results) {
if (r.isNotEmpty) {
areaList.add(AreaModel.fromMap(r));
}
}
areas.value = areaList.map((e) => e).toList();
return areaList;
}
Future<List<TableModel>> getTableList() async {
List<Map<String, dynamic>> results = await _sqliteHelper.queryObject('tables');
List<TableModel> tableList = [];
for (var t in results) {
tableList.add(TableModel.fromMap(t));
}
tables.value = tableList.map((e) => e).toList();
return tableList;
}
[1]: https://i.stack.imgur.com/fOGwg.png

compute() in flutter has no effect

I try to use compute in Flutter. Here I try to pass multiple parameters inside a Map. But the code in my function myFunction does not work. I get no errors or something else. My code seems to be ignored. Do you find an error here?
Compute function:
Map map = Map();
map['resultList'] = resultList;
map['_getImageFileFromAssets'] = _getImageFileFromAssets;
map["picturesData"] = picturesData;
map["albumID"] = albumID;
await compute(myFunction, map);
Calls the following function:
Future<bool> myFunction(map) async {
var resultList = map["resultList"];
var _getImageFileFromAssets = map["_getImageFileFromAssets"];
var picturesData = map["picturesData"];
var albumID = map["albumID"];
print("Starten");
for (var i = 0; i < resultList.length; i++) {
print(i);
File imageFile = await _getImageFileFromAssets(resultList[i]);
final appDir = await syspath.getApplicationDocumentsDirectory();
final fileName = path.basename(imageFile.path);
final savedImage =
await File(imageFile.path).copy('${appDir.path}/$fileName');
// Creating thumbnails
final thumb = image.decodeImage(await File(savedImage.path).readAsBytes());
final thumbImage = image.copyResize(thumb, width: 500);
new File('${appDir.path}/$fileName-thumb-500.jpg')
.writeAsBytes(image.encodeJpg(thumbImage));
final finalThumbImage = File('${appDir.path}/$fileName-thumb-500.jpg');
picturesData.add(Picture(
album: albumID,
path: savedImage.path,
thumbPath: finalThumbImage.path,
timestamp: Timestamp.now()));
}
return true;
}
Ok, some code - I put this in dartpad.dev:
import 'package:flutter/foundation.dart';
void main() {
Map map = Map();
compute(myFunction, map).then((result) => print(result));
}
Future<bool> myFunction(Map map) async {
print("Starten");
// fake long process
await Future.delayed(Duration(seconds: 5));
return true;
}
and get this as a console result:
Starten
true
Also: is there a reason you need the "map" parameter in your function to be dynamic? If not, I'd declare it as type Map (like I did now).

Dart List doesnt get updated with forEach loop

I am using this package to retrieve device's contacts. The lib retrieve 427 contacts and I want to loop the whole list so that I can create another list and send it to the back-end. The problem is looping does not work this the function return before looping is completed.
Here the function I use:
Future<QueryResult> uploadContacts() async {
final List<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false)).toList();
List<ContactInput> contactsListInput;
print('contactsListInput length: ${rawContacts.length}');
rawContacts.forEach((contact) {
print('contact: $contact'); //PRINTED JUST ONCE
//Contact can have more than 1 number. We need them all
contact.phones.forEach((phone) {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
print('contactsListInput length: ${contactsListInput.length}'); //NEVER PRINT ANYTHING
final ContactsListInput input =
ContactsListInput(contacts: contactsListInput);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
I have also tried using for loop and the same thing happened.
for (int i = 0; i < rawContacts.length; i++) {
final contact = rawContacts[i];
final contactInput =
ContactInput(name: contact.displayName, phone: contact.phones.first.value);
contactsListInput.add(contactInput);
}
print('contactsListInput length: ${contactsListInput.length}'); //NEVER CALLED
And I also tried Future.forEach
await Future.forEach(rawContacts, (contact) async {
print('contact: $contact');
//Since contact can have more than one number we loop them too.
await Future.forEach(contact.phones, (phone) async {
final contactInput =
ContactInput(name: contact.displayName, phone: phone.value);
contactsListInput.add(contactInput);
});
});
How to fix this? Any help will be much appreciated.
I have fixed it as
Future<QueryResult> uploadContacts() async {
final Iterable<Contact> rawContacts =
(await ContactsService.getContacts(withThumbnails: false));
final Iterable<ContactInput> contacts = rawContacts.expand((contact) => contact.phones.map(
(phone) =>
ContactInput(name: contact.displayName, phone: phone.value)));
final input = ContactsListInput(contacts: contacts);
final MutationOptions _options = MutationOptions(
document: SyncContactsMutation().document,
variables: SyncContactsArguments(input: input).toJson());
return client.mutate(_options);
}
Credit goes to #pskink and #loganrussell48
You should use it as a dynamic type object. Try something like this:
(event.snapshot.value as dynamic).forEach()
Try and see if it works.