1

I have an app that was originally written in android studio but I am trying to change it to be in flutter. Originally, I would enter data in the app and save it to my database, nothing complicated. I am however attempting to redo this in flutter.

The Issue

Utilizing the following code static const String _baseUrl = 'http://localhost:54553/api/TicketAPI/'; in my "postToApi" method I get a Connection Refused right off the bat. However, searching the site I came across a solution to use 10.0.2.2 instead of any IP or Localhost. That seemed to work but then I get an invalid host error. Please see my code

import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;

class TicketInfoApi {
  static const String _baseUrl =
      'http://localhost:54553/api/TicketAPI/';
  static Future<bool> postDataToApi({
    required String officerNumber,
    required int officerRank, //  
    String ticketNumber = "123rest",
    required String officerFirstName,
    required String officerLastName,
  }) async {
    final String apiUrl =
        '${_baseUrl}InsertTicket'; //  

    final body = json.encode({
      'officerNumber': officerNumber,
      'ticketNumber': ticketNumber,
      'officerFirstName': officerFirstName,
      'officerLastName': officerLastName,
    });

    try {
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          HttpHeaders.contentTypeHeader: 'application/json',
        },
        body: body,
      );

      if (response.statusCode == 200) {
        final responseData = json.decode(response.body);
        return responseData != null;
      } else {
        return false;
      }
    } catch (error) {
      return false;
    }
  }
}

Edit

What I think is happening is, if the address is "localhost", the emulator is looking at it's self instead of my laptop.

  • `10.0.2.2` *is* a local IP address that might have been assigned to your machine earlier. I'm guessing your server is only listening on IPv4, but localhost resolves to IPv6 as well and it's prefered by Dart. – lnl Apr 17 '23 at 01:53
  • @lnl I'm doing more reading and it seems localhost is the "phone" not my machine. Trying to get a way for it to look at my machine – unknown techh Apr 17 '23 at 02:00
  • I used the answer from this link https://stackoverflow.com/questions/52618330/android-emulator-not-connecting-to-localhost-api/52626534#52626534 – unknown techh May 10 '23 at 17:52

0 Answers0