I am simply splitting the values of string but it's showing the error
My code
List<Map<String, String>> divideString(String wording) {
final policies = wording.split('|').where((w) => w != '');
var displayData = <Map<String, String>>[];
policies.forEach((policy) {
final splited = policy.split('=');
final displayPolicy = <String, String>{
'name': splited[0],
'value': splited[1]
};
displayData.add(displayPolicy);
});
return displayData;
}
if I remove 'value': splited[1] its working fine I think in some places 'value': splited[1] is empty so maybe its showing error?
String something looks like this
I/flutter (14910): INPATIENT & DAYCARE||||||||||PRE-AUTHORIZATION=MANDATORY AT NON-PANEL HOSPITALS|||||HOSPITAL NETWORK=220+ FACILITIES NATIONWIDE|||||EMERGENCY HOTLINE NOS.=ROUND THE CLOCK|||||ACCIDENTAL EMERGENCIES=25% ENHANCEMENT IN AVAILABLE INPATIENT LIMITS|||||PRE-HOSPITALIZATION=30 DAYS BEFORE HOSPITALIZATION|||||POST-HOSPITALIZATION=30 DAYS AFTER HOSPITALIZATION|||||DAYCARE PROCEDURES=UNLIMITED|||||ICU CONFINEMENT=UNLIMITED|||||DENTAL TREATMENT=WHEN REQD. DUE TO ACCIDENT FOR PAIN RELIEF ONLY|||||LOCAL AMBULANCE=TO AND BETWEEN HOSPITALS|||||CATARACT SURGERY=COVERED WITH STANDARD FOLDABLE LENS ONLY|||||SPECIALIZED INVESTIGATIONS=COVERED e.g., CT Scan, MRI, ECHO etc.|||||VACCINATIONS=1ST DOSE COVERED AT BIRTH|||||MATERNITY BENEFITS||||||||||PRE / POST NATAL EXPENSES=10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS|||||CIRCUMCISION BENEFIT=10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS|||||DELIVERY BY MIDWIFE PKR.5000/-|||||SPECIAL BENEFITS||||||||||HEPATITIS TREATMENT=COVERED|||||CONGENITAL CONDITIONS=NOT COVERED|||||PRE EXISTI
What I am doing is break the line when this symbol shows "|" and split it when "=" symbol show but the issue is somewhere = sign isn't available
Try this:
List<Map<String, String>> divideString(String wording) {
List<String> policies = wording.split('|');
List<Map<String, String>> displayData = [];
policies.forEach((policy) {
final List<String> splited = policy.split('=');
// If an '=' sign is present, the length will be == 2
if(splited.length == 2){
final displayPolicy = <String, String>{
'name': splited[0],
'value': splited[1]
};
displayData.add(displayPolicy);
}
});
print('======= output, line by line =======');
displayData.forEach((item) => print(item));
print('\n');
print('======= returned data, unformatted =======');
print(displayData);
return displayData;
}
Output:
======= output, line by line =======
{name: PRE-AUTHORIZATION, value: MANDATORY AT NON-PANEL HOSPITALS}
{name: HOSPITAL NETWORK, value: 220+ FACILITIES NATIONWIDE}
{name: EMERGENCY HOTLINE NOS., value: ROUND THE CLOCK}
{name: ACCIDENTAL EMERGENCIES, value: 25% ENHANCEMENT IN AVAILABLE INPATIENT LIMITS}
{name: PRE-HOSPITALIZATION, value: 30 DAYS BEFORE HOSPITALIZATION}
{name: POST-HOSPITALIZATION, value: 30 DAYS AFTER HOSPITALIZATION}
{name: DAYCARE PROCEDURES, value: UNLIMITED}
{name: ICU CONFINEMENT, value: UNLIMITED}
{name: DENTAL TREATMENT, value: WHEN REQD. DUE TO ACCIDENT FOR PAIN RELIEF ONLY}
{name: LOCAL AMBULANCE, value: TO AND BETWEEN HOSPITALS}
{name: CATARACT SURGERY, value: COVERED WITH STANDARD FOLDABLE LENS ONLY}
{name: SPECIALIZED INVESTIGATIONS, value: COVERED e.g., CT Scan, MRI, ECHO etc.}
{name: VACCINATIONS, value: 1ST DOSE COVERED AT BIRTH}
{name: PRE / POST NATAL EXPENSES, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}
{name: CIRCUMCISION BENEFIT, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}
{name: HEPATITIS TREATMENT, value: COVERED}
{name: CONGENITAL CONDITIONS, value: NOT COVERED}
======= returned data, unformatted =======
[{name: PRE-AUTHORIZATION, value: MANDATORY AT NON-PANEL HOSPITALS}, {name: HOSPITAL NETWORK, value: 220+ FACILITIES NATIONWIDE}, {name: EMERGENCY HOTLINE NOS., value: ROUND THE CLOCK}, {name: ACCIDENTAL EMERGENCIES, value: 25% ENHANCEMENT IN AVAILABLE INPATIENT LIMITS}, {name: PRE-HOSPITALIZATION, value: 30 DAYS BEFORE HOSPITALIZATION}, {name: POST-HOSPITALIZATION, value: 30 DAYS AFTER HOSPITALIZATION}, {name: DAYCARE PROCEDURES, value: UNLIMITED}, {name: ICU CONFINEMENT, value: UNLIMITED}, {name: DENTAL TREATMENT, value: WHEN REQD. DUE TO ACCIDENT FOR PAIN RELIEF ONLY}, {name: LOCAL AMBULANCE, value: TO AND BETWEEN HOSPITALS}, {name: CATARACT SURGERY, value: COVERED WITH STANDARD FOLDABLE LENS ONLY}, {name: SPECIALIZED INVESTIGATIONS, value: COVERED e.g., CT Scan, MRI, ECHO etc.}, {name: VACCINATIONS, value: 1ST DOSE COVERED AT BIRTH}, {name: PRE / POST NATAL EXPENSES, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}, {name: CIRCUMCISION BENEFIT, value: 10% OF MAT. or PKR 2,000/- WHICHEVER IS LESS}, {name: HEPATITIS TREATMENT, value: COVERED}, {name: CONGENITAL CONDITIONS, value: NOT COVERED}]
modifiy your code like this to see where the problem is.
List<Map<String, String>> divideString(String wording) {
final policies = wording.split('|').where((w) => w != '');
var displayData = <Map<String, String>>[];
policies.forEach((policy) {
if(policy.contains('=')){
final splited = policy.split('=');
final displayPolicy = <String, String>{
'name': splited[0],
'value': splited[1]
};
displayData.add(displayPolicy);
}else{
print('no suitable data in ' + policy);
}
});
return displayData;
}
Related
I am new to flutter and I am in need of some help.
I have a list of objects here.
List<ProductOrdered> myList = [product1, product2, product3];
This is how the three ProductOrdered objects looks like:
ProductOrdered product1 = ProductOrdered(
name: 'Caramida 16x16 chestie, rosu, chestie chestie chestie ',
price: '4.99',
supplierName: 'Dedeman Leroy Merlin',
nr: '12345678',
day: '08',
month: '02',
year: '2002',
total: '31.99',
category: 'Solide',
);
ProductOrdered product2 = ProductOrdered(
name: 'Ciment 16x16 chestie, rosu, chestie chestie chestie ',
price: '3.99',
supplierName: 'Dedeman',
nr: '21345678',
day: '09',
month: '02',
year: '2002',
total: '41.99',
category: 'Prafoase',
);
ProductOrdered product3 = ProductOrdered(
name: 'Tigla 16x16 chestie, rosu, chestie chestie chestie ',
price: '5.99',
supplierName: 'Leroy Merlin',
nr: '31245678',
day: '10',
month: '02',
year: '2002',
total: '51.99',
category: 'Acoperis',
);
And I would like to sort the elements in this list by their prices, when a button is clicked. First time the button is clicked I want to make it ascending, second time descending. However I got stuck at the first part.
I defined a method
_onSortPrice(list) {
setState(() {
list.sort((a, b) => a.price.compareTo(b.price));
});
}
And I called it when the button was clicked
TextButton(
onPressed: () {
_onSortPrice(myList);
},
Nothing happens when I click it. I tried to remove the SetState from the funcion or used just sort method outside the button to see if the page starts with the objects sorted, and it does.
Thanks for reading.
You have set the price as String in the model. So, convert the string to double in the comparision.
list.sort((a, b) => double.parse(a.price).compareTo(double.parse(b.price)));
Good Morning everyone, I want ask a question if I have a list of map like this
[{
id: 1,
title: Medicine 500,
price: 100,
image: http://secret-taiga-11502.herokuapp.com/images/medicines,
quantity: 1,
pharmacyid: 15,
medicineID: 500
}]
and I want to search for an item medicineID to make a compression
how can I do this
this my code
var extractMap = cubit.myItems.map(
(element) => Map.fromEntries(
[MapEntry('medicine_id', element['medicineID']),])).toList();
if(
extractMap.contains(
cubit.onePharmacyModel!.data!.activeMedicines![index].id!.toInt())
){
cubit.updateQuery(
++cubit.myItems[index]["quantity"],
cubit.myItems[index]['id'],
cubit.onePharmacyModel!.data!.id!.toInt()
);
Fluttertoast.showToast(msg: "cart updated");
}else{
cubit.insertToDatabase(
title: cubit.onePharmacyModel!.data!.activeMedicines[index].name.toString(),
price: cubit.onePharmacyModel!.data!.activeMedicines[index].pivot!.price!.toString(),
image: cubit.onePharmacyModel!.data!.activeMedicines[index].photo.toString(),
quantity: 1,
pharmacyID: cubit.onePharmacyModel!.data!.id!.toInt(),
medicineID: cubit.onePharmacyModel!.data!.activeMedicines[index].id!.toInt());
Fluttertoast.showToast(msg: "product added to cart");
}
the general idea of code that the user when add a product to the cart I'm checking if it's already exist or not if yes => I'll update the amount of this product, if no => T'll insert it into my Database
Try something like:
if (myItems.any((e) => e['medicineID'] == 58)) {
// ...
}
I'm using ag-grid in Angular9 project. I'm using Transactions to do CRUD operations in grid when my backend request resolve. I need to provide RowNodeId myself, i dont want to use object-references as i have large data set.
Thing is, i've provided the ID and i can add/update item in the grid but i'm unable to delete the item. In Doc it mentions, you only need to provide id to remove the item but i'm getting the following error.
Here's the code.
class HostAppListPage
{
#ViewChild('agGrid', {static: true}) grid:AgGridAngular;
constructor()
{
}
ngOnInit()
{
this.grid.getRowNodeId = (data) => {
return data.entityId;
};
this.columns = [
{headerName: 'App Name', field: 'name', rowDrag: true, headerCheckboxSelection: true, checkboxSelection: true},
{headerName: 'App Id', field: 'id'},
{headerName: 'Compatibility', field: COMPATIBILITY'},
{headerName: 'Creation', field: 'createdAtToString'},
{headerName: 'Last Update', field: 'updatedAtToString'}
];
}
deleteRow()
{
let ids = this.gridApi.getSelectedNodes()
// .map((row) => {
// return {id: row.entityId}
// return row.entityId;
// });
console.log(ids);
this.grid.api.applyTransaction({remove: ids});
}
I tried both with and without map statement, nothing worked
but my Add and Update works fine.
Replace map with following code.
.map((row) => {
return {entityId: row.data.entityId};
});
it should be the the same field (entityId) which i set in getRowNodeId function.
In a typical situation, where one does not define a getRowNodeId, one should be able to do:
const removeData: any[] = [{id: rowNode0.id}, {id: rowNode1.id}, ...];
applyTransaction({remove: removeData});
where rowNode0, rowNode1, etc. are the nodes you want to remove.
However when you provide your own getRowNodeId callback, ag-grid will fetch the id's by applying your callback on the data you provided. Therefore, the name(s) in the data must match those used in your callback. That's why return {id: row.entityId} doesn't work, but return {entityId: row.entityId} does.
In other words, if one defines:
this.grid.getRowNodeId = (data) => {
return data.column1 + data.column5 + data.column2;
};
Then one would need to provide
const removeData: any[] = [
{column1: 'a1', column2: 'b1', column5: 'c1'},
{column1: 'a2', column2: 'b2', column5: 'c2'},
{column1: 'a3', column2: 'b3', column5: 'c3'},
];
so that ag-grid would have all the names it needs to find the id's via the given getRowNodeId.
Experimenting with charts for the first time, trying to setup a simple chart here which is simply based on 3 values from the table seen in the snapshot below (chart positioned exactly below): Type ID, Avg Gross Turnaround Time (1st occurence), Avg Net Turnaround Time (1st occurence) and (as visible) I get the aforementioned error.
Chart Error
Of course, before posting I had a look to similar questions and in all cases the solution was the same, that the values provided in the measures/dimensions of the dataset must be the same (makes sense) with the ones provided with the FeedItems method. Problem is that I have them right. Thought about a syntax error within the dataset/feed definitions (eg, single instead of double quotes). Tried numerous combinations so far, result always the same, so I ended up leaving the only syntax that wasn't giving me blue warnings in the editor. (Extremely short) controller code follows below. Does this ring any bells?
Regards
Greg
var oVizFrame = this.getView().byId("idStackedChart");
oVizFrame.setVizProperties({
plotArea: {
colorPalette: d3.scale.category20().range(),
dataLabel: {
showTotal: true
}
},
tooltip: {
visible: true
},
title: {
text: "Stacked Bar Chart"
}
});
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions: [{
name: "Type",
value: "{AgrTypeid}"
}],
measures: [{
name: "Gross Turnaround",
value: "{Yr1Avggta}"
}, {
name: "Net Turnaround",
value: "{Yr1Avgnta}"
}],
data: {
path: "/Agreement_Summary"
}
});
oVizFrame.setDataset(oDataset);
oVizFrame.setModel();
var oFeedValueAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
uid: "valueAxis",
type: "Measure",
values: ["Yr1Avggta"]
}),
oFeedValueAxis1 = new sap.viz.ui5.controls.common.feeds.FeedItem({
uid: "valueAxis",
type: "Measure",
values: ["Yr1Avgnta"]
}),
oFeedCategoryAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
uid: "categoryAxis",
type: "Dimension",
values: ["AgrTypeid"]
});
oVizFrame.addFeed(oFeedValueAxis);
oVizFrame.addFeed(oFeedValueAxis1);
oVizFrame.addFeed(oFeedCategoryAxis);
Alright, it works a little different, here's the correct feed code:
var oFeedValueAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
uid: "valueAxis",
type: "Measure",
values: ["Type"] //--> should be same as Measure name
}),
oFeedValueAxis1 = new sap.viz.ui5.controls.common.feeds.FeedItem({
uid: "valueAxis",
type: "Measure",
values: ["Gross Turnaround"] //--> should be same as Measure name
}),
oFeedCategoryAxis = new sap.viz.ui5.controls.common.feeds.FeedItem({
uid: "categoryAxis",
type: "Dimension",
values: ["Net Turnaround"] //--> should be same as Dimension name
});
I'm trying to filter food items based on their category but keep getting the below error.
The idea is to manually pass a String for the category of my choice using the Provider package and then filter and print the items that match the category from the list that has the food items.
I/flutter ( 7404): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 7404): The following _TypeError was thrown building TestClass(dirty, dependencies:
I/flutter ( 7404): [_InheritedProviderScope<DummyData>]):
I/flutter ( 7404): type 'WhereIterable<Products>' is not a subtype of type 'List<Products>'
Here is the snippet of the dummy data where I have the categories and food items defined in the lists named categories and products respectively. I'm pretty confident that the filter at the end is not very well defined.
class DummyData with ChangeNotifier {
List<Categories> categories = [
Categories(
catId: '1',
title: 'American',
imageUrl: 'https://www.recipetineats.com/wp-content/uploads/2016/02/Beef-Hamburgers_7-2.jpg?w=500&h=500&crop=1'
),
Categories(
catId: '2',
title: 'North Indian',
imageUrl: 'https://static.toiimg.com/thumb/53205522.cms?width=1200&height=1200'
),
Categories(
catId: '3',
title: 'Chinese',
imageUrl: 'https://uploads-ssl.webflow.com/5c481361c604e53624138c2f/5c6cd55ca1bcb14248ded5c4_chilli-pork-website-thumbnail-.png'
),
];
List<Products> products = [
Products(
id: '1',
name: 'Mac & Cheese',
preparationTime: '30 mins',
imageUrl: 'https://www.inspiredtaste.net/wp-content/uploads/2018/10/Easy-Creamy-Stovetop-Mac-and-Cheese-1200.jpg',
category: 'American'
),
Products(
id: '2',
name: 'Hamburger',
preparationTime: '30 mins',
imageUrl: 'https://www.recipetineats.com/wp-content/uploads/2016/02/Beef-Hamburgers_7-2.jpg?w=500&h=500&crop=1',
category: 'American'
),
Products(
id: '3',
name: 'Chilli Pork',
preparationTime: '1 Hr',
imageUrl: 'https://uploads-ssl.webflow.com/5c481361c604e53624138c2f/5c6cd55ca1bcb14248ded5c4_chilli-pork-website-thumbnail-.png',
category: 'Chinese'
),
Products(
id: '4',
name: 'Fried Rice',
preparationTime: '15 mins',
imageUrl: 'https://www.saveur.com/resizer/lijLVB5tWYhp-81mavFmDDxy_Xo=/600x600/arc-anglerfish-arc2-prod-bonnier.s3.amazonaws.com/public/SITSUSMWR7A2IQ64GMSPSIOOQE.jpg',
category: 'Chinese'
),
Products(
id: '4',
name: 'Butter Chicken',
preparationTime: '1 Hr',
imageUrl: 'https://static.toiimg.com/thumb/53205522.cms?width=1200&height=1200',
category: 'North Indian'
),
Products(
id: '5',
name: 'Chicken Tikka Masala',
preparationTime: '1 Hr',
imageUrl: 'https://i2.wp.com/spicecravings.com/wp-content/uploads/2017/08/Palak-Paneer-5-500x500.jpg',
category: 'North Indian'
),
List<Categories> get categoryType {
return [...categories];
}
List<Products> get food {
return[...products];
}
List<Products> filter(String title) {
return products.where((element) => element.category == title);
}
}
I think the question is already answered. But instead of walking through the characters of the string it is better to use the standard Java library as follows:
name = in.readLine();
if (name != null && !"".equals(name)) {
String[] arr = name.split("\\s+");
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
The split() method does what you're trying to program yourself.
The string \\s+ ist a regular expression which represents one or more space characters (space, newline, ...). You could also use " " instead, but in this case your input must contain only one space character.
Example:
System.out.println("Enter Name");
Input:
firstname secondname lastname
output:
firstname
secondname
lastname
When you first loop finishes you have last word in str variable.
You need t o add arr[k++] = str; after loop to put it into array.