简体   繁体   中英

change variables with setState in Flutter

I have an issue with setState() in Flutter. I just write a simple program that have a container and a button , the color of container is global variable mycolor and i change it in on_pressed function of button with setState but its doesn't change.

    import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(home: _Home(),));

Color bgColor = Colors.red;


class _Home extends StatefulWidget {
  @override
  __HomeState createState() => __HomeState();
}

class __HomeState extends State<_Home> {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        //First Widget
        Container(
          width: 200,
          height: 200,
          color: bgColor,
        ),
        //Second Widget
        SecondWidget()
      ],
    );
  }
}

class SecondWidget extends StatefulWidget {
  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}

class _SecondWidgetState extends State<SecondWidget> {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text("Change color"),
      onPressed: (){
        setState(() {
         bgColor = Colors.green; 
        });
      },
    );
  }
}

image of my program

You are calling setState in _SecondWidgetState not in __HomeState , so only SecondWidget redraws and it does not depend on bgColor .
What you can do here: the easiest option would be to pass a callback function from __HomeState to SecondWidget , which will call setState inside __HomeState .
Example code:

class __HomeState extends State<_Home> {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        //First Widget
        Container(
          width: 200,
          height: 200,
          color: bgColor,
        ),
        //Second Widget
        SecondWidget(callSetState);
      ],
    );
  }

  void callSetState() {
    setState((){}); // it can be called without parameters. It will redraw based on changes done in _SecondWidgetState
  }
}

class SecondWidget extends StatefulWidget {

  final Function onClick;

  SecondWidget(this.onClick);

  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}

class _SecondWidgetState extends State<SecondWidget> {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text("Change color"),
      onPressed: (){
        bgColor = Colors.green; 
        widget.onClick();
      },
    );
  }
}

This is simple solution for two widgets, but you will have problems if you will try to manage state on larger scale. I recommend you to read articles about state management in flutter. This one can be a good start.

You need to pass that variable to your sibling widget SecondWidget() .

First you declare it on your SecondWidget like this:

class SecondWidget extends StatefulWidget {

Color backgroundColor;

SecondWidget({Key key, @required this.backgroundColor}) : super(key: key);

  @override
  _SecondWidgetState createState() => _SecondWidgetState();
}

You need to pass that color from _HomeState to SecondWidget , you do it like this:

class __HomeState extends State<_Home> {
  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: <Widget>[
        //First Widget
        Container(
          width: 200,
          height: 200,
          color: bgColor,
        ),
        //Second Widget
        SecondWidget(backgroundColor: bgColor) // Here you pass that color
      ],
    );
  }
}

Then on your SecondWidgetState , you can update your other widget color using setState() , like this:

setState(() {
 widget.backgroundColor = Colors.blue;
});

Hope this helps fix your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM