Flutter error: Expected a value of type 'File', but got one of type 'FilePickerResult'

Flutter error: Expected a value of type 'File', but got one of type 'FilePickerResult'

我正在尝试将一些数据和一个文件发送到我的节点 js 服务器。该文件是一个 .txt 文件,我正在使用 FilePicker 获取文件并使用 MultiPartRequest 发送它。

这是带有文本表单和附件按钮的小部件:

Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Crear una nueva tarea'),
        backgroundColor: Colors.green[300],
      ),
      body: ChangeNotifierProvider<LoginFormProvider>(
          create: (context) => LoginFormProvider(),
          child: Consumer<LoginFormProvider>(builder: (context, value, child) {
            final loginFormProvider =
                Provider.of<LoginFormProvider>(context, listen: true);
            return Container(
                color: Colors.grey[100],
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Center(
                  child: ConstrainedBox(
                    constraints: BoxConstraints(maxHeight: 370),
                    child: Form(
                      key: loginFormProvider.formKey,
                      child: Column(
                        children: [
                          TextFormField(
                            onChanged: (value) =>
                                loginFormProvider.title = value,
                            decoration: buildInputDecoration(
                                hint: 'Enunciado',
                                label: 'Enunciado de la tarea',
                                icon: Icons.title),
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          TextFormField(
                            onChanged: (value) =>
                                loginFormProvider.date = value,
                            cursorColor: Colors.green,
                            decoration: buildInputDecoration(
                                hint: 'Fecha limite',
                                label: 'Fecha limite de entrega',
                                icon: Icons.date_range),
                          ),
                          SizedBox(
                            height: 20,
                          ),
                          ElevatedButton(
                              onPressed: () async {
                                final result =
                                    await FilePicker.platform.pickFiles(
                                  type: FileType.custom,
                                  allowedExtensions: ['txt', 'docx'],
                                );
                                final file = result!.files.first.name;
                                value.setFile(result);
                              },
                              child: Text('Seleccionar archivo')),
                          SizedBox(
                            height: 20,
                          ),
                          CustomOutlinedButton(
                              onPressed: () async {
                                if (value.file == null) return;
                                value.makePostRequest(loginFormProvider.title,
                                    id, teacherID, loginFormProvider.date);
                                
                                Navigator.pop(context);
                              },
                              text: 'Crear Tarea'),
                        ],
                      ),
                    ),
                  ),
                ));
          })),
    );
  }

并且我正尝试在 class 中按如下方式发送请求:

class LoginFormProvider extends ChangeNotifier {
  GlobalKey<FormState> formKey = new GlobalKey<FormState>();

  var file;
  String role = '';
  String id = '';
  String lastname = '';
  String firstname = '';
  String password = '';
  String tid = '';
  String name = '';
  String title = '';
  int teacherid = 0;
  int subjectid = 0;
  String date = '';

  bool validateForm() {
    if (formKey.currentState!.validate()) {
      return true;
    } else {
      return false;
    }
  }

  Future setFile(txt) async {
    this.file = txt;
    this.notifyListeners();
  }

  Future makePostRequest(
      String title, int subjectid, int teacherid, String limitDate) async {
    var url = Uri.parse('http://localhost:8000/newHomework');
    var request = http.MultipartRequest('POST', url);
    var headers = {'Content-Type': 'text/plain; charset=UTF-8'};
    File fileByte = this.file;
    Uint8List data = await fileByte.readAsBytes();
    List<int> list = data.cast();
    request.files
        .add(http.MultipartFile.fromBytes('text', list, filename: 'tarea1'));
    request.headers.addAll(headers);
    request.fields['title'] = title;
    request.fields['limitDate'] = limitDate;
    request.fields['subjectid'] = subjectid.toString();
    request.fields['teacherid'] = teacherid.toString();
    request.fields['ext'] = '.txt';

    var res = await request.send();
    return res.stream.bytesToString().asStream().listen((event) {
      var parsedJson = json.decode(event);
      print(parsedJson);
    });
  }
}

我得到 Expected a value of type 'File', but got one of type 'FilePickerResult'

我不知道如何解决这个问题来发送文件...关于如何解决这个问题有什么想法吗?

您做错的是您设置的是 FilePickerResult 而不是 File。 [使用不同的网络方法进行编辑。

ElevatedButton(
                              onPressed: () async {
                                final result =
                                    await FilePicker.platform.pickFiles(
                                  type: FileType.custom,
                                  allowedExtensions: ['txt', 'docx'],
 withReadStream:
          true,

                                );
//Edited Part 
                      var file = result!.files.single;                              
                                value.setFile(file);
                              },
                              child: Text('Seleccionar archivo'))

还有

 PlatformFile file = null;

 Future setFile(PlatformFile txt) async {
    this.file = txt;
    this.notifyListeners();
  }
 Future makePostRequest(
      String title, int subjectid, int teacherid, String limitDate) async {
    var url = Uri.parse('http://localhost:8000/newHomework');
    var request = http.MultipartRequest('POST', url);
    var headers = {'Content-Type': 'text/plain; charset=UTF-8'};
    

    request.files.add(new http.MultipartFile(
        "text", file.readStream, file.size,
        filename: "tarea1"));


    request.headers.addAll(headers);
    request.fields['title'] = title;
    request.fields['limitDate'] = limitDate;
    request.fields['subjectid'] = subjectid.toString();
    request.fields['teacherid'] = teacherid.toString();
    request.fields['ext'] = '.txt';

    var res = await request.send();
    return res.stream.bytesToString().asStream().listen((event) {
      var parsedJson = json.decode(event);
      print(parsedJson);
    });
  }