【问题标题】:Flutter: How to show array data from ListView.builder inside a ListView.builder?Flutter:如何在 ListView.builder 中显示来自 ListView.builder 的数组数据?
【发布时间】:2020-06-04 01:44:18
【问题描述】:

我有一个这样的 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"
        ]
      }
    ]
  }
]

我使用https://app.quicktype.io/ 来解析 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,
                    ],
                  );
                })));
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您需要将第二个 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),
          ],
        ),
      ),
    )
    

    【讨论】:

      【解决方案2】:

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

      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:
      

      详细描述太长了,可以直接参考完整代码

      工作演示

      完整代码

      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)),
                                                                ]);
                                                          }),
                                                    ),
                                                  ],
                                                ),
                                              )
                                            ]);
                                      }),
                                ),
                              )
                            ])
                      ],
                    );
                  }));
        }
      }
      

      【讨论】:

      • 我仍然要非常感谢您对我的帮助。你的代码太棒了,我从中学到了很多xD
      • 我能再帮个忙吗?我想要第二个ListView.separated:=> itemCount: 3,它的宽度将适合左屏幕,不能水平滚动并均匀拆分为 3 列(如 Expanded flex 1:1:1)@ 987654322@,其中的文本会自动调整大小以适应,我认为AutoSizeText 很棒。那么有什么办法可以做到吗?
      • 我建议将您的请求发布到一个新问题中,以便更多人可以帮助您。响应不同的屏幕尺寸是一个巨大的话题。
      • 我明白了,会的。谢谢:D
      • 我发布了新问题herexD
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-05
      • 1970-01-01
      • 2022-11-20
      • 2021-06-13
      • 2021-02-14
      • 1970-01-01
      相关资源
      最近更新 更多