i want to delete an object from list of inventory in which i just have description and url of the inventory and i want to delete object of inventory by description so how can i delete the object.
function in service class
this is my service class
Future<dynamic> requestToRemoveInventory(
String accessToken, List<Inventory> list) async {
try {
var response = await http.patch(Uri.parse(AppUrl.removeInventory),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $accessToken'
},
body: jsonEncode({"inventory": list}));
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = jsonDecode(response.body);
return responseJson;
} else {
var responseJson = jsonDecode(response.body);
print(responseJson);
}
} on SocketException {
throw NoInternetException('No Internet Service');
}
}
This is my Controller class
deleteInventory(List<Inventory> list, BuildContext context) async {
String? accessToken = await preferenceService.getAccessToken();
inventoryService.requestToRemoveInventory(accessToken!, list).then((value) {
getMyInvenoryFromService();
}).catchError((error) {
showSnackBar(error.toString(), context);
});
}
please tell me what logic i have to write in view to delete the object. when i am deleting then all list is deleting at a time
This is my view
PopupMenuButton(
itemBuilder: (context) => [
PopupMenuItem(
onTap: () {
var list = inventoryController
.myInventoryList1
.where((i) =>
i.description !=
inventoryController
.myInventoryList1[
index]
.description)
.toList();
inventoryController
.deleteInventory(
list, context);
},
value: 1,
child: Padding(
padding:
const EdgeInsets.all(
8.0),
child: Text(
"Delete",
style: TextStyle(
color: AppColors
.pinkAppBar,
fontWeight:
FontWeight.w700),
),
),
),
You can use removeWhere
PopupMenuItem(
onTap: () {
var list = inventoryController
.myInventoryList1;
//if you want to remove a single object from list
list.removeWhere((i) =>
i.description ==
list[index].description);
//if you want the only element in the list.
var updateList = list.firstWhere((i) => i.description ==
list[index].description)
inventoryController
.deleteInventory(
list, context);
}
Removing Objects and indexes into the list
List.remove(Object value)
Example of Removing Objects into the list
List l = [1, 2, 3,4,5,6,7,8,9];
bool res = l.remove(1);
Result
[2, 3, 4, 5, 6, 7, 8, 9]
List.removeAt(int index)
Example of Removing Index into the list
List l = [1, 2, 3,4,5,6,7,8,9];
bool res = l.removeAt(1);
result
[1, 3, 4, 5, 6, 7, 8, 9]
Try this way
Here, List contains Inventory class all data. Find or remove data by List object.
List<Inventory> list;
//For removing specific item from a list with the attribute value
list.removeWhere((item) => item.id == '001')
//Remove item by specifying the position of the item in the list
list.removeAt(2)
//Remove last item from the list
list.removeLast()
//Remove a range of items from the list
list.removeRange(2,5)
If you raise any issue raise your query to us.
Related
i want to delete an object from list of inventory in which i just have description and url of the inventory and i want to delete object of inventory by description so how can i delete the object.
function in service class
Future<dynamic> requestToRemoveInventory(
String accessToken, List<TradeWithPictures> list) async {
try {
var response = await http.patch(Uri.parse(AppUrl.removeInventory),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $accessToken'
},
body: jsonEncode({"inventory": list}));
if (response.statusCode == 200 || response.statusCode == 201) {
var responseJson = jsonDecode(response.body);
return responseJson;
} else {
var responseJson = jsonDecode(response.body);
print(responseJson);
}
} on SocketException {
throw NoInternetException('No Internet Service');
}
}
Function Controller class
deleteInventory(List<TradeWithPictures> list, BuildContext context) async {
String? accessToken = await preferenceService.getAccessToken();
inventoryService.requestToRemoveInventory(accessToken!, list).then((value) {
getMyInvenoryFromService();
}).catchError((error) {
showSnackBar(error.toString(), context);
});
}
please tell me what logic i have to write in view to delete the object. when i am deleting then all list is removed.
this is my view
PopupMenuItem(
onTap: () {
var list = inventoryController
.myInventoryList1
.where((i) =>
i.description !=
inventoryController
.myInventoryList1[
index]
.description)
.toList();
inventoryController
.deleteInventory(
list, context);
},
value: 1,
child: Padding(
padding:
const EdgeInsets.all(
8.0),
child: Text(
"Delete",
style: TextStyle(
color: AppColors
.pinkAppBar,
fontWeight:
FontWeight.w700),
),
),
),
Here is a simple example of how you can filter out your results from a list,
filteredResulst = AllRecords.where((i) => i.aParticularProperty === thingToCompare ).toList();
this is my API response
var = ''' [
{
"entity_id": "86",
"building_name": "Burj Khalifa",
"location": "Al Ttay",
"image_field": "1595916594oad.jpeg"
},
{
"entity_id": "87",
"building_name": "Azmair",
"location": " Eyal Nasser ",
"image_field": "1596541099s.jpeg"
},
{
"entity_id": "88",
"building_name": "Bella Casa",
"location": "Hatta",
"image_field": "15965463423abe68a5bc11733effefeb91194_767x0.jpg"
}
]''';
I am making it as a string using
var decoded = response as List;
var buildgnames = decoded.map<String>((e) => e['building_name']).toList();
how to get "entity_id" with the when select building name in a list?
like when I choose "Burj Khalifa" in a drop-down I want to get the "id" of it
Here is a great guide on how json and serialization works in Flutter:
https://flutter.dev/docs/development/data-and-backend/json
Basically you create a model for your data structure:
class Entity {
int entityId;
String buildingName;
String location;
String imageField;
Entity({this.entityId, this.buildingName, this.location, this.imageField});
Entity.fromJson(Map<String, dynamic> json) :
entityId = json["entity_id"],
buildingName = json["building_name"],
location = json["location"],
imageField = json["imageField"];
}
When you have done that, you can deserialize your json like this using the dart:convert package:
var jsonMap = jsonDecode(jsonString);
var entity = Entity.fromJson(jsonMap);
After this you can put your entity as the data to select in the dropdown. And when you select "Burj Khalifa". You can simply check entity.id
DropdownButtonFormField(
hint: Text("Building"),
onChanged: ((val) {
setState((){
print(val. entity_id);
selectedBuilding = val;
});
}),
value: selectedBuilding ?? null,
items: buildingList.map<DropdownMenuItem>((BuildingModel value) {
return DropdownMenuItem(
value: value,
child: Text(value.building_name),
);
}).toList(),
decoration: InputDecoration(
icon: Icon(Icons.access_time)
),
);
You can get your selected building model :
onChanged: ((val) {
setState((){
print(val. entity_id);
selectedBuilding = val;
});
}),
you can use foreach for accessing each element of list like
decoded.forEach((element) {
var entity_id = element['entity_id'];
})
In your case when you select the drop down button you will get the index of item use that index and fetch it like this
var entity_id = decoded.elementAt(index)['entity_id'];
First of all you have to create model class.
class Building {
String id;
String buildingName;
String location;
String imageField;
Building({this.id, this.buildingName, this.location, this.imageField});
Building.fromJson(Map<String, dynamic> json) {
id = json['entity_id'];
buildingName = json['building_name'];
location = json['location'];
imageField = json['image_field'];
}
}
After that convert response to Building object.
Iterable mJson = json.decode(response.body);
List<Building> buildingList = mJson.map((model) => Building.fromJson(model)).toList();
Show building list name and return building id when click.
Expanded(
child: ListView.separated(
separatorBuilder: (context, index) => Divider(
color: Colors.grey,
),
itemCount: buildings?.length ?? 0,
itemBuilder: (BuildContext ctxt, int index) {
return InkWell(
onTap: () => _handleRowTap(buildings[index].id),
child: Padding(
padding: EdgeInsets.all(8),
child: Text(
"${buildings[index].buildingName}",
),
));
}));
And the latest.
_handleRowTap(String buildingId) {
//Handle click event here
}
I'm building a selectable checkbox contact list in flutter but if a contact has only an email and no number, an error is thrown. I want to create a loop to add a number of '99999' to the contacts phone number if they don't have one. Please can someone guide me with an explanation of what I should change to make this work? I have had a go, but I am quite new to flutter so I'm not completely certain on syntax etc...
Here is the part of the code that I am trying to put the function into.
setMissingNo()async {
Iterable<Contact> contactsToLoop = (await ContactsService.getContacts()).toList();
contactsToLoop.forEach((Contact) { contactsToLoop = []..add(Item.fromMap({'label': 'work', 'value': 99999})); });
}
//fetch contacts from setMissingNo
getAllContacts() async{
Iterable<Contact> _contacts = (await ContactsService.getContacts()).toList();
setState(() {
contacts = _contacts;
}
);
}
Here is my whole code
import 'package:flutter/material.dart';
// TODO: make it ask for permissions otherwise the app crashes
import 'package:contacts_service/contacts_service.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
List<Contact> contacts = [];
List<Contact> contactsFiltered = [];
TextEditingController searchController = new TextEditingController();
#override
void initState() {
super.initState();
getAllContacts();
searchController.addListener(() => filterContacts());
}
//remove the +'s and spaces from a phone number before its searched
String flattenPhoneNumber(String phoneStr) {
return phoneStr.replaceAllMapped(RegExp(r'^(\+)|\D'), (Match m) {
return m[0] == "+" ? "+" : "";
});
}
//loop and set all contacts without numbers to 99999, pass new list to getAllContacts
setMissingNo()async {
Iterable<Contact> contactsToLoop = (await ContactsService.getContacts()).toList();
contactsToLoop.forEach((Contact) { contactsToLoop = []..add(Item.fromMap({'label': 'work', 'value': 99999})); });
}
//fetch contacts from setMissingNo
getAllContacts() async{
Iterable<Contact> _contacts = (await ContactsService.getContacts()).toList();
setState(() {
contacts = _contacts;
}
);
}
//filtering contacts function to match search term
filterContacts() {
List<Contact> _contacts = [];
_contacts.addAll(contacts);
if (searchController.text.isNotEmpty) {
_contacts.retainWhere((contact) {
String searchTerm = searchController.text.toLowerCase();
String searchTermFlatten = flattenPhoneNumber(searchTerm);
String contactName = contact.displayName.toLowerCase();
bool nameMatches = contactName.contains(searchTerm);
if (nameMatches == true) {
return true;
}
if (searchTermFlatten.isEmpty) {
return false;
}
var phone = contact.phones.firstWhere((phn) {
String phnFlattened = flattenPhoneNumber(phn.value);
return phnFlattened.contains(searchTermFlatten);
}, orElse: () => null);
return phone != null;
});
setState(() {
contactsFiltered = _contacts;
});
}
}
final selectedContacts = Set<Contact>();
#override
Widget build(BuildContext context) {
bool isSearching = searchController.text.isNotEmpty;
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
AppBar(
title: Text('Create Group'),
),
Container(
child: TextField(
controller: searchController,
decoration: InputDecoration(
labelText: 'Search Contacts',
border: OutlineInputBorder(
borderSide: new BorderSide(
color: Theme.of(context).primaryColor
)
),
prefixIcon: Icon(
Icons.search,
color: Theme.of(context).primaryColor
)
),
),
),
Expanded( child: ListView.builder(
shrinkWrap: true,
itemCount: isSearching == true ? contactsFiltered.length : contacts.length,
itemBuilder: (context, index) {
Contact contact = isSearching == true ? contactsFiltered[index] : contacts[index];
//TODO: make it so when you clear your search, all items appear again & when you search words it works
return CheckboxListTile(
title: Text(contact.displayName),
subtitle: Text(
contact.phones.elementAt(0).value
),
value: selectedContacts.contains(contact),
onChanged: (bool value) {
if (value) {
selectedContacts.add(contact);
} else {
selectedContacts.remove(contact);
}
setState((){});
// TODO: add in function to add contact ID to a list
});
},
),
/*new Expanded(
child: Align(
alignment: Alignment.bottomLeft,
child: BottomNavigationBar(
currentIndex: _currentIndex,
items: const <BottomNavigationBarItem>[
//TODO: create new contact functionality to add someone by name + email
BottomNavigationBarItem(
icon: Icon(Icons.add),
title: Text('Add Contact'),
),
BottomNavigationBarItem(
icon: Icon(Icons.create),
title: Text('Create Group'),
),
],
onTap: (index) {
setState(() {
_currentIndex = index;
});
}
)
)
)*/
)
],
)
),
);
}
}
Updating all contacts listed on the device might take a long time depending on the size of the device's contact list. Add that the task is being done on the UI thread. You may want to consider using Isolate for the task to move away the load from the UI thread. If you can also provide the errors that you're getting, it'll help us get a picture of the issue.
Another thing is, the way you're approaching the issue might be impractical. Is it really necessary to write a placeholder phone number to the contacts? The issue likely stems from trying to fetch the number from a contact but the Object returns null. Perhaps you may want to consider only updating the phone number when the contact is selected.
I am able to fetch and print the data in json format in console and I am able to display the entire body of data in list format in the flutter app. But I can't figure out how to display only a specific key and its value in list. Its a list of maps. I have removed the consumer key and secret from this code.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main(){
runApp(MaterialApp(
home: CustomHome(),
));
}
class CustomHome extends StatefulWidget {
#override
_CustomHomeState createState() => _CustomHomeState();
}
class _CustomHomeState extends State<CustomHome> {
List data;
Future<String> getData() async{
var response = await http.get('https://jbaat.com/wp-json/wc/v3/products/?consumer_key=&consumer_secret=');
setState(() {
var converted = jsonDecode(response.body);
data = converted;
});
}
#override
void initState() {
// TODO: implement initState
super.initState();
this.getData();
}
#override
Widget build(BuildContext context) {
print(data);
return Scaffold(
body: ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return Container(
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('$data'),
),
),
);
}),
);
}
}
Below is the response
[{id: 493, name: Bas 5 Min White Half Sleeve T-Shirt, slug: bas-5-min-white-half-sleeve-t-shirt, permalink: https://www.jbaat.com/product/bas-5-min-white-half-sleeve-t-shirt/, date_created: 2019-12-14T23:39:08, date_created_gmt: 2019-12-14T18:09:08, date_modified: 2019-12-14T23:48:01, date_modified_gmt: 2019-12-14T18:18:01, type: variable, status: publish, featured: false, catalog_visibility: visible, description: , short_description: , sku: , price: 500.00, regular_price: , sale_price: , date_on_sale_from: null, date_on_sale_from_gmt: null, date_on_sale_to: null, date_on_sale_to_gmt: null, price_html: <span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">₹</span>500.00</span>, on_sale: false, purchasable: true, total_sales: 0, virtual: false, downloadable: false, downloads: [], download_limit: -1, download_expiry: -1, external_url: , button_text: , tax_status: taxable, tax_class: , manage_stock: false, stock_quantity: null, stock_status: instock, backorders: no,
Jbaat, I'd recommend creating a model for your response data and use the values accordingly from each item's instance. There are few online converters available which converts your json response to Dart models, here is one - https://javiercbk.github.io/json_to_dart/. Below is a quick example of what it would look like based on your response data,
class Items {
final List<Items> items;
Items({this.items});
factory Items.fromJson(List<dynamic> json) {
List<Items> itemList = json.map((i) => Items.fromJson(i)).toList();
return Items(
items: itemList
);
}
}
class Item {
final int id;
final String name;
......
Item({this.id, this.name,.....});
factory Item.fromJson(Map<String, dynamic> json) {
return Item(
id: json['id'],
name: json['name']
......
);
}
}
And then your getData() would be,
Future<Items> getData() async{
var response = await http.get('https://jbaat.com/wp-json/wc/v3/products/?consumer_key=&consumer_secret=');
return Items.fromJson(json.decode(response.body)).items;
}
You should now have Item list which can be used to get specific item info. You should also use FutureBuilder to call your getData() instead of calling it in initState to make sure data is available before building widgets like so,
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Scaffold(
body: ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
Item item = snapshot.data[index]; //Your item
return Container(
child: Card(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(item.name),
),
),
);
}),
);
} else {
return Center(child: CircularProgressIndicator());
}
});
}
Hope this helps. Good luck!
Change the type for data to
List<Map<String,dynamic>>
A possible implementation for your use case:
Map y;
var keytobesearched='name';
List<Map<String,dynamic>> x= [{'id': 493, 'name': 'Bas 5 Min White Half Sleeve T-Shirt', 'slug': 'bas-5-min-white-half-sleeve-t-shirt'}];
x.forEach((Map<String,dynamic> ele){
if(ele.containsKey(keytobesearched))
y=Map.from(ele);
// display/alter y to your liking
});
If you would want a complete plug and play Woocommerce Sdk that handles authentication, products, customer, shipping etc for you, you can use the Woo Commerce SDK library for flutter at https://pub.dev/packages/woocommerce
Woocommerce myWoocommerce = WooCommerce(baseUrl: yourBaseUrl, consumerKey: yourConsumerKey, consumerSecret: consumerSecret);
Then simply get your lists eg:
WooProduct products = await myWocommerce.getProducts(); // returns the ist of products.
for (var product in products){ print(product.name)};
Im having trouble populating ListTile in ListView.builder from database.
I dont have "model class" since i dont need to update delete data i just need simple query.
I have ExpansionTile with three categories and in each one i need query from db. I dont know hoe to write or what to return from db class for this to work.
child: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemBuilder: (context, i) => ExpansionTile(
title: new Text(
'${categoryName[i]}',
style: TextStyle(
fontSize: 18,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(49, 85, 158, 1)),
),
children: list //final list = new List.generate(17, (i) => "Item ${i + 1}"); --just to populete with dummy items, instad of this i need db data
.map((val) => ListTile(
// leading: Icon(Icons.add),
title: new Row(
children: <Widget>[
new Checkbox(
value: _isCheck,
onChanged: (bool value) {
onChange(value);
}),
new Expanded(child: new Text(val)),
],
)))
.toList(),
),
itemCount: categoryName.length,
),
),
],
),
From my db class :
Future<List> getAllNotes() async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'books.db');
Database database = await openDatabase(path, version: 1);
//var dbClient = await database();
var result = await database.rawQuery('SELECT * FROM $booksTable WHERE $colDescription = ${'Adventure'}');
return result.toList();
}
So how to write simple query to get result in ListView/ListTile?
You really need to provide much more details about your problem. Anyways, ill try to answer with what I have understood.
Let's say you have a table names 'booksTable' with 3 fields:
bookId | bookName | bookCategory
1 Book A Adventure
2 Book B History
3 Book C Adventure
4 Book D History
Make sure you create all these database functions in DatabaseHelper() class, so that you don't have to write logic to db again and again.
Now you query will look something like this:
Future<List<String>> getAllNotes(String category) async {
var dbClient = await database();
List<String> bookNames = List<String();
var result = await dbClient.rawQuery("SELECT bookname FROM booksTable WHERE bookCategory = $category");
result.forEach((item) {
bookNames.add(item["bookname"]);
});
return bookNames;
}
This will work only if you have to deserialise 1 column. If you have multiple columns selected, you have to create a model class.
Now in your front view, you have two options:
1) You can use initState to populate your List with bookNames of category in the parameter
2) You can use FutureBuilder to populate your list as well
(You have to use StatefulWidget for both these options)
I'll show you how to do it using initState here. If you want to know how to do it using FutureBuilder, let me know in comments.
List<String> booksList =List<String>();
var db = DatabaseHelper();
readList() async {
booksList = await db.getAllNotes("Adventure");
}
#override
void initState() {
super.initState();
readList();
}
ListView.builder(
itemBuilder: (context, i) {
Column( crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ExpansionTile(
title: new Text(
"Adventure Category",
style: TextStyle(
fontSize: 18,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.bold,
color: Color.fromRGBO(49, 85, 158, 1)),
),
ListTile(
title: new Row(
children: <Widget>[
new Checkbox(
value: _isCheck,
onChanged: (bool value) {
onChange(value);
}),
Expanded(child: new Text("${booksList[i]}")),
],
)))
),])}
itemCount: booksList.length,
),
),
],
)
Note: There might be typos in the code above, since i have typed it on phone, but you get the idea how to do it, right?
So, i have ListView (with 3 expanded groups) im geting them from array: ( List categoryName = ['Part 1: Adventure', 'Part 2: History','Part 3: Horror'];
And passing then here :
child: Column(
children: [
Expanded(
child: ListView.builder(
itemBuilder: (context, i) => ExpansionTile(
title: new Text(
'${categoryName[i]}',
),
That part working fine, i get 3 expandeble titles, now children of that ( ListTile ) need to be populate from db .
With your example :
readList() async {
sinsAgainstGod = await db.getSins("Adventure");
}
I get error: ...near "Adventure": syntax error..
And keep geting 0 lenght on booksList...
Future<List<String>> getNotes(String category) async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'books.db');
Database database = await openDatabase(path, version: 1);
List<String> bookNames = List<String>();
var result = await database.rawQuery("SELECT $colDescription FROM $booksTable WHERE = $category ");
result.forEach((item) {
bookNames.add(item['Category']);
});
return bookNames;
}
What this result.forEach(item) suppose to do?
Thank you for your answer it was helpful.
Can you tell me why im getting 20 same description instead literate through all with this code:
Future<List<String>> getSins(String column) async {
var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'confession.db');
Database database = await openDatabase(path, version: 1);
List<String> bookNames = List<String>();
for (int i = 0; i < 20; i++) {
var result = await database.rawQuery(
'SELECT * FROM $plannerTable WHERE $colCategory= "Adventure');
bookNames.add((result[0][column].toString()));
}
return bookNames;
}
I want to get all decription from adventure category. Tnx