Using initialized String in asynchronous anonymous function in another page - flutter

how can you use String theFlag anywhere else outside of this anonymous function
I had to make it an anonymous function as I failed to point a separate asynchronous function into onPressed in a RaisedButton as it only worked with onChanged now i just need to pass String theFlag to another widget in another screen
please help and mind the beginner question
onPressed:() async {
Locale _temp = await setLocale(LanguageClass.languageList()[index].langCode);
BldrsApp.setLocale(context, _temp);
String theFlag = LanguageClass.languageList()[index].langFlag ; //I need to use this elsewhere
print(theFlag);
},

You can do it like this,
String iCanBeAcessed; //make this variable somewhere else, so that you can use it anywhere.
//Inside your anonymous function
iCanBeAcessed=theFlag;
How can i use that?
You can declare it outside a class, and can use it anywhere in your project.
Example,
//imports
String iCanBeAcessed;
class yourClassName{
//All your other functions and build method
Now, import the dart file( where you have declared the iCanBeAcessed ) in the following manner.
import dartFile.dart as flagString;
//Now, you can use this variable anywhere!
Text(flagString.iCanBeAcessed),

Related

Difference between Function and Function() in flutter [duplicate]

This question already has an answer here:
Function and Function()
(1 answer)
Closed 5 months ago.
I have a doubt where I'm passing a function as a parameter, for onPressed, like event, I would declare a field like final void Function() onPressed, There are some code where I have seen declarring fields like Function someFunction, I would like to know what is the differnce between using Function and Function(). Thanks,
The main() function came from Java-like languages so it's where all programs started, without it, you can't write any program on Flutter even without UI.
The runApp() function should return a widget that would be attached to the screen as a root of the widget Tree that will be rendered
As we can see in doc, Function is:
part of dart.core;
/// The base class for all function types.
///
/// The run-time type of a function object is subtype of a function type,
/// and as such, a subtype of [Function].
Now, Function(), is literally a function, see the example:
Here you can use this:
final Function() func = () {};
ElevatedButton(
onPressed: func;
)
But you can not:
final Function func = () {};
ElevatedButton(
onPressed: func;
)
Here you get the following error:
The argument type 'Function' can't be assigned to the parameter type 'void Function()?'.dartargument_type_not_assignable
Otherwise, you can use:
Function func() {
return () {};
}
ElevatedButton(
onPressed: func;
)
Use Function somename when you need to return a function from a method.
Use Function() somename when you need to use this, literally, as a function.
As per Flutter docs:
Function is the base class of all the function types. It means it represents all the functions.
Adding parenthesis like: Function() makes it one without any parameter.
To sum up: Function is general and Function() is more specific.
Yep, lets take a look whats is braces actualy means.
The main difference between Method(); and Method, is that in first case, you call a method instant and its all. If you'l try to do var someStuff = Method(), someStuff will get a returning value of Method();
In second case, when you use Method, you actually do not call it, because its a link to a method. Because of it is a link, you cant pass an arguments (which places in braces), and if you try to make set variable like this: var someStuff = Method;, variable someStuff will contains a link to a original Method(), and you can call it in code, and it'l work same.
That means, when you pass a link to a onPressed:, and if link has right signature (in and out param), you haven't write whats goes in method and out, all what you should to do will looks like: onPressed: Method. Dart automatically understand, what params in and out, by comparing theirs signature.

I am declaring private variable and function by creating a stateless class, but when I used function in body the function is showing error

I am declaring private variable and function by creating a stateless class, but when I used function in body the function is showing error.
1: enter image description here
Replace the Function to VoidCallback..It will work
final VoidCallback _handler;

Why can't I use local variable in a callback?

Let's say I've a stream() which returns Stream<int>. stream().listen returns StreamSubscription.
var subs = stream().listen((e) {
if (someCondition) subs.cancel(); // Error
});
I don't understand why is there an error, because by the time I start listening for events in the listen method, I would have definitely a valid object subs.
Note: I know this can be done by creating a StreamSubscription instance/top-level variable but why they have prevented the use of local variable like this?
We know that Stream.listen does not call its callback until after a value is returned, but the Dart compiler does not.
Consider the following function, which simply calls a callback and returns the result:
T execute<T>(T Function() callback) => callback();
Now, consider using it to assign a variable:
int myVariable = execute(() => myVariable + 1);
The problem here is that the given callback is called synchronously, before myVariable is assigned, but it tries to use myVariable to calculate a value!
To resolve this issue with your stream question, you can use the new late keyword. Using late tells the compiler that you know the variable will be assigned by the time it's accessed.
late final StreamSubscription<MyType> subscription;
subscription = stream().listen(/* ... */);
Likely because it's possible that subs will be used before it's assigned. We know that the callback passed to listen will be called on stream events, but it's also possible that the callback is called immediately and it's return value or a calculation done by it may be required for the return value of the function it was passed to.
Take this fakeFunc for instance, which I made an extension on the int class for convenience:
extension FakeListen on int {
int fakeFunc(int Function(int x) callback, int val) {
return callback(val);
}
}
The return value depends on the result of callback!
int subs = x.fakeFunc((e) {
print(e);
subs.toString();//error
return e + 1;
}, 5);
I can't use subs because subs will be guaranteed to not be exist at this point. It's not declared. This can be easily solved by moving the declaration to a separate line, but also forces you to make it nullable. Using late here won't even help, because subs won't exist by the time you try to use it in the callback.
Your scenario is different, but this is an example of where allowing that would fail. Your scenario involves a callback that is called asynchronously, so there shouldn't be any issues with using subs in the callback, but the analyzer doesn't know that. Even async-marked methods could have this issue as async methods run synchronously up until its first await. It's up to the programmer to make the right decision, and my guess is that this error is to prevent programmers from making mistakes.

Declare variable outside any class: why is it possible

I have a file fancy_button.dart for a custom Flutter widget FancyButton which is like:
class FancyButton extends StatefulWidget {
// ...
}
class _FancyButtonState extends State<FancyButton> {
// ...
}
// Declaration outside any class:
Map<_FancyButtonState, Color> _buttonColors = {};
final _random = Random();
int next(int min, int max) => min + _random.nextInt(max - min);
// ...
The application works just fine. Notice that I declare and use some variables outside any class. Now my question is: how is it even possible? Shouldn't everything be inside a class in Dart, like Java?
No, Dart supports variables and functions defined in global space. You can see this with the main() method which are declared outside any class.
Also, global variables (and static class variables) are lazy evaluated so the value are first defined when you are trying to use them. So your runtime are not going to slow down even if there are a bunch of global variables there are not used.
Are you coming from Java before touching Dart?
Basically, Dart is not single-class-single-file like how Java works. Yes, it does support Object Oriented Programming (in kinda different way). The behavior of constructor is different. There is no public, private, and protected keywords. Please just refer to the official docs.
Anyway, you don't need a complex public static void main(). The real entry point is main(). Unless you define that function, you won't be able to run a file in command line.

D: Delegates or callbacks?

I found conception of Delegates pretty hard for me. I really do not understand why I can't simply pass one function to another and need to wrap it to Delegate. I read in docs that there is some cases when I do not know it's name and Delegate is only way to call it.
But now I have trouble in understanding conception of callbacks. I tried to find more information, but I can't understand is it's simply call of other function or what is it.
Could you show examples of D callbacks and explain where they can be helpful?
import vibe.d;
shared static this()
{
auto settings = new HTTPServerSettings;
settings.port = 8080;
listenHTTP(settings, &handleRequest);
}
void handleRequest(HTTPServerRequest req,
HTTPServerResponse res)
{
if (req.path == "/")
res.writeBody("Hello, World!", "text/plain");
}
&handleRequest is it callback? How it's work and at what moment it's start?
So within memory a function is just a pile of bytes. Like an array, you can take a pointer to it. This is a function pointer. It has a type of RETT function(ARGST) in D. Where RETT is the return type and ARGST are the argument types. Of course attributes can be applied like any function declaration.
Now delegates are a function pointer with a context pointer. A context pointer can be anything from a single integer (argument), call frame (function inside of another) or lastly a class/struct.
A delegate is very similar to a function pointer type at RETT delegate(ARGST). They are not interchangeable, but you can turn a function pointer into a delegate pointer pretty easily.
The concept of a callback is to say, hey I know you will know about X so when that happens please tell me about X by calling this function/delegate.
To answer your question about &handleRequest, yes it is a callback.
You can pass functions to other functions to later be called.
void test(){}
void receiver(void function() fn){
// call it like a normal function with 'fn()'
// or pass it around, save it, or ignore it
}
// main
receiver(&test); // 'test' will be available as 'fn' in 'receiver'
You need to prepend the function name as argument with & to clarify you want to pass a function pointer. If you don't do that, it will instead call that function due to UFCS (calling without braces). It is not a delegate yet.
The function that receives your callable may do whatever it wants with it. A common example is in your question, a web service callback. First you tell the framework what should be done in case a request is received (by defining actions in a function and making that function available for the framework), and in your example enter a loop with listenHTTP which calls your code when it receives a request. If you want to read more on this topic: https://en.wikipedia.org/wiki/Event_(computing)#Event_handler
Delegates are function pointers with context information attached. Say you want to add handlers that act on other elements available in the current context. Like a button that turns an indicator red. Example:
class BuildGui {
Indicator indicator;
Button button;
this(){
... init
button.clickHandler({ // curly braces: implicit delegate in this case
indicator.color = "red"; // notice access of BuildGui member
});
button.clickHandler(&otherClickHandler); // methods of instances can be delegates too
}
void otherClickHandler(){
writeln("other click handler");
}
}
In this imaginary Button class all click handlers are saved to a list and called when it is clicked.
There were several questions in the OP. I am going to try to answer the following two:
Q: Could you show examples of D callbacks and explain where they can be helpful?
A: They are commonly used in all languages that support delegates (C# for an example) as event handlers. - You give a delegate to be called whenever an event is triggered. Languages that do not support delegates use either classes, or callback functions for this purpose. Example how to use callbacks in C++ using the FLTK 2.0 library: http://www.fltk.org/doc-2.0/html/group__example2.html. Delegates are perfect for this as they can directly access the context. When you use callbacks for this purpose you have to pass along all the objects you want to modify in the callback... Check the mentioned FLTK link as an example - there we have to pass a pointer to the fltk::Window object to the window_callback function in order to manipulate it. (The reason why FLTK does this is that back FLTK was born C++ did not have lambdas, otherwise they would use them instead of callbacks)
Example D use: http://dlang.org/phobos/std_signals.html
Q: Why I can't simply pass one function to another and need to wrap it to Delegate?
A: You do not have to wrap to delegates - it depends what you want to accomplish... Sometimes passing callbacks will just work for you. You can't access context in which you may want to call the callback, but delegates can. You can, however pass the context along (and that is what some C/C++ libraries do).
I think what you are asking is explained in the D language reference
Quote 1:
A function pointer can point to a static nested function
Quote 2:
A delegate can be set to a non-static nested function
Take a look at the last example in that section and notice how a delegate can be a method:
struct Foo
{
int a = 7;
int bar() { return a; }
}
int foo(int delegate() dg)
{
return dg() + 1;
}
void test()
{
int x = 27;
int abc() { return x; }
Foo f;
int i;
i = foo(&abc); // i is set to 28
i = foo(&f.bar); // i is set to 8
}
There are already excellent answers. I just want to try to make simple summary.
Simply: delegate allows you to use methods as callbacks.
In C, you do the same by explicitly passing the object (many times named context) as void* and cast it to (hopefully) right type:
void callback(void *context, ...) {
/* Do operations with context, which is usually a struct */
doSomething((struct DATA*)context, ...);
doSomethingElse((struct DATA*)context, ...);
}
In C++, you do the same when wanting to use method as callback. You make a function taking the object pointer explicitly as void*, cast it to (hopefully) right type, and call method:
void callback(void* object, ...) {
((MyObject*)object)->method(...);
}
Delegate makes this all implicitly.