Flutter consolidateHttpClientResponseBytes not defined error? - http

I'm trying to parse a url image in order to turn it into Uint8 bytes and share across my share provider. When trying to consolidate my http response into bytes I get the following error The method 'consolidateHttpClientResponseBytes' isn't defined by my class. Here is the code I'm trying to use..... Please help!
Future<Null> shareImage() async{
var request = await HttpClient().getUrl(Uri.parse('network_image_url'));
var response = await request.close();
Uint8List bytes = await consolidateHttpClientResponseBytes(response);
}

Import this :
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:path_provider/path_provider.dart';
And you should be good

Related

Flutter Web Http request strange response

Hello i am trying to make a http request in flutter for web, but I am having a lot of problems here.
Response for any request I am doing looks like this:
I am making requests like this:
Ok, I realised that if i decode response like this:
var responseBody = json.decode(utf8.decode(response.bodyBytes));
I get:
Still I don't have full key-value response and the status code
How can I get normal respone?
I think you you need to decode you response body with json.decode from dart:convert.
import 'package:http/http.dart' as http;
import 'dart:convert';
final response = await http.get('https://dog.ceo/api/breeds/image/random');
if (response.statusCode == 200) {
final Map<String, dynamic> responseMap = json.decode(response.body);
}

How to test "signInWithEmailAndPassword" from firebase_auth

I'm trying to write some unit test in my Flutter app. I'm using firebase and i write this function (that i want to test) :
import 'dart:core';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
class FirebaseUtils {
static final FirebaseAuth _auth = FirebaseAuth.instance;
static Exception _exception;
static Future<bool> signIn(String email, String password) async {
FirebaseUser user;
try{
user = await _auth.signInWithEmailAndPassword(email: email, password: password);
} catch (ex){
print(ex);
_exception = ex;
user = null;
}
return user!=null;
}
}
my test :
import "package:test/test.dart";
import 'package:toolpad/utils/firebase/firebase_utils.dart';
import 'dart:async';
void main() {
test("Sign In user from firebase (working)", () async {
bool result = await FirebaseUtils.signIn("test#gmail.com", "lollollol");
expect(result, equals(true));
});
}
When i launch the test that throw an exception :
MissingPluginException(No implementation found for method signInWithEmailAndPassword on channel plugins.flutter.io/firebase_auth)
ERROR: Expected: <true>
Actual: <false>
I have no idea how fix it, anyone have an idea ?
After lot of search it seems that it is not possible without specify an Firebase.initialize before.
So if u want test some functions linked to Firebase, u should use testWidget. That's going to test your app not juste function)

Store Firebase Data as JSON locally

I want to use JSON as a local database for my firebase data ,I don't want offline data store.I am using path_provider to store my data on the phone
So I tried storing data with
file.writeAsStringSync(json.encode(snapshot.toString()))
And it worked the stored data file looked like a JSON file
"{-key:{name:name,age:age},-key:{name:name,age:age}}"
The " " where missing and I can't decode it.
So what can be done here ?
(Edit:Does Firestore provide anything that can help me with this ?)
You can use the shared_preferences package to store JSON,
or if you want to write to a custom file use the path_provider package to get paths to directories where you app has permissions to write to.
You might also need to use the async versions of the dart:io API to access files in Flutter (not sure about that tough)
"{-key:{name:name,age:age},-key:{name:name,age:age}}" is not valid JSON
Either use
import 'dart:convert';
...
var myJson = {'-key':{'name:name','age:age'},'-key':{'name:name','age:age'}}";
var myJsonString = jsonEncode(myJson);
await file.writeAsString(myJsonString);
or
var myJsonString = '{"-key":{"name:name","age:age"},"-key":{"name:name","age:age"}}';
await file.writeAsString(myJsonString);
Create a JSON File
Future<String> get _localPath async {
final directory = await getExternalStorageDirectory();
return directory.path;
}
Future<File> get _dbFile async {
final path = await _localPath;
return new File("$path/demo.json");
}
Write data into a file
Future<File> write(DataSnapshot snapshot,String chatId) async {
final path = await _dbFile;
final String key = snapshot.key;
final String name = snapshot.value['senderUid'];
final int age= snapshot.value['receivedUid'];
String content = '{"$key":{"name":"$name","age":"$age"}}';
return file.writeAsStringSync(content);
}
Read Data
Future<Null> read() async {
try {
final file = await _dbFile;
String content = file.readAsStringSync();
Map<String, dynamic> chatMap=json.decode(content);
chatMap.keys.forEach((E){debugPrint(E);});
} catch (e) {
debugPrint('Error : '+e.toString());
}
}

No response from JSR223 Sampler

I have code like this in JSR223 Sampler , and it gets passed also. But not able to see any output as response. Not sure what i have missed in it.
import android.util.Base64;
import java.security.spec.X509EncodedKeySpec;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import javax.crypto.Cipher;
String Original_String= ctx.getPreviousResult().getResponseDataAsString();
String Trim1=Original_String.substring(0, Original_String.lastIndexOf(","));
String Trim2=Trim1.replaceFirst("-----BEGIN PUBLIC KEY-----", "");
String Trim3=Trim2.replaceFirst("-----END PUBLIC KEY-----", "");
String[] parts = Trim3.split(":");
String myString = parts[1].substring(1, parts[1].length()-1);
String final_string=myString.replaceAll("\\\\n", "");
log.info(final_string);
String input="4000221111111111";
try{
byte[] byteKey = Base64.decode(final_string.getBytes(), Base64.DEFAULT);
X509EncodedKeySpec X509publicKey = new X509EncodedKeySpec(byteKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
Key k=kf.generatePublic(X509publicKey);
//return (PublicKey) k;
def cipher = Cipher.getInstance("RSA/NONE/OAEPPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE, k);
byte[] encryptedBytes = cipher.doFinal(input.getBytes());
log.info( Base64.encodeToString(encryptedBytes, Base64.NO_WRAP));
}
catch(Exception e){
e.printStackTrace();
}
Could any one help me out on this Please ?
If you want your JSR223 Sampler to have response data you need to go for one of the following approaches:
return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP)
or even better:
SampleResult.setResponseData(Base64.encodeToString(encryptedBytes, Base64.NO_WRAP), 'UTF-8')
See SampleResult class JavaDoc for all available functions, this way you have full control of response code, headers, body, message, etc.
You may also be interested in Apache Groovy - Why and How You Should Use It article which contains comprehensive information on Groovy scripting in JMeter tests.

Issue with httpclient.getstringasync

I want to develop a Dragon Timer Windows Store App for GuildWars 2.
Whatever, I save a timestamp in a sql database. To get this timestamp in the app, I made a php script that writes the content of the database to a page. Now I'm trying to receive that string via the HttpClient.GetStringAsync() Method. Here's the code snipped:
async Task<Dictionary<String, DateTime>> GetKillTimes()
{
Dictionary<String, DateTime> killTimes = new Dictionary<String,DateTime>();
HttpClient httpClient = new HttpClient();
Task<string> getStringTask = httpClient.GetStringAsync("http://www.wp10454523.server-he.de/truhentimer/getTimes.php");
String rawKillTimes = await getStringTask;
//Parse to Dictionary...
return killTimes;
}
I tried some different Methods I got from google (WebRequest ...), but every one got stuck at the Get-Part. Am I maybe misinterpreting the function? Shouldn't I get the content of the page, which is a simple String?
You have to use await keyword as web request & response in WinRT are asynchronous so you have to use await keyword. await before httpClient.GetStringAsync(...)
Task<string> getStringTask = await httpClient.GetStringAsync("http://www.wp10454523.server-he.de/truhentimer/getTimes.php");

Resources