Flutter HTTP POST请求教程

Flutter http post:Flutter http post请求方法用于根据用户提供的输入从api获取值

同样,当您试图在数据库中搜索员工详细信息时,您需要提供员工id,以便您可以从所有员工数据中获取该特定员工的详细信息。

post请求的最好例子是字典应用程序、youtube、google、facebook等搜索引擎,在这些搜索引擎中,你可以搜索数据,并基于这些搜索结果返回结果。

在本教程的这一部分中,我们将用一个简单的例子来处理flutter HTTP POST请求方法,以便您更好地理解在以前的教程中我们已经看到通过改型库发出的请求可以检查它们。

创建一个模型类,在这个类中我们可以指定用于解析数据的变量,比如api中的id、title和body。

final int id;
final String title;
final String body;

创建构造函数以使用这些变量

Posts({this.id, this.title, this.body});

根据变量的键值分析变量。

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


class Posts {
  final int id;
  final String title;
  final String body;

  Posts({this.id, this.title, this.body});

  factory Posts.fromJson(Map<String, dynamic> json) {
    return Posts(
      id: json['id'],
      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<Posts> 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


```MaterialApp(
  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
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Photos',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data With Http Call'),
        ),
        body: 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<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)),
      ],
    ),
  );
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值