Flutter/Dart: How to get list value where key equals - list

I'm not sure why I'm having such a hard time finding an answer for this, but I have a list that I need to get the value from where the key matches certain criteria. The keys are all unique. In the example below, I want to get the color where the name equals "headache". Result should be "4294930176".
//Example list
String trendName = 'headache';
List trendsList = [{name: fatigue, color: 4284513675}, {name: headache, color: 4294930176}];
//What I'm trying
int trendIndex = trendsList.indexWhere((f) => f.name == trendName);
Color trendColor = Color(int.parse(trendsList[trendIndex].color));
print(trendColor);
Error I get: Class '_InternalLinkedHashMap' has no instance getter 'name'. Any suggestions?
EDIT:
Here's how I'm adding the data to the list, where userDocuments is taken from a Firestore collection:
for (int i = 0; i < userDocument.length; i++) {
var trendColorMap = {
'name': userDocument[i]['name'],
'color': userDocument[i]['color'].toString(),
};
trendsList.add(trendColorMap);
}

I guess, I got what the problem was. You were making a little mistake, and that was, you're trying to call the Map element as an object value.
A HashMap element cannot be called as f.name, it has to be called f['name']. So taking your code as a reference, do this, and you are good to go.
String trendName = 'headache';
List trendsList = [{'name': 'fatigue', 'color': 4284513675}, {'name': headache, 'color': 4294930176}];
//What I'm trying
// You call the name as f['name']
int trendIndex = trendsList.indexWhere((f) => f['name'] == trendName);
print(trendIndex) // Output you will get is 1
Color trendColor = Color(int.parse(trendsList[trendIndex]['color'])); //same with this ['color'] not x.color
print(trendColor);
Check that out, and let me know if that helps you, I am sure it will :)

Related

How to make an If statement check for if a variable equals a negative number; issue making an adventure game with X,Y coordinates

I'm new to Javascript (and coding in general), and I'm trying to make a pretty basic in-browser adventure game, but immediately I've encountered a problem. I wanted it to plot your location as if on an X,Y graph so I could easily mark out a map for it later with coordinates. So, you start at 0,0, and when you move West it changes to -1,0, so on, and I'm using If statements to check your location. But, it always assumes you're at the lowest negative possible, and so always says you're at 'Room 3'.
I think it does this because it doesn't recognise the - in the check as part of the number, and instead thinks you're asking if it equals the number minus itself, which would be zero, which is the game's default position. But, at the same time, it still thinks you're at the lowest possible position even if you move off 0,0, so I don't know. If that is the case, I would like to know how to fix it, and if that isn't the case, I would like to know what the real problem is.
Below is the entire program so far. This is my first time really trying to code something by myself, with no tutorial involved, so I apologise for how training-wheels-y it is.
let x=0
let y=0
let time=0
let button = document.getElementById('button');
let buttonNorth = document.getElementById('buttonNorth');
let buttonWest = document.getElementById('buttonWest');
let buttonEast = document.getElementById('buttonEast');
let buttonSouth = document.getElementById('buttonSouth');
button.onclick = function() {
reporter()
locatron()
}
buttonNorth.onclick = function() {
updateNorth()
reporter()
locatron()
}
buttonWest.onclick = function() {
updateWest()
reporter()
locatron()
}
buttonEast.onclick = function() {
updateEast()
reporter()
locatron()
}
buttonSouth.onclick = function() {
updateSouth()
reporter()
locatron()
}
function reporter() {
console.log(`location is: ${x},${y}`)
console.log(`time is: ${time}`)
}
function updateNorth() {
y = y+1
time=time+1
}
function updateWest() {
x = x-1
time=time+1
}
function updateEast() {
x = x+1
time=time+1
}
function updateSouth() {
y = y-1
time=time+1
}
function locatron() {
if(x==0,y==0) {
totalDescription.innerHTML = `Room 1`
}
if(x==-1,y==0) {
totalDescription.innerHTML = `Room 2`
}
if(x==-2,y==0) {
totalDescription.innerHTML = `Room 3`
}
else {
totalDescription.innerHTML = `This area has not been written yet.`
}
}
I've tried turning the number in the If statement into a string, but it just does the same thing. The only way I can get it to display any message other than 'Room 3' is by moving it along the Y axis, at which point it changes to my equivalent of an error message, 'This area has not been written yet.'. I also tried looking the problem up, but the wording on it is so finnicky that the only results I would get back are how to 'check if a variable is negative', which is not at all what I want.
I appreciate any help I can get.

Get Index Number of a element in the List

Iam creating a quiz App in flutter , to find whether the currect answer is selected i want to get the index number of the selected button, i doesnt know whether it is a correct approach to check the correct answer.Please help me how to get the index number when user presses the answer.
{'questionText': "What is your name",
'answers':['honest','devika','monisha','khyathy'],
'correctAnswer':'3',
},
{'questionText': "What is your Mobile Name",
'answers':['Iphone','Huawei','Applele','SAMSUNG'],
'correctAnswer':'2',
},
];
void answered(){
//find the index of the selected answer
final result = (questions[questionIndex ]['answers']indexOf());
if (result== ) {
print(result);
} `
Iam calling this List in a raised button in below code:
...(questions[questionIndex]['answers'] as List<String>).map((answer) {
return ReusableButton(
child: Text(answer),
onPressed:() =>[currentQuestion(),answered()],
color: Colors.green,
);
}).toList(),`
I think that you could just make 'correctAnswer' not the index of the answer but the answer itself, so you rather check the two string instead of checking indexes.
It should look like this.
{'questionText': "What is your name",
'answers':['honest','devika','monisha','khyathy'],
'correctAnswer':'khyathy',
},
{'questionText': "What is your Mobile Name",
'answers':['Iphone','Huawei','Applele','SAMSUNG'],
'correctAnswer':'Applele',
},
];
void answered(answer){
final result = (questions[questionIndex ]['correctAnswer']);
if (result == answer) {
print(result);
} `
I think that's right, it's my first answer in stack overflow so to all the OGs feel free to correct me.
If you want to check indexes you could use this.
{'questionText': "What is your name",
'answers':['honest','devika','monisha','khyathy'],
'correctAnswer':'3',
},
{'questionText': "What is your Mobile Name",
'answers':['Iphone','Huawei','Applele','SAMSUNG'],
'correctAnswer':'2',
},
];
void answered(answer){
final result = (questions[questionIndex ]['correctAnswer']);
final answerIndex = questions[questionIndex]['answers'].indexOf(answer).toString()
if (result == answerIndex) {
print(result);
}
...(questions[questionIndex]['answers'] as List<String>).map((answer) {
return ReusableButton(
child: Text(answer),
onPressed:() =>[currentQuestion(),answered(answer)],
color: Colors.green,
);
}).toList(),`
This should do it, I don't know what your questionIndex function does because you didn't post it so I assumed it returns an int value of the index of the current question.
Also, I don't know if you noticed but in your question, you wrote:
final result = (questions[questionIndex ]['answers']indexOf());
indexOf is a list built-in method so when you call it on a list you have to put a dot before it like so:
final result = (questions[questionIndex ]['answers'].indexOf(itemYouWantTheIndex));
There is also another error when you check the validity of the answer but I think it is just because you didn't know how to compare.
Tell me if my answer satisfied you, I'd be really happy if it did.

Google Charts "Uncaught (in promise) Error: Invalid column index 3. Should be an integer in the range [0-3]."

Before you mark this as duplicate, note that others are asking about the error Invalid column index undefined. ... or Invalid column index 5. Should be an integer in the range [0-4]. But no. Mine is "3 should be an integer in the range of [0-3]." Also, the table does work without the formatter.format() line (just no formatting).
google.charts.load('current', {'packages':[data.chartType.toLowerCase()]});
google.charts.setOnLoadCallback(function(){
var googleData = new google.visualization.DataTable();
for (var h in data.headers) {
googleData.addColumn(data.headers[h].type, data.headers[h].html);
if (data.headers[h].format) {
var formatter = new google.visualization.NumberFormat(data.headers[h].format);
console.log(data.headers[h].format);
formatter.format(googleData, h); // Errors Here
}
}
/* ... Add Rows ... Draw Chart ... */
}
The header in question looks like this:
header[3] = {
"html": "Total Amount",
"source": "total_amount",
"type": "number",
"format": {
"negativeColor": "#F05840", //orange
"negativeParens": true,
"pattern": "#,###",
"prefix": "$",
"suffix": "",
}
}
I can't figure out why it would be erroring.
Please forgive me for any typos here, I had to hand-edit the spacing and remove my company's specific info upon pasting the code here.
Edit
WhiteHat is correct in that my h variable was a string instead of an integer, and calling parseInt did remove that error. However, instead of calling parseInt on the formatter and wherever else it's needed, I got rid of my for (var h in data.headers) calls and went with the bog-standard for (var h = 0; h < data.headers.length; h++). Although more verbose with more room for typos, it's far more standardized and predictable.
I'm still having issues with GoogleCharts NumberFormatter, but that's for another round of research and questions, not this one.
make sure you're passing a number (3),
and not a string ('3'),
by using --> parseInt...
e.g.
formatter.format(googleData, parseInt(h)); // <-- here

Reflection on EmberJS objects? How to find a list of property keys without knowing the keys in advance

Is there a way to retrieve the set-at-creations properties of an EmberJS object if you don't know all your keys in advance?
Via the inspector I see all the object properties which appear to be stored in the meta-object's values hash, but I can't seem to find any methods to get it back. For example object.getProperties() needs a key list, but I'm trying to create a generic object container that doesn't know what it will contain in advance, but is able to return information about itself.
I haven't used this in production code, so your mileage may vary, but reviewing the Ember source suggests two functions that might be useful to you, or at least worth reviewing the implementation:
Ember.keys: "Returns all of the keys defined on an object or hash. This is useful when inspecting objects for debugging. On browsers that support it, this uses the native Object.keys implementation." Object.keys documentation on MDN
Ember.inspect: "Convenience method to inspect an object. This method will attempt to convert the object into a useful string description." Source on Github
I believe the simple answer is: you don't find a list of props. At least I haven't been able to.
However I noticed that ember props appear to be prefixed __ember, which made me solve it like this:
for (f in App.model) {
if (App.model.hasOwnProperty(f) && f.indexOf('__ember') < 0) {
console.log(f);
}
};
And it seems to work. But I don't know whether it's 100% certain to not get any bad props.
EDIT: Adam's gist is provided from comments. https://gist.github.com/1817543
var getOwnProperties = function(model){
var props = {};
for(var prop in model){
if( model.hasOwnProperty(prop)
&& prop.indexOf('__ember') < 0
&& prop.indexOf('_super') < 0
&& Ember.typeOf(model.get(prop)) !== 'function'
){
props[prop] = model[prop];
}
}
return props;
}
Neither of these answers are reliable, unfortunately, because any keys paired with a null or undefined value will not be visible.
e.g.
MyClass = Ember.Object.extend({
name: null,
age: null,
weight: null,
height: null
});
test = MyClass.create({name: 'wmarbut'});
console.log( Ember.keys(test) );
Is only going to give you
["_super", "name"]
The solution that I came up with is:
/**
* Method to get keys out of an object into an array
* #param object obj_proto The dumb javascript object to extract keys from
* #return array an array of keys
*/
function key_array(obj_proto) {
keys = [];
for (var key in obj_proto) {
keys.push(key);
}
return keys;
}
/*
* Put the structure of the object that you want into a dumb JavaScript object
* instead of directly into an Ember.Object
*/
MyClassPrototype = {
name: null,
age: null,
weight: null,
height: null
}
/*
* Extend the Ember.Object using your dumb javascript object
*/
MyClass = Ember.Object.extend(MyClassPrototype);
/*
* Set a hidden field for the keys the object possesses
*/
MyClass.reopen({__keys: key_array(MyClassPrototype)});
Using this method, you can now access the __keys field and know which keys to iterate over. This does not, however, solve the problem of objects where the structure isn't known before hand.
I use this:
Ember.keys(Ember.meta(App.YOUR_MODEL.proto()).descs)
None of those answers worked with me. I already had a solution for Ember Data, I was just after one for Ember.Object. I found the following to work just fine. (Remove Ember.getProperties if you only want the keys, not a hash with key/value.
getPojoProperties = function (pojo) {
return Ember.getProperties(pojo, Object.keys(pojo));
},
getProxiedProperties = function (proxyObject) {
// Three levels, first the content, then the prototype, then the properties of the instance itself
var contentProperties = getPojoProperties(proxyObject.get('content')),
prototypeProperties = Ember.getProperties(proxyObject, Object.keys(proxyObject.constructor.prototype)),
objectProperties = getPojoProperties(proxyObject);
return Ember.merge(Ember.merge(contentProperties, prototypeProperties), objectProperties);
},
getEmberObjectProperties = function (emberObject) {
var prototypeProperties = Ember.getProperties(emberObject, Object.keys(emberObject.constructor.prototype)),
objectProperties = getPojoProperties(emberObject);
return Ember.merge(prototypeProperties, objectProperties);
},
getEmberDataProperties = function (emberDataObject) {
var attributes = Ember.get(emberDataObject.constructor, 'attributes'),
keys = Ember.get(attributes, 'keys.list');
return Ember.getProperties(emberDataObject, keys);
},
getProperties = function (object) {
if (object instanceof DS.Model) {
return getEmberDataProperties(object);
} else if (object instanceof Ember.ObjectProxy) {
return getProxiedProperties(object);
} else if (object instanceof Ember.Object) {
return getEmberObjectProperties(object);
} else {
return getPojoProperties(object);
}
};
In my case Ember.keys(someObject) worked, without doing someObject.toJSON().
I'm trying to do something similar, i.e. render a generic table of rows of model data to show columns for each attribute of a given model type, but let the model describe its own fields.
If you're using Ember Data, then this may help:
http://emberjs.com/api/data/classes/DS.Model.html#method_eachAttribute
You can iterate the attributes of the model type and get meta data associated with each attribute.
This worked for me (from an ArrayController):
fields: function() {
var doc = this.get('arrangedContent');
var fields = [];
var content = doc.content;
content.forEach(function(attr, value) {
var data = Ember.keys(attr._data);
data.forEach(function(v) {
if( typeof v === 'string' && $.inArray(v, fields) == -1) {
fields.push(v);
}
});
});
return fields;
}.property('arrangedContent')

CFGRID - replace data store or filter on more than one column

ColdFusion 8
I have a cfgrid that that is based on a query. It is not bound to a cfc function because I want a scrolling grid, not a paged grid (you must supply the page number and page size if you use BIND).. I can figure out how to make it filter on one column by using the following code, but I really need to filter on three columns...
grid.getDataSource().filter("OT_MILESTONE",t1);
Adding more to the filter string does not do the trick...it ignores anything more than the first pair of values..
so..I thought if I called a function that passes the three values and returned the query results to me, I could replace the Data Store for the grid..but I cannot figure out the syntax to get it to replace.
The returned variable for the query has the following format:
{"COLUMNS":["SEQ_KEY","ID","OT_MILESTONE"],"DATA":[[63677,"x","y"]]}
Any ideas?
have you looked at queryconvertforgrid()?
http://www.cfquickdocs.com/cf9/#queryconvertforgrid
Update: have you looked at these?
http://www.danvega.org/blog/index.cfm/2008/3/10/ColdFusion-8-Grid-Filtering
http://www.coldfusion-ria.com/Blog/index.cfm/2009/1/13/Playing-with-cfgrid--Filter-showhide-Columns-and-using-the-YUI-Buttons-library
http://cfsilence.com/blog/client/index.cfm/2007/8/9/Filtering-Records-In-An-Ajax-Grid
after much blood, sweat, tears and swearing..here's the answer, in case anyone else might need to filter a cfgrid by more than one variable:
var w1 = ColdFusion.getElementValue('wbs');
var t1 = ColdFusion.getElementValue('task');
var p1 = ColdFusion.getElementValue('project');
grid = ColdFusion.Grid.getGridObject('data');
store = grid.getDataSource();
store.clearFilter();
store.filterBy(function myfilter(record) {
var wantit = true;
if (trim(w1) != '') {
if(record.get('WBS_ID') != w1) {
wantit = false;
}}
if (trim(t1) != '') {
if(record.get('OT_MILESTONE') != t1) {
wantit = false;
}}
if (trim(p1) != '') {
if(record.get('PROJECT') != p1) {
wantit = false;
}}
return wantit;
});
ColdFusion.Grid.refresh('data',false);
you will need a JS trim function...
Make sure the column names are caps...