在DART中:如何访问字符串列表的元素1,即Map主列表元素1的键"respostas"的值?


void main() {
final List<Map<String, Object>> perguntas = [
{ 
'texto': 'Qual é a sua cor favorita?',
'respostas': ['Preto', 'Vermelho', 'Verde','Branco'],
},
{ 
'texto': 'Qual é o seu animal favorito?',
'respostas': ['Coelho', 'Cobra', 'Elefante','Leão'],
}, { 
'texto': 'Qual é o seu instrutor favorito?',
'respostas': ['Jacob', 'Rodrigo', 'Daniel','Leo'],
},
];
}

如何访问String列表中的元素1,即Map主列表中元素1的键respostas的值?

(科埃略,眼镜蛇,Elefante里昂)——比;我想访问元素1:'Elefante'

在dartPad或gist上

Main function


void main() {
final List<Map<String, Object>> perguntas = [
{
'texto': 'Qual é a sua cor favorita?',
'respostas': ['Preto', 'Vermelho', 'Verde', 'Branco'],
},
{
'texto': 'Qual é o seu animal favorito?',
'respostas': ['Coelho', 'Cobra', 'Elefante', 'Leão'],
},
{
'texto': 'Qual é o seu instrutor favorito?',
'respostas': ['Jacob', 'Rodrigo', 'Daniel', 'Leo'],
},
];
int? foundValueAt;
print(perguntas.length);
for (int i = 0; i < perguntas.length; i++) {
final items = perguntas[i]['respostas'] as List<String>;
// finding where `Elefante` contains
print(items.contains("Elefante") ? "YEs" : "NO");
if (foundValueAt == null && items.contains("Elefante")) {
foundValueAt = i;
///finding index of `Elefante` inside of list<String>
final index = items.indexWhere((element) => element == 'Elefante');
print("index of Elefante => $index");
///let's change the value
perguntas[i]['respostas'] = items
..removeAt(index)
..add("newValue");
}
}
print('Elefante found onMainList:  index $foundValueAt');
print("new Value>> ");
perguntas.forEach((e) {
print(e.toString());
});
}

结果

3
NO
YEs
index of Elefante => 2
NO
Elefante found onMainList:  index 1
new Value>> 
{texto: Qual é a sua cor favorita?, respostas: [Preto, Vermelho, Verde, Branco]}
{texto: Qual é o seu animal favorito?, respostas: [Coelho, Cobra, Leão, newValue]}
{texto: Qual é o seu instrutor favorito?, respostas: [Jacob, Rodrigo, Daniel, Leo]}

最新更新