SlideShare a Scribd company logo
MODULE 5.pptx MODULE 4 (1).pptx flutter dart programming
TRAINING
Transforming Lives Through
Skilling
Networking
and APIs in
Flutter
Networking is a key part of modern mobile applications, allowing apps to fetch data, interact
with external services, and synchronize with backends. Flutter provides robust tools to handle
networking and APIs efficiently.
What is an API?
An Application Programming Interface (API) allows communication between apps and
external data sources.
Common APIs in Apps:
● Weather APIs (e.g., OpenWeather).
● Map APIs (e.g., Google Maps).
● Payment Gateways (e.g., Stripe, PayPal).
● Data Format: JSON (JavaScript Object Notation).
Lorem Ipsum is simply dummy text of the
printing and typesetting industry. Lorem ipsum
has been industry’s standard dummy text ever
since the 1500s, when an unknown printer took
a gallery of ty. Lorem Ipsum is simply dummy
text of the printing and typesetting industry.
Lorem ipsum has been industry’s standard
dummy text ever since the 1500s, when an
unknown printer took a gallery of type.
Image
a) HTTP Protocol
● Most networking in Flutter uses the HTTP protocol to send requests and receive responses.
● Common HTTP methods:
○ GET: Fetch data from a server.
○ POST: Submit data to a server.
○ PUT: Update existing data on a server.
○ DELETE: Delete data from a server.
b) Asynchronous Nature
● Network calls are asynchronous, meaning they don’t block the main thread.
● Use Future, async, and await to handle asynchronous operations.
Core Concepts of Networking in Flutter
HTTP Package
The http package is the most commonly used library for making HTTP requests in Flutter.
a) Adding the Package
1. Add http to your pubspec.yaml file:
dependencies
http: ^0.15.0
2. Install dependencies:
flutter pub get
b) Basic HTTP GET Request
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
Image
Image Image Image
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data);
} else {
print('Failed to load data: ${response.statusCode}');
}
}
c) HTTP POST Request
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<void> fetchData() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
print(data);
} else {
print('Failed to load data: ${response.statusCode}');
}
}
JSON Parsing
Most APIs return data in JSON (JavaScript Object Notation) format. Flutter provides tools to parse and convert JSON data
into Dart objects.
Example:
{
"id": 1,
"title": "Flutter Networking",
"completed": false
}
Create a model class:
class Task {
final int id;
final String title;
final bool completed;
Task({required this.id, required this.title, required this.completed});
factory Task.fromJson(Map<String, dynamic> json) {
return Task(
id: json['id'],
title: json['title'],
completed: json['completed'],
);
}
}
Use the model:
Future<void> fetchTask() async {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
if (response.statusCode == 200) {
Task task = Task.fromJson(jsonDecode(response.body));
print('Task: ${task.title}, Completed: ${task.completed}');
}
}
Error Handling in Networking
Always handle errors to avoid app crashes due to network failures or unexpected server responses.
Future<void> fetchData() async {
try {
final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
print('Data: ${response.body}');
} else {
throw Exception('Failed to load data');
}
} catch (e) {
print('Error: $e');
}
}
State Management with Networking
To update the UI based on network data, combine state management with networking.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
// Data Provider
class PostProvider with ChangeNotifier {
List<dynamic> posts = [];
Future<void> fetchPosts() async {
final response = await
http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
posts = jsonDecode(response.body);
notifyListeners();
}
}
}
// Main App
void main() {
runApp(
ChangeNotifierProvider(
create: (context) => PostProvider(),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: PostScreen(),
);
}
}
// UI Screen
class PostScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
final provider = Provider.of<PostProvider>(context);
return Scaffold(
appBar: AppBar(title: Text('Posts')),
body: provider.posts.isEmpty
? Center(
child: ElevatedButton(
onPressed: provider.fetchPosts,
child: Text('Load Posts'),
),
)
: ListView.builder(
itemCount: provider.posts.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(provider.posts[index]['title']),
);
},
),
);
}
}
Handling Authentication in APIs
Token-Based Authentication
● Send tokens (e.g., JWT) in the request headers.
Future<void> fetchDataWithToken() async {
final response = await http.get(
Uri.parse('https://example.com/protected-resource'),
headers: {'Authorization': 'Bearer YOUR_TOKEN_HERE'},
);
if (response.statusCode == 200) {
print('Protected Data: ${response.body}');
}
}
Common Networking Use Cases
● Fetching Data
○ Use GET requests to retrieve data from an API.
● Sending Data
○ Use POST requests to submit forms or send JSON data to a server.
● Pagination
○ Fetch data in chunks using query parameters like page or limit.
● File Uploads
○ Use the dio package or http package for multipart file uploads.
Hands-On Activities
● Activity 1: Build a weather app to fetch and display current weather data using an API.
● Activity 2: Create a basic CRUD app using an API to manage user data.
● Activity 3: Implement error handling for failed API requests.
THANK YOU
+91 78150 95095 codemithra@ethnus.com www.codemithra.com

More Related Content

Similar to MODULE 5.pptx MODULE 4 (1).pptx flutter dart programming (20)

PDF
Dart Power Tools
Matt Norris
 
PPTX
Intro to Flutter SDK
digitaljoni
 
PDF
Flutter101
인수 장
 
PDF
Flutter workshop @ bang saen 2020
Anuchit Chalothorn
 
DOCX
flutter-general-report.docx
KuntalSasmal1
 
PPTX
All a flutter about Flutter.io
Steven Cooper
 
PDF
Flutter 에서 Native(iOS, Android) 코드와 통신하기
인수 장
 
PDF
Animations in Flutter - FlutterConf LATAM 2024
johnpryan
 
PDF
Introduction to Flutter - truly crossplatform, amazingly fast
Bartosz Kosarzycki
 
PPTX
Flutter presentation.pptx
FalgunSorathiya
 
PDF
Native mobile application development with Flutter (Dart)
Randal Schwartz
 
PPT
UNIT-1 __ Introduction to Flutter.ppt
leela rani
 
PDF
Flutter For Web: An Intro
Fahad Murtaza
 
PPTX
What’s new in Flutter3.pptx
ShantanuApurva1
 
PDF
Flutter_GTU 8th Sem Gtu Format PPT for Presentation
IGVinit
 
PPTX
Flutter Leap of Faith
Damith Warnakulasuriya
 
PPTX
Firebase integration with Flutter
pmgdscunsri
 
PDF
GDSC-FlutterBasics.pdf
GDSCSSN
 
PDF
Fluttering
Sercan Yusuf
 
PPTX
Performance #4 network
Vitali Pekelis
 
Dart Power Tools
Matt Norris
 
Intro to Flutter SDK
digitaljoni
 
Flutter101
인수 장
 
Flutter workshop @ bang saen 2020
Anuchit Chalothorn
 
flutter-general-report.docx
KuntalSasmal1
 
All a flutter about Flutter.io
Steven Cooper
 
Flutter 에서 Native(iOS, Android) 코드와 통신하기
인수 장
 
Animations in Flutter - FlutterConf LATAM 2024
johnpryan
 
Introduction to Flutter - truly crossplatform, amazingly fast
Bartosz Kosarzycki
 
Flutter presentation.pptx
FalgunSorathiya
 
Native mobile application development with Flutter (Dart)
Randal Schwartz
 
UNIT-1 __ Introduction to Flutter.ppt
leela rani
 
Flutter For Web: An Intro
Fahad Murtaza
 
What’s new in Flutter3.pptx
ShantanuApurva1
 
Flutter_GTU 8th Sem Gtu Format PPT for Presentation
IGVinit
 
Flutter Leap of Faith
Damith Warnakulasuriya
 
Firebase integration with Flutter
pmgdscunsri
 
GDSC-FlutterBasics.pdf
GDSCSSN
 
Fluttering
Sercan Yusuf
 
Performance #4 network
Vitali Pekelis
 

More from trwdcn (20)

PPTX
Unit 3 AI.pptxArtificial Intelligence unit 1 notes - intelligent agent.pptx
trwdcn
 
PPTX
Unit 2 AI.pptxUnit 2 AI.pptxUnit 2 AI.pptx
trwdcn
 
PPTX
jsonHMI ppt.pptxjsonHMI ppt.pptxjsonHMI ppt.pptx
trwdcn
 
PPTX
hmi ppt.pptxhmi ppt.pptxhmi ppt.pptxhmi ppt.pptx
trwdcn
 
PPTX
JSON Presentation.pptx JSON Presentation.pptx
trwdcn
 
PPTX
Wireless USB.pptx Wireless USB.pptx Wireless USB.pptx
trwdcn
 
PPTX
Module 2 - Dart Programming.pptx MODULE 3.pptx
trwdcn
 
PPTX
MODULE 3.pptxMODULE 3.pptxMODULE 3.pptxMODULE 3.pptx
trwdcn
 
PPTX
MODULE 4 (1).pptx flutter dart programming
trwdcn
 
PPTX
Practical Python.pptx Practical Python.pptx
trwdcn
 
PPTX
function ppt.pptx function ppt.pptx function ppt.pptx
trwdcn
 
PPTX
D 10 mark.pptx D 10 mark.pptx D 10 mark.pptx
trwdcn
 
PPTX
DAY1 PPT.pptx DAY1 PPT.pptx DAY1 PPT.pptx
trwdcn
 
PPTX
Wireless_Network_Experiments.pptx Wireless_Network_Experiments
trwdcn
 
PPTX
Introduction to Python.pptx Introduction to Python.pptx
trwdcn
 
PPTX
Storage Virtualization.pptx Storage Virtualization.pptx
trwdcn
 
PDF
Module 2 Azure Services for Web Developement.pdf
trwdcn
 
PPT
Artificial Intelligence AI Class notes unit 1
trwdcn
 
PPT
introdution-to-html html tags heml basics
trwdcn
 
PPTX
project Management system details and maintainence
trwdcn
 
Unit 3 AI.pptxArtificial Intelligence unit 1 notes - intelligent agent.pptx
trwdcn
 
Unit 2 AI.pptxUnit 2 AI.pptxUnit 2 AI.pptx
trwdcn
 
jsonHMI ppt.pptxjsonHMI ppt.pptxjsonHMI ppt.pptx
trwdcn
 
hmi ppt.pptxhmi ppt.pptxhmi ppt.pptxhmi ppt.pptx
trwdcn
 
JSON Presentation.pptx JSON Presentation.pptx
trwdcn
 
Wireless USB.pptx Wireless USB.pptx Wireless USB.pptx
trwdcn
 
Module 2 - Dart Programming.pptx MODULE 3.pptx
trwdcn
 
MODULE 3.pptxMODULE 3.pptxMODULE 3.pptxMODULE 3.pptx
trwdcn
 
MODULE 4 (1).pptx flutter dart programming
trwdcn
 
Practical Python.pptx Practical Python.pptx
trwdcn
 
function ppt.pptx function ppt.pptx function ppt.pptx
trwdcn
 
D 10 mark.pptx D 10 mark.pptx D 10 mark.pptx
trwdcn
 
DAY1 PPT.pptx DAY1 PPT.pptx DAY1 PPT.pptx
trwdcn
 
Wireless_Network_Experiments.pptx Wireless_Network_Experiments
trwdcn
 
Introduction to Python.pptx Introduction to Python.pptx
trwdcn
 
Storage Virtualization.pptx Storage Virtualization.pptx
trwdcn
 
Module 2 Azure Services for Web Developement.pdf
trwdcn
 
Artificial Intelligence AI Class notes unit 1
trwdcn
 
introdution-to-html html tags heml basics
trwdcn
 
project Management system details and maintainence
trwdcn
 
Ad

Recently uploaded (20)

PDF
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
PDF
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
PPSX
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
PDF
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
PDF
CLIP_Internals_and_Architecture.pdf sdvsdv sdv
JoseLuisCahuanaRamos3
 
PDF
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
PPTX
Comparison of Flexible and Rigid Pavements in Bangladesh
Arifur Rahman
 
PDF
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
PDF
Validating a Citizen Observatories enabling Platform by completing a Citizen ...
Diego López-de-Ipiña González-de-Artaza
 
PDF
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
PDF
June 2025 Top 10 Sites -Electrical and Electronics Engineering: An Internatio...
elelijjournal653
 
PPTX
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
PPTX
Mobile database systems 20254545645.pptx
herosh1968
 
PPTX
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
PPTX
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
PDF
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
PPTX
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
PPTX
WHO And BIS std- for water quality .pptx
dhanashree78
 
PDF
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
NFPA 10 - Estandar para extintores de incendios portatiles (ed.22 ENG).pdf
Oscar Orozco
 
Python Mini Project: Command-Line Quiz Game for School/College Students
MPREETHI7
 
OOPS Concepts in Python and Exception Handling
Dr. A. B. Shinde
 
Rapid Prototyping for XR: Lecture 5 - Cross Platform Development
Mark Billinghurst
 
CLIP_Internals_and_Architecture.pdf sdvsdv sdv
JoseLuisCahuanaRamos3
 
Designing for Tomorrow – Architecture’s Role in the Sustainability Movement
BIM Services
 
Comparison of Flexible and Rigid Pavements in Bangladesh
Arifur Rahman
 
تقرير عن التحليل الديناميكي لتدفق الهواء حول جناح.pdf
محمد قصص فتوتة
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
Validating a Citizen Observatories enabling Platform by completing a Citizen ...
Diego López-de-Ipiña González-de-Artaza
 
Rapid Prototyping for XR: Lecture 2 - Low Fidelity Prototyping.
Mark Billinghurst
 
June 2025 Top 10 Sites -Electrical and Electronics Engineering: An Internatio...
elelijjournal653
 
Bharatiya Antariksh Hackathon 2025 Idea Submission PPT.pptx
AsadShad4
 
Mobile database systems 20254545645.pptx
herosh1968
 
LECTURE 7 COMPUTATIONS OF LEVELING DATA APRIL 2025.pptx
rr22001247
 
MATERIAL SCIENCE LECTURE NOTES FOR DIPLOMA STUDENTS
SAMEER VISHWAKARMA
 
May 2025: Top 10 Read Articles in Data Mining & Knowledge Management Process
IJDKP
 
Introduction to File Transfer Protocol with commands in FTP
BeulahS2
 
WHO And BIS std- for water quality .pptx
dhanashree78
 
Rapid Prototyping for XR: Lecture 6 - AI for Prototyping and Research Directi...
Mark Billinghurst
 
Ad

MODULE 5.pptx MODULE 4 (1).pptx flutter dart programming

  • 4. Networking is a key part of modern mobile applications, allowing apps to fetch data, interact with external services, and synchronize with backends. Flutter provides robust tools to handle networking and APIs efficiently. What is an API? An Application Programming Interface (API) allows communication between apps and external data sources. Common APIs in Apps: ● Weather APIs (e.g., OpenWeather). ● Map APIs (e.g., Google Maps). ● Payment Gateways (e.g., Stripe, PayPal). ● Data Format: JSON (JavaScript Object Notation).
  • 5. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem ipsum has been industry’s standard dummy text ever since the 1500s, when an unknown printer took a gallery of ty. Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem ipsum has been industry’s standard dummy text ever since the 1500s, when an unknown printer took a gallery of type. Image a) HTTP Protocol ● Most networking in Flutter uses the HTTP protocol to send requests and receive responses. ● Common HTTP methods: ○ GET: Fetch data from a server. ○ POST: Submit data to a server. ○ PUT: Update existing data on a server. ○ DELETE: Delete data from a server. b) Asynchronous Nature ● Network calls are asynchronous, meaning they don’t block the main thread. ● Use Future, async, and await to handle asynchronous operations. Core Concepts of Networking in Flutter
  • 6. HTTP Package The http package is the most commonly used library for making HTTP requests in Flutter. a) Adding the Package 1. Add http to your pubspec.yaml file: dependencies http: ^0.15.0 2. Install dependencies: flutter pub get b) Basic HTTP GET Request import 'dart:convert'; import 'package:http/http.dart' as http; Future<void> fetchData() async { Image
  • 7. Image Image Image final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')); if (response.statusCode == 200) { var data = jsonDecode(response.body); print(data); } else { print('Failed to load data: ${response.statusCode}'); } }
  • 8. c) HTTP POST Request import 'dart:convert'; import 'package:http/http.dart' as http; Future<void> fetchData() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')); if (response.statusCode == 200) { var data = jsonDecode(response.body); print(data); } else { print('Failed to load data: ${response.statusCode}'); } }
  • 9. JSON Parsing Most APIs return data in JSON (JavaScript Object Notation) format. Flutter provides tools to parse and convert JSON data into Dart objects. Example: { "id": 1, "title": "Flutter Networking", "completed": false }
  • 10. Create a model class: class Task { final int id; final String title; final bool completed; Task({required this.id, required this.title, required this.completed}); factory Task.fromJson(Map<String, dynamic> json) { return Task( id: json['id'], title: json['title'], completed: json['completed'], );
  • 11. } } Use the model: Future<void> fetchTask() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1')); if (response.statusCode == 200) { Task task = Task.fromJson(jsonDecode(response.body)); print('Task: ${task.title}, Completed: ${task.completed}'); } }
  • 12. Error Handling in Networking Always handle errors to avoid app crashes due to network failures or unexpected server responses. Future<void> fetchData() async { try { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')); if (response.statusCode == 200) { print('Data: ${response.body}'); } else { throw Exception('Failed to load data'); } } catch (e) {
  • 13. print('Error: $e'); } } State Management with Networking To update the UI based on network data, combine state management with networking. import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; // Data Provider class PostProvider with ChangeNotifier {
  • 14. List<dynamic> posts = []; Future<void> fetchPosts() async { final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts')); if (response.statusCode == 200) { posts = jsonDecode(response.body); notifyListeners(); } } } // Main App
  • 15. void main() { runApp( ChangeNotifierProvider( create: (context) => PostProvider(), child: MyApp(), ), ); } class MyApp extends StatelessWidget { @override
  • 16. Widget build(BuildContext context) { return MaterialApp( home: PostScreen(), ); } } // UI Screen class PostScreen extends StatelessWidget { @override Widget build(BuildContext context) { final provider = Provider.of<PostProvider>(context); return Scaffold(
  • 17. appBar: AppBar(title: Text('Posts')), body: provider.posts.isEmpty ? Center( child: ElevatedButton( onPressed: provider.fetchPosts, child: Text('Load Posts'), ), ) : ListView.builder( itemCount: provider.posts.length, itemBuilder: (context, index) {
  • 19. Handling Authentication in APIs Token-Based Authentication ● Send tokens (e.g., JWT) in the request headers. Future<void> fetchDataWithToken() async { final response = await http.get( Uri.parse('https://example.com/protected-resource'), headers: {'Authorization': 'Bearer YOUR_TOKEN_HERE'}, ); if (response.statusCode == 200) { print('Protected Data: ${response.body}'); } }
  • 20. Common Networking Use Cases ● Fetching Data ○ Use GET requests to retrieve data from an API. ● Sending Data ○ Use POST requests to submit forms or send JSON data to a server. ● Pagination ○ Fetch data in chunks using query parameters like page or limit. ● File Uploads ○ Use the dio package or http package for multipart file uploads. Hands-On Activities ● Activity 1: Build a weather app to fetch and display current weather data using an API. ● Activity 2: Create a basic CRUD app using an API to manage user data. ● Activity 3: Implement error handling for failed API requests.
  • 21. THANK YOU +91 78150 95095 [email protected] www.codemithra.com