【问题标题】:Flutter: Is it Possbile to have Multiple Futurebuilder or A Futurebuilder for Multiple Future Methods?Flutter:是否可以有多个 Futurebuilder 或一个 Futurebuilder 用于多个 Future 方法?
【发布时间】:2018-08-03 05:49:13
【问题描述】:

假设我从不同的 URL 获取不同的列表 所以 Future 函数看起来像这样

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

因此 Widget Builder 将如下所示

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

有没有办法解决这个问题?我正在尝试找到如何实现这个的答案,还是有另一种方法?

【问题讨论】:

  • 我最终创建了一个调用这两种方法并适当等待的方法。因此,调用此方法会返回两个未来结果的单个未来。

标签: dart flutter


【解决方案1】:

我想你正在寻找类似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"],
    );
  }
}

【讨论】:

  • 请不要只回答链接。在此处添加特定代码,这样即使您的链接失效,它仍然存在。
猜你喜欢
  • 2020-06-30
  • 2018-12-25
  • 2021-07-31
  • 2022-11-27
  • 2019-09-12
  • 1970-01-01
  • 2018-10-22
  • 2021-02-14
  • 1970-01-01
相关资源
最近更新 更多