Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/dart/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Flutter 如何基于相同的字符串值显示来自第二个JSON的数据_Flutter_Dart - Fatal编程技术网

Flutter 如何基于相同的字符串值显示来自第二个JSON的数据

Flutter 如何基于相同的字符串值显示来自第二个JSON的数据,flutter,dart,Flutter,Dart,我有两个JSON文件: country.json [ { "countryName": "United States", "countryContinent": "North America" }, { "countryName": "Germany", "countryContinent": "Europe" }, { "countryName": "United Kingdom", "countryContinent": "

我有两个JSON文件:

country.json

[
  {
    "countryName": "United States",
    "countryContinent": "North America"
  },
  {
    "countryName": "Germany",
    "countryContinent": "Europe"
  },
  {
    "countryName": "United Kingdom",
    "countryContinent": "Europe"
  }
]
containment.json

[
  {
    "continentName": "North America",
    "continentCountry": [
      "Canada",
      "Mexico",
      "Cuba"
    ],
    "continentArea": 24790000,
    "continentFlag": [
      "https://www.countryflags.io/ca/shiny/64.png",
      "https://www.countryflags.io/mx/shiny/64.png",
      "https://www.countryflags.io/cu/shiny/64.png"
    ]
  },
  {
    "continentName": "Europe",
    "continentCountry": [
      "Denmark",
      "Finland",
      "France"
    ],
    "continentArea": 10180000,
    "continentFlag": [
      "https://www.countryflags.io/dk/shiny/64.png",
      "https://www.countryflags.io/fi/shiny/64.png",
      "https://www.countryflags.io/fr/shiny/64.png"
    ]
  }
]
我想建立一个基于country.json的列表,然后针对
countrycontainment
的每个值,它==
containtname
=>的值显示containment.json中值
containtCountry
的数据,如下所示

Expanded(
 child: MyArea(
 continent: _continent.firstWhere((continent) =>  continent.continentName == country.countryContinent)
 //This should return the first ocurrence, only one continent object
),

class MyArea extends StatelessWidget{
  final String area;

  MyArea({Continent continent}) :
    this.area = continent.continentArea.toString(); //You need to give a string to the Text widget anyway

  @override
  Widget build(BuildContext context) {
    return Text(area);
  }
}

所以请帮助我,这是主文件:

import 'package:ask/model/continent_model.dart';
import 'package:ask/model/country_model.dart';
import 'package:ask/services/continent_services.dart';
import 'package:ask/services/country_service.dart';
import 'package:flutter/material.dart';

class Demo2 extends StatefulWidget {
  Demo2() : super();
  @override
  _Demo2State createState() => _Demo2State();
}

class _Demo2State extends State<Demo2> {
  List<Country> _country = [];
  List<Continent> _continent = [];

  @override
  void initState() {
    super.initState();
    CountryServices.getCountry().then((countries) {
      setState(() {
        _country = countries;
      });
    });
    ContinentServices.getContinent().then((continents) {
      setState(() {
        _continent = continents;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Demo 2')),
        body: Column(
          children: <Widget>[
            for (Country country in _country)
              Row(
                children: <Widget>[
                  Expanded(child: Text(country.countryName)),
                  Expanded(child: Text(country.countryContinent)),
                  Expanded(child: Text('')), // How to show data of continentCountry
                ],
              )
          ],
        ));
  }
}

因此,我想显示“北美”的所有
大陆国家
,如下所示:


请帮助

您可以在一个单独的函数中循环查看字符串列表列表,如
列表getSameContinentCountries

用于数据表示的类 国家

国家级{
字符串countryName;
非洲大陆;
国家({this.countryName,this.countrycontainment});
factory Country.fromJson(映射json){
返回国(
countryName:json['countryName'],
CountryContinental:json['CountryContinental'],
);
}
}
大陆

类大陆{
字符串名称;
国家名单;
大陆({this.continentName,this.continentCountry});
factory Continental.fromJson(映射json){
返回大陆(
大陆名称:json['continentName'],
大陆国家:json[“大陆国家],
);
}
}
现在,您可以在initState中使用以下命令生成
列表(国家
列表(大陆)
):

//TODO生成列表
for(在响应中映射json){
大陆2=大陆.fromJson(_json);
本._大陆。添加(大陆2);
}
for(countryListResponse中的Map\u json){
country2=Country.fromJson(_-json);
本._country.add(country2);
}
各大洲国家的职能 仅限文本

列出GetSameContinetCountries({@required String countryContinentCountries}){
int=index=this
欧洲大陆
.indexWhere((大陆)=>大陆。大陆名称==国家大陆);
列表_cC=this._大陆[大陆索引]。大陆国家;
列表wrapText=[Text('未找到任何国家]);
如果(_cC.length>0){
wrapText=[];
用于(字符串所在国家/地区){
wrapText.add(文本(国家));
}
}
返回wrapText;
}
所有小部件

列出GetSameContinetCountries({@required String countryContinentCountries}){
//返回任何小部件的列表,可能有多种组合
//例如芯片、卡片等。
int=index=this
欧洲大陆
.indexWhere((大陆)=>大陆。大陆名称==国家大陆);
列表_cC=this._大陆[大陆索引]。大陆国家;
列表wrapText=[Text('未找到任何国家]);
如果(_cC.length>0){
wrapText=[];
用于(字符串所在国家/地区){
//您可能需要使用填充
wrapText.add(填充(
填充:常量边集。对称(水平:2),
儿童:文本(国家),
));
//带有文本小部件的简单|分隔符
wrapText.add(填充(
填充:常量边集。对称(水平:2),
子项:文本(“|”),
));
//或者使用垂直分隔器,该分隔器需要具有高度的父级
wrapText.add(
容器(
身高:15,
儿童:垂直分隔器(
颜色:颜色,红色,
宽度:4,
厚度:2,
)),
);
//或者使用任何其他小部件,例如芯片
wrapText.add(芯片(
标签:文本(国家),
));
}
}
//拆下最后一个“分隔器”
wrapText.removeLast();
返回wrapText;
}
使用函数生成的小部件 在这里,我建议您使用
Wrap
小部件

@覆盖
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(标题:Text('Demo 2')),
正文:专栏(
儿童:[
适用于(国家/地区/地区)
划船(
儿童:[
扩展(子项:文本(country.countryName)),
扩展(子项:文本(country.countrycontraction)),
扩大(
孩子:包裹(
儿童:getSameContinentCountries(
CountryContinume:country.CountryContinume),
),
],
)
],
));
}

更新 我还不能对另一个答案发表评论,所以我必须在我的答案中包含这个简短的信息

要使用图像,只需返回一个图像小部件,您可能需要将其包装在一个
大小的框中
或一个
按钮中
/
手势检测器
,用于单击事件

List getFlags({@required String countrycontainment}){
//返回任何小部件的列表,可能有多种组合
//例如芯片、卡片、图像、按钮等。
int=index=this
欧洲大陆
.indexWhere((大陆)=>大陆。大陆名称==国家大陆);
列表_cF=this._大陆[大陆索引].大陆旗;
列表wrapWidget=[Text('no Countries found');
如果(_cF.length>0){
wrapWidget=[];
for(字符串标志在_cF中){
//添加标志
wrapWidget.add(Image.network(flag));
}
}
返回wrapWidget;
}
结果:

更新2 要访问具有相同
名称的所有标志
,必须提取匹配的元素,然后循环新的
列表
。 更改
getFlags
函数的代码,如下所示:

List getFlags({@required String countrycontainment}){
//返回任何小部件的列表,可能有多种组合
//例如芯片、卡片、图像、按钮等。
//!更新
List sameContient=此
欧洲大陆
.其中((大陆)=>大陆。大陆名称==countryCo
Expanded(
   child: MyCountries(
     continent: List<Continent>.from(_continent)..retainWhere((continent) => 
       continent.continentName == country.countryContinent)
),
continent.continentName == country.countryContinent
class MyCountries extends StatelessWidget{
  final String countries;


  MyCountries({List<Continent> continent}) :
    this.countries = continent.reduce((prev, curr) => 
     prev..continentCountry.addAll(curr.continentCountry)).continentCountry.join(' | ');

  @override
  Widget build(BuildContext context) {
    return Text(countries);
  }
}
Expanded(
 child: MyArea(
 continent: _continent.firstWhere((continent) =>  continent.continentName == country.countryContinent)
 //This should return the first ocurrence, only one continent object
),

class MyArea extends StatelessWidget{
  final String area;

  MyArea({Continent continent}) :
    this.area = continent.continentArea.toString(); //You need to give a string to the Text widget anyway

  @override
  Widget build(BuildContext context) {
    return Text(area);
  }
}
Expanded(
 child: MyFlags(
 continent: _continent.firstWhere((continent) =>  continent.continentName == country.countryContinent)
 //This should return the first ocurrence, only one continent object
),

class MyFlags extends StatelessWidget{
  final List<String> flags;

  MyFlags ({Continent continent}) :
    this.flags= continent.continentFlag;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly, //or try other alignments or using Spacer() between widget in children
      children: [
        for(String flag in flags)
         Image.network(flag, height: 16, width: 25, fit: BoxFit.contain)
         //A flag is wider thatn taller, but you could try other sizes if you want 
      ]
    );
  }
}
Expanded(
 child: MyFlags(
 continent: List<Continent>.from(_continent)..retainWhere((continent) => 
       continent.continentName == country.countryContinent)
),

class MyFlags extends StatelessWidget{
  final List<String> flags;
  final List<String> countries;

  MyFlags ({List<Continent> continent}) :
    this.flags = continents.expand<String>((continent) => continent.continentFlag).toList(),
    this.countries = continents.expand<String>((continent) => continent.continentCountry).toList(),
    assert(flags.length == countries.length); //They should have the same length

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly, //or try other alignments or using Spacer() between widget in children
      children: [
        for(int i = 0; i < flags.length; i++)
         Column(
           children: [
             Image.network(flags[i], height: 16, width: 25, fit: BoxFit.contain),
             Text(countries[i])
           ]
         )
      ]
    );
  }
}
Expanded(
 child: MyFlags(
 continent: List<Continent>.from(_continent)..retainWhere((continent) => 
       continent.continentName == country.countryContinent)
),

class MyFlags extends StatelessWidget{
  final List<Continent> continent;

  MyFlags({this.continent});

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        for(int i = 0; i < continent.length; i++)
          Row(
            children: [
              Text(continent[i].continentArea.toString()), // or 'Area ${i+1}' if you want to show Area 1, Area 2, etc
              for(String flag in continent[i].continentFlag)
                Image.network(flags[i], height: 16, width: 25, fit: BoxFit.contain),
            ]
          )
      ]
    );
  }
}