DioError [DioErrorType.DEFAULT]: Bad state: Can‘t finalize a finalized MultipartFile

class DioPostPage extends StatefulWidget {
  @override
  createState() => new DioPostPageState();
}

FormData formData = new FormData.fromMap({'username': 'DeMon', 'password': 'lh1995623'});
class DioPostPageState extends State<DioPostPage> {
  var futureBuilder = FutureBuilder(
      future: dio.post<String>("/user/login", data: formData),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        //请求完成
        if (snapshot.connectionState == ConnectionState.done) {
          //发生错误
          if (snapshot.hasError) {
            return Text(snapshot.error.toString());
          }
          //请求成功,通过项目信息构建用于显示项目名称的ListView
          Response response = snapshot.data;
          return Text(response.data);
        }
        //请求未完成时弹出loading
        return CircularProgressIndicator();
      });

  @override
  Widget build(BuildContext context) {
    return Center(child: futureBuilder);
  }
}

使用Dio进行如上代码的post请求时,第一次请求正常,第二次请求报错如下:

DioError [DioErrorType.DEFAULT]: Bad state: Can't finalize a finalized MultipartFile

查询Dio的Issues-482 大概知道了原因:

Because MultipartFile is based on Stream, and a Stream can be read only once, you should create a new MultipartFile when the request is resubmitted.

Dio使用post提交表单请求时,每次重新提交时,data参数都需要传入一个新的表单对象。

修改后的正常代码如下:

class DioPostPage extends StatefulWidget {
  @override
  createState() => new DioPostPageState();
}

class DioPostPageState extends State<DioPostPage> {
  var futureBuilder = FutureBuilder(
      future: dio.post<String>("/user/login", data: new FormData.fromMap({'username': 'DeMon', 'password': 'lh1995623'})),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        //请求完成
        if (snapshot.connectionState == ConnectionState.done) {
          //发生错误
          if (snapshot.hasError) {
            return Text(snapshot.error.toString());
          }
          //请求成功,通过项目信息构建用于显示项目名称的ListView
          Response response = snapshot.data;
          return Text(response.data);
        }
        //请求未完成时弹出loading
        return CircularProgressIndicator();
      });

  @override
  Widget build(BuildContext context) {
    return Center(child: futureBuilder);
  }
}

你可能感兴趣的:(#,Flutter,dio)