First, add the dependencies
One cannot make bricks without straw
The first thing we need to do is find the URL to write the test. A good place to start is that Github offers a lot of apis
But before we do that, we need to do some things first. For example, register a Github account and get a token. The Github account that I have prepared for my Flutter is not encrypted.
1.1: How to obtain the token
Small avatar -->Settings-->Developer Settings--> Personal Access Tokens -->Generate new tokens
1.2: How to add a file to your Github project with a Post request
api:https://api.github.com/repos/ username/project name/contents/file path? Access_token = token value
Request header: Content-type =application/json; request body: content_64; request header: Content-type =application/json
{"message": "commit from toly ",// "content": "aGVsbG8="// data content}Copy the code
Send a PUT request in Flutter to add a file to the Github project
import 'package:http/http.dart' as client; main() { put(); } void put() { var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/contents/"; var path="http-put-file.txt"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+ path+params; //url Map<String ,String> headers = {"Content-Type":"application/json"}; Var reqBody="" {"message": "commit from commit from toly", "content": "aGVsbG8="} ""; / / client request body. The put (API, headers, headers and body: reqBody). Then ((rep) {print (rep. StatusCode); print(rep.body); }); }Copy the code
Note that Dart converts a string to base64 :base64Encode(utf8.encode("hello"));
1.3: Modify a Github file with a PUT request
api:https://api.github.com/repos/ username/project name/contents/file path? Access_token = token value
Request header: content-type =application/json, request body: Each change also returns a new SHA value
{"message": "update by toly ",// submit message" content": "aGVsbG8="// data content": "sha":" the sha value of the file "}Copy the code
Send a PUT request in Flutter to modify a file in the Github project
void update() { var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/contents/"; var path="http-put-file.txt"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+ path+params; //url Map<String ,String> headers = {"Content-Type":"application/json"}; Var reqBody=""" {"message": "update by toly", "content": "5byg6aOO5o2354m554OI", "sha":"b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0" } """; / / client request body. The put (API, headers, headers and body: reqBody). Then ((rep) {print (rep. StatusCode); print(rep.body); }); }Copy the code
1.4: Delete a Github file with a delete request
api:https://api.github.com/repos/ username/project name/contents/file path? Access_token = token value
Content-type =application/json; content-type =application/json
{"message": "delete by toly ",// submit message" sha":" file corresponding sha value "}Copy the code
HTTP library delete request can not add request body? ! Here’s a PostMan demonstration
1.5: Submit an issue with post
api:https://api.github.com/repos/ username/project name/issues? Access_token = token value
Content-type =application/json; content-type =application/json
{"title": "Let's take a Flutter trip ", "body":" How are you feeling? Shouldn't be difficult!" }Copy the code
Send a post request in the Flutter to add an issue to the Github project
void post() { var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/issues"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+operate+params; //url Map<String ,String> headers = {"Content-Type":"application/json"}; // Request header var reqBody=""" {"title": "let's go on our flyover ", "body":" How do you feel? Shouldn't be difficult!" } "" "; / / client request body. Post (API, headers, headers and body: reqBody). Then ((rep) {print (rep. StatusCode); print(rep.body); }); }Copy the code
1.6: Obtain an issue using a GET request
api:https://api.github.com/repos/ username/project name/issues/p1? Access_token = token value
void get(){ //GET /repos/:owner/:repo/issues/:issue_number var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/issues/1"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+operate+params; //url client.get(api).then((rep){ print(rep.statusCode); print(rep.body); }); }Copy the code
Ok, several common Http request methods will be basic.
2. Parsing Json
2.0:
The Map<String,String> object in Dart is very similar to Json, so you can use it as a transformation medium
With the json.decode method in the convert package, you can convert the JSON string into a Map object that can be instantiated in the entity class based on the attributes of the Map object.
import 'dart:convert'; The main () {String jsonStr = "" "{" name ":" Flutter tour ", "author" : "packer jet strong"} "" "; var book = Book.fromMap(json.decode(jsonStr)); print(book.name); / / Flutter trip to print (book. The author); } class Book {String name; String author; Book.frommap (Map<String, dynamic> json) {// Name = json["name"]; author = json["author"]; }}Copy the code
2.1: get json
Making https://api.github.com/users/ username can get the user basic information
Here is to parse my https://api.github.com/users/toly1994328
{ "login": "toly1994328", "id": 26687012, "node_id": "MDQ6VXNlcjI2Njg3MDEy", "avatar_url": "https://avatars3.githubusercontent.com/u/26687012?v=4", "gravatar_id": "", "url": "https://api.github.com/users/toly1994328", "html_url": "https://github.com/toly1994328", "followers_url": "https://api.github.com/users/toly1994328/followers", "following_url": "https://api.github.com/users/toly1994328/following{/other_user}", "gists_url": "https://api.github.com/users/toly1994328/gists{/gist_id}", "starred_url": "https://api.github.com/users/toly1994328/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/toly1994328/subscriptions", "organizations_url": "https://api.github.com/users/toly1994328/orgs", "repos_url": "https://api.github.com/users/toly1994328/repos", "events_url": "https://api.github.com/users/toly1994328/events{/privacy}", "received_events_url": "https://api.github.com/users/toly1994328/received_events", "type": "User", "site_admin": false, "name": ", "company": "company", "blog": "http://www.toly1994.com", "location": "China", "email": null, "hireable": null, "bio": "The king of coder.", "public_repos": 64, "public_gists": 0, "followers": 238, "following": 9, "created_at": "2017-03-26T09:55:25Z", "updated_at": "2019-07-15T08:05:52Z" }Copy the code
2.2: Entity class generation
You can also write out the entity class bit by bit, but it is recommended to use the generated method, because sometimes there are too many fields and it is difficult to compare
Here’s a nice place to use JSON to Dart. If you have time, write your own conversion plugin
class User {
String login;
int id;
String nodeId;
String avatarUrl;
String gravatarId;
String url;
String htmlUrl;
String followersUrl;
String followingUrl;
String gistsUrl;
String starredUrl;
String subscriptionsUrl;
String organizationsUrl;
String reposUrl;
String eventsUrl;
String receivedEventsUrl;
String type;
bool siteAdmin;
String name;
String company;
String blog;
String location;
String email;
String hireable;
String bio;
int publicRepos;
int publicGists;
int followers;
int following;
String createdAt;
String updatedAt;
User.fromJson(Map<String, dynamic> json) {
login = json['login'];
id = json['id'];
nodeId = json['node_id'];
avatarUrl = json['avatar_url'];
gravatarId = json['gravatar_id'];
url = json['url'];
htmlUrl = json['html_url'];
followersUrl = json['followers_url'];
followingUrl = json['following_url'];
gistsUrl = json['gists_url'];
starredUrl = json['starred_url'];
subscriptionsUrl = json['subscriptions_url'];
organizationsUrl = json['organizations_url'];
reposUrl = json['repos_url'];
eventsUrl = json['events_url'];
receivedEventsUrl = json['received_events_url'];
type = json['type'];
siteAdmin = json['site_admin'];
name = json['name'];
company = json['company'];
blog = json['blog'];
location = json['location'];
email = json['email'];
hireable = json['hireable'];
bio = json['bio'];
publicRepos = json['public_repos'];
publicGists = json['public_gists'];
followers = json['followers'];
following = json['following'];
createdAt = json['created_at'];
updatedAt = json['updated_at'];
}
Copy the code
2.3. Use of network request + JSON
It’s now possible to change the interface you’ve written and populate it with Github data
Here is just a simple show, that the network data and layout interface docking, and did not do too fine GithubPanel is written before the interface slightly modified, here the code will not stick.
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as client;
import 'day6/github_panel.dart';
import 'day6/user.dart';
void main() {
var baseUrl = "https://api.github.com/";
var operate = "users/";
var name = "toly1994328";
var api = baseUrl + operate + name; //url
client.get(api).then((rep) {
var user = User.fromJson(json.decode(rep.body));
print(user.avatarUrl);
var scaffold = Scaffold(
appBar: AppBar(title: Text("Flutter之旅"),),
body: GithubPanel(user: user,)
);
var app = MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: scaffold,
);
return runApp(app);
});
}
Copy the code
2.4. Reencapsulation of components
You will find that although the above can be used, but really very uncomfortable to look at, how to make it use a bit more cool, two word encapsulation
Implement a GithubUserPanel by passing in a user name parameter. And reuse previous panels. Since network access is asynchronous, we need a stateful component to be rerendered by setState when the asynchronous load is complete.
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as client; import 'github_panel.dart'; import 'user.dart'; class GithubUserPanel extends StatefulWidget { GithubUserPanel({ Key key, this.userName, }) : super(key: key); final String userName; @override _GithubUserPanelState createState() => _GithubUserPanelState(); } class _GithubUserPanelState extends State<GithubUserPanel> { var baseUrl = "https://api.github.com/"; var operate = "users/"; var panel; @override void initState() { super.initState(); var api = baseUrl + operate + widget.userName; //url client.get(api).then((rep) { var user = User.fromJson(json.decode(rep.body)); panel = GithubPanel( user: user, ); setState(() {}); }); } @override Widget build(BuildContext context) { return Container( child: panel, ); }}Copy the code
Also this write code on the line, is not to feel the GithubPanel reuse cool feeling.
2.5. Use
So it works as usual, just pass the name
Void main() {var scaffold = scaffold (appBar: appBar (title: Text(" journey "),), body: GithubUserPanel(userName: "toly1994328",) ); var app = MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: scaffold, ); return runApp(app); }Copy the code
3. Use of network request packet DIO
Dio is one of the big bosses of JoJo’s wonderful adventures. The name sounds quite awesome. There is no Flutter on dio when you search for dio on the web
The above HTTP package is relatively primitive, better encapsulated in DIO, and more used. Anyway, how to play, can not be separated from THE HTTP request, so to distinguish priorities, do not ignore the essentials.
Dependencies: dio: ^ 2.1.13Copy the code
3.1:get Obtain Github user information
var dio=Dio();
var baseUrl = "https://api.github.com/";
var operate = "users/";
var api=baseUrl+operate+"toly1994328";
dio.get(api).then((rep)=>print(rep.data));
Copy the code
3.2: Put requests to add Github project files
void put() { var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/contents/"; var path="http-put-file-dio.txt"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+ path+params; //url Map<String ,String> headers = {"Content-Type":"application/json"}; Var reqBody="" {"message": "commit from commit from toly", "content": "aGVsbG8="} ""; / / request body Dio (). The put (API, queryParameters: headers, data: reqBody). Then ((rep) {print (rep. StatusCode); print(rep.data); }); }Copy the code
3.3: Delete requests to delete github project files
Delete in dio can add the request body
void delete() { var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/contents/"; var path="http-put-file-dio.txt"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+ path+params; //url Map<String ,String> headers = {"Content-Type":"application/json"}; var reqBody=""" { "message": "delete by toly", "sha": "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0" } """; Dio().delete(api,queryParameters:headers,data: reqBody).then((rep){ print(rep.data); }); }Copy the code
3.4: Post submits an issue
void post() { var baseUrl="https://api.github.com/"; var operate="repos/toly-flutter/flutter_journey/issues"; var params="? access_token=4514388836f6da9f6c6cf7ba0721f2a6d1e89528"; Var API =baseUrl+operate+params; //url Map<String ,String> headers = {"Content-Type":"application/json"}; Var reqBody=""" {"title": "", "body": "who am I, where am I, where am I going?" } "" "; / / request body Dio (). The post (API, queryParameters: headers, data: reqBody). Then ((rep) {print (rep. StatusCode); print(rep.data); }); }Copy the code
3.5: Download through dio
Just take the Nuggets app and download it, which is very convenient in dio, one line.
var url="https://landing.juejin.im/app-download? utm_source=app_download&utm_medium=yingyongbao&utm_campaign=app1808"; Dio (). The download (url, ". / the Denver nuggets. Apk "), then ((rep) {print (rep. StatusCode); print(rep.data); });Copy the code
3.6: Uploading through dio
File uploading has always been a difficult problem, and to implement file uploading, you need a little knowledge of the back end
The core is that the client will request the data to the server, the server will request the content of the operation and upload, that is, the server will store the data or files to the specified location of the server. Usually through form submission, but also directly through the request body binary flow to the server.
FormData FormData = formData. from({// create form "name": "toly", "age": 25, "data": UploadFileInfo(File("./data.json"), "data.json"), "image": UploadFileInfo(File("./photo.png"), "photo.png"), }); var api="/loadFile"; Dio().post(API, data: formData).then((rep){// pass the form to the server via the request body});Copy the code
3.7: Basic configuration parameters
The source code for Dio has an optional parameter, BaseOptions
-- -- -- - > [dio - 2.1.13 / lib/SRC/dio. Dart: 53] -- class dio {/ / / the Create dio instance with default [Options]. / / / It 's mostly Just one Dio instance in your application. Dio ([BaseOptions options]) {-- -- -- - > [Dio 2.1.13 / lib/SRC/options. The dart: 39] - Class BaseOptions extends _RequestConfig {BaseOptions({String method,// Request method int connectTimeout,// link timeout int ReceiveTimeout,// receiveTimeout Iterable<Cookie> cookies,//cookies this.baseurl,// baseUrl this.queryparameters,// request parameter Map<String, dynamic> extra, Map<String, Dynamic > headers, ResponseType ResponseType = responsetype. json,// return type ContentType ContentType,// ContentType ValidateStatus validateStatus, bool receiveDataWhenStatusError = true, bool followRedirects = true, int maxRedirects = 5, RequestEncoder requestEncoder, ResponseDecoder responseDecoder, }) : super(Copy the code
For more dio usage, I’m not going to go into this, but you can go here and see the dio author
conclusion
As we come to the end of this article, if you want to have a quick taste of the new Flutter, Seven Days of Flutter is for you. If you want to explore it, follow my footsteps and take a Flutter tour. In addition, I have a Wechat communication group with Flutter. Welcome to join my wechat group to discuss the problem of Flutter. My wechat signal is ZDL1994328.