ave created an API using Laravel and I am trying to fetch the data in flutter using HTTP but I keep getting this error.
The error I keep getting in Emulator is SocketException:Connection refused (OS Error:Connection refused, errno=111), address = 127.0.0.1, port = 41068
Below is an excerpt of my code.
Future<List<Category>> fetchCategories() async {
final http.Response response = await http.get(
Uri.parse('http://127.0.0.1:8000/api/categories'),
);
if (response.statusCode == 200) {
return (json.decode(response.body) as List)
.map((category) => Category.fromJson(category))
.toList();
} else {
throw Exception('Failed to load post');
}
}
I added these to android manifest file
<uses-permission android:name="android.permission.INTERNET" />
Fetching the data here
ListView.builder(
itemCount: snapshot.data!.length,
itemBuilder: (BuildContext context, index) {
Category category = snapshot.data![index];
return ListTile(
title: Text(category.name),
onTap: () {
Navigator.pushNamed(
context,
'/categories/${snapshot.data![index].id}',
);
},
);
},
);
The android manifest files in both debug folder and the main has internet permission,
I have read this enter link description here but it did not solve the problem
And I have read this as well enter link description here but none helped
CodePudding user response:
Because 127.0.0.1 mean the localhost of the current machine which is the android device. Your server is not runing on the android device but the PC machine. You should use the ip address of your PC like 192.168.1.100, and make sure the Android device can access this ip.