http - createHttpClient 未定义 - 颤振
问题描述
我想通过 HTTP 监听器解析 JSON。我是 Flutter 的新手,所以我在网上搜索了它,并将http: ^0.12.2
包添加到 YAML 文件中的依赖项中,但仍然收到错误消息:"The method 'createHttpClient' isn't defined for the type '_MyHomePageState'."
这是我的两个文件main.dart
和pubspec.yaml
. 在main.dart
import 'package:flutter/material.dart';
看起来像未使用和灰色。你能帮我解决我所缺少的吗?
主要飞镖:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _ipAddress = 'Unknown';
_getIPAddress() async {
String url = 'https://httpbin.org/ip';
var httpClient = createHttpClient();
var response = await httpClient.read(url);
Map data = json.decode(response);
String ip = data['origin'];
// If the widget was removed from the tree while the message was in flight,
// we want to discard the reply rather than calling setState to update our
// non-existent appearance.
if (!mounted) return;
setState(() {
_ipAddress = ip;
});
}
@override
Widget build(BuildContext context) {
var spacer = new SizedBox(height: 32.0);
return new Scaffold(
body: new Center(
child: new Column(
children: <Widget>[
spacer,
new Text('Your current IP address is:'),
new Text('$_ipAddress.'),
spacer,
new RaisedButton(
onPressed: _getIPAddress,
child: new Text('Get IP address'),
),
],
),
),
);
}
}
pubspec.yaml:
name: httpdeneme2
description: A new Flutter application.
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
http: '^0.12.2'
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
解决方案
你需要像这样导入http包
import 'package:http/http.dart' as http;
然后用下面的代码替换你的方法
_getIPAddress() async {
String url = 'https://httpbin.org/ip';
var response = await http.get(url);
Map data = json.decode(response.body);
String ip = data['origin'];
if (!mounted) return;
setState(() {
_ipAddress = ip;
});
}
推荐阅读
- swift - 如何将 podspec 设置为依赖于其他本地 pod
- spring-cloud-sleuth - 自定义行李密钥未显示在 Spring Cloud sleuth 的日志中
- getusermedia - Google Cloud Speech-to-Text:“INVALID_ARGUMENT:无效识别‘配置’:错误编码..”编解码器音频编码错误
- c# - c# 使用动态工具
- javascript - 等到第一个可观察完成后再执行第二个订阅逻辑的最值得的方法?
- mysql - 如何在 SQL 中过滤表中的唯一列?
- google-cloud-platform - 如何找出对话流的响应来自哪里?
- javascript - 如何在单击时使用传入的道具渲染 React 组件
- javascript - 在 JS 中使用 `sort()` 方法对多个名称进行排序
- reactjs - React - TypeError:baseReducer 不是函数