Flutter วิธีแสดงรายการโดย for loop
ฉันได้สร้างรายการง่ายๆเพื่อแสดงโดยการวนซ้ำ
List categories = [
{
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
}
];
จากนั้นฉันกำหนดวิดเจ็ตเช่นนี้
List<Widget> CatWidget = List<Widget>();
แล้วฉันจะใช้มันแบบนี้
for (int i = 0; i < 8; i++) {
CatWidget.add(
Container(
child: Text(categories[i]['CatName']),
),
);
}
แสดงข้อผิดพลาด Class '_CompactLinkedHashSet<Map<String, String>>' has no instance method '[]'.
คำตอบ
รายการของคุณมีวงเล็บปีกกามากเกินไป:
List categories = [
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
];
และห่วงของคุณควรจะใช้กับ3ไม่ได้8เพราะคุณไม่ได้มี 8
ดังนั้นสิ่งต่อไปนี้จะได้ผลฉันขอแนะนำให้คุณตรวจสอบคำตอบอื่นเพื่อแนวทางที่ดีกว่าโดยทั่วไป:
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),
),
);
}
}
คุณสามารถใช้ list.generate เพื่อวนซ้ำรายการของคุณและส่งคืนวิดเจ็ต
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]),
),
),
),
),
คุณมีอาร์เรย์ JSON ภายในอาร์เรย์ JSON คุณมี JSON Object และภายในออบเจ็กต์ JSON นั้นคุณมีออบเจ็กต์ JSON หลายตัวซึ่งคุณต้องการวนซ้ำทีละรายการซึ่งไม่เหมาะสม
JSON Array> ออบเจ็กต์ JSON True
อาร์เรย์ JSON> อาร์เรย์ JSON> ออบเจ็กต์ JSON True
อาร์เรย์ JSON> วัตถุ JSON> วัตถุ JSON เท็จ
สำหรับลูปสามารถทำงานได้เฉพาะกับอาร์เรย์หรือรายการวัตถุและ json ควรเป็นดังนี้:
[
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
]