Network and Web Socket
Network and Web Socket
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
model
HTTP REQUEST
Property
Bodys
04 Binar
HTTP RESPONSE
informational
the request was received,
3XX redirection
order to complete the request
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
03
DELETE
Deletes the specified resource.
04
PUT
Replaces all current representations of the target resource with the
uploaded content.
HOW TO START
what is Future?
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);
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);
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
@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
background.
charset=UTF-8',},
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
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
}
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.
A client in the application that is ready to receive the new stream of data.
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.
THANKS FOR
PARTICIPATE