GetX doesn't accept method parameters either - flutter

I cannot use the ".obs" property variables that I have created as parameters in my api service methods. and it gives the error The prefix 'coinTwo' can't be used here because it is shadowed by a local declaration.
Try renaming either the prefix or the local declaration.
I wrote the problem in getx, but they did not understand the problem.
I would appreciate it if you could take a look at my issue on github.
İssue link: text
I would appreciate it if you could take a look at my issue on github.
İssue link: text

Your problem is in the declaration of getOrderBookData
Instead of
getOrderBookData(coinOne.value, coinTwo.value) async {
...
you should either have
getOrderBookData() async {
...
//Do stuff with coinOne.value, coinTwo.value
...
OR
getOrderBookData(String firstCoin, String secondCoin) async {
coinOne.value = firstCoin;
coinTwo.value = secondCoin;
...
Edit
Seeing your post on GetX's Github, it looks like you're missing some basic understanding on how functions and methods work.
The code you wrote is the equivalent of the following method signature :
getOrderBookData("aValue", "anotherValue") async {
and it doesn't makes any sense.
Your method's signature should only declare the parameters it's expecting and their type.
You can also define a default value for those parameters if needed.
getOrderBookData({String firstCoin = coinOne.value, String secondCoin = coinTwo.value}) async {

in function declarations you just tell what type it is, and not actual values
So either do
getOrderbookData(String one, String two) async {
var res = await api.fetchOrderBookData(one, two);
purchase.value = res.result!.buy!;
sales.value = res.result!.sell!;
}
or hardcode it to always use coinOne and coinTwo and give no parameters
getOrderbookData() async {
var res = await api.fetchOrderBookData(coinOne.value, coinTwo.value);
purchase.value = res.result!.buy!;
sales.value = res.result!.sell!;
}

Make these changes and the error will be gone.
First, make a minor change to your getOrderBookData method:
void getOrderBookData() async {...} // Don't pass any parameter here.
And then make a change to your onInit method too.
#override
void onInit() {
getOrderBookData();
super.onInit();
}

Related

Call _method not producing result Flutter

The issue seems to be around calling a method with a _ before it, such as Future _showFirstPolylineMapMarkers
In my main.dart at the end of a method I call 2 entities, one is within main.dart and works fine, the other is in another Class, _mapItemsExample2.
...
_sendIntermodalDataToSecondScreen(context, mappedValues, dest); //works fine
_mapItemsExample2?.getroute(deplat, deplong, deplocname);
}
});
}
It will pass data to
Future getroute(deplat, deplong, deplocname) async {
print('getroutetest');
_showFirstPolylineMapMarkers(deplat, deplong, deplocname);
}
void _showFirstPolylineMapMarkers(deplat, deplong, deplocname) async {
...
But it goes dead and doesn't print or call _showFirstPolylineMapMarkers
If i replace .getroute... with ._showFirstPolylineMapMarkers(deplat, deplong, deplocname) to call the method directly it shows an error
The method '_showFirstPolylineMapMarkers' isn't defined for the type 'MapItemsExample2'.
If i remove the underscore at the start _ errors go away but it doesnt call it when ran
Any guidance appreciated
Thank you
The _ indicates a private field or method, meaning that it can only be used within the file it's defined in.
It is a good practice to use the _ to make methods private to ensure they're only used where they are defined.

How to test a void function in Dart?

I am new to unit tests in Dart/Flutter and I would like to write a test for a void function. When functions return something I am writing a test like this:
test('Gets user save', () async {
final userSave = await mockSource!.getUserSave();
expect(userSave!.age, equals(20));
});
In such a scenario like above expect can be used since getUserSave function returns a user model.
How about checking if test passes of fails for a void/Future function like below? I can not use expect because it does not return a value.
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.clear();
}
I use flutter_test and mockito for testing.
Typically a void function will produce a side effect of some sort. When writing a test for a void function, I would check whatever state is effected by the void function before and after calling the function to be sure that the desired side effect has occurred.
In this specific case, you are calling clear on a DatabaseClient. I don't know the specifics of the DatabaseClient api, but I would construct a test where the client contains some data before calling clear, and then check that the data is no longer there after calling clear.
Something along the lines of this:
Future<void> clearUserSave() async {
DatabaseClient mockDBClient = MockDatabaseClientImpl();
mockDBClient.add(SOMEDATA);
expect(mockDBClient.hasData, true);
mockDBClient.clear();
expect(mockDBClient.hasData, false);
}
you can add nullable variable and assign variable value in method, after call method check if this varaible isNotNull
like this:
test('Gets user save', () async {
await mockSource?.getUserSave();
final userSave=mockSource.user;
expect(userSave,isNotNull );
});
testing a function that return void :
expect(
() async => await functionThatReturnsVoid(),
isA<void>(),
);

How can I access a variable from another file in dart

I am trying to access a variable called _countryfrom another file in dart, but an error occured: The getter '_country' isn't defined for the type 'CurrentCountry'.
Here's the code where the variable I want to access is(in another file):
class CurrentCountry {
static String _country = 'All';
}
And here's the code where I want to access the variable:
Future<Map<String, dynamic>> fetchWorldData() async {
Response activeResponse = await get(Uri.parse(
'https://disease.sh/v3/covid-19/countries/${CurrentCountry._country}'));
return json.decode(activeResponse.body);
}
If you can help me, I will be very grateful.
You should remove the underscore of the variable.
If an identifier starts with an underscore (_), it’s private to its
library
Reference here: Dart language Important concepts

How to check 'late' variable is initialized in Dart

In kotlin we can check if the 'late' type variables are initialized like below
lateinit var file: File
if (this::file.isInitialized) { ... }
Is it possible to do something similar to this in Dart..?
Unfortunately this is not possible.
From the docs:
AVOID late variables if you need to check whether they are initialized.
Dart offers no way to tell if a late variable has been initialized or
assigned to. If you access it, it either immediately runs the
initializer (if it has one) or throws an exception. Sometimes you have
some state that’s lazily initialized where late might be a good fit,
but you also need to be able to tell if the initialization has
happened yet.
Although you could detect initialization by storing the state in a
late variable and having a separate boolean field that tracks whether
the variable has been set, that’s redundant because Dart internally
maintains the initialized status of the late variable. Instead, it’s
usually clearer to make the variable non-late and nullable. Then you
can see if the variable has been initialized by checking for null.
Of course, if null is a valid initialized value for the variable, then
it probably does make sense to have a separate boolean field.
https://dart.dev/guides/language/effective-dart/usage#avoid-late-variables-if-you-need-to-check-whether-they-are-initialized
Some tips I came up with from advice of different dart maintainers, and my self-analysis:
late usage tips:
Do not use late modifier on variables if you are going to check them for initialization later.
Do not use late modifier for public-facing variables, only for private variables (prefixed with _). Responsibility of initialization should not be delegated to API users. EDIT: as Irhn mentioned, this rule makes sense for late final variables only with no initializer expression, they should not be public. Otherwise there are valid use cases for exposing late variables. Please see his descriptive comment!
Do make sure to initialize late variables in all constructors, exiting and emerging ones.
Do be cautious when initializing a late variable inside unreachable code scenarios. Examples:
late variable initialized in if clause but there's no initialization in else, and vice-versa.
Some control-flow short-circuit/early-exit preventing execution to reach the line where late variable is initialized.
Please point out any errors/additions to this.
Enjoy!
Sources:
eernstg's take
Hixie's take
lrhn's take
leafpetersen's final verdict as of 2021 10 22
Effective Dart
Self-analysis on how to approach this with some common-sense.
You can create a Late class and use extensions like below:
import 'dart:async';
import 'package:flutter/foundation.dart';
class Late<T> {
ValueNotifier<bool> _initialization = ValueNotifier(false);
late T _val;
Late([T? value]) {
if (value != null) {
this.val = value;
}
}
get isInitialized {
return _initialization.value;
}
T get val => _val;
set val(T val) => this
.._initialization.value = true
.._val = val;
}
extension LateExtension<T> on T {
Late<T> get late => Late<T>();
}
extension ExtLate on Late {
Future<bool> get wait {
Completer<bool> completer = Completer();
this._initialization.addListener(() async {
completer.complete(this._initialization.value);
});
return completer.future;
}
}
Create late variables with isInitialized property:
var lateString = "".late;
var lateInt = 0.late;
//or
Late<String> typedLateString = Late();
Late<int> typedLateInt = Late();
and use like this:
print(lateString.isInitialized)
print(lateString.val)
lateString.val = "initializing here";
Even you can wait for initialization with this class:
Late<String> lateVariable = Late();
lateTest() async {
if(!lateVariable.isInitialized) {
await lateVariable.wait;
}
//use lateVariable here, after initialization.
}
Someone may kill you if they encounter it down the road, but you can wrap it in a try/catch/finally to do the detection. I like it better than a separate boolean.
We have an instance where a widget is disposed if it fails to load and contains a late controller that populates on load. The dispose fails as the controller is null, but this is the only case where the controller can be null. We wrapped the dispose in a try catch to handle this case.
Use nullable instead of late:
File? file;
File myFile;
if (file == null) {
file = File();
}
myFile = file!;
Note the exclamation mark in myFile = file!; This converts File? to File.
I'm using boolean variable when I initiliaze late varible.
My case is :
I'm using audio player and I need streams in one dart file.
I'm sharing my code block this methodology easily implement with global boolean variables to projects.
My problem was the exception i got from dispose method when user open and close the page quickly

How can I use async in a named constructor? [duplicate]

This question already has answers here:
Calling an async method from a constructor in Dart
(3 answers)
Closed 4 months ago.
I created a class, and I want to use async in a named constructor or a method in the class that is accessible outside the class. When making the named constructer return a Future type, I get an error saying: Constructors can't have a return type.
I then tried removing the Future type, and I still get an error saying The modifier 'async' can't be applied to the body of a constructor.
How can I use async in a named constructor?
class HttpService {
Future<void> HttpService.getAll() async {
final response = await http.get(
Uri.encodeFull('http://localhost:4000/'),
headers: {'headers': 'application/json'},
);
if (response.statusCode == 200) {}
}
}
I am new to oop, so I may be using it wrong? Any guidance is accepted.
Constructors can't be asynchronous. If you find yourself wanting an asynchronous constructor, you instead could make a static asynchronous method that acts like an asynchronous factory. From the perspective of the caller, there isn't much difference (and what differences there are mostly favor having a static method). You additionally could make all other constructors (including the default constructor) private to force callers to use the static method to get an instance of your class.
That said, in your case, you might not even need a class at all. Do you intend to have other methods on an HttpService? Is your HttpService maintaining any internal state? If not, then you would be better off with a freestanding function.
You can't use async in constructor. You should create a separate method for this.
Solution: 1 (Recommended)
class Foo {
static Future<void> fetch() async { // method
await future();
}
}
Solution: 2
class Foo {
Foo.named() { // named constructor
future().then((_) {
// future is completed do whatever you need
});
}
}