首页 > 解决方案 > createHttpClient 未定义 - 颤振

问题描述

我想通过 HTTP 监听器解析 JSON。我是 Flutter 的新手,所以我在网上搜索了它,并将http: ^0.12.2包添加到 YAML 文件中的依赖项中,但仍然收到错误消息:"The method 'createHttpClient' isn't defined for the type '_MyHomePageState'."

这是我的两个文件main.dartpubspec.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

标签: httpflutter

解决方案


你需要像这样导入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;
   });
}  

推荐阅读