Converting object to an encodable object failed: Instance of 'Future<dynamic>' - dart

I am trying to get base64 string from image file. When I am using following method
Future convertBase64(file) async{
List<int> imageBytes = fileImage.readAsBytesSync();
String base64Image = await 'data:image/png;base64,' + base64Encode(imageBytes);
// print('length of image bytes ${base64Image.length}');
return base64Image;
}
It shows me an error :
exception---- Converting object to an encodable object failed: Instance of 'Future<dynamic>'
If I use without future it directly pass to next step without converting to base64 String. It usually takes time to convert.

The variable fileImage doesn't seem to match the variable file passed to the function. Might this be the one causing the issue?
I'm curious on why the need to call await on a String - this seems to be unnecessary. The error might be caused on how convertBase64() was called. For async methods like Future<T>, I suggest calling it like:
convertBase64(imageFile).then((String base64Image) {
// Handle base64Image
});
Also, as previously recommended in the comments, it's better to use Uri.dataFromBytes() instead of parsing the encoded String on your own.
Future<String> convertBase64(File file) async{
List<int> imageBytes = file.readAsBytesSync();
return Uri.dataFromBytes(imageBytes, mimeType: "image/png").toString();
}

Related

createdAt updatedAt aqueduct

In mongoose, there's the timestamp: true option to a schema, which auto-populates a createdAt and updatedAt for any model item added.
Is there something similar in Aqueduct?
If not, how do I manually do so?
I currently tried this, which is failing, as usual:
#Operation.post()
Future<Response> createICD(#Bind.body() ICD body) async {
body.createdAt = DateTime.now();
final query = Query<ICD>(context)..values = body;
final insertICD = await query.insert();
return Response.ok({'state': true, 'data': insertICD});
}
Error from the above approach is:
Converting object to an encodable object failed: Instance of 'ICD'
It's failing when you send the response; you need to call asMap() on insertICD. The response body object you are providing is a standard Dart map - it doesn't have any special encoding behavior, so it doesn't know how to encode a complex type like ManagedObject. Invoke asMap() on the managed object to convert it to a standard Dart map:
#Operation.post()
Future<Response> createICD(#Bind.body() ICD body) async {
body.createdAt = DateTime.now();
final query = Query<ICD>(context)..values = body;
final insertICD = await query.insert();
return Response.ok({'state': true, 'data': insertICD.asMap()});
}
Also, see http://aqueduct.io/docs/db/validations/#update-and-insert-callbacks for setting timestamps at create/update events.

Convert a UInt8List to Image in flutter/dart-ui

I have this scenario where I have to get a UInt8List from an image like that:
List stuff = image.toByteData().buffer.asUInt8List()
Do some manipulations and get back to a Image.
I've tried the following:
List stuff = image.toByteData().buffer.asUInt8List()
ui.decodeImageFromList(stuff, (image){
// do stuff with image
});
But I keep getting this Exception:
E/flutter (10201): [ERROR:flutter/lib/ui/painting/codec.cc(97)] Failed decoding image. Data is either invalid, or it is encoded using an unsupported format.
E/flutter (10201): [ERROR:flutter/shell/common/shell.cc(186)] Dart Error: Unhandled exception:
...
Take notice that even without any changes in the List the exception is thrown. How can I make the list have a encodable format?
You can use memory image as given below, for the direct byte rendering
child: Image.memory(Uint8List bytes);
You can use MemoryImage class to convert a Uint8List to image.
var _image = MemoryImage(image);
You can find more details about this class here
ui.Image can turn itself into an RGBA bitmap (or PNG), but cannot convert itself back from a bitmap. (The reason for this is that there isn't any way to tell the image codec things like the color depth, geometry, etc.) The solution is to add a BMP file header onto the front of your bitmap, where you can describe those missing things, then pass that to instantiateImageCodec. See this answer, but note that in that case the bitmap in question had a strange packed color map. In your case of 32 bit RGBA, the header would be even simpler.
use this.
static Future<ui.Image> bytesToImage(Uint8List imgBytes) async{
ui.Codec codec = await ui.instantiateImageCodec(imgBytes);
ui.FrameInfo frame = await codec.getNextFrame();
return frame.image;
}
this method worked for me, got the reference from another answer to a similar kind of problem at stackoverflow here
Future<ui.Image> loadImage(Uint8List img) async {
final Completer<ui.Image> completer = Completer();
ui.decodeImageFromList(img, (ui.Image img) {
return completer.complete(img);
});
return completer.future;
}
Here is a tested code for you.
final directory = await getApplicationDocumentsDirectory();
final pathOfImage = await File('${directory.path}/legendary.png').create();
final Uint8List bytes = stuff.buffer.asUint8List();
await pathOfImage.writeAsBytes(bytes);
final Uint8List bytes = stuff.buffer.asUint8List();
Here, stuff refers to the Uint8List that should be converted to an image.

Grab a single value from json response

First check two screen shots. One is debug error one is for json data visual view to give you better understanding. My main goal is to grab only "campaignId" value form this json response. I already tried to use JObject parse but getting error because RestSharp output not json string format so. Now tell me how can i grab that "campaignId" value of json response. Thanks in advance.
static void addEmailToList(string ListName, string Email, string Name)
{
var client = new RestClient("https://api.getresponse.com/v3/campaigns?query[name]="+ListName);
var GetIdreq = new RestRequest(Method.GET);
GetIdreq.AddHeader("X-Auth-Token", "api-key 948df-my-key-7f3c6");
GetIdreq.AddParameter("application/json", ParameterType.RequestBody);
var GetIdres = client.Execute(GetIdreq);
dynamic data = JObject.Parse(GetIdres);
}
You should assign the value of Content of response to your local variable. You can try this.
var GetIdres = client.Execute(GetIdreq).Content;
dynamic data = JObject.Parse(GetIdres);

IronResponse calls an JsObjectImpl object, but I cant find class docs on it

I was trying to parse the return of an IronAjax success handler and set the response to an instance of Map. It seems to not like that.
My HTML Markup is:
<iron-ajax id="myAjaxId" auto
url="http://localhost:12345/test_server/v1/daily"
handle-as="json"
on-response="handleResponse" on-error="handleError"></iron-ajax>
My Dart Code is:
void handleResponse(CustomEventWrapper cew, IronRequest ir){
print("inside handleResponse");
var data = ir.response; // <-- is type JsObjectImpl
print("data");
print(data);
if (data == null) return;
print ("About to set rows");
List<Map> rows = data.containsKey("data") ? data["data"] : [];
print("Variables are Set locally");
$['myDatagrid'].render();
}
#reflectable
String camelToFormal (String input){
String out;
RegExp regex = new RegExp("([A-Z])");
out = input[0].toUpperCase() + input.substring(1).replaceAllMapped(regex, (Match m) => " ${m[1]}");
return out;
}
#reflectable
void handleError(CustomEventWrapper cew, IronRequest ir){
print("____Error:____");
print(ir.response);
}
The Error I get is:
type 'JsObjectImpl' is not a subtype of type 'Map' of 'other'.
I wasnt sure if I need to run convert over it, even though the return type set by IronAjax was json
So, since ir.response will either be set or null, i check if it is null first. the var data line in responseHandler currently sets is, but i have also attempted to do something like: Map data = new Map.from(ir.response); which fails as well.
Even though this is said to be handled as JSON, and is returning a jslint confirmed objected, it seems to have issues to convert it to a proper map instance.
According to Polymer IronRequest at: https://elements.polymer-project.org/elements/iron-ajax?active=iron-request
it says that responseis *, the parsed response body. Am I mistaken as to how this is properly set up, or am I missing something?
You could try Object instead of map on the property and then use convertToDart. Not sure this results in a Map but worth a try I guess. See also Polymer 1.0 - iron-list - selection

Dart Date String Formatting [duplicate]

Is there a function to do urlencoding in Dart? I am doing a AJAX call using XMLHttpRequest object and I need the url to be url encoded.
I did a search on dartlang.org, but it didn't turn up any results.
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri
Update: There is now support for encode/decode URI in the Dart Uri class
Dart's URI code is placed in a separate library called dart:uri (so it can be shared between both dart:html and dart:io). It looks like it currently does not include a urlencode function so your best alternative, for now, is probably to use this Dart implementation of JavaScript's encodeUriComponent.
Uri.encodeComponent(url); // To encode url
Uri.decodeComponent(encodedUrl); // To decode url
I wrote this small function to convert a Map into a URL encoded string, which may be what you're looking for.
String encodeMap(Map data) {
return data.keys.map((key) => "${Uri.encodeComponent(key)}=${Uri.encodeComponent(data[key])}").join("&");
}
I dont' think there is yet. Check out http://unpythonic.blogspot.com/2011/11/oauth20-and-jsonp-with-dartin-web.html and the encodeComponent method.
Note, it's lacking some characters too, it needs to be expanded. Dart really should have this built in and easy to get to. It may have it in fact, but I didn't find it.
Safe Url Encoding in flutter
Ex.
String url = 'http://example.org/';
String postDataKey = "requestParam="
String postData = 'hdfhghdf+fdfbjdfjjndf'
In Case of get request :
Uri.encodeComponent(url+postDataKey+postData);
In Case of Post Data Request use flutter_inappwebview library
var data = postDataKey + Uri.encodeComponent(postData);
webViewController.postUrl(url: Uri.parse(url), postData: utf8.encode(data));
Uri.encodeComponent() is correct, Uri.encodeFull() has a bug, see below example:
void main() {
print('$text\n');
var coded = Uri.encodeFull(text);
print(coded);
print('\n');
coded = Uri.encodeComponent(text);
print(coded);
}
var text = '#2020-02-29T142022Z_1523651918_RC2EAF9OOHDB_RT.jpg';

Resources