我正在开发需要发出http请求的Flutter应用程序。我像往常一样安装了http包,但是当需要在真实设备中测试该应用程序时,http请求挂起了,我从没得到响应或状态码。我决定然后启动一个新应用程序只是为了弄乱http包,但仍然遇到相同的问题。
This is what I get while debugging in Android Emulator (I get a response almost immediately)和this is what I get on a real device (hanging forever).
我已经尝试过的可能解决方案:构建带符号的和未签名的apk,在构建apk之前运行干净,使用--no-shrink
标志构建apk,更改pubspec.yaml中的http软件包的版本,而这些似乎都没有解决问题。
我正在使用Flutter SDK(v1.17.5)的最新稳定版本,用于编码的Android Studio和作为操作系统的Ubuntu 20.04。
这是我的飞镖代码:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
class AuthScreen extends StatefulWidget {
@override
_AuthScreenState createState() => _AuthScreenState();
}
class _AuthScreenState extends State<AuthScreen> {
final TextEditingController _urlController = TextEditingController();
String _status = 'Waiting for request';
void _submit() async {
setState(() {
_status = 'Waiting for response...';
});
var response = await http.get(_urlController.text);
if (response.statusCode == 200) {
setState(() {
_status = response.body.substring(0, 40) + ' [...]';
});
} else {
_status = 'Something went wrong';
}
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: _urlController,
),
FlatButton(
child: Text('Send request'),
onPressed: _submit,
),
Text(_status)
],
),
),
);
}
}
如果有用,这是我的pubspec.yaml:
name: testingHttpPackage
description: A new Flutter application.
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
http: ^0.12.1
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
答案 0 :(得分:1)
您是否在AndroidManifest.xml
文件中提到了互联网许可?
在android / app / src / main /中,有AndroidManifest.xml文件,将以下行放在manifest标签之后,即在第一个标签之后。
<uses-permission android:name="android.permission.INTERNET" />