Flutter for 루프로 목록을 표시하는 방법
Dec 01 2020
for 루프로 표시하는 간단한 목록을 만들었습니다.
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 '[]'.
답변
3 nvoigt Dec 01 2020 at 15:51
목록에 너무 많은 중괄호가 있습니다.
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),
),
);
}
}
3 UsmanAkhlaq Dec 01 2020 at 15:43
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]),
),
),
),
),
RohitSingh Dec 01 2020 at 16:03
JSON 배열이 있고, JSON 배열 안에는 JSON 객체가 있고, 그 JSON 객체 안에는 여러 개의 JSON 객체가 있습니다.이 객체를 하나씩 반복하려는 것은 부적절합니다.
JSON 배열> JSON 객체 True
JSON 배열> JSON 배열> JSON 객체 True
JSON 배열> JSON 개체> JSON 개체 False
For 루프는 배열 또는 객체 목록에서만 작동 할 수 있으며 json은 다음과 같아야합니다.
[
{
'CatID': '0',
'CatName': 'All'
},
{
'CatID': '1',
'CatName': 'Computer Hardware'
},
{
'CatID': '2',
'CatName': 'Computer Software'
},
]