文/毛毛

我准备开一个Flutter零基础入门连载,后期会不定期更新《Flutter入门》系列文档,敬请关注!

背景


今天继续学习Flutter,学习至通过Http获取网络数据一节,跟着Flutter官方文档写demo,遇到以下问题。

错误:找不到“fluwx/FluwxPlugin.h”


我把官方文档的完整例子放到项目里运行,运行失败
遇到“error: 'fluwx/FluwxPlugin.h' file not found”错误。

fluwx/FluwxPlugin.h是Flutter基础框架的必要文件,少了它项目编译不通过↓↓↓

我下意识地去找fluwx是什么,网上没有资料。

后来我在“pubspec.yaml”文件里发现fluwx正好在我添加的http依赖库上边,我怀疑是我添加的依赖库影响了,把http: 0.12.0删掉,再次运行。——结果还是报同样的错误。

删掉我新加的依赖库

最后没辙了,我把“pubspec.yaml”文件上边的所有按钮都点了一遍。最重要的是Flutter doctor,它是去检查Flutter环境是否满足条件。运行之后我发现:是我的iOS配置项没弄好

  • 根据Flutter doctor的指示,多次安装必要插件,最后运行成功了。

运行成功之后页面内容如下↓↓↓:

页面上展示的内容就是获取到网络上的内容(获取成功)。
完整示例如下(可复制到你的项目):

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/posts/1');
  final responseJson = json.decode(response.body);

  return new Post.fromJson(responseJson);
}

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return new Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Fetch Data Example',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new Scaffold(
        appBar: new AppBar(
          title: new Text('Fetch Data Example'),
        ),
        body: new Center(
          child: new FutureBuilder<Post>(
            future: fetchPost(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return new Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return new Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return new CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

从代码里看:

          if (snapshot.hasData) {
                return new Text(snapshot.data.title);
          } else if (snapshot.hasError) {
                return new Text("${snapshot.error}");
          }

这段代码表示:如果返回有数据,就显示数据里面的title字段,而https://jsonplaceholder.typicode.com/posts/1网站的内容是:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

可见title字段内容就是屏幕上显示的内容,即——网络获取数据成功。

(欢迎留言交流)
————————————
我是毛毛,感恩遇见!
关注我,了解更多的我。
~2018年11月26日~