Flutter source - Future<String?>? Function(String) - flutter

I'm new to flutter?
Can someone explain to me what the following line of code means?
typedef RecoverCallback = Future<String?>? Function(String);
This line is contained in the auth.dart file of the flutter_login plugin
https://github.com/NearHuscarl/flutter_login/blob/master/lib/src/providers/auth.dart
So Function(String) Where is it implemented?

typedef RecoverCallback = Future<String?>? Function(String);
It's function-type alias, gives a function type a name that you can use when declaring fields and return types.
As you can see in 45 line of class Auth implementation, that function you need to pass to the constructor of
new Auth(onRecoverPassword: yourFunction);
yourFunction must be a Function that take some String parameter and return Future<String?> or null;

The reason I want to understand the above line of code is because
final error = await auth.onRecoverPassword!(auth.email);
error = null;
but no mail is sent to auth.email.

Related

Flutter, external DLL and Pointer<Char> vs Pointer<Utf8>

I try to call the tesseract C api within flutter. So far without success. The function "TessBaseAPIInit3" requires the 2nd and 3rd parameter to be of type Pointer<Char>. The following is what dart run ffigen generated out of tesseract's capi.h:
import 'dart:ffi' as ffi;
...
int TessBaseAPIInit3(
ffi.Pointer<TessBaseAPI> handle,
ffi.Pointer<ffi.Char> datapath,
ffi.Pointer<ffi.Char> language,
) {
return _TessBaseAPIInit3(
handle,
datapath,
language,
);
}
late final _TessBaseAPIInit3Ptr = _lookup<
ffi.NativeFunction<
ffi.Int Function(ffi.Pointer<TessBaseAPI>, ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>)>>('TessBaseAPIInit3');
late final _TessBaseAPIInit3 = _TessBaseAPIInit3Ptr.asFunction<
int Function(ffi.Pointer<TessBaseAPI>, ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>)>();
The following is my code which calls TessBaseAPIInit3 which requires 3 parameters of type Pointer<TessBaseAPI>, Pointer<Char>, Pointer<Char>. The string literals i create with toNativeUtf8 have type Pointer<Utf8> which i cast to Pointer<Char> in the hope that they are equivalent. But the cast from Pointer<Utf8> to Pointer<Char> gives an error.
import 'dart:ffi';
...
final DynamicLibrary tesseractDLL = DynamicLibrary.open(Platform.script.resolve("build/windows/runner/Debug/libtesseract-5.dll").toFilePath());
NativeLibrary tesseractLib = NativeLibrary(tesseractDLL);
final handle = tesseractLib.TessBaseAPICreate();
final Pointer<Char> dataPath = ''.toNativeUtf8() as Pointer<Char>;
final Pointer<Char> language = 'eng'.toNativeUtf8() as Pointer<Char>;
if (tesseractLib.TessBaseAPIInit3(handle, dataPath, language) != 0)
print("Error initializing tesseract\n");
The error message is: [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'Pointer<Utf8>' is not a subtype of type 'Pointer<Char>' in type cast
Any ideas what goes wrong? I have no idea how to create a string literal of type Pointer<Char>. The function 'toNativeUtf8' generates Pointer<Utf8>.
Is this "the right way" to call tesseract functions? Is it possible to use the c++ api anyhow? I don't want to use any wrapper, i would like to interact with the tesseract api directly.
Following did the trick. The native utf8 string needed to be cast to Char.
final dataPath = ''.toNativeUtf8().cast<Char>();
final language = 'eng'.toNativeUtf8().cast<Char>();

Flutter/Dart API Call Throws Error (sometimes)

APIs:
https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY
https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY
API Call Method:
import 'package:http/http.dart';
import '../Models/fetched_data.dart';
Future<FetchedData?> fetchIndexDetails(String index) async {
final String url =
'https://www.nseindia.com/api/option-chain-indices?symbol=$index';
try {
final response = await get(
Uri.parse(url),
);
final FetchedData? fetchedData = fetchedDataFromJson(response.body);
return fetchedData;
} catch (e) {
print('$index Error: $e');
}
return null;
}
The json file is same for both the APIs, hence the model class too.
However, the second API call works smoothly but the first API call throws an error saying:
type 'double' is not a subtype of type 'int?'
Can anybody help me decode the problem here? Much tia :)
This is a JSON parsing issue for unmatched type parsing of the API and the your Dart Model ..
How to diagnose it?
You can always catch those errors while the development by enabling the dart debugger for uncaught exceptions, which gives you exactly the broken casting
type 'double' is not a subtype of type 'int?'
The API has returned a double value where an int is expected.
In your model or where appropriate replace the expected type to use num which int and double are both subtypes of
Check your model class where you have defined different variables and match with data type you are getting in response from the json.
There must be a variable you have defined in model class as int? but u r getting double as a response so u got to convert the data type .
Seems like you are trying to map a double to int?, the response had a double and you are assigning it to int?, add a breakpoint when mapping the response to see the corresponding field. You can try casting it to int or just changing the type all together.

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

Flutter Dart Function as a Parameter to Another Function

I was looking into the documentation and failed to find an answer to my question:
Suppose I have a function the returns a Future<String> that I want to imbed in a second function which could take any other function that is of type Future<String>, the syntax -if I am not wrong- would be:
String functionTwo(Future<User> Function() putFunctionHere) async {
await code
return 'some string';
}
If I had to guess with regards to Dart syntax, I would say that it would be:
String functionTwo(Function putFunctionHere){...}
Which leads me to my question, why do we have to specify Future<User> Function() is it the only way?
And why do we have to put the parentheses next to Function
The syntax are as follow:
OutputType Function(ParameterType1 paramater1, ParameterType2 parameter2...) nameOfFunctionForUsageInsideTheMethod
So the following can be read we take a function as argument which must return Future<User> and takes no arguments.
Future<User> Function() putFunctionHere
This function can then be referred to as putFunctionHere like:
final value = await putFunctionHere()

Unable to use generic function in a generic function

I have the following class in my code
abstract class DatabaseKey<T> implements Built<DatabaseKey<T>, DatabaseKeyBuilder<T>> {
DatabaseKey._();
factory DatabaseKey([void Function(DatabaseKeyBuilder<T>) updates]) = _$DatabaseKey<T>;
String get name;
}
Then, I define the following generic typedef function:
typedef ObserveDatabaseEntity = Observable<DatabaseEntity<T>> Function<T>(DatabaseKey<T> key);
But, when I try to use it as follows, the code has an error.
static ObserveConfigurationValue observe(
GetConfigurationState getState,
ObserveDatabaseEntity observeDatabaseEntity,
) {
assert(getState != null);
assert(observeDatabaseEntity != null);
return <KT>(ConfigKey<KT> key) {
return Observable.just(getState())
.flatMap((state) {
final dbKey = _databaseKeyFromConfig<KT>(key);
return observeDatabaseEntity(dbKey)
.map(_configValueFromDatabaseEntity);
});
}
}
DatabaseKey<T> _databaseKeyFromConfig<T>(ConfigKey<T> key) {
return DatabaseKey((build) => build
..name = key.value,
);
}
The error I am getting is:
The argument type DatabaseKey can't be assigned to the parameter DatabaseKey.
I see nothing wrong with this code or why it shouldn't work, but maybe my understanding of what can be written in Dart is wrong. What would be the correct way to write this, if possible at all?
EDIT#1:
Note:
The typedef ObserveDatabaseEntity is in one file
The static ObserveConfigurationValue observe(GetConfigurationState getState, ObserveDatabaseEntity observeDatabaseEntity) is is another file
From playing around, it seems that placing them in a single file, the error disappears.
Still, I believe that this should work in separate files as well,
This error looks like an import mismatch.
In dart, you can import file either through relative path or package.
import 'lib/some_file.dart'; //relative
import 'package:myapp/lib/some_file.dart'; //package
There's really no better way but once you choose one, you have to stick to it. If you don't (meaning you have imported a file using a package import and the same file elsewhere with a relative path) Dart will place them in two different namespaces and think they are two different classes.