我有2个JSON文件:
json1:字符串人物名称(API)
[
{
"name": "Oliver"
},
{
"name": "George"
},
{
"name": "Harry"
}
]
json2:字符串服装和一系列适合该服装的人(API)
[
{
"outfit": "T-shirt",
"fit": [
"Oliver",
"George"
]
},
{
"outfit": "Hat",
"fit": [
"George",
"Harry"
]
},
{
"outfit": "Jacket",
"fit": [
"Harry"
]
}
]
我希望在单击人的名字时=>显示适合他们的服装
Ex。乔治穿着T恤和帽子
请帮助我,这是主文件:
import 'package:ask/model/page1_model.dart';
import 'package:ask/model/page2_model.dart';
import 'package:ask/services/json2_service.dart';
import 'package:ask/services/json1_service.dart';
import 'package:flutter/material.dart';
class Demo extends StatefulWidget {
@override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
List<Json1> _json1 = [];
List<Json2> _json2 = [];
@override
void initState() {
super.initState();
Json1Services.getData().then((data) {
setState(() {
_json1 = data;
});
});
Json2Services.getData().then((data) {
setState(() {
_json2 = data;
});
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('List Name')),
body: ListView.builder(
itemCount: _json1.length,
itemBuilder: (BuildContext context, int index) {
Json1 json1 = _json1[index];
return Column(children: [
InkWell(
child: Text(json1.name),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(title: Text('${json1.name} fits:')),
body: ShowWhatFit(json2: List<Json2>.from(_json2)..retainWhere((element) => element.fit[index] == json1.name)), // I think this line is not right
))))
]);
},
));
}
}
class ShowWhatFit extends StatelessWidget {
final List<Json2> json2;
ShowWhatFit({this.json2});
@override
Widget build(BuildContext context) {
return Row(
children: [
for (int i = 0; i < json2.length; i++) Text(json2[i].outfit),
],
);
}
}
............................................... ...............................
答案 0 :(得分:1)
List<Json2>.from(_json2)..retainWhere((element) => element.fit[index] == json1.name))
retainWhere
将检查每个元素,并仅保留条件为true的那些元素。问题是element.fit[index] == json1.name
只需检查列表index
的索引fit
上的元素并将其与名称json1.name
进行比较,并不会真正检查名称是否在列出fit
。试试:
List<Json2>.from(_json2)..retainWhere((element) => element.fit.contains(json1.name)))
这将迭代json2中的每个元素,然后检查列表fit
是否包含相等的对象json1.name
,如果存在则返回true,否则返回false