我创建了一个项目来寻找我所在城镇的体育场馆。它从网站的 Swagger API 获取所有数据,例如地址、价格、图像和名称。
Swagger主持人:http://admin.sports.com.kg/swagger/
我创建了 ApiRemote 来从 swagger 主机获取数据。第一周工作正常,但后来返回异常。也许是因为http。
终端返回此错误:
E / flutter(26867):[错误:flutter/lib/ui/ui_dart_state.cc(198)]未处理的异常:主机查找失败:'admin.sports.com.kg'
它说这一行有一个例外:
var 响应 = 等待 client.get(uri);
import 'dart:async';
import 'dart:convert';
import 'package:untitled/models/post.dart';
import 'package:http/http.dart' as http;
class RemoteService {
Future<List<Result>?> getPosts() async {
List<Result> list;
var client = http.Client();
var uri = Uri.parse('http://admin.sports.com.kg/api/sports_areas');
var responses = await client.get(uri);
if (responses.statusCode == 200) {
final parsed = json.decode(responses.body) as Map<String, dynamic>;
list = parsed['results'].map<Result>((e) =>Result.fromJson(e)).toList();
print(parsed['results']);
// final p = Post.fromJson(parsed);
// list.add(p);
return list;
}
}
}
包含 Swagger 的所有数据的发布文件
import 'dart:convert';
Post postFromJson(String str) => Post.fromJson(json.decode(str));
String postToJson(Post data) => json.encode(data.toJson());
class Post {
Post({
required this.next,
this.previous,
required this.count,
required this.pageSize,
required this.numPages,
required this.results,
});
int next;
dynamic previous;
int count;
int pageSize;
int numPages;
List<Result> results;
factory Post.fromJson(Map<String, dynamic> json) => Post(
next: json["next"],
previous: json["previous"],
count: json["count"],
pageSize: json["page_size"],
numPages: json["num_pages"],
results:
List<Result>.from(json["results"].map((x) => Result.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"next": next,
"previous": previous,
"count": count,
"page_size": pageSize,
"num_pages": numPages,
"results": List<dynamic>.from(results.map((x) => x.toJson())),
};
}
class Result {
Result({
required this.id,
required this.title,
required this.price,
required this.address,
required this.image,
});
int id;
String title;
int price;
String address;
String image;
factory Result.fromJson(Map<String, dynamic> json) => Result(
id: json["id"],
title: json["title"],
price: json["price"],
address: json["address"],
image: json["image"],
);
Map<String, dynamic> toJson() => {
"id": id,
"title": title,
"price": price,
"address": address,
"image": image,
};
}
主页类
class _HomePageState extends State<HomePage> {
int _selind = 0;
List<Result>? _stadiums;
var isLoaded = false;
@override
void initState() {
super.initState();
getData();
}
void getData() async {
_stadiums = (await RemoteService().getPosts()) as List<Result>?;
if (_stadiums != null) {
setState(() {
isLoaded = true;
});
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Colors.indigo[50],
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 30),
child: Visibility(
visible: isLoaded,
child: ListView.builder(
itemCount: _stadiums?.length,
itemBuilder: (context, index) {
return Column(
// child: _widgetopt.elementAt(_selind),
children: [
Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15.0),
),
child: Column(
children: [
Image.network(_stadiums![index].image),
Text('Sportclubs "${_stadiums![index]
.title}"', textDirection: TextDirection.ltr,
style: TextStyle(fontSize: 20,
fontWeight: FontWeight.bold),),
Row(
children: [
Icon(Icons.location_on_outlined,
color: Colors.redAccent, size: 40,),
Text(_stadiums![index].address),
],
)
]
),
),
SizedBox(
height: 10,
),
],
);
}),
replacement: Center(child: CircularProgressIndicator()),
),
),),);
}
}
我正在解析一个不完整的 URL。确保你的正确。以下是我犯的错误。
http://nest-services-app-production.up.railway.app //base URL
终点是:
static const String getAllProducts = "products/all";
完整的 URL 为:
http://nest-services-app-production.up.railway.appproducts/all";
我在基本 URL 末尾缺少反斜杠,因此导致它返回
Unhandled Exception: Failed host lookup:
错误。
检查您是否在 Android.Manifest.XML 上授予互联网权限