Flutter Como mostrar a lista por loop for
Criei uma lista simples para mostrar por loop for.
List categories = [
{
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
}
];
então eu defino um widget como este
List<Widget> CatWidget = List<Widget>();
Então eu uso assim
for (int i = 0; i < 8; i++) {
CatWidget.add(
Container(
child: Text(categories[i]['CatName']),
),
);
}
Está mostrando erro Class '_CompactLinkedHashSet<Map<String, String>>' has no instance method '[]'.
Respostas
Sua lista contém muitas chaves:
List categories = [
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
];
E seu loop deve ir para 3, não 8, porque você não tem 8.
Portanto, o seguinte funcionaria, no entanto, incentivo você a verificar a outra resposta para uma abordagem melhor em geral:
import 'package:flutter/material.dart';
void main() {
List categories = [
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
];
final catWidget = List<Widget>();
for (int i = 0; i < 3; i++) {
catWidget.add(
Container(
child: Text(categories[i]['CatName']),
),
);
}
runApp(MyApp(catWidget));
}
class MyApp extends StatelessWidget {
final List<Widget> children;
const MyApp(this.children);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Column(children: children),
),
);
}
}
Você pode usar list.generate para percorrer sua lista e retornar um widget.
Column(
children: List.generate(
tags.length,
(index) => Container(
// margin: EdgeInsets.symmetric(),
child: NativeButton(
borderRadius: BorderRadius.circular(4),
padding: EdgeInsets.symmetric(
vertical: sizeConfig.height(.01),
horizontal: sizeConfig.width(.02),
),
color: Colors.grey[200],
child: Text(tags[index]),
),
),
),
),
Você tem uma matriz JSON, dentro da matriz JSON, você tem um objeto JSON e dentro desse objeto JSON, você tem vários objetos JSON, que deseja iterar um por um, o que é inadequado.
Matriz JSON> Objetos JSON True
Matriz JSON> Matriz JSON> Objeto (s) JSON Verdadeiro
Matriz JSON> Objeto JSON> Objeto (s) JSON falso
O loop for pode funcionar apenas em array ou lista de objetos e o json deve ser assim:
[
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
]