HTTP通信をやってみる
Flutter: 2.8.0を使用
こちらのサイトのAPIを使用
https://reqres.in/
pabspec.yaml
name: getx_app
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.15.0 <3.0.0"
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
http: ^0.13.4
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^1.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
// get data url api
var response =
await http.get(Uri.parse("https://reqres.in/api/users"));
List data =
(json.decode(response.body) as Map<String, dynamic>)["data"];
data.forEach((element) {
Map<String, dynamic> user = element;
print(user);
});
},
child: Text("KLIK"),
),
),
);
}
}
実行結果
flutter: [{id: 1, email: george.bluth@reqres.in, first_name: George, last_name: Bluth, avatar: https://reqres.in/img/faces/1-image.jpg}, {id: 2, email: janet.weaver@reqres.in, first_name: Janet, last_name: Weaver, avatar: https://reqres.in/img/faces/2-image.jpg}, {id: 3, email: emma.wong@reqres.in, first_name: Emma, last_name: Wong, avatar: https://reqres.in/img/faces/3-image.jpg}, {id: 4, email: eve.holt@reqres.in, first_name: Eve, last_name: Holt, avatar: https://reqres.in/img/faces/4-image.jpg}, {id: 5, email: charles.morris@reqres.in, first_name: Charles, last_name: Morris, avatar: https://reqres.in/img/faces/5-image.jpg}, {id: 6, email: tracey.ramos@reqres.in, first_name: Tracey, last_name: Ramos, avatar: https://reqres.in/img/faces/6-image.jpg}]
Reloaded 1 of 638 libraries in 279ms.
2
flutter: {id: 1, email: george.bluth@reqres.in, first_name: George, last_name: Bluth, avatar: https://reqres.in/img/faces/1-image.jpg}
Reloaded 1 of 638 libraries in 204ms.
flutter: {id: 1, email: george.bluth@reqres.in, first_name: George, last_name: Bluth, avatar: https://reqres.in/img/faces/1-image.jpg}
flutter: {id: 2, email: janet.weaver@reqres.in, first_name: Janet, last_name: Weaver, avatar: https://reqres.in/img/faces/2-image.jpg}
flutter: {id: 3, email: emma.wong@reqres.in, first_name: Emma, last_name: Wong, avatar: https://reqres.in/img/faces/3-image.jpg}
flutter: {id: 4, email: eve.holt@reqres.in, first_name: Eve, last_name: Holt, avatar: https://reqres.in/img/faces/4-image.jpg}
flutter: {id: 5, email: charles.morris@reqres.in, first_name: Charles, last_name: Morris, avatar: https://reqres.in/img/faces/5-image.jpg}
flutter: {id: 6, email: tracey.ramos@reqres.in, first_name: Tracey, last_name: Ramos, avatar: https://reqres.in/img/faces/6-image.jpg}
flutter: {id: 1, email: george.bluth@reqres.in, first_name: George, last_name: Bluth, avatar: https://reqres.in/img/faces/1-image.jpg}
flutter: {id: 2, email: janet.weaver@reqres.in, first_name: Janet, last_name: Weaver, avatar: https://reqres.in/img/faces/2-image.jpg}
flutter: {id: 3, email: emma.wong@reqres.in, first_name: Emma, last_name: Wong, avatar: https://reqres.in/img/faces/3-image.jpg}
flutter: {id: 4, email: eve.holt@reqres.in, first_name: Eve, last_name: Holt, avatar: https://reqres.in/img/faces/4-image.jpg}
flutter: {id: 5, email: charles.morris@reqres.in, first_name: Charles, last_name: Morris, avatar: https://reqres.in/img/faces/5-image.jpg}
flutter: {id: 6, email: tracey.ramos@reqres.in, first_name: Tracey, last_name: Ramos, avatar: https://reqres.in/img/faces/6-image.jpg}
flutter: {id: 1, email: george.bluth@reqres.in, first_name: George, last_name: Bluth, avatar: https://reqres.in/img/faces/1-image.jpg}
flutter: {id: 2, email: janet.weaver@reqres.in, first_name: Janet, last_name: Weaver, avatar: https://reqres.in/img/faces/2-image.jpg}
flutter: {id: 3, email: emma.wong@reqres.in, first_name: Emma, last_name: Wong, avatar: https://reqres.in/img/faces/3-image.jpg}
flutter: {id: 4, email: eve.holt@reqres.in, first_name: Eve, last_name: Holt, avatar: https://reqres.in/img/faces/4-image.jpg}
flutter: {id: 5, email: charles.morris@reqres.in, first_name: Charles, last_name: Morris, avatar: https://reqres.in/img/faces/5-image.jpg}
flutter: {id: 6, email: tracey.ramos@reqres.in, first_name: Tracey, last_name: Ramos, avatar: https://reqres.in/img/faces/6-image.jpg}
printを**print(user["email"]);**に変更
flutter: george.bluth@reqres.in
flutter: janet.weaver@reqres.in
flutter: emma.wong@reqres.in
flutter: eve.holt@reqres.in
flutter: charles.morris@reqres.in
flutter: tracey.ramos@reqres.in
printを**print(user["first_name"]);**に変更
flutter: George
flutter: Janet
flutter: Emma
flutter: Eve
flutter: Charles
flutter: Tracey
SNS風のUIを作成
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: ListView.builder(
itemCount: 5,
itemBuilder: (context, index) =>
ListTile(leading: CircleAvatar(),
title: Text("Name Lengkap"),
subtitle: Text("email"),
)));
}
}
FutureBuilderに書き換える
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
// ユーザーのデータをAPIから取得するメソッド
Future getAllUser() async {
// 3秒たって読み込む処理
await Future.delayed(Duration(seconds: 3));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: FutureBuilder(
// ListViewをBuilderでラップしてFutureBuilderに書き換える
future: getAllUser(),
builder: (context, snapshot) {
//, snapshotを追加
if (snapshot.connectionState == ConnectionState.waiting) {
// 読み間でいるWidgetを表示
return Center(
child: Text("LOADING ...."),
);
} else {
return ListView.builder(
itemCount: 5,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(),
title: Text("Name Lengkap"),
subtitle: Text("email"),
));
}
}));
}
}
例外処理を追加
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({Key? key}) : super(key: key);
// ユーザーのデータをAPIから取得するメソッド
Future getAllUser() async {
try {
var response = await http.get(Uri.parse("https://reqres.in/api/users"));
print(response.body);
} catch (e) {
print("例外処理が発生");
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: FutureBuilder(
// ListViewをBuilderでラップしてFutureBuilderに書き換える
future: getAllUser(),
builder: (context, snapshot) {
//, snapshotを追加
if (snapshot.connectionState == ConnectionState.waiting) {
// 読み間でいるWidgetを表示
return Center(
child: Text("LOADING ...."),
);
} else {
return ListView.builder(
itemCount: 5,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(),
title: Text("Name Lengkap"),
subtitle: Text("email"),
));
}
}));
}
}
実行結果
Restarted application in 1,273ms.
Reloaded 1 of 638 libraries in 314ms.
flutter: {"page":1,"per_page":6,"total":12,"total_pages":2,"data":[{"id":1,"email":"george.bluth@reqres.in","first_name":"George","last_name":"Bluth","avatar":"https://reqres.in/img/faces/1-image.jpg"},{"id":2,"email":"janet.weaver@reqres.in","first_name":"Janet","last_name":"Weaver","avatar":"https://reqres.in/img/faces/2-image.jpg"},{"id":3,"email":"emma.wong@reqres.in","first_name":"Emma","last_name":"Wong","avatar":"https://reqres.in/img/faces/3-image.jpg"},{"id":4,"email":"eve.holt@reqres.in","first_name":"Eve","last_name":"Holt","avatar":"https://reqres.in/img/faces/4-image.jpg"},{"id":5,"email":"charles.morris@reqres.in","first_name":"Charles","last_name":"Morris","avatar":"https://reqres.in/img/faces/5-image.jpg"},{"id":6,"email":"tracey.ramos@reqres.in","first_name":"Tracey","last_name":"Ramos","avatar":"https://reqres.in/img/faces/6-image.jpg"}],"support":{"url":"https://reqres.in/#support-heading","text":"To keep ReqRes free, contributions towards server costs are appreciated!"}}
Listを使ってみる
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
// const MyHomePage({Key? key}) : super(key: key);
// ユーザーというコレクションを定義
List<Map<String, dynamic>> allUser = [];
// ユーザーのデータをAPIから取得するメソッド
Future getAllUser() async {
try {
var response = await http.get(Uri.parse("https://reqres.in/api/users"));
List data = (json.decode(response.body)
as Map<String, dynamic>)["data"]; // MapでString, dynamic型に変換
data.forEach((element) {
allUser.add(element);
});
print(allUser);
} catch (e) {
print("例外処理が発生");
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: FutureBuilder(
// ListViewをBuilderでラップしてFutureBuilderに書き換える
future: getAllUser(),
builder: (context, snapshot) {
//, snapshotを追加
if (snapshot.connectionState == ConnectionState.waiting) {
// 読み間でいるWidgetを表示
return Center(
child: Text("LOADING ...."),
);
} else {
return ListView.builder(
itemCount: 5,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(),
title: Text("Name Lengkap"),
subtitle: Text("email"),
));
}
}));
}
}
実行結果
Restarted application in 452ms.
flutter: [{id: 1, email: george.bluth@reqres.in, first_name: George, last_name: Bluth, avatar: https://reqres.in/img/faces/1-image.jpg}, {id: 2, email: janet.weaver@reqres.in, first_name: Janet, last_name: Weaver, avatar: https://reqres.in/img/faces/2-image.jpg}, {id: 3, email: emma.wong@reqres.in, first_name: Emma, last_name: Wong, avatar: https://reqres.in/img/faces/3-image.jpg}, {id: 4, email: eve.holt@reqres.in, first_name: Eve, last_name: Holt, avatar: https://reqres.in/img/faces/4-image.jpg}, {id: 5, email: charles.morris@reqres.in, first_name: Charles, last_name: Morris, avatar: https://reqres.in/img/faces/5-image.jpg}, {id: 6, email: tracey.ramos@reqres.in, first_name: Tracey, last_name: Ramos, avatar: https://reqres.in/img/faces/6-image.jpg}]
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
// const MyHomePage({Key? key}) : super(key: key);
// ユーザーというコレクションを定義
List<Map<String, dynamic>> allUser = [];
// ユーザーのデータをAPIから取得するメソッド
Future getAllUser() async {
try {
var response = await http.get(Uri.parse("https://reqres.in/api/users"));
List data = (json.decode(response.body)
as Map<String, dynamic>)["data"]; // MapでString, dynamic型に変換
data.forEach((element) {
allUser.add(element);
});
print(allUser);
} catch (e) {
print("例外処理が発生");
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: FutureBuilder(
// ListViewをBuilderでラップしてFutureBuilderに書き換える
future: getAllUser(),
builder: (context, snapshot) {
//, snapshotを追加
if (snapshot.connectionState == ConnectionState.waiting) {
// 読み間でいるWidgetを表示
return Center(
child: Text("LOADING ...."),
);
} else {
return ListView.builder(
itemCount: allUser.length, // Listのデータを数える
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(),
// ユーザーのファーストネームとラストネームを取得
title: Text("${allUser[index]['first_name']} ${allUser[index]['last_name']}"),
subtitle: Text("${allUser[index]['email']}"),
));
}
}));
}
}
List型のallUserから取得したデータを画面に表示
allUserから、画像、名前、メールアドレスを取得
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.indigo,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
// const MyHomePage({Key? key}) : super(key: key);
// ユーザーというコレクションを定義
List<Map<String, dynamic>> allUser = [];
// ユーザーのデータをAPIから取得するメソッド
Future getAllUser() async {
try {
var response = await http.get(Uri.parse("https://reqres.in/api/users"));
List data = (json.decode(response.body)
as Map<String, dynamic>)["data"]; // MapでString, dynamic型に変換
data.forEach((element) {
allUser.add(element);
});
print(allUser);
} catch (e) {
print("例外処理が発生");
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: FutureBuilder(
// ListViewをBuilderでラップしてFutureBuilderに書き換える
future: getAllUser(),
builder: (context, snapshot) {
//, snapshotを追加
if (snapshot.connectionState == ConnectionState.waiting) {
// 読み間でいるWidgetを表示
return Center(
child: Text("LOADING ...."),
);
} else {
return ListView.builder(
itemCount: allUser.length, // Listのデータを数える
itemBuilder: (context, index) => ListTile(
// CircleAvatarはイメージと画像を丸くしてくれる。
leading: CircleAvatar(
backgroundColor: Colors.grey[300],
// コンソールのjsonのデータのavatarを表示
backgroundImage: NetworkImage(allUser[index]['avatar']),
),
// コンソールのjsonのデータのfirst_nameとlast_nameを表示
title: Text("${allUser[index]['first_name']} ${allUser[index]['last_name']}"),
// コンソールのjsonのデータのemailを表示
subtitle: Text("${allUser[index]['email']}"),
));
}
}));
}
}
モデルを作成してロジック分ける
lib
├── main.dart
└── models
└── user.dart
models/user.dart
// To parse this JSON data, do
//
// final userModel = userModelFromJson(jsonString);
import 'dart:convert';
UserModel userModelFromJson(String str) => UserModel.fromJson(json.decode(str));
String userModelToJson(UserModel data) => json.encode(data.toJson());
class UserModel {
UserModel({
required this.id,
required this.email,
required this.firstName,
required this.lastName,
required this.avatar,
});
int id;
String email;
String firstName;
String lastName;
String avatar;
factory UserModel.fromJson(Map<String, dynamic> json) => UserModel(
id: json["id"],
email: json["email"],
firstName: json["first_name"],
lastName: json["last_name"],
avatar: json["avatar"],
);
Map<String, dynamic> toJson() => {
"id": id,
"email": email,
"first_name": firstName,
"last_name": lastName,
"avatar": avatar,
};
}
main.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import './models/user.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
List<UserModel> allUser = [];
Future getAllUser() async {
try {
var response = await http.get(Uri.parse("https://reqres.in/api/users"));
List data = (json.decode(response.body) as Map<String, dynamic>)["data"];
data.forEach((element) {
allUser.add(UserModel.fromJson(element));
});
print(allUser);
} catch (e) {
//print jika terjadi error
print("Terjadi kesalahan");
print(e);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Future Builder"),
),
body: FutureBuilder(
future: getAllUser(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: Text("LOADING ...."),
);
} else {
if (allUser.length == 0) {
return Center(
child: Text("TIDAK ADA DATA"),
);
}
return ListView.builder(
itemCount: allUser.length,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey[300],
backgroundImage: NetworkImage(allUser[index].avatar),
),
title: Text("${allUser[index].firstName} ${allUser[index].lastName}"),
subtitle: Text("${allUser[index].email}"),
),
);
}
},
),
);
}
}
問題なく、buildできてます
最後に
今回やってみたUdemyのGetxの講座で紹介されていたFutureBuilderのチュートリアルをやってみて、Web通信のやり方がわかってきた気がします。
Mapとかjson.decodeとか色々出てきました!
やってることは、jsonのデータの型を変換している。
これで、人間でも理解できるデータに変換してくれている。