【发布时间】:2019-09-18 08:34:22
【问题描述】:
我正在按照 Flutter Networking/HTTP 教程向运行在我的 localhost:8000 上的服务器发出 GET 请求。通过我的浏览器访问我的本地主机工作正常。当我指向任何真实的 URL(例如 https://example.com)时,这也可以正常工作,但是当我指向 https://127.0.0.1:8000 时,我会收到类似“连接被拒绝”的错误
每次我重新加载应用程序时,上述错误中的端口都会更改。我查看了 http 包代码,似乎没有办法为 URL 指定端口。我如何指向我的本地主机,这是我第一次使用颤振? PS:我在我的手机设备上运行,我的电脑和手机连接同一个wifi,我的网络是私有的。
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'dart:convert';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
static const url = 'http://127.0.0.1:8000/api/membres/';
// static const url = 'http://10.0.2.2:8000/api/membres/';
//static const url = 'http://localhost:8000/api/membres/';
//static const url= "192.168.1...:8000/association/api/membres";
//static const url = 'https://jsonplaceholder.typicode.com/users';
Future<List<Map<String, dynamic>>> _future;
@override
void initState() {
super.initState();
_future = fetch();
}
Future<List<Map<String, dynamic>>> fetch() {
return http
.get(url)
.then((response) {
return response.statusCode == 200
? response.body
: throw 'Error when getting data';
})
.then((body) => json.decode(body))
.then((list) => (list as List).cast<Map<String, dynamic>>());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: RefreshIndicator(
onRefresh: () async {
_future = fetch();
setState(() {});
return _future;
},
child: FutureBuilder<List<Map<String, dynamic>>>(
future: _future,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Center(
child: Container(
constraints: BoxConstraints.expand(),
child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Text(snapshot.error.toString()),),),);}
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);}
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
final item = snapshot.data[index];
return ListTile(
title: Text(item['name']),
subtitle: Text(item['email']),
);
},
);
},
),
),
);
}
}
【问题讨论】:
-
使用命令
ipconfig(对于 Windows)或ifconfig(对于 mac/linux)检查笔记本电脑的本地 IP。使用该 IP 而不是 localhost 或 127.0.0.1。这些地址是访问它们的设备的环回地址。 -
另外,错误中的端口不是您要连接的服务器端口,而是客户端端口。这个值每次都会改变,因为系统会从可用端口中随机选择一个端口来发出请求。
-
请问该怎么做?我已经尝试过使用我的 ip 地址,但它也返回错误
static const url= "192.168.1.102:8000/association/api/membres";==> 没有到主机的路由,errno = 113,地址 = 192.168.1.102,端口 = 46862 -
你使用的是mac、windows还是linux?
-
我正在使用 Windows,并且我已将我的网络更改为私有