我正在开发显示产品的应用程序。该应用程序在 ListView 中有 4 个 block 。每个 block 都展示产品图像及其信息,并且可以水平滚动以获取更多数据。
我有以下示例代码
class Home extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return HomeState();
}
}
class HomeState extends State<Home> {
//------- other codes
@override
void initState() {
bloc.fetchNewProperties(0);
super.initState();
}
Widget build(BuildContext context) {
return Scaffold(
drawer: CustomDrawer(),
backgroundColor: Constants.scaffoldColor,
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
expandedHeight: 216,
floating: false,
titleSpacing: 0.0,
pinned: true,
flexibleSpace: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Constants.gradientStart, Constants.gradientEnd]),
),
child: FlexibleSpaceBar(
centerTitle: true,
background: Swiper(
itemBuilder: (BuildContext context, int index) {
return new Image.asset(
tempBannerImages[index],
fit: BoxFit.fill,
);
},
itemCount: 2,
pagination: new SwiperPagination(),
autoplay: true,
autoplayDelay: 8000,
autoplayDisableOnInteraction: true,
),
),
),
),
];
},
body: ListView(
padding: EdgeInsets.only(
left: size.getSizePx(10), right: size.getSizePx(10)),
children: <Widget>[
newProductsBlock(),
newProductsBlock(),
newProductsBlock(),
newProductsBlock(),
newProductsBlock(), //have added widget multiple times to make stuff scrollable
],
),
),
);
}
Widget newProductsBlock() {
print("---This gets called just once---");
return Column(
children: <Widget>[
Text("New Products"),
Container(
height: 230,
child: StreamBuilder(
stream: bloc.allNewProps,
builder: (context, AsyncSnapshot<ProductsModel> snapshot) {
print("--this gets called multiple times.---");
if (snapshot.hasData) {
return buildNewPropListSwipe(snapshot);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return showCirularLoadingIndicator();
},
),
)
],
);
}
}
问题 产品已成功加载到这些 block 中。但是当我一路向下滚动并回到顶部时。在第一个 block 中,循环加载指示器变得可见,而不是已经加载的项目。当我检查时,我发现当我向下滚动并再次向上滚动时,Streambuilder 被多次调用。
任何人都可以帮助我吗,我对 flutter 还很陌生。
谢谢
最佳答案
对于任何偶然发现同样问题的人,
我将 Parent Listview
更改为 ScrollSingleChildView
并将小部件包装到 Column 中,现在似乎已修复
关于Flutter:Streambuilder 被多次调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58823125/