flutter - 如何让未来的小部件在有连接时自动加载数据
问题描述
我正在尝试制作产品信息应用程序,我使用未来的构建器来构建类别列表。我面临两个问题 1. 当应用程序最初离线然后变为在线时,它不会加载数据。2.有什么办法可以得到快照的长度。我将粘贴下面的代码:
FutureBuilder(
future: getAllCategory(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.data == null) {
return Center(
child: Container(
child: CircularProgressIndicator(),
),
);
} else {
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: categorylist.length != 0 || categorylist.length!= null ? categorylist.length:0,
shrinkWrap: true,
itemBuilder: (context, index) {
return GestureDetector(
onTap: () async {
pr.show();
print('clicked custom category');
print(categorylist[index].catName);
print(categorylist[index].catId);
await getAllProductsInCategory(categorylist[index].catId);
setState(() {
catId = categorylist[index].catId;
myinitlist.clear();
myinitlist = List.from(productList);
pr.hide();
_selectedIndex = index;
});
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Card(
color: _selectedIndex != null && _selectedIndex == index
? selectedColor
: defColor,
elevation: _selectedIndex != null && _selectedIndex == index
? 4.0
: 1.0,
child: Center(
child: Padding(
padding: const EdgeInsets.all(3.0),
child: Container(
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Column(
children: <Widget>[
Image.network(
categorylist[index].catThumbnail,
width: 80.0,
height: 50.0,
scale: 1.0,
),
Padding(
padding: const EdgeInsets.only(top: 4.0),
child: Text(
categorylist[index].catName,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.black, fontSize: 10.0, fontWeight: FontWeight.w500),
),
)
],
),
),
),
),
),
),
],
),
);
});
}
},
),
我认为如果有任何方法可以获得快照的长度,那么我可以解决我的第一个问题。
解决方案
我改变了这样的代码
FutureBuilder(
future: getAllCategory(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return Center(
child: Container(
child: CircularProgressIndicator(),
),
);
} else {
print('snapshot length ${snapshot.data.length}');
return ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: snapshot.data.length,
shrinkWrap: true,
itemBuilder: (context, index) {
}
推荐阅读
- java - 使用 Wildfly Elytron 安全的程序化登录
- java - android studio中的依赖微调器
- python - 在 Raspberry PI 和 Cloud Server 之间进行实时通信然后在 Web 应用程序中显示输出的正确方法是什么?
- python - 查找多个句子中的出现
- android - 搜索视图不使用 setOnQueryTextListener 过滤 ListView 数据
- python - 如何从python中的列表中删除所有重复元素?
- r - 通过循环赋值
- angular - Angular Heroes 示例中令人费解的 Typescript 函数语法
- spring-boot - 应用程序/x-www-form-urlencoded 的 Spring WebClient POST 和内容长度标头
- python - 如何在 pandasper 每天 9 点、12 点和 18 点创建自定义频率