error: Only static members can be accessed in initializers - flutter

i will import images BASE64 stored in DB.
code :
profileimage()async{
var userimage1 = await DBHelper().getuserIMAGE1('roro');
print(userimage1);
if(userimage1 == Null){
print('Empty');
}else{
setState(() {
userimage1.map((e) {
tmpimage = e['image0'];
}).toList();
print(tmpimage);
_TmpBytesImage = Base64Decoder().convert(tmpimage);
print(_TmpBytesImage);
return Image.memory(_TmpBytesImage);
});
}
}
File pimage = profileimage(); << error
and i got error 'flutter: Only static members can be accessed in initializers'
how can i do?

You need to call like below.
Future.delayed(Duration.zero, () {
// your code
});

The following items appear wrong:
Your return statement is inside a setstate() function so returns a value from that function.
processImage probably should be
Static Future processImage()
The call should be something like below but not at class level. It also needs to of type Image not of type File.
pimage = await processImage();
If there is nothing in the database, what do you want to return?

Related

Flutter - loop not working while parsing json

I am trying to create model and parse json data from api
for that i created the model class you can see below
class FeatureModel {
String? PlanFeatures;
bool? FeatureStatus;
FeatureModel({this.PlanFeatures, this.FeatureStatus});
FeatureModel.fromJson(parsonJson) {
PlanFeatures = parsonJson['PlanFeatures'];
FeatureStatus = parsonJson['FeatureStatus'];
}
}
now i am trying to parse json with the help of loop
let me show you my method
List<FeatureModel> featureModel = [];
Uri featureAPI = Uri.parse(
planFeatureApi);
apiCall() async {
try {
http.Response response = await http.get(featureAPI);
// print(response.statusCode);
if (response.statusCode == 200) {
var decode = json.decode(response.body);
print(decode);
for (var i = 0; i < decode.length; i++) {
print(i);
featureModel.add(
FeatureModel.fromJson(decode[i]),
);
}
}
} catch (e) {}
}
I am calling it here
onPressed: () async{
await apiCall();
}
but the problem is here
loop is not working while parsing data
in that particular code i remains on 0 only
when i removes featureModel.add( FeatureModel.fromJson(decode[i]), ); i started increaing till 10
please let me know if i am making any mistake or what
thanks in advance
Here is the sample of api respone
[{"PlanFeatures":"Video Link Sharing","FeatureStatus":"true"},{"PlanFeatures":"Email \u0026amp; Telephonic Support","FeatureStatus":"true"},{"PlanFeatures":"Remove Pixeshare Branding","FeatureStatus":"false"},{"PlanFeatures":"Add Custom logo on uploaded photos","FeatureStatus":"false"},{"PlanFeatures":"Get Visitor Info","FeatureStatus":"false"},{"PlanFeatures":"Mobile Apps","FeatureStatus":"false"},{"PlanFeatures":"Send Questionnaries","FeatureStatus":"false"},{"PlanFeatures":"Create \u0026amp; Send Quotation","FeatureStatus":"false"},{"PlanFeatures":"Online Digital Album Sharing","FeatureStatus":"false"},{"PlanFeatures":"Analytics","FeatureStatus":"false"}]
thanks
I found many errors, first, the fromJson is not a factory constructor and doesn't return a class instance from the JSON.
the second one is that the bool values from the sample you added are String not a bool so we need to check over it.
try changing your model class to this:
class FeatureModel {
String? PlanFeatures;
bool? FeatureStatus;
FeatureModel({this.PlanFeatures, this.FeatureStatus});
factory FeatureModel.fromJson(parsonJson) {
return FeatureModel(
PlanFeatures: parsonJson['PlanFeatures'],
FeatureStatus: parsonJson['FeatureStatus'] == "false" ? false : true,
);
}
}

Create a class that calls a future for reusability

I have a future that is used a few different times on some pages and I'm trying to include it instead and reference it when needed to cut down on the code overhead.
I've created a working future and wrapped it inside a class, the problem is that Flutter states that
"2 positional argument(s) expected, but 0 found."
I've tried String and Function type declarations for the client variable and I am including them, but I'm not sure what else I'm missing here?
FetchCats.getCats(client: http.Client(), filter: filter);
class FetchCats {
String client; <-- this shouldn't be string but I don't know what else to declare it as
int catType;
FetchCats({Key? key, required this.client, required this.catType});
Future<List<CatDetails>> getCats(http.Client client, int catType) async {
var ct = catType;
var catResults;
var response = await client.get(Uri.parse('/cats/breeds/$ct/'));
if (response.statusCode == 200) {
catResults = compute(convertCatDetails, response.body);
} else {
print("error");
}
return catResults;
}
}
List<CatDetails> convertCatDetails(String responseBody) {
final parsed = jsonDecode(responseBody).cast<Map<String, dynamic>>();
return parsed
.map<CatDetails>((json) => CatDetails.fromJson(json))
.toList();
}
Your function is defined using positional parameters, rather than named parameters, but you are calling it with named arguments.
Here are a few changes that should allow you to use the class as I think you're intending:
It's not necessary to store catType on the class, since that's something you would probably change between requests - so it makes more sense to only pass it into the getCats function.
To fix the positional parameter issue, you can also change catType into a named parameter.
You don't need a Key parameter on the constructor - those are usually used with Widgets.
The type of the client should be http.Client, not String.
With those changes, your class should look something like this:
class FetchCats {
final http.Client client;
FetchCats({required this.client});
Future<List<CatDetails>> getCats({required int catType}) async {
int ct = catType;
var catResults;
var response = await client.get(Uri.parse('/cats/breeds/$ct/'));
if (response.statusCode == 200) {
catResults = compute(convertCatDetails, response.body);
} else {
print("error");
// Return an empty list, rather than the uninitialized catResults
return [];
}
return catResults;
}
}

How to use a variable for method name

I want to use a variable to access a certain value in my hive database:
In the code below if I use myBox.getAt(i).attributeSelect I get an error because attributeSelect is not defined for the box.
If I use myBox.getAt(i).test it works. How can I make flutter recognise that attributeSelect is a variable and put the value there? I have a total of 181 different variables the user can choose from. Do I really need that many if clauses? The variables are booleans. So I want to check if that attribute is true for the document at index i.
Error: NoSuchMethodError: 'attributeSelect'
method not found
Receiver: Instance of 'HiveDocMod'
attributeSelect = 'test'; //value depends on user choice
Future<void> queryHiveDocs() async {
final myBox = await Hive.openBox('my');
for (var i = 0; i < myBox.length; i++) {
if (attributeSelect == 'All Documents') {
_hiveDocs.add(myBox.getAt(i)); // get all documents
//print(myBox.getAt(24).vesselId);
} else {
// Query for attribute
if (myBox.getAt(i).attributeSelect) {
_hiveDocs.add(myBox.getAt(i)); // get only docs where the attributeSelect is true
}
}
}
setState(() {
_hiveDocs = _hiveDocs;
_isLoading = false;
});
}
I solved it the annoyingly hard way:
if (attributeSelect == 'crsAirCompressor') {
if (myBox.getAt(i).crsAirCompressor) {
_hiveDocs.add(myBox.getAt(i));
}
} else if (attributeSelect == 'crsBatteries') {
if (myBox.getAt(i).crsBatteries) {
_hiveDocs.add(myBox.getAt(i));
}...

Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)

I tried to fetch data from the internet with moviedb API, I followed the tutorial at https://flutter.io/cookbook/networking/fetch-data/
but I'm getting the below error.
Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function 'createDataList':.)
This my code
Future<List<DataModel>> fetchData() async{
final response = await http.get("https://api.themoviedb.org/3/movie/now_playing?api_key=d81172160acd9daaf6e477f2b306e423&language=en-US");
if(response.statusCode == 200){
return compute(createDataList,response.body.toString());
}
}
List<DataModel> createDataList(String responFroJson) {
final parse = json.decode(responFroJson).cast<Map<String, dynamic>>();
return parse.map<DataModel> ((json) => DataModel.fromtJson(json)).toList();
}
Screenshot of the error message
compute can only take a top-level function, but not instance or static methods.
Top-level functions are functions declared not inside a class
and not inside another function
List<DataModel> createDataList(String responFroJson) {
...
}
class SomeClass { ... }
should fix it.
https://docs.flutter.io/flutter/foundation/compute.html
R is the type of the value returned. The callback argument must be a top-level function, not a closure or an instance or static method of a class.
As per today (2020. Aug) the compute is working fine with static methods.
For me, the issue was that I was trying to return a http.Response object from the compute() methods.
What I did is I've created a simplified version of this class, containing what I need:
class SimpleHttpResponse {
String body;
int statusCode;
Map<String, String> headers;
}
Then I've updated the original method from this:
static Future<http.Response> _executePostRequest(EsBridge bridge) async {
return await http.post(Settings.bridgeUrl, body: bridge.toEncryptedMessage());
}
to this:
static Future<SimpleHttpResponse> _executePostRequest(EsBridge bridge) async {
http.Response result = await http.post(Settings.bridgeUrl, body: bridge.toEncryptedMessage());
if (result == null) {
return null;
}
SimpleHttpResponse shr = new SimpleHttpResponse();
shr.body = result.body;
shr.headers = result.headers;
shr.statusCode = result.statusCode;
return shr;
}
Worked like charm after this change. Hope this helps somebody ranning into similar problem.

Resolving Promise Angular 2

I have the following problem.
In a function I have a promise as a return type. This function is in the class Hierarchy.
updateNodeValues(entity: String, data: {}): Promise<any>{
let jsonBody = JSON.stringify(data);
let url = environment.endpointCore + '/api/' + entity + '/' + data['id'];
return this.http.put(url, jsonBody, this.options)
.toPromise()
.then(response => {
return response;
})
.catch(this.handleError);
}
This function is in class node.
onSubmit(): void{
var currentForm = this.form.value;
var entityName = this.inflection.classify(this.node.type).toLowerCase();
var requiredData = {};
for(var i = 0; i < this.formItems.length; i++){
this.formItems[i].value = currentForm[Object.keys(currentForm)[i]];
}
for(var i=0; i<this.formItems.length; i++){
requiredData[this.globalService.camelize(this.formItems[i].label)] = this.formItems[i].value
}
Promise.resolve(this.hierarchyService.updateNodeValues(entityName, requiredData)).then(response => {
alert(response.ok);
if(response.ok){
this.globalService.showSuccessMessage('Values updated');
this.refreshGui(requiredData);
}
});
this.editMode = false;
}
The problem is that when i try to resolve promise and invoke this.refreshGui(requireddata) nothing is happening. I have read about how the fat arrow is preserving the 'context' of this, and I do not understand why invoking this method is not doing anything, while invoking successMessage produces expected outcome.
The method that I am invoking looks like this, and it is also in the class node.
private refreshGui(data: {}){
this._node.data = data;
this.objectProperties = new Array();
this.nodeChildren = new Array();
for (var property in data) {
var propertyValue = data[property];
if (propertyValue instanceof Array) {
this.nodeChildren.push({label: property, value: "total: ".concat(propertyValue.length.toString())});
} else {
this.objectProperties.push({label: property, value: propertyValue});
}
}
}
The solution that I found to be working was to implement custom event. The problem was that within the async callback resolution, the context of what this is would "get lost". The fat arrow enabled me to invoke class method with this, but the properties within the would be "lost". Because of this reason I have took the logic from the method, and put it in the callback part and set expected and needed results in some variable. This variable was passed to my custom event and set to class variable in the custom event handler appropriately.