如何将Flutter与我的本地主机上的API关联起来?

huangapple go评论77阅读模式
英文:

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 the mobile app because snapshot.hasData returns a false value. When I send a mock API to the 'url' variable in my code, snapshot.hasData finally returns true, and data from the 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({Key? 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({Key? 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,
              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!")
              ],
            ));
          }
        },
      ),
    );
  }
}

如何将Flutter与我的本地主机上的API关联起来?

英文:

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 &#39;dart:convert&#39;;
import &#39;package:beetech_crud/models/personel.dart&#39;;
import &#39;package:http/http.dart&#39; as http;
class PersonelAPI {
Future&lt;List&lt;Personel&gt;&gt; findAll() async {
dynamic url = Uri.parse(&#39;http://localhost:50288/api/personels&#39;);
var response = await http.get(url);
if (response.statusCode == 200) {
List&lt;dynamic&gt; body = json.decode(utf8.decode(response.bodyBytes));
return body.map((personel) =&gt; Personel.fromJson(personel)).toList();
} else {
throw Exception(&quot;Personel listesi oluşturulurken bir hata oldu!&quot;);
}
}
}

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&lt;String, dynamic&gt; json) {
return Personel(
id: json[&quot;id&quot;] as int,
name: json[&quot;name&quot;] as String,
surname: json[&quot;surname&quot;] as String,
salary: json[&quot;salary&quot;] as double,
);
}
Map&lt;String, dynamic&gt; toJson() {
return {
&quot;id&quot;: id,
&quot;name&quot;: name,
&quot;surname&quot;: surname,
&quot;salary&quot;: salary,
};
}
}

Homepage code:

// ignore_for_file: prefer_const_constructors
import &#39;package:beetech_crud/api/personel_api.dart&#39;;
import &#39;package:flutter/material.dart&#39;;
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State&lt;HomePage&gt; createState() =&gt; _HomePageState();
}
class _HomePageState extends State&lt;HomePage&gt; {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(&quot;Personel Listesi&quot;),
centerTitle: true,
),
body: ListPage(),
);
}
}
class ListPage extends StatefulWidget {
const ListPage({super.key});
@override
State&lt;ListPage&gt; createState() =&gt; _ListPageState();
}
class _ListPageState extends State&lt;ListPage&gt; {
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.all(10),
child: FutureBuilder(
future: PersonelAPI().findAll(),
builder: (context, AsyncSnapshot&lt;List&gt; 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(
&quot;Kişi : ${snapshot.data![index].name} ${snapshot.data![index].surname}&quot;),
subtitle: Text(
&quot;Maaş : ${snapshot.data![index].salary} TL&quot;.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(&quot;Verilere ulaşırken bir sorun oluştu!&quot;)
],
));
}
},
),
);
}
}

[[new]]photo

答案1

得分: 0

你应该将基本网址更改为:http://10.0.2.2:8080,如果你确实想要访问本地环境。

我假设你正在使用端口:8080

英文:

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.

huangapple
  • 本文由 发表于 2023年3月4日 05:17:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定