首页 > 解决方案 > Flutter setState 在内部 Widget 中

问题描述

是否可以setState在 statefulls 内部小部件中使用(在主上下文之外)?

我想要实现的是在用户点击它时进行Button更改。color它在里面,ListView.builder因为有多个按钮,但我希​​望它只发生在_buildAnsers小部件中

Widget _buildAnswers(int questionIndex) {

    //I need this to be inside this widget
    Color _buttonColor = Colors.red;

    return new ListView.builder(
      itemCount: 10,
      physics: ClampingScrollPhysics(),
      shrinkWrap: true,
      itemBuilder: (context, answerIndex) {

        return Padding(
            child: new RaisedButton(
              onPressed: () {
                setState(() {
                  _buttonColor = Colors.green; //this doesn't work?
                });
              },

              color: _buttonColor,
              splashColor: Color(0xFFde1f28),
              disabledColor: Color(0xFFc54b51),

              child: new Text('Container ${answerIndex}'),
            )
        );

      },
    );

  }

标签: dartwidgetflutterstateful

解决方案


不,它不起作用,更好的选择是使用StreamController和广播/订阅模型。


推荐阅读