0% found this document useful (0 votes)
43 views

Network and Web Socket

1. The document discusses the HTTP protocol and related concepts like HTTP requests, responses, status codes, and methods. 2. It explains JSON and strategies for serialization, including manual and automated serialization using code generation. 3. The steps to make a network request using Dart's HTTP package and display the response data using FutureBuilder are outlined.

Uploaded by

Blank User
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Network and Web Socket

1. The document discusses the HTTP protocol and related concepts like HTTP requests, responses, status codes, and methods. 2. It explains JSON and strategies for serialization, including manual and automated serialization using code generation. 3. The steps to make a network request using Dart's HTTP package and display the response data using FutureBuilder are outlined.

Uploaded by

Blank User
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

AHENDA

1 2 3 4
TCP model Http Http respond Http status
request request

5 6 7
JSON and serialization HTTP Methods Websocket
User browser/app

inter URL

HTTP://WWW.GOOGLE.COM

translate domain to ip

DNC Server

Customers
server
04 Application HTTP,FTP.POP3.SMTP

03 Transport TCP,UDP

TCP MODEL
Miss Jones Science Class
02 Networking IPV4 , IPV6

01 DataLink Ethernet
HTTP
protocol for transmitting hypermedia

documents, such as HTML

It was designed for communication between web

browsers and web servers, but it can also be used for

other purposes. HTTP follows a classical client-server

model
HTTP REQUEST
Property

Method type Headers


URL
01 www.Example.com
02 get , post , 03 Content
put , delete

Bodys
04 Binar

HTTP RESPONSE

status code Headers Body


01 100 - 511
02 Content
03 Binanry
HTTP STATUS CODE

informational
the request was received,

1xx response continuing process


This is a list of Hypertext Transfer

Protocol (HTTP) response status

the request was successfully

codes. Status codes are issued by a

2xx successful received, understood, and

server in response to a client's


accepted
request made to the server.

further action needs to be taken in

3XX redirection
order to complete the request

the request contains bad syntax or

4XX client error cannot be fulfilled

the server failed to fulfil an

5XX server error apparently valid request


HTTP METHODS
There are four main HTTP methods that you use in REST APIs. Here’s

what each of them does:

01
GET
Requests a representation of the specified resource. Requests using GET

only retrieve data – they should have no other effect on the data.

02
POST
submits data to the specified resource. You use this method to send data

to the server, such as customer information or file uploads.

03
DELETE
Deletes the specified resource.

04
PUT
Replaces all current representations of the target resource with the

uploaded content.
HOW TO START

-After creating our project


- should know about async and await keyword in dart.
-a little about the state management dependencies:
-we need to add the dependence, http: <latest_version>

Import the HTTP package. import 'package:http/http.dart' as http;

Additionally, in your AndroidManifest.xml file, add the Internet permission.

<!-- Required to fetch data from the internet. -->


<uses-permission android:name="android.permission.INTERNET" />

MAKE A NETWORK REQUEST


This recipe covers how to fetch a sample album from the

JSONPlaceholder using the http.get() method.

The http.get() method returns a


Future<http.Response> fetchAlbum() {
Future that contains a Response return http.get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1'));
}

what is Future?

Can you use the response ?


JSON AND SERIALIZATION
two general strategies for working with JSON:

Manual serialization
For smaller proof-of-concept projects or quick prototypes,
Automated serialization using code generation
For apps with several JSON models with more complexity
MANUAL SERIALIZATION
you can decode the JSON by calling the jsonDecode() function,
user.dart
with the JSON string as the method argument.
class User {
final String name;
-A Model.fromJson() constructor, for constructing a new Model final String email;
instance from a map structure.
- A toJson() method, which converts a Model instance into a map. User(this.name, this.email);

User.fromJson(Map<String, dynamic> json)


: name = json['name'],
Map<String, dynamic> userMap = jsonDecode(jsonString); email = json['email'];
Encode
var user = User.fromJson(userMap);
Map<String, dynamic> toJson() => {
'name': name,
'email': email,
Decode String json = jsonEncode(user); };
}
AUTOMATED SERIALIZATION ( CODE GENERATION)
Setting up json_serializable
you need one regular dependency, and two dev dependencies. In short, dev

dependencies user.dart
import

'package:json_annotation/json_annotation.dart';
dependencies: part 'user.g.dart';
json_annotation: <latest_version> @JsonSerializable()
class User {
dev_dependencies: User(this.name, this.email);
build_runner: <latest_version> String name;String email;
json_serializable: <latest_version>
factory User.fromJson(Map<String, dynamic> json) =>

_$UserFromJson(json);

Map<String, dynamic> toJson() => _$UserToJson(this);


}
AFTER MAKEING THE RESQUEST

to expalin more we use an exaple of album class of


user
then to fetch the data from the network or API class Album {
final int userId;
we use the Feture<Album> fuction final int id;
final String title;
Future<Album> fetchAlbum() async {
final response = await http.get( const Album({
Uri.parse('https://jsonplaceholder.typicode.c
required this.userId,required this.id,
om/albums/1')); required this.title,
});

if (response.statusCode == 200) {
factory Album.fromJson(Map<String, dynamic> json) {
return Album.fromJson(
return Album(
jsonDecode(response.body));
userId: json['userId'],
} else { id: json['id'],
throw Exception('Failed to load album'); title: json['title'],
} ); } }
}
FETCH THE DATA

Call the fetchAlbum() method in either the initState()


The initState() method is called exactly once and then never again. If you want to have

the option of reloading the API in response to an InheritedWidget changing.

class _MyAppState extends State<MyApp> {


late Future<Album> futureAlbum;

@override
void initState() {
super.initState();
futureAlbum = fetchAlbum();
}
// ···
}
DISPLAY THE DATA
To display the data on screen, use the FutureBuilder widget. The FutureBuilder widget

comes with Flutter and makes it easy to work with asynchronous data sources.the

function should throw an exception even in the case of a “404 Not Found” server

response.

FutureBuilder<Album>(
future: futureAlbum,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');}
// By default, show a loading spinner.
return const CircularProgressIndicator();
},
)
PARSE HUGE SIZED JSON

even that we are using async for this request bellow we still working as
the same loop evens of the the single isolate

List<Photo> parsePhotos(String responseBody) {


final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed.map<Photo>((json) => Photo.fromJson(json)).toList();
}
Future<List<Photo>> fetchPhotos(http.Client client) async {
final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
return parsePhotos(response.body);}
4- separate isolate
You can remove the jank by moving the parsing

and conversion to a background isolate using the

compute() function provided by Flutter. The

compute() function runs expensive functions in a

background isolate and returns the result. In this

case, run the parsePhotos() function in the

background.

Future<List<Photo>> fetchPhotos(http.Client client) async {


final response = await client
.get(Uri.parse('https://jsonplaceholder.typicode.com/photos'));
return compute(parsePhotos, response.body);
}
AUTHENTICATED REQUESTS (HTTPS)
to provide authorization, there are multiple ways but We use the most

common one the Authorization HTTP header


The HTTP package provides a convenient way to add headers to your requests.

Alternatively, use the HttpHeaders class from the dart:io library.

final response = await http.get(


Uri.parse('https://jsonplaceholder.typicode.com/albums/1'),
// Send authorization headers to the backend.
headers: {
HttpHeaders.authorizationHeader: 'Basic your_api_token_here' ,
},
);
SEND DATA TO THE INTERNET
Sending data to the internet is necessary for most apps. The http

package has got that covered, too


This recipe uses the following steps:
1. Add the http package.
2. Send data to a server using the http package.
3. Convert the response into a custom Dart object.
4. Get a title from user input.
5. Display the response on screen. Future<http.Response> createAlbum(String title) {
return http.post(Uri.parse(
3.Sending data to server 'https://jsonplaceholder.typicode.com/albums'),
headers:
<String, String>{
'Content-Type': 'application/json; charset=UTF-8',},
body: jsonEncode(<String, String>{'title': title,}),);
}
SEND DATA TO THE INTERNET
3.Create an Album class
Future<http.Response> createAlbum(String title) {
return http.post(Uri.parse(
'https://jsonplaceholder.typicode.com/albums'),
headers: 4.convert the http.Response to an Album
<String, String>{
'Content-Type': 'application/json; charset=UTF-8',
}, Future<Album> createAlbum(String title) async {
body: jsonEncode(<String, String>{'title': title,}),); final response = await http.post(
} Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{'Content-Type': 'application/json;

charset=UTF-8',},

body: jsonEncode(<String, String>{'title': title,}),);


if (response.statusCode == 201) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to create album.');}
}
OTHER METHODS
Update data
Future<http.Response> updateAlbum(String title) {
return http.put(Uri.parse(
'https://jsonplaceholder.typicode.com/albums/1'),
headers:
<String, String>{
'Content-Type': 'application/json; charset=UTF-8',},
body: jsonEncode(<String, String>{'title': title,}),); Future<Album> updateAlbum(String title) async {
} final response = await

http.put(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')

,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',},
body: jsonEncode(<String, String>{'title': title,}),);if

(response.statusCode == 200) {
return Album.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to update album.');}
}
OTHER METHODS
Update data
FutureBuilder<Album>(
To display the data on screen, use the FutureBuilder

widget. The FutureBuilder widget comes with Flutter


future: _futureAlbum,
and makes it easy to work with async data sources. builder: (context, snapshot) {
Note that snapshot.hasData only returns true when
if (snapshot.hasData) {
the snapshot contains a non-null data value. return Text(snapshot.data!.title);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
}
return const

CircularProgressIndicator();},
);
OTHER METHODS
Delete data
Future<http.Response> deleteAlbum(String id) async {
final http.Response response = await http.delete(Uri.parse(
In order to check whether the data has been deleted or not, first

'https://jsonplaceholder.typicode.com/albums/$id'),
fetch the data from the JSONPlaceholder using the http.get()

headers:
method, and display it in the screen.
<String, String>{
'Content-Type': 'application/json; charset=UTF-8',},);
Column(
return response;
mainAxisAlignment: MainAxisAlignment.center,
}
children: <Widget>[
Text ( snapshot.data?.title ?? 'Deleted'),
ElevatedButton(
child: const Text('Delete Data'),
onPressed: () {
setState(() {
_futureAlbum =
deleteAlbum(snapshot.data!.id.toString());
});
},),],
);
OTHER METHODS
Delete data
Returning a response from the deleteAlbum() method

Once the delete request has been made, you

can return a response from the deleteAlbum()


class Album {Future<Album> deleteAlbum(String id) async {
method to notify our screen that the data has
final http.Response response = await http.delete(
been deleted. Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'),
headers: <String, String>{
FutureBuilder() now rebuilds when it

'Content-Type': 'application/json; charset=UTF-8',},);


receives a response. Since the response

won’t have any data in its body if the


if (response.statusCode == 200) {
request was successful, the
return Album.fromJson(jsonDecode(response.body));
Album.fromJson() method creates an
} else {
instance of the Album object with a default
throw Exception('Failed to delete album.');
value (null in our case). This behavior can be

}
altered in any way you wish.
}
WEB
SOCKET
The WebSocket API: is an advanced technology that makes it
possible to open a two-way interactive communication session
between the user's browser and a server. With this API, you can send
messages to a server and receive event-driven responses without
having to poll the server for a reply.
why we need Websocket?
reduces server latency.
makes real-time communication much more efficient.
for simplicity.
provide advanced capabilities to HTML5 applications.
for applications that needs an incoming stream of data such as (stock
exchange , IOT application , etc.. ).

Nowadays, many applications need real-time data to provide instant feedback to users, be
it a chat application that shows a person typing in real-time or a remote application that
plots data directly from a hardware sensor

REST can be used to solve this problem but for more complex problem we have to ping
the server several times per minute that leads to overloading in the server.

Firebase Realtime Database can be used, that each time data is added to DB, the Flutter
application receives it as a Stream and shows the data to the user.

Firebase depends on very important piece of tech that is:


WebSockets are composed of:
A server that streams information.

A client in the application that is ready to receive the new stream of data.

A channel to communicate between the client and the server.


Messages sent between the client and the server.


how websocket works in flutter?
1.Connect to a WebSocket server:
The web_socket_channel package provides the tools you need to connect to a
WebSocket server.
The package provides a WebSocketChannel that allows you to both listen for
messages from the server and push messages to the server.
In Flutter, use the following line to create a WebSocketChannel that connects to a
server:
how websocket works in flutter?
2. Listen for messages from the server:

Now that you’ve established a connection, listen to messages from the server.
After sending a message to the test server, it sends the same message
back.
In this example, use a StreamBuilder widget to listen for new messages, and a
Text widget to display them.
how websocket works in flutter?
3. Send data to the server:
To send data to the server, add() messages to the sink provided by the
WebSocketChannel.

4. Close the WebSocket connection

After you’re done using the WebSocket, close the connection:


AN EXAMPLE
It's Time to Say

THANKS FOR
PARTICIPATE

You might also like