Hi,大家好,我是编程小6,很荣幸遇见你,我把这些年在开发过程中遇到的问题或想法写出来,今天说一说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);
}
}
今天的分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。
上一篇
已是最后文章
下一篇
已是最新文章