如何在flutter和blocks管理中使用file_picker包?https://pub.dev/packages/file_picker
我有以下代码:
class NewAuction extends StatelessWidget {
late final FilePickerResult? filePickerResults;
final _formKey = GlobalKey<FormState>();
final _priceController = TextEditingController();
final _descriptionController = TextEditingController();
final _titleController = TextEditingController();
NewAuction({Key? key, this.filePickerResults}) : super(key: key);
@override Widget build(BuildContext context) {
return Scaffold(
...
child: SizedBox(
width: double.infinity,
height: 48,
child: ElevatedButton.icon(
icon: const Icon(
Icons.camera_alt,
color: Colors.white,
),
style: ButtonStyle(
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32),
side: const BorderSide(
color: Colors.deepPurple),
),
),
),
label: const Text(
'Upload images',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w400),
),
onPressed: () async {
final results =
await FilePicker.platform.pickFiles(
allowMultiple: true,
type: FileType.image,
);
THROWS ERROR WHEN ASSIGNING if (results != null) {
--------------------------> filePickerResults = results;
}
if (results == null) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text('No files selected'),
));
return;
}
if (results.paths.length > 5) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text('Maximum 5 files allowed'),
));
return;
}
},
),
),
),
...
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 8),
child: SizedBox(
width: double.infinity,
height: 48,
child: ElevatedButton.icon(
icon: const Icon(
Icons.post_add,
color: Colors.white,
),
style: ButtonStyle(
shape: MaterialStateProperty.all<
RoundedRectangleBorder>(
RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(32),
side: const BorderSide(
color: Colors.deepPurple),
),
),
),
label: const Text(
'Post',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.w400),
),
onPressed: () async {
if (_formKey.currentState!
.validate()) {
context.read<AuctionBloc>().add(
PostNewAuctionEvent(
_titleController.text,
double.parse(
_priceController.text),
_descriptionController.text,
-------------------------> filePickerResults));
}
},
),
...
);
}
return Container();
},
),
); } }
当分配最后的final时,会抛出一个LateError._throwFieldAlreadyInitialized。我如何将我的filepicker结果传递到我的块?
这种情况下的最佳实践是什么?
从我的构造函数中删除filepickerResults,使它只有在初始化时才能工作,但情况并不总是这样...
谢谢
1条答案
按热度按时间jslywgbw1#
FilePicker需要一个列表,所以我做了以下:
这可以是最终的,可以在一个无状态的小部件中使用块来进行操作。