如何在FutureBuilder中从请求呈现数据

时间:2019-05-14 03:16:08

标签: dart flutter

我正在尝试从我的api列出宠物小精灵,当我调用列表时它可以工作,但是当我尝试获取每个宠物小精灵的数据时,它不会呈现数据。

更新了@Gazihan Alankus答案的代码。

Widget build(BuildContext context) {
    return FutureBuilder<PokeData>(
      future: api.getPokemonList(),
      builder: (
        BuildContext context,
        AsyncSnapshot<PokeData> pokedata
      ) {
        if(pokedata.hasData && pokedata.connectionState == ConnectionState.done) {
          return Container(
            child: ListView(
              children: pokedata.data.results.map((pokemon) {
                FutureBuilder(
                  future: api.getPokeDetail(pokemon.url),
                  builder: (
                    BuildContext context,
                    AsyncSnapshot snapshot
                  ) {
                    print('------------widget------------');
                    if(snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
                      return Container(child: PokemonWidget(
                        pokemon.name,
                        snapshot.data.sprites.normal,
                        snapshot.data.types
                      ),);
                    } else {
                      return Container(
                        child: CircularProgressIndicator(),
                      );
                    }
                  }
                );
              }).toList(),
            ),
          );
        } else {
          return Center(
            child: CircularProgressIndicator(),
          );
        }
      },
    );
  }

但是现在我在运行应用程序时遇到此错误,第一个请求运行良好,但从未调用第二个请求。

flutter: ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
flutter: The following assertion was thrown during performLayout():
flutter: 'package:flutter/src/widgets/sliver.dart': Failed assertion: line 553 pos 12: 'child != null': is
flutter: not true.
flutter:
flutter: Either the assertion indicates an error in the framework itself, or we should provide substantially
flutter: more information in this error message to help you determine and fix the underlying cause.
flutter: In either case, please report this assertion by filing a bug on GitHub:
flutter:   https://github.com/flutter/flutter/issues/new?template=BUG.md
flutter:
flutter: (elided 5 frames from class _AssertionError and package dart:async)
flutter:
flutter: The following RenderObject was being processed when the exception was fired:
flutter:   RenderSliverList#04cee relayoutBoundary=up2 NEEDS-LAYOUT NEEDS-PAINT
flutter:   creator: SliverList ← MediaQuery ← SliverPadding ← Viewport ← IgnorePointer-[GlobalKey#b48da] ←
flutter:   Semantics ← Listener ← _GestureSemantics ←
flutter:   RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#865eb] ← _ScrollableScope ←
flutter:   _ScrollSemantics-[GlobalKey#8f9cb] ← Scrollable ← ⋯
flutter:   parentData: paintOffset=Offset(0.0, 0.0) (can use size)
flutter:   constraints: SliverConstraints(AxisDirection.down, GrowthDirection.forward, ScrollDirection.idle,
flutter:   scrollOffset: 0.0, remainingPaintExtent: 603.0, crossAxisExtent: 375.0, crossAxisDirection:
flutter:   AxisDirection.right, viewportMainAxisExtent: 667.0, remainingCacheExtent: 853.0 cacheOrigin: 0.0 )
flutter:   geometry: null
flutter:   no children current live
flutter: This RenderObject has no descendants.
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: Another exception was thrown: NoSuchMethodError: The getter 'scrollOffsetCorrection' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The method 'debugAssertIsValid' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The getter 'visible' was called on null.
flutter: Another exception was thrown: NoSuchMethodError: The getter 'visible' was called on null.

1 个答案:

答案 0 :(得分:1)

一种方法是为每个项目创建一个FutureBuilder,如下所示:

Widget build(BuildContext context) {
  return FutureBuilder<PokeData>(
    future: api.getPokemonList(),
    builder: (
      BuildContext context,
      AsyncSnapshot<PokeData> snapshot
    ) {
      if(snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
        return Container(
          child: ListView(
            children: snapshot.data.results.map((pokemon) {
              FutureBuilder(
                future: api.getPokeDetail(pokemon.url),
                builder: (
                  BuildContext context,
                  AsyncSnapshot snapshot
                ) {
                  if(snapshot.hasData && snapshot.connectionState == ConnectionState.done) {
                    return PokemonWidget(
                      pokemon.name,
                      resp.sprites.normal,
                      resp.types
                    );
                  } else {
                    return Center(
                      child: CircularProgressIndicator(),
                    );
                  }
                }
              )
              }).toList(),
          ),
        );
      } else {
        return Center(
          child: CircularProgressIndicator(),
        );
      }
    },
  );
}