Dart programming calling the method from another class - dart

I need some help here i am trying to this getdetails.getuserid method in the another class but i am getting error like this type 'Future<dynamic>' is not a subtype of type 'String'
class getdetails {
Future<Null> getuserid() async {
SharedPreferences pref = await SharedPreferences.getInstance();
String userid = pref.getString('userid');
return userid;
}
}
I am getting this error Closure: () => dynamic from Function 'getuserid': static.() in dart if i try to call like below
String getuserid() async {
SharedPreferences pref = await SharedPreferences.getInstance();
String userid = pref.getString('userid');
return userid;
}

You need to define the return type of your function to Future<String>
Future<String> getuserid() async {
....
}

remove null and place String after Future...
Future

You have got quiet a few errors there .
1. In the first code sample you were returning a null future while your code you were returning a string . that dosen't make any sense.
2. In your second code sample you are returning just a string while your function is an async function so its another error that might even be shown to u on whichever IDE you are working with .
something like -> you need to return a future . So it should be Future
as mentioned in the previous answer.
Future<String>
Create a String var just say
String userId = "";
inside your class getdetails.
then inside your function getuserid() do this supposing that you already have some value in userid key that you are using for shared preferences.
getuserid() async{
SharedPreferences pref = await SharedPreferences.getInstance();
String u = pref.getString('userid');
userId = u ;
}
now create another function in same class just to make things simple and clear .
String userdetails(){
return userId;
}
now in the class/widget(stateful/stateless) where you want to get the userId do this :-
create an object of that class like this
getdetails g ;
now call the functions created like this ..
g.getuserid().then((){
String ID = g.userdetails();
});
What i am doing here is first create a function that gets your value and stores it into a local variable then call another function to get the value of that local variable when the value have been retrieved from the shared prefs class and stored into that local variable using the same object i.e why i used .then((){}) function
I hope it helps .

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.

Save string from firestore to variable

I am trying to get a value from firestore and save it to a variable in flutter. I tried using StreamBuilder, but since i am not building a widget it does not work.
To clarify my problem, I am trying to get a url from a firestore document and then open it when i press a button in the app.
I also tried to adapt code i found in another question, but that returns null.
Future _getUrl() async{
DocumentReference docRef = Firestore.instance.collection('information').document('pdf');
var data;
docRef.get().then((datasnapshot){
data = datasnapshot.data['url'];
});
return data;
}
The collection is called information, the document pdf, and the field url
This method will return null because you are not waiting for the get() future to return before you return data. docRef.get() is a Future, so it will execute asychronously. Meanwhile, your program will move on to the next line, which is return data.
Something like this would do what you want I think:
Future _getUrl() async{
DocumentReference docRef = Firestore.instance.collection('information').document('pdf');
return docRef.get().then((datasnapshot){
return datasnapshot.data['url'];
});
}
Since _getUrl is already marked as async you can also use await in its body to return the right value:
Future _getUrl() async {
DocumentReference docRef = Firestore.instance.collection('information').document('pdf');
await datasnapshot = docRef.get();
let data = datasnapshot.data['url'];
return data;
}

Push objects into array in Dart

List returnMovies = [];
Future<List> _getData() async {
final response = await http.get("https:../getTodayMovies",
headers: {HttpHeaders.AUTHORIZATION: Acess_Token.access_token});
if (response.body != null) {
returnMovies = json.decode(response.body);
.....
setState(() {});
} else {
final responseUpcoming = await http.get("/upcoming",
headers: {HttpHeaders.AUTHORIZATION: Acess_Token.access_token});
returnMovies = json.decode(responseUpcoming.body);
}
The response.body looks like:
[{"id":394470548,"host_group_name":"heyab redda","movie_image":"..png","type":"horror","code":"X123","name":"Lovely","start_time":1554364800,"end_time":1554393600,"}]
The responseUpcoming.body looks like:
{"id":394470545,"host_group_name":"foo redda","movie_image":".png","type":"horror","code":"X123","name":"Lovely","start_time":1554364800,"end_time":1554393600,"}, {"id":394470548,"host_group_name":"foo1 redda","movie_image":"..png","type":"comic","code":"X125","name":"Lovely1","start_time":1554364800,"end_time":1554393600,"}
The error I get is: String, dynamic is not a subtype of type List<dynamic>.
In the first API call that I am doing I normally get in return an array of objects, however, when this is empty, the second API call returns a list of objects that I want to push into the array called returnMovies, how can I achieve this?? Is there any way to .push these objects in the array?? So then I want to use this array to build dynamically a Listview.builder.
Also is it correct the way I am declaring it? I am quite new on Dart. Thank you
Sounds like you are looking for addAll
returnMovies.addAll(json.decode(returnUpcoming.body))
I will suggest to use
returnMovies.addAll({your object here})
When you do this json.decode(response.body) you are getting a List of Map you should use List<dynamic> movieListData and get the items like this:
movieListData = json.decode(response.body);
returnMovies = movieListData.map((dynamic movieData) {
String id = movieData['_id'];
String host_group_name = movieData['host_group_name'];
String duration = movieData['duration'];
return new Movie(id,title, duration);
}).toList();

Why toList() creates a List<dynamic> in Dart?

I have this method, which compiles with no problems in Dart 2. However at run-time I get the following error
type 'List<dynamic>' is not a subtype of type 'List<ExchangeRate>'
As you see in the code I create and return new ExchangeRate objects within .map() and then after that I return a rateEntries.toList() which I expect to be of type List<ExchangeRate>, however it seems to be inferred as type List<dynamic>!!!
#override
Future<List<ExchangeRate>> getExchangeRatesAt(DateTime time, Currency baseCurrency) async {
final http.Client client = http.Client();
final String uri = "some uri ...";
return await client
.get(uri)
.then((response) {
var jsonEntries = json.decode(response.body) as Map<String, dynamic>;
var rateJsonEntries = jsonEntries["rates"].entries.toList();
var rateEntries = rateJsonEntries.map((x) {
return new ExchangeRate(x.value.toDouble());
});
return rateEntries.toList(); // WHY IS IT RETURNING A List<dynamic> here?
})
.catchError((e) => print(e))
.whenComplete(() => client.close());
}
However if I cast it specifically to ExchangeRate it would be fine.
return rateEntries.toList().cast<ExchangeRate>();
This casting at the end seems redundant to me, why should I need it?
Well, it seems that the cast is necessary to fully define the type.
But, you can avoid the cast if you add any of the following snippets:
Give the correct type to the rateJsonEntries variable
List<dynamic> rateJsonEntries = jsonEntries["rates"].entries.toList();
For whatever reason this works in my case.
Add the parameter type to the map() method
var rateEntries = rateJsonEntries.map<ExchangeRate>((x) {
return new ExchangeRate(x.value.toDouble());
});

mvvmcross showviewmodel byte[] as param

I work with iOS throw Xamarin. I want's send byte[] from one viewModel to another using showviewmodel.
I invoke this Command:
private MvxCommand _editUser;
public System.Windows.Input.ICommand EditUser
{
get{
return new MvxCommand
(() => ShowViewModel<UserViewModel> (new {array = new byte[3]}));
}
}
and wait my byte[] as param in Init method on another viewModel(UserViewModel):
public void Init(byte[] array)
{
}
Constructor works good, but then does not reach the the Init method;
It throws an exception:
Failed to construct and initialize ViewModel for type AccountApp.Core.iOS.UserViewModel from locator MvxDefaultViewModelLocator - check MvxTrace for more information.
Any ideas?
Thanks.
Only strings, ints, doubles and bools are allowed in this constructor parameter passing at present. You would need to serialize this byte[] array to a string and then reconstruct it in the constructor of the view model you are navigating to.

Resources