gpt4 book ai didi

rest - 为什么flutter拒绝在本地主机上连接:8000 or 127. 0.01 :8000?

转载 作者:行者123 更新时间:2023-12-03 13:30:36 26 4
gpt4 key购买 nike

我正在遵循Flutter Networking/HTTP教程对运行在localhost:8000上的服务器进行GET请求。通过我的浏览器访问我的本地主机工作正常。当我指向诸如https://example.com之类的任何真实URL时,此方法也能正常工作,但是当我指向https://127.0.0.1:8000时,会出现类似“连接被拒绝”之类的错误消息

每次我重新加载应用程序时,上述错误中的端口都会更改。我查看了http程序包代码,似乎没有一种方法可以指定URL的端口。我如何指向我的本地主机,这是我第一次 flutter ?
PS:我在我的电话设备上运行,我的PC和电话连接到相同的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']),
);
},
);
},
),
),
);
}
}

enter image description here

enter image description here

enter image description here

最佳答案

您必须将手机和计算机保持相同的网络网络连接。

然后假设您的ip和url是此192.168.1.102:8000,则传递您的url

static const url= "192.168.1.102:8000/association/api/membres";

关于rest - 为什么flutter拒绝在本地主机上连接:8000 or 127. 0.01 :8000?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55908089/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com