Get Index Number of a element in the List - 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.

Related

How can I prevent from adding duplicate on a list in React?

Hello all knowledgeable and talented SO members :)
I hope you can help me with this one too. I wish to do the following:
on submit check if the item is already on the list
if yes show an alert, and NOT add
if NO add the item to the list
After searching online, I came up with the following code
const submitHandler = (e) => {
e.preventDefault();
const newScorer = e.target.value;
const existingScorer = players.includes(newScorer);
if (existingScorer) {
console.log('already on list!');
} else {
const newPlayer = {id: nanoid(4), nummer: number};
setPlayers([...players, newPlayer]);
setNumber('');
}
};
The problem is that it does not work, adds even though "newScorer" is already on the list!?!
Thanks in advance
Regards
Peter
Based on the comments, you want to check if number is in the players array so...
const existingScorer = players.find(player => player.nummer === number);
... assuming nummer is correct property.

How to iterate a class?

UPDATES
This is my final codes just in case anyone needs it:
int index = -2; //I am not 100% sure why I need to start -2, but I assume that `forEach((item){})` probably increase `index` by one, and I also increase `index` inside of the loop, so that's probably why.
recyclable.forEach((item) {
index++;
if (item.title == _outputs[0]["label"]) {
//your code for when the match is found
//move to the detailed page to show more description
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DetailScreen(recyclable: recyclable[index]),
),
);
}
}
END OF UPDATES
I created a class named Recyclable, and using the class, I created a list named recyclable. The list recyclable has a string named title, and I am trying to iterate that title to find a match with _outputs[0]["label"].
To do it, I tried the following code:
while (_outputs[0]["label"] != recyclable[index].title) {
index++;
}
Somehow, there was a red underline for index, which I have no idea why.
I also tried for loop as below to remove that red underline by removing index from my code:
for (var _outputs[0]["label"] in recyclable.title) {
index++;
}
But the code seems to be completely off.
FYI, Here is my class Recyclable:
class Recyclable {
final String title;
final String description;
final String instruction;
final String why;
final String
recycle; //put either "recyclable" or "not recyclable" (This item "can be recycled")
final String
donate; //put either "can be donated" or "cannot be donated" (This item "can be donated")
Recyclable(this.title, this.description, this.instruction, this.why,
this.recycle, this.donate);
}
And here is the list:
List<Recyclable> recyclable = [
Recyclable('PAPERS', 'abc2', 'instruction123', 'why123', 'recyclable',
'cannot be donated'),
Recyclable('CLOTHING', 'abc3', 'instruction123', 'why123', 'recyclable',
'can be donated'),
Recyclable('CARDBOARDS', 'abc4', 'instruction123', 'why123',
'can be recycled', 'cannot be donated'),
Recyclable('COMPUTERS', 'abc4', 'instruction123', 'why123', 'recyclable',
'can be donated'),
];
One way you can iterate over the recyclable list is like this using forEach method
recyclable.forEach((item){
if(item.title == _outputs[0]["label"]){
//your code for when the match is found
}
});

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

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 :)

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

EmberJS: Questionnaire:bind 2 checkboxes to same value, one of them Inverted

im trying to implement a simple questionnaire component in EmberJS consisting of 10 different questions, where each additional question depends on the answer of the question before(maximum depth is 6) and appears after answering that. All of those questions are yes or no questions.
What i want now is 2 checkboxes/buttons, one representing yes, one representing no.
I know i could achieve that by having 2 computed properties for each question bound to the checkboxes and setting each other(even there im not quite sure,because of the opposite binding, how to make certain none of those is true by default, resulting in the next question being shown ), but i cant help but think that having 20 computed properties for this use case isnt the best way to do things
Any better and cleaner ideas for this problem are much appreciated!
Build a question component.
App.CQuestionComponent = Ember.Component.extend({
q: null,
isYes: false,
isNo: false,
result: null,
_yes: function() {
var isYes = this.get('isYes');
if ( isYes ) {
this.removeObserver('isNo', this, '_no');
this.set('isNo', ! isYes);
this.addObserver('isNo', this, '_no');
this.set('result', true);
} else {
this.set('result', null);
}
}.observes('isYes'),
_no: function() {
var isNo = this.get('isNo');
if ( isNo ) {
this.removeObserver('isYes', this, '_yes');
this.set('isYes', ! isNo);
this.addObserver('isYes', this, '_yes');
this.set('result', false);
} else {
this.set('result', null);
}
}.observes('isNo'),
});
http://emberjs.jsbin.com/sifewitahu/1/edit?html,js,output