how to add http caching using "dio_http_cache" package to flutter - flutter

I have a code that I use to download data, through a query (get) and display it. But I want to change something, I want to cache the data and display it. So that if the device was offline, I could display the latest data. Someone is already doing this, I will be grateful for your help)
import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:test_axles/models/seals_model.dart';
import 'package:test_axles/setting_var/globalvar.dart' as global;
class ApiProvider {
final Dio _dio = Dio();
final String _url = global.urlVar;
Future<Objects> fetchSealsList() async {
try {
Response response = await _dio.get(_url);
return Objects.fromJson(response.data);
} catch (error, stacktrace) {
return Objects.withError(" ");
}
}
}

Related

Save image into gallery in Flutter

I try to save an image to gallery from a chat. I utilise for that gallery_saver package that does not helpfull. Please advise a proven package to save image into gallery. Or suggest how to fix the issue with method implementation.
void _saveNetworkImage(String url) async {
try {
GallerySaver.saveImage(url).then<void>((bool? success) {
if (success ?? false) {
GetIt.I
.get<NotificationService>()
.showSnackBar(context, S.current.image_saved_to_gallery);
} else {
GetIt.I
.get<NotificationService>()
.showSnackBar(context, S.current.error_image_saving_to_gallery);
}
}).onError((error, stackTrace) {
GetIt.I
.get<NotificationService>()
.showSnackBar(context, S.current.error_image_saving_to_gallery);
});
} catch (e) {
GetIt.I
.get<NotificationService>()
.showSnackBar(context, S.current.error_image_saving_to_gallery);
rethrow;
}
}
You can use path_provider package(link) for getting the local storage data and dio(link) or http(link) to get and save the image to the local storage.
Here's an example:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
var response = await http.get(imgUrl);
Directory tempDirectory = await getApplicationDocumentsDirectory();
File file = File(join(tempDirectory.path, 'image.png'));
file.writeAsBytesSync(response.bodyBytes);
Also, there's another package called image_gallery_saver(link) that makes saving images an easy task. You can checkout there package because we have to initially setup for some files. After that you can use this method to save image to the gallery.
_save() async {
var response = await Dio().get(
"https://ss0.baidu.com/94o3dSag_xI4khGko9WTAnF6hhy/image/h%3D300/sign=a62e824376d98d1069d40a31113eb807/838ba61ea8d3fd1fc9c7b6853a4e251f94ca5f46.jpg",
options: Options(responseType: ResponseType.bytes));
final result = await ImageGallerySaver.saveImage(
Uint8List.fromList(response.data),
quality: 60,
name: "hello",
);
print(result);
}

The argument type 'UserModel' can't be assigned to the parameter type 'Iterable<UserData>'

this is mycode .please solve this problem
import 'dart:convert' as convert;
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:internetconnectivityusingbloc/repos/user_model.dart';
class UserRepositories {
Future<void> getUsers() async {
List<UserData>? userData = [];
String urlEndPoint = "https://reqres.in/api/users?page=2";
// Await the http get response, then decode the json-formatted response.
Response response = await http.get(Uri.parse(urlEndPoint));
if (response.statusCode == 200) {
userData = [];
// final List result = jsonDecode(response.body);
return userData.addAll(UserModel.fromjson(response.body));
} else {
throw Exception(response.reasonPhrase);
// print('Request failed with status: ${response.statusCode}.');
}
}
}
i am trying to solve this problem .but i am failed.so i expecting u are solve this problem
Add [] inside addAll:
return userData.addAll([UserModel.fromjson(response.body)]);
If you are only adding one model is better to only use the method add.
Howerver you are trying to add a type UserModel to a list of UserData and that might throw another error if UserModel is not a child of UserData. So if you are expecting to fill the variable userData you should use UserData.fromjson(response.body) to fill the new data, so you should adjust UserData parameters to get the data that response.body will bring.

This function has a return type of 'FutureOr<Xmodel>, but doesnt end with a return statement

I'm trying to integrate a stock API into my app. I'm trying to create a service page but I get this error. I searched for similar topics but I couldn't find a solution.
import 'dart:convert';
import 'dart:io';
import 'package:myapp/models/apis/stocks.dart';
import 'package:http/http.dart' as http;
class StocksService {
final String url = "https://api.collectapi.com/economy/hisseSenedi";
Future<StocksModel> fetchStocks() async {
var res = await http.get(Uri.parse(url),
headers: {
HttpHeaders.authorizationHeader:
"apikey xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
},
);
if (res.statusCode == 200) {
var jsonBody = StocksModel.fromJson(jsonDecode(res.body));
return jsonBody;
} else {
print("İstek başarısız oldu => ${res.statusCode}");
}
}
}
You are not returning anything in your else block. It this is what you require in your code then change the return type of the function to dynamic. And if not then you are required to return the same data type in the else block too.

Dart/Flutter - HttpServer how to update image with websocket?

I am streaming my display to webserver. My current code is very basic and I don't know exactly how websockets work.
Right now the user have to refresh the page to get a new image. I would like to refresh on new image arrival.
Do I need to create a JavaScript page or can I render everything server side?
Here is my current code
import 'dart:io';
import 'package:flutter/services.dart';
const EventChannel eventChannel = EventChannel('bla.bla.io/screenshotStream');
dynamic image;
void handleNewImage(dynamic imageData) {
image = imageData;
}
registerScreenshotStreamSubscription() {
eventChannel.receiveBroadcastStream().listen(handleNewImage);
}
Future webServer() async {
registerScreenshotStreamSubscription();
HttpServer.bind(InternetAddress.anyIPv6, 3000).then((server) {
server.listen((HttpRequest request) async {
request.response.headers.set('Content-Type', 'image/png');
request.response.add(image);
request.response.close();
});
});
}

Dart Is there a way to get HTTPS content?

I really need help. I try to get the rss feed from this url:
- https://www.france24.com/fr/rss?time=1573661731673
But I don't know how to do it when using a https url, I tried to use the HTTP dart library. Here is my code:
import 'package:html/parser.dart';
import 'package:html/dom.dart';
import 'dart:async';
import 'package:http/http.dart';
class Parser {
final String urlSite = "http://www.france24.com/fr/actualites/rss";
Future chargerRSS() async{
final reponse = await get(urlSite);
if(reponse.statusCode == 200){
final feed = RssFeed.parse(reponse.body);
print("$feed at parser");
}
else{
print("Erreur: ${reponse.statusCode}");
}
}
}```