SliverGrid 未显示在 Flutter 中的 CustomScrollView 内部

SliverGrid not showing inside CustomScrollView in Flutter

我想从 REST api 获取数据,使用未来应该构建的 SliverGrid。但它没有显示,只显示白色,而且我也不知道如何在 SliverGrid 中指定网格项目总数。所以如果它显示它必须产生比实际数量更多的东西。


SliverGrid(
              gridDelegate:
                  SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              delegate: SliverChildBuilderDelegate(
                (BuildContext context, int index)
                {
                  return FutureBuilder(
                    future: _items,
                    builder: (context, snapshot) {
                      return snapshot.connectionState == ConnectionState.done
                          ? snapshot.hasData
                              ? GridItem()
                              : Text('Retry')
                          : Text('progress');
                    },

                  );

                },

              ),)


演示片段

未来

  Future<List<int>> _f() async {
     return await Future.delayed(Duration(seconds: 3))
        .then((value) => [1, 3, 5, 56, 65]);
  }

并在内部使用 CustomScrollView

        FutureBuilder<List<int>>(
            future: _f(),
            builder: (context, snapshot) => !snapshot.hasData //handle more situation here  
                ? SliverToBoxAdapter(child: Text("loading"))
                : SliverGrid(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                    ),
                    delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                        return Text(snapshot.data![index].toString());
                      },
                      childCount: snapshot.data!.length,
                    ),
                  ),
          ),

全组件


class HomeScreen extends StatefulWidget {
  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  Future<List<int>> _f() async {
    return await Future.delayed(Duration(seconds: 3))
        .then((value) => [1, 3, 5, 56, 65]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        slivers: [ 
          FutureBuilder<List<int>>(
            future: _f(),
            builder: (context, snapshot) => !snapshot.hasData
                ? SliverToBoxAdapter(child: Text("loading"))
                : SliverGrid(
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                    ),
                    delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                        return Text(snapshot.data![index].toString());
                      },
                      childCount: snapshot.data!.length,
                    ),
                  ),
          ),
        ],
      ),
    );
  }
}


它是否解决了您的问题?