Flutter HTTP POST请求教程_flutter post请求(1)

  title: json['title'],
  body: json['body'],
);

}
}


我们需要声明用于获取数据的api,我们将发布相关数据将以响应形式返回的num


我们需要声明一个异步方法,以便等待响应返回



If response is success we will post back the data to be parsed based on the key values


if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Posts.fromJson(json.decode(response.body));}



If the response is failure then we will throw a sample message stating the exception.



else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception(‘Failed to load album’);
}

import ‘dart:convert’;

import ‘package:http/http.dart’ as http;
import ‘Posts.dart’;

Future fetchPosts(String num) async {
final response =
await http.get(‘https://jsonplaceholder.typicode.com/posts/${num}’);

if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return Posts.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception(‘Failed to load album’);
}
}


使用void main()初始化应用程序


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



Create a default class MyApp and a state


Declare variables text editing controller and boolean  
 TextEditingController postNum = TextEditingController();bool pressed = false;



Inside the MaterialApp declare a scaffold in home widget

  title: 'Fetch Photos',
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: 
);

在脚手架里面声明一个appBar

appBar: AppBar(
  title: Text('Fetch Data With Http Call'),
),

在body小部件中,声明一个列,我们在其中提供一个textfield来获取用户输入,并抛出按钮将输入发布到api并监听输出。

Column(
  children: <Widget>[
    TextField(
      controller: postNum,
      decoration: InputDecoration(
        hintText: "Enter Post Id",
        border: InputBorder.none,
      ),

    ),
    RaisedButton(child: Text("Fetch Post"),
        onPressed: () => {setState(() {
       pressed = true;
      //fetchData(postNum);
    })}),

    pressed ? fetchData(postNum): SizedBox(),

  ],
),

声明FutureBuilder以接受用户输入并将其发布到api并侦听输出。

FutureBuilder<Posts> fetchData(postNum) {
  return FutureBuilder<Posts>(
    future: fetchPosts(postNum.text.toString()),
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        return getData(snapshot);
      } else if (snapshot.hasError) {
        return Text("${snapshot.error}");
      }

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

获取数据后,使用此方法将数据解析到屏幕上。

Widget getData(snapshot) {
  return Padding(
    padding: const EdgeInsets.all(35.0),
    child: Column(
      children: <Widget>[

        Padding(padding: EdgeInsets.all(20)),
        Text("Title : " + snapshot.data.title, style: TextStyle(fontSize: 20)),
        Padding(padding: EdgeInsets.all(20)),
        Text("Body : " + snapshot.data.body, style: TextStyle(fontSize: 20)),
      ],
    ),
  );
}

完整代码:

import 'package:flutter/material.dart';

import 'Posts.dart';
import 'Network.dart';

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

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  TextEditingController postNum = TextEditingController();

  bool pressed = false;

  @override


## 文末

那么对于想坚持程序员这行的真的就一点希望都没有吗?
其实不然,在互联网的大浪淘沙之下,留下的永远是最优秀的,我们考虑的不是哪个行业差哪个行业难,就逃避掉这些,无论哪个行业,都会有他的问题,但是无论哪个行业都会有站在最顶端的那群人。我们要做的就是努力提升自己,让自己站在最顶端,学历不够那就去读,知识不够那就去学。人之所以为人,不就是有解决问题的能力吗?挡住自己的由于只有自己。
**Android希望=技能+面试**

* **技能**
  ![](https://img-blog.csdnimg.cn/img_convert/2b99e2b496af303527a0960f0616067e.webp?x-oss-process=image/format,png)
* **面试技巧+面试题**
  ![](https://img-blog.csdnimg.cn/img_convert/f2380548ecfe5e8869f17b37ec4cdc94.webp?x-oss-process=image/format,png)



**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618156601)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化学习资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618156601)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值