php - Fix the Model Flutter / Dart
I have a PHP backend and I use it on my localhost so everything okay but I have a problem that the image URL I get from API is a wrong path and I can't change it from server-side so I decide to fix it on my client-side
I can display an image on my emulator with this path :
http://10.0.2.2:8000/storage/app/public/171/conversions/api-icon.jpg
and the API gives me this path
http://192.168.1.114/multi-restaurants/public/storage/app/public/171/conversions/api-icon.jpg
I fix it by making a function to change the path but it takes a lot of work like I should put this function in every place I wanna display an image!!
I'm sure there is a way to change the path directly from the model when I receive the api here is my model
class Media {
String id;
String name;
String url;
String thumb;
String icon;
String size;
Media();
Media.fromJSON(Map<String, dynamic> jsonMap)
: id = jsonMap['id'].toString(),
name = jsonMap['name'],
url = jsonMap["url"] ,
thumb = jsonMap['thumb'],
icon = jsonMap['icon'],
size = jsonMap['formated_size'];
This function that I'm using in every class to change path Url
String changepath(String uuu) {
final uri = Uri.parse(uuu);
print("This is $uri");
if (uri.path.contains("multi-restaurants")) {
print("http://10.0.2.2:8000/${uri.pathSegments[2]}/${uri.pathSegments[3]}/${uri.pathSegments[4]}/${uri.pathSegments[5]}/${uri.pathSegments[6]}");
return"http://10.0.2.2:8000/${uri.pathSegments[2]}/${uri.pathSegments[3]}/${uri.pathSegments[4]}/${uri.pathSegments[5]}/${uri.pathSegments[6]}";
}
}
}
Answer
Solution:
If the API constantly sending the URL in "http://192.168.1.114/multi-r ... " in this format, then there is a solution for it, don't know is this a smart move or anything you looking for.Just create String type Function,pass the url from json url = changer(jsonMap["url"]);
and use it to convert the URL to desired URL.
String changer(String _string1) {
String _string2 = _string1.replaceAll("http://192.168.1.114/multi-restaurants/public", "http://10.0.2.2:8000");
return _string2;
}
Answer
Solution:
I Solve the Problem with Create a Helper Class and put inside it a static function and call it in every widget I wanna display (Url)
static String changer(String _string1) {
String _string2 = _string1.replaceAll(
"http://192.168.1.114/multi-restaurants/public",
"http://10.0.2.2:8000");
print(_string2);
return _string2;
}
Source