Reputation: 1369
I am new with Flutter and I face a problem as I want to update Text widget with the value passed from numbers() function.
The problem is the value inside Text does not change on the screen when I press on the button but it changes in the console.
class _HomeState extends State<Home> {
int n = 10;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.deepPurpleAccent,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(n.toString()),
RaisedButton(
onPressed: (){
n += numbers();
print(n.toString());
},
),
],
),
),
);
}
}
int numbers (){
List<int> numbersList = List(1);
numbersList[0] = 30;
int n1 = numbersList[0];
return n1;
print(numbersList[0].toString());
}
Upvotes: 3
Views: 12139
Reputation: 2839
This how you can change it
RaisedButton(
onPressed: (){
final newVal = numbers();
setState((){
n += newVal;
});
print(n.toString());
},
),
Upvotes: 1
Reputation: 1578
If you want to update UI then you should be call setState((){});
method in flutter.This method available in StatefulWidget
You Should be implement below way
class _HomeState extends State<Home> {
int n = 10;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.deepPurpleAccent,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(n.toString()),
RaisedButton(
onPressed: () {
setState(() {
n += numbers();
});
},
),
],
),
),
);
}
}
int numbers() {
List<int> numbersList = List(1);
numbersList[0] = 30;
int n1 = numbersList[0];
return n1;
}
Upvotes: 8
Reputation: 3384
This is expected since in flutter whenever you want to "refresh" screen you have to call setState()
for the widget that you want to update. So what you do is, inside your onPressed function you do the following:
setState(){
n += numbers();
}
print(n.toString());
You can read more about stateful widgets and setState here
Upvotes: 0