Flutter 颤振:如何在ListView.builder中显示ListView.builder中的数组数据?

Flutter 颤振:如何在ListView.builder中显示ListView.builder中的数组数据?,flutter,dart,Flutter,Dart,我有这样一个JSON文件: [ { "id": 1, "continent": "North America", "country": [ { "name": "United States", "capital": "Washington, D.C.", "language": [ "English" ] }, { "name": "

我有这样一个JSON文件:

[
  {
    "id": 1,
    "continent": "North America",
    "country": [
      {
        "name": "United States",
        "capital": "Washington, D.C.",
        "language": [
          "English"
        ]
      },
      {
        "name": "Canada",
        "capital": "Ottawa",
        "language": [
          "English",
          "French"
        ]
      }
    ]
  },
  {
    "id": 2,
    "continent": "Europe",
    "country": [
      {
        "name": "Germany",
        "capital": "Berlin",
        "language": [
          "German"
        ]
      }
    ]
  }
]
我曾经解析JSON数据。 我创建了一个
ListView.builder
来显示大陆的名称现在我想显示每个大陆的“国家名称”、“首都”和“语言”。

所以请帮我做这个,这是主文件

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

class ContinentPage extends StatefulWidget {
  ContinentPage() : super();
  @override
  _ContinentPageState createState() => _ContinentPageState();
}

class _ContinentPageState extends State<ContinentPage> {
  List<Continent> _continent;
  List<Country> _country;

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

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(),
        body: Container(
            child: ListView.builder(
                itemCount: null == _continent ? 0 : _continent.length,
                itemBuilder: (context, index) {
                  return Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(_continent[index].continent),
                      // how to create a ListView show a Column that includes:
                      // _country[index].name,
                      // _country[index].capital,
                      // _country[index].language,
                    ],
                  );
                })));
  }
}

导入“包装:颤振/材料.省道”;
导入“model/contraction_model.dart”;
导入“服务/大陆服务.dart”;
类页扩展StatefulWidget{
第页():超级();
@凌驾
_ContinentPageState createState()=>\u ContinentPageState();
}
类PageState扩展了状态{
欧洲大陆名单;
国家名单;
@凌驾
void initState(){
super.initState();
ContinentServices.getContinental().then((大陆){
设置状态(){
_大陆=大陆;
});
});
}
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(),
主体:容器(
子项:ListView.builder(
itemCount:null==\u大陆?0:\u大陆.length,
itemBuilder:(上下文,索引){
返回行(
mainAxisAlignment:mainAxisAlignment.spaceBetween,
儿童:[
文本(_大陆[索引].大陆),
//如何创建ListView以显示包含以下内容的列:
//_国家[索引]。名称,
//_国家[指数]。首都,
//_国家[索引]。语言,
],
);
})));
}
}

您需要将第二个listview.builder放置在具有定义高度的容器中

Container(
  height: 120,
  child: ListView.builder(
    shrinkWrap: true,
    scrollDirection: Axis.horizontal,
    itemCount: map.length,
    itemBuilder: (context, index) => Column(
      children: [
        Text(_country.elementAt(index).name),
        Text(_country.elementAt(index).capital),
Text(_country.elementAt(index).language),
      ],
    ),
  ),
)

您需要将第二个listview.builder放置在具有定义高度的容器中

Container(
  height: 120,
  child: ListView.builder(
    shrinkWrap: true,
    scrollDirection: Axis.horizontal,
    itemCount: map.length,
    itemBuilder: (context, index) => Column(
      children: [
        Text(_country.elementAt(index).name),
        Text(_country.elementAt(index).capital),
Text(_country.elementAt(index).language),
      ],
    ),
  ),
)

您可以复制粘贴运行下面的完整代码
您可以使用嵌套的
ListView.separated

代码片段

ListView.separated(
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 10,
              );
            },
            shrinkWrap: true,
            itemCount: null == _continent ? 0 : _continent.length,
            itemBuilder: (context, index) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                            flex: 1, child: Text(_continent[index].continent)),
                        Expanded(
                          flex: 2,
                          child: Container(
                            height: 50,
                            child: ListView.separated(
                                separatorBuilder:
ListView.com(
separatorBuilder:(BuildContext,int索引){
返回大小框(
身高:10,
);
},
收缩膜:对,
itemCount:null==\u大陆?0:\u大陆.length,
itemBuilder:(上下文,索引){
返回列(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
划船(
mainAxisAlignment:mainAxisAlignment.center,
crossAxisAlignment:crossAxisAlignment.center,
儿童:[
扩大(
flex:1,child:Text(_contraction[index].contraction)),
扩大(
弹性:2,
子:容器(
身高:50,
子项:ListView.separated(
分离器生成器:
描述所有细节太长,您可以直接参考完整代码

工作演示

完整代码

import 'package:flutter/material.dart';
// To parse this JSON data, do
//
//     final continent = continentFromJson(jsonString);

import 'dart:convert';

List<Continent> continentFromJson(String str) =>
    List<Continent>.from(json.decode(str).map((x) => Continent.fromJson(x)));

String continentToJson(List<Continent> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Continent {
  Continent({
    this.id,
    this.continent,
    this.country,
  });

  int id;
  String continent;
  List<Country> country;

  factory Continent.fromJson(Map<String, dynamic> json) => Continent(
        id: json["id"],
        continent: json["continent"],
        country:
            List<Country>.from(json["country"].map((x) => Country.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "continent": continent,
        "country": List<dynamic>.from(country.map((x) => x.toJson())),
      };
}

class Country {
  Country({
    this.name,
    this.capital,
    this.language,
  });

  String name;
  String capital;
  List<String> language;

  factory Country.fromJson(Map<String, dynamic> json) => Country(
        name: json["name"],
        capital: json["capital"],
        language: List<String>.from(json["language"].map((x) => x)),
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "capital": capital,
        "language": List<dynamic>.from(language.map((x) => x)),
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class ContinentServices {
  Future<List<Continent>> getContinent() {
    String jsonString = '''
    [
  {
    "id": 1,
    "continent": "North America",
    "country": [
      {
        "name": "United States",
        "capital": "Washington, D.C.",
        "language": [
          "English"
        ]
      },
      {
        "name": "Canada",
        "capital": "Ottawa",
        "language": [
          "English",
          "French"
        ]
      }
    ]
  },
  {
    "id": 2,
    "continent": "Europe",
    "country": [
      {
        "name": "Germany",
        "capital": "Berlin",
        "language": [
          "German"
        ]
      }
    ]
  }
]
    ''';
    List<Continent> continentList = continentFromJson(jsonString);
    return Future.value(continentList);
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<Continent> _continent;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: ListView.separated(
            separatorBuilder: (BuildContext context, int index) {
              return SizedBox(
                height: 10,
              );
            },
            shrinkWrap: true,
            itemCount: null == _continent ? 0 : _continent.length,
            itemBuilder: (context, index) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Expanded(
                            flex: 1, child: Text(_continent[index].continent)),
                        Expanded(
                          flex: 2,
                          child: Container(
                            height: 50,
                            child: ListView.separated(
                                separatorBuilder:
                                    (BuildContext context, int index) {
                                  return SizedBox(
                                    width: 10,
                                  );
                                },
                                shrinkWrap: true,
                                scrollDirection: Axis.horizontal,
                                itemCount: null == _continent
                                    ? 0
                                    : _continent[index].country.length,
                                itemBuilder: (context, countryIndex) {
                                  print(_continent[index]
                                      .country[countryIndex]
                                      .name);
                                  return Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.center,
                                      children: <Widget>[
                                        Container(
                                          width: 120,
                                          child: Column(
                                            children: <Widget>[
                                              Text(
                                                _continent[index]
                                                    .country[countryIndex]
                                                    .name,
                                                style: TextStyle(
                                                    color: Colors.red),
                                              ),
                                              Text(
                                                  _continent[index]
                                                      .country[countryIndex]
                                                      .capital,
                                                  style: TextStyle(
                                                      color: Colors.red)),
                                              Expanded(
                                                child: ListView.separated(
                                                    separatorBuilder:
                                                        (BuildContext context,
                                                            int index) {
                                                      return SizedBox(
                                                        width: 2,
                                                      );
                                                    },
                                                    shrinkWrap: true,
                                                    scrollDirection:
                                                        Axis.horizontal,
                                                    itemCount: null ==
                                                            _continent
                                                        ? 0
                                                        : _continent[index]
                                                            .country[
                                                                countryIndex]
                                                            .language
                                                            .length,
                                                    itemBuilder: (context,
                                                        languageIndex) {
                                                      return Row(
                                                          mainAxisAlignment:
                                                              MainAxisAlignment
                                                                  .spaceEvenly,
                                                          children: <Widget>[
                                                            Text(
                                                                _continent[index]
                                                                        .country[
                                                                            countryIndex]
                                                                        .language[
                                                                    languageIndex],
                                                                style: TextStyle(
                                                                    color: Colors
                                                                        .red)),
                                                          ]);
                                                    }),
                                              ),
                                            ],
                                          ),
                                        )
                                      ]);
                                }),
                          ),
                        )
                      ])
                ],
              );
            }));
  }
}
导入“包装:颤振/材料.省道”;
//要解析此JSON数据,请执行以下操作
//
//最终大陆=大陆从JSON(jsonString);
导入“dart:convert”;
List fromJSON(字符串str)=>
List.from(json.decode(str.map)((x)=>contraction.fromJson(x));
字符串JSON(列表数据)=>
encode(List.from(data.map((x)=>x.toJson());
阶级大陆{
大陆({
这个身份证,
这个大陆,
这个国家,
});
int-id;
弦大陆;
名单国家;
工厂大陆。fromJson(映射json)=>大陆(
id:json[“id”],
大陆:json[“大陆”],
国家:
List.from(json[“country”].map((x)=>country.fromJson(x)),
);
映射到JSON()=>{
“id”:id,
“大陆”:大陆,
“country”:List.from(country.map((x)=>x.toJson()),
};
}
阶级国家{
国家({
这个名字,
这个首都,,
这种语言,
});
字符串名;
字符串资本;
列表语言;
工厂国家。fromJson(映射json)=>国家(
名称:json[“名称”],
大写:json[“大写”],
语言:List.from(json[“language”].map((x)=>x)),
);
映射到JSON()=>{
“姓名”:姓名,
“资本”:资本,
“语言”:List.from(language.map((x)=>x)),
};
}
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
视觉密度:视觉密度。自适应平台密度,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类服务{
未来的非洲大陆(){
字符串jsonString='''
[
{
“id”:1,
“大陆”:“北美”,
“国家”:[
{
“名称”:“美国”,
“首都”:“华盛顿特区”,
“语言”:[
“英语”
]
},
{
“姓名”:“加拿大”,
“首都”:“渥太华”,
“语言”:[
“英语”,
“法语”
]
}
]
},
{
“id”:2,
“大陆”:“欧洲”,
“国家”:[
{
“名称”:“德国”,
“首都”:“柏林”,
“语言”:[
“德语”
]
}
]
}
]
''';
List CONTRONLIST=大陆fromJSON(jsonString);
返回Future.value(列表);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
欧洲大陆名单;
@凌驾
void initState(){
super.initState();
服务().getContine