flutter - SliverGrid 未在 Flutter 的 CustomScrollView 中显示
问题描述
我想从 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,
),
),
),
],
),
);
}
}
它解决了你的问题吗?
推荐阅读
- php - PHP:如何使用 GET 发送 cURL 请求?
- python - Keras model.inputs 不保存名称
- angular - 在 Angular 中使用 Alpine JS 和 Tailwind UI
- typescript - 有时无法识别对象类型
- angular - 如何在 Angular - Spring Boot - Auth0 中获取电子邮件声明
- java - 在 wildfly jar 中包含第三方库(keycloak SPI)
- javascript - 在 v-html 属性中显示原始 html
- imagemagick - imagemagick 嵌套重心
- tensorflow - 张量流中的 MS-SSIM
- javascript - 从缓存填充输入时,jquery更改功能不起作用