0

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?

1 Answer 1

1

If your server is running on localhost and you are testing your app on an Android emulator & then replace the below-mentioned things.

http://localhost:3000

with

http://10.0.2.2:3000
Sign up to request clarification or add additional context in comments.

3 Comments

do you mean in the website url or in flutter?
If you're using a local server, then instead of using localhost:<port>, use 10.0.2.2:<port>. It will only work on an Android emulator.
i am using the ip. but didn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.