I have a List of String stored in a variable like this:
var question = [
'whats your favorite name',
'whats your favorite color',
'whats your favorite shape',
];
And have function that increase a variable each time I call it
void _Press(){
setState((){
_PressedNo = _PressedNo 1;
});
print(_PressedNo );
}
And in my scaffold iam checking if the _PressedNo is smaller that List so it rebuild the scaffold with the new question each time i press the button till the questions finished like this :
return MaterialApp(
home: Scaffold(
body:_PressedNo < question.length ? Container(
child: RaisedButton(
child: Text('yes'),
onPressed:() {
_Press();
},
),
) : // here i want to go to another page
And after the else : i want to go to another Flutter page, but I can only add widgets here so any solution how to do that..
CodePudding user response:
You'll have to take a bit of a different approach. The build method should only provide things that appear on the screen and not directly trigger a specific action or state change, such as navigating to another page.
You can handle this in the _Press() method:
void _Press() {
if(_PressedNo < questions.length) {
setState(() {
_PressedNo = _PressedNo 1;
});
} else {
Navigator.of(context).push(...); // navigate to another page
// optionally set the _PressedNo back to 0
setState(() {
_PressedNo = 0;
});
}
}
Your build method should not change, since on this page it should always show the same button.
return MaterialApp(
home: Scaffold(
body: Container(
child: RaisedButton(
child: Text('yes'),
onPressed:() {
_Press();
},
),
),
);
Some other pointers:
- use lowerCase for functions and variables:
_press()and_pressedNo. - You can directly pass in the function to
onPressedlikeonPressed: _press,(note that there are no parentheses since the function is not called but just passed along)
