Flutter使用Provider时对话框内选中视频缩略图的状态无法更新问题
问题原因
你当前的实现没有监听GetThumbnailImage的状态变化,notifyListeners触发时UI层没有收到重绘信号,所以只有热重载强制刷新页面才能看到更新后的效果。
解决步骤
- 首先确认你已经在应用父级节点正确注册了ChangeNotifierProvider:
ChangeNotifierProvider( create: (context) => GetThumbnailImage(), child: YourAppWidget(), )
- 将对话框内展示缩略图的InkWell组件用
Consumer包裹,通过Consumer实时获取最新的GetThumbnailImage实例状态,只要调用notifyListeners,Consumer的builder就会自动重绘子组件,修改后的代码如下:
Consumer<GetThumbnailImage>( builder: (context, thumbnailProvider, child) { return InkWell( onTap: () { getVideoImage().then((image) { print(image); if (image != null) { thumbnailProvider.setImage(image); } }); }, child: SizedBox( width: MediaQuery.of(context).size.width * 0.8, height: MediaQuery.of(context).size.height * 0.25, child: Center( child: thumbnailProvider.image == null ? SizedBox( width: 200, height: 200, child: FadeInImage( image: NetworkImage( apiBase + productId.toString() + apiLaterPart), placeholder: AssetImage("assets/images/Otherimages/addvideo.jpg"), imageErrorBuilder: (context, error, stackTrace) { return Image.asset( 'assets/images/Otherimages/addvideo.jpg', fit: BoxFit.fitWidth); }, fit: BoxFit.fitWidth, ), ) : Image.file( File(thumbnailProvider.image!.path), ), ), )); } )
注意事项
如果弹出对话框时提示找不到GetThumbnailImage实例,是因为对话框的上下文独立于父页面,需要在showDialog时通过ChangeNotifierProvider.value将已有的实例透传给对话框子树,示例如下:
showDialog( context: context, builder: (dialogContext) { return ChangeNotifierProvider.value( value: Provider.of<GetThumbnailImage>(context, listen: false), child: YourDialogWidget(), ); } );
内容的提问来源于stack exchange,提问作者Muhammad Moiz
相关产品推荐
相关产品推荐

