Flutter Function to reload variable - flutter

I wanted to make like a currency converter so I created this,
final montant = TextEditingController()..text = '500';
double convertEuro(montant) {
double convtEur = (double.parse(montant.text) / 3.2);
return convtEur;
}
double converted = 0;
I had a problem with my function here because the function when the screen loads it's null so I created that converted variable ( It's a stupid move I know at least to get rid of the error on my screen but only showing the initial value from my textController above
Text(
"${double.parse(montant.text)}" +
"DT = $converted" +
" €",
)
Anyway, the function is triggered when a button is pressed.
onPressed: () {
if (_formKey.currentState.validate()) {
converted = convertEuro(montant);
}
},
Can anyone help me how to change that variable value and make it change on my screen when the button is pressed?

You can do like this:
setState(() {
converted = convertEuro(montant);
});
In this, you're basically doing a rebuild of the widget.
Thus to implement this in your code, put setState under the onPress:
onPressed: () {
if (_formKey.currentState.validate()) {
setState(() {
converted = convertEuro(montant);
});
}
},

Related

Flutter: how to execute multiple functions in a single button

in Flutter I have made a custom button that does a small animation when pressing it. The issue is that when I add a VoidCallBack function, which is a parameter that I give to the button widget, to the same onTap, then the function does not get executed whilst the animation does.
I did find this question ( how do we execute two function in single button pressed in flutter) that seems to be similar to mine but I have tried the suggestions and they do not work for me.
Here is a code snippet of when Im trying to use the button widget:
MyButton (
onTap = () {
print(_isSelected);
setState(() {
_isSelected[0] = !_isSelected[0];
});
},
)
Also I dont know if it makes a difference but Ive tried it both with and without the setState part.
Then in the button itself I do:
onTap: () {
widget.onTap;
setState(() {
_clicked = !_clicked;
});
},
I also tried to do this, like in the other stackOverflow question which had the same result:
onTap: () => [
widget.onTap,
{
setState(() {
_clicked = !_clicked;
})
}
],
Though it does work if I only use the parameter: onTap: widget.onTap,
This is usually how I do it.
onTap: () {
widget.onTap();
your_function_here();
},
Declare function variable:
final Function onTap;
and call widget.onTap with round brackets as below:
onTap: (){
widget.onTap();
setState(() {
_clicked = !_clicked;
});
}
You need to declare a constructor which takes onTap function as a parameter.
class MyButton extends StatelessWidget {
final Function onTap;
const MyButton ({Key? key, this.onTap,}) : super(key: key);
}
Since the onTap parameter needs a function as argument, you simply write a function that runs your functions.
MyButton(
onTap: () {
your_function1();
your_function2();
},
)

Flutter Search bar not refreshing the initial list

i'm having a little trouble in getting back the initial list in my app, after searching an item.
I have a list car and i'm using code from tutorials, if i let the text in the formfield and change tabs, when i back the filter continues and the bar is empty.
I already tried 100 forms and keeps getting the same result.
Here's parts of the code.
List<Car> car = cars;
final _pesquisaController = TextEditingController();
I have a default textformfield with this controller above and a onchange calling the method below.
void pesquisarCarro(String query) {
var carrosPesquisados = {
...car.where(
(cars) {
var nomedoCarro = cars.nomeCarro.toLowerCase();
var input = query.toLowerCase();
return nomedoCarro.contains(input);
},
),
...car.where(
(cars) {
var codigodoCarro = cars.codigo.toLowerCase();
var input = query.toLowerCase();
return codigodoCarro.contains(input);
},
)
}.toList();
setState(
() {
cars = carrosPesquisados;
},
);
}
Already tried putting the list on the initState but not work, can someone give me a light?
Like said, the search filters perfectly, the problem is when i let text in the form and change tabs in the bottomtabbar.
is your problem is initial value always empty?
#override
void initState() {
onInit();
super.initState();
WidgetsBinding.instance.addPostFrameCallback((callback) {
// set your list here
});
}

Flutter: How to change button depending on state?

I'm trying to do the following: I have a container, and a button inside it and upon clicking on the button (onPressed) I would like to display a different button (aka. change the widget).
Would appreciate some help in doing so, thanks in advance!!
define the initial value for example
double paddingLeft = 10.0;
And after clicking on that button update the state with actual value Like
setState(() {
paddingLeft = 20.0
});
There might be different ways. One of the methods is:
bool _val = true;
Container(
child: _val ? button1( // when _val is true button1 will be the child of container. So it will be visible.
onPressed: () {
_val = !_val;
setState(() {
});
})
: button2(), // when _val is false button2 will be the child of container. So it will be visible.
);
First of all, you need to make sure that the class you are in extends a StatefulWidget, because that means that the class will rerender when a state changes, which is what you need to be able to show another button.
Then you can define a state bool _showButton1 = true;
In your Container you can then have something like this:
Container(
child: _showButton1 ? _button1() : _button2();
)
(Meaning: if _showButton1 is true, show the widget _button1, else show _button2)
where _button1 would look something like this:
Widget _button1() {
return Button(
onPressed: () => setState(() {
_showButton1 = false;
})
);
}
(Meaning: when this button is pressed, update the state _showButton1 to false and rerender this class --> button 2 will be shown)

How to display time on buttons in Flutter

Requirement:
I have 2 buttons, I want when I click on button 1 its text should be replaced by the current time, and the same for button 2.
Problem:
The problem is when I click on button 1 its text change to the current time, but when I click on button 2 after a few minutes its text changes to the same time that button 1 has.
Here is my code:
void initState() {
// TODO: implement initState
super.initState();
_getTime();
}
void _getTime() {
final String formattedDateTime =
DateFormat('kk:mm:ss').format(DateTime.now()).toString();
setState(() {
getTime = formattedDateTime;
print(getTime[0]);
});
}
var timeInText="Time in";
var timeOutText="Time out";
\\button 1
RoundedButton(icon: Icon(Icons.timer,color: Colors.white),
text:timeInText,
bgcolor: Colors.blue[500],
press:(){
setState(() {
timeInText=getTime;
});
})
//button 2
RoundedButton(icon: Icon(Icons.timer,color: Colors.white),
text:timeoutText,
bgcolor: Colors.blue[500],
press:(){
setState(() {
timeoutText=getTime;
});
})
please help to fix it. thanks
You call _getTime() only in initState. Time is stored on initialization and never updated after that. Since it's never updated it's showing the same time constantly.
To fix that add a _getTime() call to both of your onPressed functions like this:
onPressed: () {
_getTime();
setState(() {
timeoutText = getTime;
});
}),
You get the time one, when the button clicked. You have to write your method codes in setState too i think. And get the current time 🤔 i hope it will help

I need to press the button 2 times in order to function (flutter)

I have a problem implementing a login button, when I press it, it will not function at first, but when I press it again (same value fields) it works.
here's my code
Button:
Center(child: RaisedButton(onPressed: (){
setState(() {
onPressedLogin(userName.text,password.text);
});
}
The OnPressedLogin():
void onPressedLogin(String userName,String password) async{
bool isValid = false;
var value = await dataBaseHelper.getUserList();
for(User userOB in value){
//print(userOB.password+" "+password),
if(userName == userOB.username && password == userOB.password) {
isValid = true;
this.password.clear();
this.userName.clear();
inputTextColor = Colors.grey[850];
invalidCredentials = "";
print("YES");
//Navigator.push(context, MaterialPageRoute(builder: (context) => Home()));
break;
}
}
if(!isValid){
inputTextColor = Colors.red[800];
invalidCredentials = "Invalid Credentials";
}
You are using a Future but in setState() you are not waiting for it so that's way it work in the second press (the value take time to change).
To make it work with single press you have to a wait the Future to complete before rebuilding, here how:
First change the return type of the function
Future<void> onPressedLogin(String userName,String password)
Then in the RaisedButton
onPressed: () async {
await onPressedLogin(userName.text,password.text);
setState(() {});
},
The moment you setState(), the UI will refresh!
Probably that's the issue, let me explain:
What you should do is to call your function before setState(), so that the screen is refreshed with the new info.
Center(child: RaisedButton(onPressed: (){
onPressedLogin(userName.text,password.text);
setState(() {
//Variables that change for the refresh.
});
}
In your specific case, I don't see the need for SetState() as you are only printing values in log, not changing the UI.
Hope it is helpful.