Flutter Cómo mostrar la lista por bucle for
He creado una lista simple para mostrarla por bucle for.
List categories = [
{
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
}
];
luego defino un widget como este
List<Widget> CatWidget = List<Widget>();
Entonces lo uso así
for (int i = 0; i < 8; i++) {
CatWidget.add(
Container(
child: Text(categories[i]['CatName']),
),
);
}
Está mostrando error Class '_CompactLinkedHashSet<Map<String, String>>' has no instance method '[]'.
Respuestas
Tu lista contiene demasiados frenos:
List categories = [
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
];
Y su ciclo debería correr a 3, no a 8 porque no tiene 8.
Entonces, lo siguiente funcionaría, sin embargo, lo animo a verificar la otra respuesta para un mejor enfoque en general:
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),
),
);
}
}
Puede usar list.generate para recorrer su lista y devolver un 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]),
),
),
),
),
Tiene una matriz JSON, dentro de la matriz JSON, tiene un objeto JSON y dentro de ese objeto JSON, tiene varios objetos JSON, que desea iterar uno por uno, lo cual es inapropiado.
Matriz JSON> Objetos JSON True
Matriz JSON> Matriz JSON> Objeto (s) JSON Verdadero
Matriz JSON> Objeto JSON> Objeto (s) JSON Falso
El bucle for puede funcionar solo en una matriz o lista de objetos y el json debería ser como:
[
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
]