'Pass a function in onFocusChange Flutter
I got this function :
void _CalculTotal() {
total = total + double.tryParse(widget.controllers.last.text);
setState(() {
totalDocument.text = total.toString();
});
}
I want to pass it in onFocusChange when the user loses the focus .
Container(
width: MediaQuery.of(context).size.width / 3.7,
color: Color.fromARGB(255, 255, 255, 255),
child: Focus(
onFocusChange: (hasFocus) {
if (!hasFocus)
widget.Prix;
},
child: TextFormField(
textInputAction: TextInputAction.done,
enabled: true,
controller: widget.fieldController4,
validator: widget.fieldValidator,
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
),
decoration: InputDecoration(
contentPadding: EdgeInsets.all(10.0),
hintText: "${widget.content4}",
hintStyle: TextStyle(
color: Color.fromARGB(255, 190, 190, 190),
fontSize: 14),
fillColor: Color.fromARGB(255, 0, 0, 0),
),
),
),
),
this is my widget constructor :
class InputRefNomProduit extends StatefulWidget {
final VoidCallback Prix;
InputRefNomProduit(
{
// ...
this.Prix
});
and this is where I'm calling the widget in my main screen :
InputRefNomProduit(
// ..
Prix: _CalculTotal,
)
I'm not getting any error but the function won't work .(I tried to print a message when the function is triggered but the message won't show up , so the call wasn't successful). If I put a simple print statement here , It works :
onFocusChange: (hasFocus) {
if (!hasFocus)
print("Hello");
},
Solution 1:[1]
You can do that using a focusNode like this
FocusNode firstFocusNode = FocusNode();
In your initState add a listener of the focusNode and call function onFocus change
void initState() {
super.initState();
firstFocusNode.addListener(() {
if (!firstFocusNode.hasFocus) {
_CalculTotal();
}
});
}
Here's the textFormField.
TextFormField(
focusNode: firstFocusNode,
onFieldSubmitted: (v) {
FocusScope.of(context)
.requestFocus(firstFocusNode);
}, //your other properties
)
Let me know if it works for you.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fahmida |
