As pointed out in the comments, this topic is called state management (in English).
About this, there are many applicable solutions and each has its pros and cons. Which one is best for your application depends a lot on how it is structured and how your state is manipulated. For a large application, this is a decision much important. Undoubtedly it is something that yields many hours of discussion and debate.
But as an example, I leave one of the simplest ways to do what you want.
Your button class should receive as a parameter a Function
which will serve as callback for when it is clicked:
class MeuBotao extends StatelessWidget {
MeuBotao({this.callback});
final Function callback;
@override
Widget build(BuildContext context) {
return RaisedButton(
onPressed: callback,
child: Text('Texto do botão'),
);
}
}
Your main class HomeScreen
which should manage the variable status now. Create a function that will be called when the button is pressed:
class _HomeScreenState extends State<HomeScreen> {
bool variavel = false;
void alterarValor() {
setState((){
variável = !variável;
})
}
[...]
}
And when you build the button, it takes this callback as a parameter:
child: MeuBotao(callback: alterarValor),
Therefore, some caveats:
- Using only this method hardly your program will be scalable for a larger application. If there is a more complex widgets tree, it will take several callbacks that call each other. It is impractical and very easy to get confused and generate errors.
- In the example I put your button as
StatelessWidget
. If he needs the value of variável
for drawing, you can receive as a parameter setState()
higher will rebuild it. It may own state as well if necessary. There may be more actions within your onPressed
and in the end call the callback. Customization is due to the use.
- Google calls this solution "Raise the state" (of the English: Lifting state up). This is because the state variable was present in a lower widget in the widgets tree and was moved to a higher widget. This in turn manages to pass it on to all Widgets who need it.
Search for state management.
– Julio Henrique Bitencourt