【问题标题】:How to change state of one child widget from parent widget where the child is a separate class in a separate file?如何从父小部件更改一个子小部件的状态,其中子小部件是单独文件中的单独类?
【发布时间】:2020-01-27 11:46:40
【问题描述】:

如何通过单击 RaisedButton 将框的颜色从蓝色更改为绿色?我正在使用 Flutter 网页版。

class _MyAppState extends State<MyApp> {
  Color colorOfBox = Colors.blue;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "App",
      home: Scaffold(
        body: Container(
          padding: EdgeInsets.all(50),
          child: Center(
            child: Column(
              children: <Widget>[
                Text("This blue has to change to green."),    
                Box(colorOfBox),
                RaisedButton(
                  color: Colors.red,
                  onPressed: () {
                    setState(() {
                      colorOfBox = Colors.green;

                    });
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
class Box extends StatefulWidget {
  Color c;
  Box(this.c, {Key key}) : super(key: key);

  @override
  _BoxState createState() => _BoxState(c);
}

class _BoxState extends State<Box> {
  Color c;
  _BoxState(this.c);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 40,
      height: 40,
      color: c,
    );
  }
}

【问题讨论】:

  • 感谢@Augustin R 的编辑

标签: flutter flutter-web


【解决方案1】:

_BoxState 中删除Color c

class Box extends StatefulWidget {
  Color c;
  Box(this.c, {Key key}) : super(key: key);

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

class _BoxState extends State<Box> {

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 40,
      height: 40,
      color: widget.c,
    );
  }
}

【讨论】:

    猜你喜欢
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 2021-07-20
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多