Flutter:将json响应传递到下一个屏幕



我试图将JSON响应传递到下一个屏幕,但收到以下错误:

错误:无法将参数类型"Response"分配给参数类型"List"。(argument_type_not_assignable at[nutrivisor]lib/scan_screen.dart:179(

代码:

Future<void> _clearImage() async {
try {
String filename = imageFile!.path.split('/').last;
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(imageFile!.path,
filename: filename, contentType: MediaType('image', 'jpg')),
"type": "image/png"
});
Response response = await dio.post('http://IP:8000/scan/',
data: formData,
options: Options(
followRedirects: false,
// will not throw errors
validateStatus: (status) => true,
headers: {
"accept": "*/*",
"Content-Type": "multipart/form-data",
}));
print(response);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScanScreen2(jsondata: response)),
);
} catch (e) {
print(e);
}
setState(() {});
}
}

ScanScreen2:的代码

class ScanScreen2 extends StatefulWidget {
final List jsondata;
ScanScreen2({Key key, this.jsondata}) : super(key: key);
@override
_ScanScreen2State createState() => _ScanScreen2State();
}

此外,在将响应传递到另一个屏幕后,我想知道如何在下一个屏幕中使用它。请提供相同的代码。

我相信您的响应主体包含一个映射;

Future<void> _clearImage() async {
try {
String filename = imageFile!.path.split('/').last;
FormData formData = FormData.fromMap({
"image": await MultipartFile.fromFile(imageFile!.path,
filename: filename, contentType: MediaType('image', 'jpg')),
"type": "image/png"
});
Response response = await dio.post('http://IP:8000/scan/',
data: formData,
options: Options(
followRedirects: false,
// will not throw errors
validateStatus: (status) => true,
headers: {
"accept": "*/*",
"Content-Type": "multipart/form-data",
}));
if(response.statusCode == 200) {
print(response);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScanScreen2(jsondata: response.data!)),
);}
else{
print("Some thing went wrong : responseStatusCode = ${response.statusCode}")}
} catch (e) {
print(e);
}
setState(() {});
}
}

Edit2:Op刚刚添加了json数据结构。

class ScanScreen2 extends StatefulWidget {
// Change from List -> Map
final Map jsondata;
ScanScreen2({Key key, this.jsondata}) : super(key: key);
@override
_ScanScreen2State createState() => _ScanScreen2State();
}

也许您想要的是响应的正文,看看错误,应该修复它:

final json = jsonDecode(response.body) as List;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScanScreen2(jsondata: json)),
);

编辑:我看到你使用的是dio包,而不是HTTP包,我对dio不是很熟悉,但试试这个:

Response<List> response = await dio.post('http://IP:8000/scan/',
data: formData,
options: Options(
followRedirects: false,
// will not throw errors
validateStatus: (status) => true,
headers: {
"accept": "*/*",
"Content-Type": "multipart/form-data",
}));
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ScanScreen2(jsondata: response.data)),);}

相关内容

最新更新