简体   繁体   中英

The property 'files' can't be unconditionally accessed because the receiver can be 'null'

Recently i made a file_picker using bloc builder, and then i couldn't make a variable because there's an error on this code:

          onTap: () async {
            FilePickerResult? result = await FilePicker.platform.pickFiles();
            PlatformFile file = result.files.first;
            if (result != null) {
              fileFieldBloc.updateValue(file);
            }; 

the error that being highlighted is on PlatformFile file = result.files.first; and here's my full code:

class FileFieldBlocBuilder extends StatelessWidget {
  FileFieldBlocBuilder({
    Key? key, required this.fileFieldBloc}) : super(key: key);

  final InputFieldBloc<File, Object> fileFieldBloc;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<InputFieldBloc<File, Object>,
        InputFieldBlocState<File, Object>>(
      bloc: fileFieldBloc,
      builder: (context, state) {

        return GestureDetector(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: InputDecorator(
              decoration: InputDecoration(
                labelText: 'Select a File',
                suffixIcon: AnimatedOpacity(
                  duration: Duration(milliseconds: 400),
                  opacity: state.value == null ? 0.0 : 1.0,
                  child: InkWell(
                    borderRadius: BorderRadius.circular(25),
                    child: Icon(Icons.clear),
                    onTap: state.value == null ? null : fileFieldBloc.clear,
                  ),
                ),
              ),
              //child: Text(state?.value?.path?.split('/')?.last ?? ''),
            ),
          ),
          onTap: () async {
            FilePickerResult? result = await FilePicker.platform.pickFiles();
            PlatformFile file = result.files.first;
            if (result != null) {
              fileFieldBloc.updateValue(file);
            };
          },
        );
      },
    );
  }
}
    FilePickerResult? result = await 
    FilePicker.platform.pickFiles();
    
        if (result.files != null) {
        PlatformFile file = 
        result.files.first;
          
        fileFieldBloc.updateValue(file);

        };

try

PlatformFile? file = result.files?.first;
if (result != null && file!=null) {
    fileFieldBloc.updateValue(file);
};

Based on answer above i've already solved it

         onTap: () async {
            FilePickerResult? result = await FilePicker.platform.pickFiles();
            if (result != null) {
              PlatformFile file = result.files.first;
              fileFieldBloc.updateValue(file);
            }
          },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM