I am trying to connect the local host database to flutter. I used asp.net core Web API to get the data to the local host web. This is how the information is displayed.
information in local host along with url
I tried referring how to call data from a live server https://docs.flutter.dev/cookbook/networking/fetch-data#1-add-the-http-package and this worked. When I tried changing to local however, it eventually stops working with a connection time out. For reference this is how the code looks like:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Employee> fetchEmployee() async {
final response = await http
.get(Uri.parse('https://192.168.156.1:7040/api/Employees/GetAllEmployees/2'));
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Employee.fromJson(jsonDecode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load album');
}
}
class Employee {
final int Id;
final String l_name;
final String f_name;
const Employee({
required this.Id,
required this.l_name,
required this.f_name,
});
factory Employee.fromJson(Map<String, dynamic> json) {
return Employee(
Id: json['Id'],
l_name: json['l_name'],
f_name: json['f_name'],
);
}
}
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Future<Employee> futureAlbum;
@override
void initState() {
super.initState();
futureAlbum = fetchEmployee();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fetch Data Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: const Text('Fetch Data Example'),
),
body: Center(
child: FutureBuilder<Employee>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.f_name);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
),
),
),
);
}
}
I read somewhere if I try passing uri as http://localhost:7040/ it wont work and also it refuses connection so I am using the laptop's IP address. I also made sure the emulator's IP address matches the ip address I inserted. Does anyone know why this is happening and any suggestions to fix it please?
CodePudding user response:
If your server is running on localhost and you are testing your app on Android emulator then replace...
http://localhost:3000
with
http://10.0.2.2:3000