Home > Enterprise >  File_picker in stateless bloc widget
File_picker in stateless bloc widget

Time:01-23

How do you go about using file_picker package in flutter and bloc management? https://pub.dev/packages/file_picker

I have following code:

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();
        },
      ),
    );   } }

When assigining the late final a LateError._throwFieldAlreadyInitialized is throwed. How do I pass my filepicker results to my bloc?

What is the best practice for this kind of situation?

Removing filepickerResults from my constructor mad it work ONLY if it gets initialized, but that is not always the case...

Thank you

CodePudding user response:

FilePicker needs a List so I did following:

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,
                              );

                              if (results != null) {
 -------------------------->      for (var element in results.files) {
                                  filePickerResults.add(element);
                                }
                              }

                              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();
    },
  ),
);   } }

This CAN be final and be played around with in a stateless widget with bloc.

  • Related