使用提供程序时,在对话框中处于未更新状态



我正试图打开一个对话框,让用户添加两件事:

  1. 1-视频缩略图(图像文件(
  2. 视频URL(字符串(

用户点击一个墨水井,打开对话框,然后用户点击对话框中的墨水井以选择视频缩略图,即图像文件。图像文件被设置,但它不会更新墨水井的状态,墨水井需要显示拾取的文件。热重新加载后会更新状态。我使用提供程序来设置图像文件,并使用其实例来检查文件是否已拾取。

更改通知程序->

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class GetThumbnailImage extends ChangeNotifier {
PickedFile? image;
Future setImage(var file) async {
image = file;
notifyListeners();
}
}

使用更改通知程序的小工具->

InkWell(
onTap: () {
getVideoImage().then((image) {
print(image);
if (image != null) {
_imageInstance.setImage(image);
}
});
},
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.height * 0.25,
child: Center(
child: _imageInstance.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(_imageInstance.image!.path),
),
),
))

在要重建的小部件上添加一个消费者小部件

Center(
child: Consumer<GetThumbnailImage>(
builder:(context, model, child) => model.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(model.image!.path),
),
),
),

原因是"对话框不是小部件树的一部分;

你的代码不完整,但这里有一些建议。

解决方案1。

您可以将父窗口小部件的context传递给对话框,因此对话框的行为也应该类似于窗口小部件树的一部分

解决方案2。(更好(

showDialogBox方法中使用类似的内容。。。

final image = context.watch<GetThumbnailImage>();
ChangeNotifierProvider.value(
value: image
child: Dialog(...)
);

现在您可以在对话框中使用提供者的实例,它还将重建小部件树来更新UI

对代码进行了更改,并尝试

class GetThumbnailImage extends ChangeNotifier {
PickedFile? _image;

PickedFile get image => _image;
Future setImage(var file) async {
_image = file;
notifyListeners();
}
}

最新更新