Search code examples
databaseflutterdartlocalhostasp.net-core-webapi

How can I associate flutter with the API on my localhost?


I wanted to communicate with flutter the asp.net core web API I created with the C# Entity Framework library to be able to do CRUD operations. But I can't list data in mobile app because snapshot.hasData returns false value. When I send mock API to url variable in my code, snapshot.hasData finally returns true and data from mock API appears in my mobile app. How can I list data on my localhost?

I've been trying to fix this problem for a week. I need to finish this project. I'm waiting for your help.

Which code is wrong?

API Services:

import 'dart:convert';
import 'package:beetech_crud/models/personel.dart';
import 'package:http/http.dart' as http;

class PersonelAPI {
  Future<List<Personel>> findAll() async {
    dynamic url = Uri.parse('http://localhost:50288/api/personels');
    var response = await http.get(url);
    if (response.statusCode == 200) {
      List<dynamic> body = json.decode(utf8.decode(response.bodyBytes));
      return body.map((personel) => Personel.fromJson(personel)).toList();
    } else {
      throw Exception("Personel listesi oluşturulurken bir hata oldu!");
    }
  }
}

Models:

class Personel {
  int id;
  String name;
  String surname;
  double salary;

  Personel({
    required this.id,
    required this.name,
    required this.surname,
    required this.salary,
  });

  factory Personel.fromJson(Map<String, dynamic> json) {
    return Personel(
      id: json["id"] as int,
      name: json["name"] as String,
      surname: json["surname"] as String,
      salary: json["salary"] as double,
    );
  }

  Map<String, dynamic> toJson() {
    return {
      "id": id,
      "name": name,
      "surname": surname,
      "salary": salary,
    };
  }
}

Homepage code:

// ignore_for_file: prefer_const_constructors

import 'package:beetech_crud/api/personel_api.dart';
import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Personel Listesi"),
        centerTitle: true,
      ),
      body: ListPage(),
    );
  }
}

class ListPage extends StatefulWidget {
  const ListPage({super.key});

  @override
  State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(10),
      child: FutureBuilder(
        future: PersonelAPI().findAll(),
        builder: (context, AsyncSnapshot<List> snapshot) {
          if (snapshot.hasData) {
            return ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                return Card(
                  child: ListTile(
                    leading: CircleAvatar(
                      backgroundColor: Colors.grey,
                      child: Text(snapshot.data![index].id.toString()),
                    ),
                    title: Text(
                        "Kişi : ${snapshot.data![index].name} ${snapshot.data![index].surname}"),
                    subtitle: Text(
                        "Maaş : ${snapshot.data![index].salary} TL".toString()),
                  ),
                );
              },
            );
          } else {
            return Center(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              // ignore: prefer_const_literals_to_create_immutables
              children: [
                Padding(
                  padding: const EdgeInsets.only(right: 60, left: 60),
                  child: LinearProgressIndicator(
                    backgroundColor: Color.fromARGB(0, 0, 0, 0),
                    color: Colors.white,
                  ),
                ),
                Text("Verilere ulaşırken bir sorun oluştu!")
              ],
            ));
          }
        },
      ),
    );
  }
}

[[new]]

photo


Solution

  • you should change your base url to: http://10.0.2.2:8080 if you do want to hit your local enviroment.

    i assumed that you are using :8080 for your port.