Flutter使用FutureBuilder
2020-12-30 本文已影响0人
刘铁崧
// 每次构建都会请求并刷新页面
// 有一定局限性:如加载更多等功能叠加不合适使用FutureBuilder
class TestFutureBuilder extends StatelessWidget {
@override
Widget build(BuildContext context) {
CYScreenUtils.init(designedWidth: 750);
return FutureBuilder<List<CategoryModel>>(
future: CYJsonDecode.getCategory(),//异步请求
builder: (context,snapshot){
if (!snapshot.hasData) return Center(child: CircularProgressIndicator());// 数据不存在,加载选型进度条
if (snapshot.error) return Center(child: Text("请求失败"));// 请求失败
final data = snapshot.data;
return GridView.builder(
padding: EdgeInsets.all(10.px),
itemCount: data.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,// 一排两个
crossAxisSpacing: 10.px,//间距
mainAxisSpacing: 10.px,//
childAspectRatio: 1.5
),
itemBuilder: (context,index){
return TestItem(data[index]);
},
);
},
);
}
}