Exhausted heap space, trying to allocate 48 bytes riverpod provider issue - flutter

when I use provider inside another provider as DI that uses provider the app stops working and printing in the console
E/DartVM (16967): Exhausted heap space, trying to allocate 669296
bytes.
my code
final client = Provider.autoDispose(
(ref) => dio.Dio()
..interceptors.add(RequestsInspectorInterceptor())
..options.headers = {
'Content-Lang': ref.read(getLanguageUseCase),
'Accept': 'application/json',
//TODO CHANGE THIS FROM LOCAL
'country_id': 'countryId',
},
);
final dioHelper =
Provider.autoDispose((ref) => DioHelper(dio: ref.read(client)));
if I commented this line the app works if not the app will stop working and will seem like hang up
'Content-Lang': ref.read(getLanguageUseCase),

Related

How can I test values generated by an async function in a provider in Flutter?

I am trying to write some test for an app, but I can't test values stored in a provider. I am relatively new to testing, so there might be something that I am doing wrong, but anyway. What I want to test is to verify is two values are not the same, which should be the expected behavior, but I just can't make it pass.
This is the code that I want to test:
class RSAKeysProvider with ChangeNotifier {
String? _privateKey;
String? _publicKey;
String? get privateKey => _privateKey;
String? get publicKey => _publicKey;
Future<void> generate(String bits) async {
var keyPair = await RSA.generate(int.parse(bits));
_privateKey = keyPair.privateKey;
_publicKey = keyPair.publicKey;
notifyListeners();
}
}
and this is the test I'm writing:
test('Private and public keys should be different', () async {
final RSAKeysProvider rsaKeys = RSAKeysProvider();
await rsaKeys.generate('2048');
expect(rsaKeys.publicKey == rsaKeys.privateKey, false);
});
Since both keys are different when generated, the condition false would be met, and the test would pass, but for some reason it return true. When I just print the condition in the code while I run it on my phone, it return false as expected, but in the test doesn't. What am I doing wrong?
This is the message error I am getting:
Invalid argument(s): Failed to load dynamic library 'librsa_bridge.dylib': dlopen(librsa_bridge.dylib, 0x0001): tried: 'librsa_bridge.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OSlibrsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/./librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/../../../librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/Frameworks/librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/./librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/../../../librsa_bridge.dylib' (no such file), '/opt/homebrew/Caskroom/flutter/3.7.3/flutter/bin/cache/artifacts/engine/darwin-x64/Frameworks/librsa_bridge.dylib' (no such file), '/usr/lib/librsa_bridge.dylib' (no such file, not in dyld cache), 'librsa_bridge.dylib' (no such file), '/usr/lib/librsa_bridge.dylib' (no such file, not in dyld cache)
dart:ffi new DynamicLibrary.open
package:fast_rsa/bridge/binding.dart 117:33 Binding.openLib
package:fast_rsa/bridge/binding.dart 26:16 new Binding._internal
package:fast_rsa/bridge/binding.dart 17:45 Binding._singleton
package:fast_rsa/bridge/binding.dart Binding._singleton
package:fast_rsa/bridge/binding.dart 22:12 new Binding
package:fast_rsa/fast_rsa.dart 40:32 RSA.bindingEnabled
package:fast_rsa/fast_rsa.dart RSA.bindingEnabled
package:fast_rsa/fast_rsa.dart 43:9 RSA._call
package:fast_rsa/fast_rsa.dart 79:22 RSA._keyPairResponse
package:fast_rsa/fast_rsa.dart 437:18 RSA.generate
package:labsec_desafio_principal/providers/rsa_key.dart 17:29 RSAKeysProvider.generate
test/rsa_keys.test.dart 9:15 main.<fn>.<fn>
===== asynchronous gap ===========================
dart:async _CustomZone.registerBinaryCallback
package:labsec_desafio_principal/providers/rsa_key.dart 17:19 RSAKeysProvider.generate
test/rsa_keys.test.dart 9:15 main.<fn>.<fn>

Not able to fetch data in flutter from local web server

I'm trying to fetch data from a web server running on http://localhost:5050 and print it. At first it gave me a Socket Exception, so I looked it up and looks like you're supposed to replace "localhost" with your computer's IP address, so I did that, and now when I fetch it, it just seems to be... stuck? I have a print statement after the request but it doesn't print anything, no error, no output.. nothing. I'm using a Physical device, Here's my code:
class AllFlights extends StatefulWidget {
const AllFlights({Key? key}) : super(key: key);
#override
_AllFlightsState createState() => _AllFlightsState();
}
class _AllFlightsState extends State<AllFlights> {
Future<void> getAllFlights() async {
try {
log("here");
final res = await http.get(Uri.parse("http://192.168.8.100:5050/iflive/atc")); //fetch data -- gets stuck here
log(res.body); // "log" statement, imported from dart:developer
} catch (e) {
log(e.toString());
}
}
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: ElevatedButton(child: Text("All Flights",), onPressed: getAllFlights,),
),
);
}
}
Note: if it matters, the web server is running in a Docker container on port 5050 mapped to port 5050 on the host.
EDIT: I just noticed that a solid 2-3 mins after calling the api, it gives me a Socket Exception: [log] SocketException: OS Error: Connection timed out, errno = 110, address = 10.0.2.2, port = 44046
Is this normal?
Update: I was able to fix this by using adb (Android Debug Bridge) .
adb reverse tcp:5050 tcp:5050
this command routes your phone's requests on port 5050 to your computer's port 5050. Now you can just make requests to localhost directly instead on your computer's IP. The first port argument is your phone's port and second is your computer's.
example: adb reverse tcp:5000 tcp:5050 will map port 5000 on your phone to 5050 on your computer.
Have a nice day everyone!

Future not completed on PostgreSQL + Dart

I have got follow code:
void main() async {
connection = PostgreSQLConnection('localhost', 5432, 'db', username: 'postgres', password: '12345');
await connection.open();
//...
// some http handler that have next code inside:
List<List<dynamic>> result = await connection.query(body['sql']).timeout(Duration(seconds: 90));
If I run a lot of queries to http handler I am getting error:
TimeoutException after 0:00:30.000000: Future not completed
It's very strange, because on query I have timeout 90 seconds. So it's happens on connection. But I am opening connection only once in main.
Could anybody explain how it's happens? And how to fix it?
PostgreSQLConnection has parameters: timeoutInSeconds and queryTimeoutInSeconds and they both default to 30. I suggest you use them instead of timeout of Future.

CERTIFICATE_VERIFY_FAILED when trying to import data from API

I'm trying to learn Flutter/Dart and I'm having to much problems. Now I'm trying to obtain some values from an API. My code is:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:myapp01_apirequest/src/models/uplink_models.dart';
class UplinksProvider{
String _url = 'xxx.yyy.com';
Future<List<Uplink>> getEnCines() async{
try{
final url = Uri.https(_url, ':14442/api/external/login', {
'username': 'Joe689',
'password': '15.Job_1825zz'
});
final resp = await http.get(url);
final decodedData = json.decode(resp.body);
print('Patata');
print(decodedData);
return [];
}catch (error){
print('++++++++++///////++++++++++++++++');
print(error);
print('++++++++++*******++++++++++++++++');
}
}
}
Reading the Uri constructor documentation I understood that I have to split in 3 my url.
First one is authority. In my case I think is xxx.yyy.com.
Second is the unencodedPath. In my case I think is :14442/api/external/login.
Finally a map with params in my case the username and pass (the only thing I'm pretty sure is correct in my code).
If I do this, any problem appears, but the print('Patata'); and print(decodeData); don't appear. In addition, a file called io_client.dart opens and marks the next line.
var ioRequest = (await _inner.openUrl(request.method, request.url))
The console shows nothing (I think):
Launching lib\main.dart on LG M700 in debug mode...
lib\main.dart:1
Formato de par�metros incorrecto:
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:55883/KBAtv2-Jljc=/ws
Why no errors appears but I can't obtain my desired data?
EDIT:
According for what #Preet Shah's said I press the "VS run button" and appears the following exception three times:
I/flutter ( 1932): ++++++++++///////++++++++++++++++
I/flutter ( 1932): HandshakeException: Handshake error in client (OS Error:
I/flutter ( 1932): CERTIFICATE_VERIFY_FAILED: Hostname mismatch(handshake.cc:354))
I/flutter ( 1932): ++++++++++*******++++++++++++++++
And finally appears:
I/Choreographer( 1932): Skipped 148531 frames! The application may be doing too much work on its main thread.
D/vndksupport( 1932): Loading /vendor/lib/hw/android.hardware.graphics.mapper#2.0-impl.so from current namespace instead of sphal namespace.
D/vndksupport( 1932): Loading /vendor/lib/hw/gralloc.msm8937.so from current namespace instead of sphal namespace.
I/Choreographer( 1932): Skipped 35 frames! The application may be doing too much work on its main thread.
Then the problem is a certification problem, CERTIFICATE_VERIFY_FAILED. As I feel more comfortable with python, I have done some tests to understand the problem. I have been able to verify that this API requires having all the certification verifications in false, otherwise it never leaves the loop. Here is my Python code (just to show what I'm saying).
import requests
import json
log_params = {'username': 'Joe689', 'password': '15.Job_1825zz'}
headers = {'Content-type': 'application/json'}
url = 'https://xxx.yyy.com:14442/api/external/login'
response = requests.post(url, data=json.dumps(params), headers=self.headers, verify=False)
finalRes = json.loads(response.text)
As I said, this code is just for me to understand the problem because I am a newbie to Dart. Here I found this answer and it seems has the solution but I don't know how to implement it, using my Uri.https estructure (maybe it's not possible).
I tried this, but isn't working:
Map<String, String> requestHeaders = {
'Content-type': 'application/json'
};
final resp = await http.get(url, headers:requestHeaders);
Thank you very much.
Try this:
HttpClient client = new HttpClient();
client.badCertificateCallback = ((X509Certificate cert, String host, int port) => true);
String url ='xxx.yyy.com:14442/api/external/login';
Map map = {
"email" : "Joe689" ,
"password" : "15.Job_1825zz"
};
HttpClientRequest request = await client.getUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
Now, check what reply contains. And accordingly, return the data.

iOS: Error When accessing Async Storage: "No such file or directory"

I'm trying to access the async storage to get the array of podcasts. I add a podcast to the array and stringify it and try to persist it, and then I get the error:
Error: Failed to write value.Error Domain=NSCocoaErrorDomain Code=4
"The folder “a5a1507954e095ba66ba428410066532” doesn’t exist."
UserInfo={NSFilePath=/Users/clundberg/Library/Developer/CoreSimulator/Devices/F4A61A1A-9998-4C72-AD02-D6969E56990F/data/Containers/Data/Application/171D43CC-4BE5-4D64-8D30-C9582898A324/Documents/RCTAsyncLocalStorage_V1/a5a1507954e095ba66ba428410066532,
NSUserStringVariant=Folder, NSUnderlyingError=0x604002e5c080 {Error
Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}
Relevant code:
AsyncStorage.getItem("#podcasts")
.then(string => {
console.log(string)
const item = JSON.parse(string);
const podcasts = [...(item ? item : []), p];
console.log(podcasts)
return AsyncStorage.setItem("#podcasts", JSON.stringify(podcasts));
})
.catch(error => console.log(error));
Environment:
OS: macOS High Sierra 10.13.3
Node: 8.11.1
Yarn: Not Found
npm: 5.6.0
Watchman: 4.9.0
Xcode: Xcode 9.3 Build version 9E145
Android Studio: Not Found
Packages: (wanted => installed)
react: 16.2.0 => 16.2.0
react-native: 0.53.0 => 0.53.0
AsyncStorage.getItem("#podcasts").then( (error,stringReturn) => {
console.log(stringReturn);
//the first parameter is the error checking the second one is the string you need i think
});
I'm not sure, but I think it's probably erroring where you return the setItem() call. If that's true, maybe try this...
AsyncStorage.getItem("#podcasts")
.then(string => {
console.log(string)
const item = JSON.parse(string);
const podcasts = [...(item ? item : []), p];
console.log(podcasts)
return podcasts;
})
.then(podcasts => AsyncStorage.setItem("#podcasts", JSON.stringify(podcasts))
.catch(error => console.log(error));
Another thought is that your simulator's AsyncStorage cache has become corrupted. The simulator stores the data on the actual file system. I'm just guessing here, but maybe the pointer to the directory has become invalid somehow. I would first try a very simple setItem() to see if it works. If it fails, then try restarting the app, clearing the cache, etc, etc. Make it all as fresh as possible.