logo icon
Taninut.com

91

 
 
 
Content ID91
Category ID3
Writer ID(not set)
User ID(not set)
Lang Modeth
Content Nameการเรียกใช้งาน API ใน Flutter ด้วย dio
Content Urlการเรียกใช้งาน-API-ใน-Flutter-ด้วย-dio
Content Desc<p data-pm-slice="1 1 []">นอกจาก package http แล้ว ยังมี package อีกหนึ่งตัวที่ชื่อว่า dio ที่ใช้สำหรับการเรียกใช้งาน API ใน Flutter ได้อีกด้วย โดย dio มีการจัดการการเชื่อมต่อแบบ asynchronous และมีฟีเจอร์เพิ่มเติมอีกมากมาย เช่น การกำหนด timeout, การกำหนด header และ interceptor สำหรับตรวจสอบ token ก่อนทำการเรียก API เป็นต้น ดังนั้น การใช้งาน dio จึงเป็นทางเลือกที่ดีกว่าในบางกรณี ดังนี้<br><br></p>
<ol>
<li>
<p>Import package: ก่อนอื่นเราต้อง import package dio โดยเพิ่มโค้ดด้านล่างนี้ที่ด้านบนของไฟล์ Dart ของเรา</p>
</li>
</ol>
<pre style="padding-left: 40px;"><code>import 'package:dio/dio.dart';</code></pre>
<ol start="2">
<li>
<p>สร้าง instance ของ Dio: เราต้องสร้าง instance ของ Dio ก่อนเพื่อใช้สำหรับการเรียกใช้งาน API ดังนี้</p>
</li>
</ol>
<pre style="padding-left: 40px;"><code>final dio = Dio();</code></pre>
<ol start="3">
<li>
<p>สร้าง function สำหรับเรียกใช้ API: เราสามารถสร้าง function ที่รับ parameter เป็น URL ของ API และเมื่อเรียกใช้ function จะส่ง request ไปยัง API และรับ response กลับมา ดังนี้</p>
</li>
</ol>
<pre style="padding-left: 40px;"><code>void fetchData(String url) async { <br> try { <br> final response = await dio.get(url); <br> // ดึงข้อมูลจาก response.data <br> final data = response.data; <br> // ทำอะไรต่อก็ได้ <br> } catch (error) { <br> // แสดง error message <br> throw Exception('Failed to load data'); <br> }<br>}</code></pre>
<ol start="4">
<li>
<p>ใช้ function เพื่อเรียกใช้ API: เมื่อเราสร้าง function เพื่อเรียกใช้ API แล้ว เราสามารถเรียกใช้ function นั้นๆ ด้วย URL ของ API ที่เราต้องการได้ ดังนี้</p>
</li>
</ol>
<pre style="padding-left: 40px;"><code>fetchData('https://jsonplaceholder.typicode.com/todos/1');</code></pre>
<pre style="padding-left: 40px;">&nbsp;</pre>
<p>โดย URL ที่ใช้ในตัวอย่างนี้เป็นตัวอย่างเท่านั้น สามารถเปลี่ยน URL เป็น URL ของ API ต่างๆ ที่ต้องการเรียกใช้งานได้<br><br></p>
<p>การใช้งาน dio ทำให้เราสามารถจัดการการเชื่อมต่อแบบ asynchronous ได้ง่ายขึ้น และมีฟีเจอร์เพิ่มเติมที่ช่วยให้การเรียกใช้งาน API มีประสิทธิภาพมากขึ้น โดยไม่ต้องเขียน code ที่ซับซ้อนเหมือนกับการใช้งาน package http ซึ่งทำให้ dio เป็นทางเลือกที่ดีกว่าในบางกรณี.<br><br>ตัวอย่าง 1<br><br></p>
<p style="padding-left: 40px;"><code><span style="font-size: 8pt;">import 'package:flutter/material.dart';</span></code><br><span style="font-size: 8pt;"><code>import 'package:dio/dio.dart';</code></span></p>
<p style="padding-left: 40px;"><span style="font-size: 8pt;"><code>class ApiExample extends StatefulWidget {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; @override</code></span><br><span style="font-size: 8pt;"><code>&nbsp; _ApiExampleState createState() =&gt; _ApiExampleState();</code></span><br><span style="font-size: 8pt;"><code>}</code></span></p>
<p style="padding-left: 40px;"><span style="font-size: 8pt;"><code>class _ApiExampleState extends State&lt;ApiExample&gt; {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; List&lt;dynamic&gt; _posts = [];</code></span></p>
<p style="padding-left: 40px;"><span style="font-size: 8pt;"><code>&nbsp; @override</code></span><br><span style="font-size: 8pt;"><code>&nbsp; void initState() {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; super.initState();</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; _fetchPosts();</code></span><br><span style="font-size: 8pt;"><code>&nbsp; }</code></span></p>
<p style="padding-left: 40px;"><span style="font-size: 8pt;"><code>&nbsp; Future&lt;void&gt; _fetchPosts() async {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; try {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; final response = await Dio().get('https://jsonplaceholder.typicode.com/posts');</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; if (response.statusCode == 200) {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; setState(() {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _posts = response.data;</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; });</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; }</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; } catch (error) {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; print('Error fetching posts: $error');</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; }</code></span><br><span style="font-size: 8pt;"><code>&nbsp; }</code></span></p>
<p style="padding-left: 40px;"><span style="font-size: 8pt;"><code>&nbsp; @override</code></span><br><span style="font-size: 8pt;"><code>&nbsp; Widget build(BuildContext context) {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; return Scaffold(</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; appBar: AppBar(</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; title: Text('API Example'),</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; ),</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; body: ListView.builder(</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; itemCount: _posts.length,</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; itemBuilder: (BuildContext context, int index) {</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; final post = _posts[index];</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ListTile(</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; title: Text(post['title']),</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; subtitle: Text(post['body']),</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; &nbsp; },</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; &nbsp; ),</code></span><br><span style="font-size: 8pt;"><code>&nbsp; &nbsp; );</code></span><br><span style="font-size: 8pt;"><code>&nbsp; }</code></span><br><code><span style="font-size: 8pt;">}</span><br></code></p>
<p>&nbsp;</p>
<p><strong>โค้ดนี้เป็นตัวอย่างการใช้ Flutter ในการเรียกใช้งาน API </strong>ด้วย Dio package ซึ่งเป็น library สำหรับ HTTP client ในภาษา Dart ในตัวอย่างนี้ โค้ดจะเรียกใช้งาน API จาก JSONPlaceholder แล้วนำมาแสดงผลใน ListView widget<br><br></p>
<p>class ApiExample คือ class ของ Widget ที่สร้างเป็น stateful widget เพื่อให้ widget นี้เปลี่ยนแปลงได้ โดย _ApiExampleState คือ class ของ state ซึ่งกำหนดตัวแปร _posts เป็น List สำหรับเก็บข้อมูลที่ดึงมาจาก API<br><br></p>
<p>initState() คือ method ที่เรียกใช้งานในขณะที่ widget กำลังถูกสร้างขึ้น ซึ่งใน method นี้จะเรียกใช้ _fetchPosts() เพื่อดึงข้อมูลโพสต์จาก API<br><br></p>
<p>_fetchPosts() เป็น asynchronous method ที่ใช้ Dio package เพื่อเรียกใช้งาน API จาก URL ที่กำหนด โดย method นี้จะตรวจสอบ response ว่าสำเร็จหรือไม่ ถ้าสำเร็จจะเก็บข้อมูลที่ได้ไว้ในตัวแปร _posts และเรียกใช้งาน setState() เพื่อแสดงผลลัพธ์ใหม่บนหน้าจอ<br><br></p>
<p>build() เป็น method ที่สร้าง widget tree โดยในตัวอย่างนี้จะสร้าง Scaffold widget ที่ประกอบด้วย AppBar widget และ ListView.builder widget ที่ใช้แสดงผลลัพธ์โพสต์ที่ดึงมาจาก API โดยกำหนดจำนวนรายการและรายการแต่ละรายการให้แสดงผลโดยใช้ itemBuilder() ซึ่งจะสร้าง ListTile widget สำหรับแสดงข้อมูลแต่ละรายการโพสต์</p>
<p>&nbsp;</p>
<div class="flex flex-grow flex-col gap-3">
<div class="min-h-[20px] flex flex-col items-start gap-4 whitespace-pre-wrap">
<div class="markdown prose w-full break-words dark:prose-invert light">
<p><strong>ตัวอย่างที่ 2&nbsp;</strong></p>
<p>ใน Dio package สามารถแปลงข้อมูลจาก JSON string เป็น Object ในภาษา Dart ได้โดยตรงโดยไม่จำเป็นต้องใช้&nbsp;<code>json.decode()</code>&nbsp;หรือการสร้าง Class ในการแปลง JSON เช่นเดียวกับที่ใช้กับ http package</p>
<p>ตัวอย่างการใช้งานดังนี้</p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">&nbsp;</div>
<div class="p-4 overflow-y-auto"><code class="!whitespace-pre hljs language-dart">import 'package:dio/dio.dart';

void main() async {
Dio dio = Dio();
Response response = await dio.get('https://jsonplaceholder.typicode.com/users/1');

Map&lt;String, dynamic&gt; userMap = response.data;
String name = userMap['name'];
int age = userMap['age'];
String city = userMap['address']['city'];

print(name); // Output: Leanne Graham
print(age); // Output: 18
print(city); // Output: Gwenborough
}
</code></div>
</div>
<p>จากตัวอย่างข้างต้น เมื่อส่ง request ไปยัง URL&nbsp;<code>https://jsonplaceholder.typicode.com/users/1</code>&nbsp;และได้รับ response กลับมาในรูปแบบของ JSON string ที่มี key-value pairs ในรูปแบบของ Map โดยใช้ Dio package สามารถนำ Map ที่ได้ไปใช้งานได้โดยตรง ไม่จำเป็นต้องแปลงเป็น Object หรือใช้&nbsp;<code>json.decode()</code>&nbsp;ในการแปลง JSON ก่อนแล้วแปลงให้อยู่ในรูปแบบของ Object อีกทีแล้วสามารถใช้ key ในการเข้าถึง value ได้เช่นเดียวกับการใช้ http package</p>
<p><br><strong>ตัวอย่างที่ 3&nbsp;<br><br></strong></p>
<p>ใน Flutter จะใช้ Map และ Object เพื่อเก็บข้อมูลได้เช่นกัน โดยใน Dio package สามารถแปลง JSON string ให้อยู่ในรูปแบบของ Map หรือ Object ได้ตามต้องการ ตัวอย่างการใช้งาน Map และ Object ด้วย Dio package ใน Flutter ดังนี้<br><br></p>
<div class="bg-black rounded-md mb-4">
<div class="flex items-center relative text-gray-200 bg-gray-800 px-4 py-2 text-xs font-sans justify-between rounded-t-md">&nbsp;</div>
<div class="p-4 overflow-y-auto"><code class="!whitespace-pre hljs language-dart">import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class User {
final String name;
final int age;
final String city;

User({this.name, this.age, this.city});

factory User.fromJson(Map&lt;String, dynamic&gt; json) {
return User(
name: json['name'],
age: json['age'],
city: json['city'],
);
}
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Dio Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Dio Demo'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: &lt;Widget&gt;[
RaisedButton(
child: Text('Fetch User'),
onPressed: () async {
Dio dio = Dio();
Response response = await dio.get('https://jsonplaceholder.typicode.com/users/1');

Map&lt;String, dynamic&gt; userMap = response.data;
String name = userMap['name'];
int age = userMap['age'];
String city = userMap['address']['city'];

print(name); // Output: Leanne Graham
print(age); // Output: 18
print(city); // Output: Gwenborough

User user = User.fromJson(userMap);
print(user.name); // Output: Leanne Graham
print(user.age); // Output: 18
print(user.city); // Output: Gwenborough
},
),
],
),
),
),
);
}
}
</code></div>
</div>
<p>จากตัวอย่างข้างต้น เมื่อกดปุ่ม "Fetch User" จะทำการส่ง request ไปยัง URL <code>https://jsonplaceholder.typicode.com/users/1</code> และได้รับ response กลับมาในรูปแบบของ JSON string ที่มี key-value pairs ในรูปแบบของ Map แล้วสามารถนำ Map ที่ได้ไปใช้งานได้โดยตรง หรือใช้ Class <code>User</code> ที่สร้างขึ้นเพื่อแปลง JSON string เป็น Object ก็ได้ การใช้ Map และ Object ขึ้นอยู่กับว่าต้องการใช้งานแบบใดเหมาะสมกับสถานการณ์แต่ละกรณี</p>
</div>
</div>
</div>
<div class="flex justify-between lg:block">
<div class="text-gray-400 flex self-end lg:self-center justify-center mt-2 gap-2 md:gap-3 lg:gap-1 lg:absolute lg:top-0 lg:translate-x-full lg:right-0 lg:mt-0 lg:pl-2 visible">&nbsp;</div>
</div>
Content Short
Content View4449
Content Thumb Highlight
Content Thumb/uploads/article/lDkBGfo8vJ.png
Content Img Alt
Content Tag
Content Date(not set)
Active Status1
Sort99999
Meta Titleการเรียกใช้งาน API ใน Flutter ด้วย dio
Meta Descการเรียกใช้งาน API ใน Flutter ด้วย dio
Meta Keywordการเรียกใช้งาน API ใน Flutter ,dio,การเรียกใช้งาน API
Og Titleการเรียกใช้งาน API ใน Flutter ด้วย dio
Og Descการเรียกใช้งาน API ใน Flutter ด้วย dio
Status1
Create Date Time2023-03-16 19:01:15
Update Date Time2023-04-01 13:07:34
Create By
Update By