I'm a beginner with Flutter and am trying to print a list of doctors in a widget via a GET request and FutureBuilder. All doctors are currently in a local MySQL database and are accessible via Postman, but the GET request seems to hang in my code.
I've tried using the code snippet provided by Postman and the same issue seems to occur. Here is my code:
class _DoctorSelectionScreen extends State<DoctorSelectionScreen> {
DoctorService doctorService = DoctorService();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
drawer: const NavigationDrawerWidget(),
appBar:
AppBar(backgroundColor: Colors.green, title: const Text("Doctors")),
body: FutureBuilder(
future: doctorService.getDoctors(),
builder:
(BuildContext context, AsyncSnapshot<List<Doctor>> snapshot) {
if (snapshot.hasData) {
List<Doctor>? doctors = snapshot.data;
// return Column(children: <Widget>[
// for (var doctor in doctors!) buildDoctor(doctor)
// ]);
return const Center(child: Text("Found doctors"));
} else {
return const Center(child: Text("No doctors found."));
}
}),
),
);
}
class DoctorService {
final String appointmentURL = 'localhost:8082/appointments';
Future<List<Doctor>> getDoctors() async {
print("TEST");
var res = await get(Uri.parse(appointmentURL));
print("TEST2");
if (res.statusCode == 200) {
final obj = jsonDecode(res.body);
List<Doctor> doctors = <Doctor>[];
return doctors;
} else {
throw "Unable to retrieve doctors.";
}
}
}
The code seems to hang at:
var res = await get(Uri.parse(appointmentURL));
Any guidance would be greatly appreciated.
CodePudding user response:
If you are trying this on an emulator then the localhost for the emulator is not 127.0.0.0
it is 10.0.2.2
, so you need to write https://10.0.2.2:YOUR_PORT_NO
. Also https://127.0.0.0:YOUR_PORT_NO
won't work on a real device as well.
You can check this for more detailed information.