📜  Flutter – 向互联网发送数据

📅  最后修改于: 2021-09-23 06:31:20             🧑  作者: Mango

与 Internet 交互对于大多数应用程序的函数至关重要。在Flutter, http包用于将数据发送到互联网。在本文中,我们将详细探讨同一主题。要通过您的应用程序将数据发送到互联网,请按照以下步骤操作:

  1. 导入http包
  2. 通过http包向服务器发送数据
  3. 将响应更改为自定义dart对象
  4. 显示响应

导入 http 包:

要安装 http 包,请在命令提示符中使用以下命令:

pub get

或者,如果您使用的是flutter cmd,请使用以下命令:

flutter pub get

依赖

安装完成后,将依赖添加到 pubsec.yml 文件中,如下所示:

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

向服务器发送数据:

在本文中,我们将创建一个相册数据并通过http.post() 方法将其发送到 JSONPlaceholder。

Dart
Future createAlbum(String title) {
  return http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode({
      'title': title,
    }),
  );
}


Dart
class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map


Dart
Future createAlbum(String title) async {
  final http.Response response = await http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode({
      'title': title,
    }),
  );
    
  // Dispatch action depending upon 
  // the server response
  if (response.statusCode == 201) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Album loading failed!');
  }
}


Dart
Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        controller: _controller,
        decoration: InputDecoration(hintText: 'Enter Title'),
      ),
    ),
    RaisedButton(
      child: Text('Create Data'),
      onPressed: () {
        setState(() {
          _futureAlbum = createAlbum(_controller.text);
        });
      },
    ),
  ],
)


Dart
FutureBuilder(
  future: _futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
  
    return CircularProgressIndicator();
  },
)


Dart
import 'dart:async';
import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
Future createAlbum(String title) async {
  final http.Response response = await http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode({
      'title': title,
    }),
  );
  
  if (response.statusCode == 201) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to create album.');
  }
}
  
class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}
  
class _MyAppState extends State {
  final TextEditingController _controller = TextEditingController();
  Future _futureAlbum;
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Creating Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),
          child: (_futureAlbum == null)
              ? Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: _controller,
                decoration: InputDecoration(hintText: 'Enter Title'),
              ),
              RaisedButton(
                child: Text('Create Data'),
                onPressed: () {
                  setState(() {
                    _futureAlbum = createAlbum(_controller.text);
                  });
                },
              ),
            ],
          )
              : FutureBuilder(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
  
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}


转换响应:

虽然发出网络请求没什么大不了的,但处理原始响应数据可能很不方便。为了让您的生活更轻松,请将原始数据(即 http.response)转换为dart对象。在这里,我们将创建一个包含 JSON 数据的 Album 类,如下所示:

Dart

class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map

将 http.Respone 转换为相册:

现在,按照以下步骤更新fetchAlbum()函数以返回 Future

  1. 使用dart: convert 包将响应正文转换为 JSON Map。
  2. 如果服务器返回状态码为 200 的 OK 响应,则使用fromJSON()工厂方法将 JSON Map 转换为 Album。
  3. 如果服务器没有返回状态码为 200 的 OK 响应,则抛出异常。

Dart

Future createAlbum(String title) async {
  final http.Response response = await http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode({
      'title': title,
    }),
  );
    
  // Dispatch action depending upon 
  // the server response
  if (response.statusCode == 201) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Album loading failed!');
  }
}

向用户询问专辑名称:

现在为用户创建一个TextField以输入标题和一个RaisedButton以将数据发送到服务器。此外,定义一个TextEditingController以从TextField读取用户输入,如下所示:

Dart

Column(
  mainAxisAlignment: MainAxisAlignment.center,
  children: [
    Padding(
      padding: const EdgeInsets.all(8.0),
      child: TextField(
        controller: _controller,
        decoration: InputDecoration(hintText: 'Enter Title'),
      ),
    ),
    RaisedButton(
      child: Text('Create Data'),
      onPressed: () {
        setState(() {
          _futureAlbum = createAlbum(_controller.text);
        });
      },
    ),
  ],
)

显示响应:

使用FlutterBuilder小部件在屏幕上显示数据,如下所示:

Dart

FutureBuilder(
  future: _futureAlbum,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data.title);
    } else if (snapshot.hasError) {
      return Text("${snapshot.error}");
    }
  
    return CircularProgressIndicator();
  },
)

完整的源代码:

Dart

import 'dart:async';
import 'dart:convert';
  
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
  
Future createAlbum(String title) async {
  final http.Response response = await http.post(
    'https://jsonplaceholder.typicode.com/albums',
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
    },
    body: jsonEncode({
      'title': title,
    }),
  );
  
  if (response.statusCode == 201) {
    return Album.fromJson(json.decode(response.body));
  } else {
    throw Exception('Failed to create album.');
  }
}
  
class Album {
  final int id;
  final String title;
  
  Album({this.id, this.title});
  
  factory Album.fromJson(Map json) {
    return Album(
      id: json['id'],
      title: json['title'],
    );
  }
}
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);
  
  @override
  _MyAppState createState() {
    return _MyAppState();
  }
}
  
class _MyAppState extends State {
  final TextEditingController _controller = TextEditingController();
  Future _futureAlbum;
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Creating Data',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('GeeksForGeeks'),
          backgroundColor: Colors.green,
        ),
        body: Container(
          alignment: Alignment.center,
          padding: const EdgeInsets.all(8.0),
          child: (_futureAlbum == null)
              ? Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextField(
                controller: _controller,
                decoration: InputDecoration(hintText: 'Enter Title'),
              ),
              RaisedButton(
                child: Text('Create Data'),
                onPressed: () {
                  setState(() {
                    _futureAlbum = createAlbum(_controller.text);
                  });
                },
              ),
            ],
          )
              : FutureBuilder(
            future: _futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }
  
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!