假设我从不同的Url获取不同的列表

Future<List<City>> getCityDetails(Region selectedRegion) async {}
Future<List<Region>> getregionDetails() async {}

因此,小部件生成器将如下所示

 FutureBuilder<List<Region>>(
        future: getregionDetails(),
        builder: (context, snapshot) {}

在这个问题上有什么办法或解决办法吗?我正在努力寻找如何实现这一点的答案,或者还有其他方法吗?

推荐答案

我想您要找的是this左右的东西.

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(MaterialApp(
      home: MyApp(),
    ));

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Widget createRegionsListView(BuildContext context, AsyncSnapshot snapshot) {
    var values = snapshot.data;
    return ListView.builder(
      itemCount: values.length,
      itemBuilder: (BuildContext context, int index) {
        return values.isNotEmpty
            ? Column(
                children: <Widget>[
                  ListTile(
                    title: Text(values[index].region),
                  ),
                  Divider(
                    height: 2.0,
                  ),
                ],
              )
            : CircularProgressIndicator();
      },
    );
  }

  Widget createCountriesListView(BuildContext context, AsyncSnapshot snapshot) {
    var values = snapshot.data;
    return ListView.builder(
      itemCount: values == null ? 0 : values.length,
      itemBuilder: (BuildContext context, int index) {
        return GestureDetector(
          onTap: () {
            setState(() {
              selectedCountry = values[index].code;
            });
            print(values[index].code);
            print(selectedCountry);
          },
          child: Column(
            children: <Widget>[
              new ListTile(
                title: Text(values[index].name),
                selected: values[index].code == selectedCountry,
              ),
              Divider(
                height: 2.0,
              ),
            ],
          ),
        );
      },
    );
  }

  final String API_KEY = "03f6c3123ea549f334f2f67c61980983";

  Future<List<Country>> getCountries() async {
    final response = await http
        .get('http://battuta.medunes.net/api/country/all/?key=$API_KEY');

    if (response.statusCode == 200) {
      var parsedCountryList = json.decode(response.body);
      List<Country> countries = List<Country>();
      parsedCountryList.forEach((country) {
        countries.add(Country.fromJSON(country));
      });
      return countries;
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load ');
    }
  }

  Future<List<Region>> getRegions(String sl) async {
    final response = await http
        .get('http://battuta.medunes.net/api/region/$sl/all/?key=$API_KEY');

    if (response.statusCode == 200) {
      var parsedCountryList = json.decode(response.body);
      List<Region> regions = List<Region>();
      parsedCountryList.forEach((region) {
        regions.add(Region.fromJSON(region));
      });
      return regions;
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load ');
    }
  }

  String selectedCountry = "AF";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Row(children: [
        Expanded(
          child: FutureBuilder(
              future: getCountries(),
              initialData: [],
              builder: (context, snapshot) {
                return createCountriesListView(context, snapshot);
              }),
        ),
        Expanded(
          child: FutureBuilder(
              future: getRegions(selectedCountry),
              initialData: [],
              builder: (context, snapshot) {
                return createRegionsListView(context, snapshot);
              }),
        ),
      ]),
    );
  }
}

class Country {
  String name;
  String code;

  Country({this.name, this.code});

  factory Country.fromJSON(Map<String, dynamic> json) {
    return Country(
      name: json['name'],
      code: json['code'],
    );
  }
}

class Region {
  String country;
  String region;

  Region({this.country, this.region});

  factory Region.fromJSON(Map<String, dynamic> json) {
    return Region(
      region: json["region"],
      country: json["country"],
    );
  }
}

enter image description here

Dart相关问答推荐

数字到字符串的转换在 Dart 中总是不变的(即没有文化)?

如何防止 getter 或函数每次都重新计算?

切换到可靠的零安全后简单分配中的可空性不匹配

如何判断一个数字是否是dart中另一个数字的倍数?

自定义主题无法正常工作

Flutter tabview刷新问题

flutter命令运行失败

如何调整ShowDialog的子级大小

Dart 中使用 ifAbsent 的 Map Update 方法

如何在 Flutter DropDown 按钮中搜索

什么是NoSuchMethod错误,如何修复?

Dart null 安全性不适用于类字段

在 Dart 中编写单元测试的最佳方式是什么?

Dart 中的构造函数和初始化列表有什么区别?

具有 Maps 的 Null 感知运算符

Dart 中使用的包命名约定是什么?

`FutureOr` 的目的是什么?

是否可以在 Dart 中的一行上初始化列表?

extends与 implements与 with

什么是 ?? Dart 中的双问号?