这确实很简单,但是我找不到问题的原因。我有2个有状态的小部件A和B,在小部件A的init函数中,我正在调用netwok调用并获取api响应并呈现最新数据。 B,我填写表格并推送到服务器,然后将数据成功发布到服务器后,我调用小部件A来呈现最新数据。
Navigator.pushNamed(context, 'A');
现在的问题是,一切正常,但是当我移动widetA将数据更新到服务器后,我的网络调用返回null。
在其中工作的情况。 1)如果我不调用小部件B中的sendPetPost函数,也不将其从B移到A,那么它将正常工作。
2)来自Postman api可以正常工作,没有多次调用的问题,我每次都得到响应。
3)没有http调用的null实例错误,问题只是响应为null 初始化函数的代码A
if(await utiles.isNetworkAvailbale())
{
model.getPostList(10, 1, 1, "", "token");
model.getNewsList(10, 1, 1, "", "token");
model.getEventsList(10, 1, 1, "", "token");
model.getPetsList(35, 0, Provider.of<User>(context).id.toInt(), "token");
print("====================================================");
}else{
isNetworkAvailable=false;
}
更新数据后,从Widget B移至A。
sendingPetPost(
endPOINT,
widget.petDataImg,
widget.isImgAdded)
.whenComplete(() {
Navigator.pushNamed(context, 'homeview');
});
API调用
Future<List<Post>> getPostList(
int pageSize, int pageNo, int cateId, String search, token) async {
var posts = List<Post>();
var response;
print('$ENDPOINT/List?Type=blogs&PageNo=$pageNo&PageSize=$pageSize&Search');
try {
response = await client.get(
//'$ENDPOINT/Data?PageSize=$pageSize&PageNo=$pageNo&nCategorieID=$cateId&Search=$search',
'$ENDPOINT/List?Type=Blogs&PageNo=$pageNo&PageSize=$pageSize&Search',
headers: headers);
} catch (e) {
print("error" + e.toString());
}
if (response.statusCode == 200) {
// parse into List
print("post =>> data received");
var parsed = json.decode(response.body) as List<dynamic>;
// loop and convert each item to Post
for (var post in parsed) {
posts.add(Post.fromJson(post));
}
return posts;
}
return null;
}
错误
errorNoSuchMethodError: The getter 'codeUnits' was called on null.
I/flutter ( 7630): Receiver: null
I/flutter ( 7630): Tried calling: codeUnits
E/flutter ( 7630): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The getter 'statusCode' was called on null.
E/flutter ( 7630): Receiver: null
E/flutter ( 7630): Tried calling: statusCode
更新
太奇怪了,我将标头放在函数中,现在它可以工作了,
Future<String> sendingPetPost(
String _endpoint, Map<String, dynamic> map, bool isIm) async {
/// if we make _headers gloable it create exception (same exception which is described above), but if we put _headers inside the fucntion like this, then it works.
Map<String, String> _headers = {
'content-type': 'application/json',
'accept': 'application/json',
'authorization':
'Basic ' + base64Encode(utf8.encode('Sau***:Sa*****'))
};
Dio dio = Dio();
try {
FormData formData = FormData.fromMap({
"pet_image": await MultipartFile.fromFile(
map['path'],
filename: map['name'],
)
});
Response response = await dio.post("$ENDPOINT/AddPet?$_endpoint",
data: formData, options: Options(headers: _headers));
return json.decode(response.data)['message'];
} on SocketException {
throw Failure(UIHelper.NO_INTERNET_EXCEP);
}
}