我正在Flutter中编写一个表单,其中要包含图像/视频的上传。
一切正常-我的媒体正在上传到Cloud Storage for Firebase,并且可以使用File
和uploadUrl
。我想向用户显示上传的媒体,无论是图像还是视频。
我已经实现了一个小部件,其中给定了一些TextFieldController
,一些验证器等,将构建具有这么多TextFormFields
的表单-该小部件还接受了一个参数additional: List<Widget>
用于提供实际表单字段和表单中的“提交”按钮之间的多余小部件。就我而言,这是我要显示上传的媒体的地方。我将尝试在代码中显示它:
实际的小部件:
class MainWidget extends StatefulWidget {
MainWidget({Key key}) : super(key: key);
@override
State<StatefulWidget> createState() => MainState();
}
class MainState extends State<MainWidget> implements Base {
MainState({Key key});
@override
void initState() {
super.initState();
form = CommonForm( // Will create the TextFormFields,the submit button etc.
validators = [...],... // Label texts,hint texts etc.
additional = [ // This will show between TextFormFields and the submit button
imageUrl.value == "" && videoUrl.value == ""
? Image(image: AssetImage('assets/placeholder.png'))
: videoUrl.value == ""
? CachedNetworkImage(
imageUrl: imageUrl.value,placeholder: (context,url) =>
CircularProgressIndicator(),)
: videoController.value.initialized
? AspectRatio(
aspectRatio: videoController.value.aspectRatio,child: VideoPlayer(videoController),)
: Image(
image: AssetImage('assets/placeholder.png')),],);
}
CommonForm form;
PrimitiveWrapper<String> imageUrl = PrimitiveWrapper<String>(""),videoUrl = PrimitiveWrapper<String>("");
... // Validators,controllers
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
...
),body: SingleScrollView(
child: form,padding: EdgeInsets.all(30.0),),);
}
}
上传图像/视频上的点击处理程序(此处未显示)正确地将两个PrimitiveWrapper
更改为实际URL,并在此小部件上调用setState()
。
CommonForm
仅将additional
中的小部件包含在其build
函数中的字段和提交按钮之间。 PrimitiveWrapper
包含一个包含实际值的字段value
-试图通过引用传递以查看是否是问题是一种黑客。但是,即使value
已正确更新,它也不起作用。
那么..如何在Flutter中做到这一点,同时又保持这种简单的方式来创建常见表单?是否有可能将这样的事情传递给另一个有状态的小部件并更新其状态?仅仅是因为CommonForm
总是看到例如imageUrl
作为初始值""
?以及如何解决呢?我也尝试过简单地提供Object
并检查它是否为空(并在上传媒体的点击处理程序中正确初始化它),但这都不起作用。
希望有个聪明的人知道该怎么做-干杯! :)