首页 > 解决方案 > 如何将数据从 StatelessWidget 传递和接收到另一个?

问题描述

当我开始学习 Flutter 时,我正在使用我的知识来创建一个带有这个框架的基本计算器。我在我的应用程序中发现了一个问题......那就是:如何将参数和信息从一个小部件传递到另一个小部件?特别是从一个无状态小部件到另一个。我一直在寻找不同的地方,但我不明白我该怎么做以及它是如何工作的。

提前感谢所有可以解释我的人。

这是我正在使用的代码:

class CalcStructure extends StatelessWidget {

  final List<String> rowOne = ['AC', 'Del', '%', '/'];
  final List<String> rowTwo = ['7', '8', '9', '*'];
  final List<String> rowThree = ['4', '5', '6', '-'];
  final List<String> rowFour = ['1', '2', '3', '+'];
  final List<String> rowFive = ['00', '0', '.', '='];

  @override
  Widget build(BuildContext context) {
    return Column(
        children: <Widget>[
          Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height * 0.44,
            color: Colors.red,
          ),
          RowStructure(),
          RowStructure(),
          RowStructure(),
          RowStructure(),
          RowStructure(),         
        ],
      );
  }
}

和 RowStructure 的类

class RowStructure extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Row(
            children: <Widget>[
              Container(
                child: FlatButton(
                  onPressed: () => print('Pressed'), 
                  child: Text('AC'),
                ),
                width: MediaQuery.of(context).size.width * 0.25,
                height: MediaQuery.of(context).size.height * 0.09,
              ),
              Container(
                child: FlatButton(
                  onPressed: () => print('Pressed'), 
                  child: Text('AC'),
                ),
                width: MediaQuery.of(context).size.width * 0.25,
                height: MediaQuery.of(context).size.height * 0.09,
              ),
              Container(
                child: FlatButton(
                  onPressed: () => print('Pressed'), 
                  child: Text('AC'),
                ),
                width: MediaQuery.of(context).size.width * 0.25,
                height: MediaQuery.of(context).size.height * 0.09,
              ),
              Container(
                child: FlatButton(
                  onPressed: () => print('Pressed'), 
                  child: Text('AC'),
                ),
                width: MediaQuery.of(context).size.width * 0.25,
                height: MediaQuery.of(context).size.height * 0.09,
              ),
            ],
          );
  }
}

这个想法是将每个列表(rowOne,rowTow ...)作为参数传递给另一个类,所以我可以重用代码......你能帮帮我吗?

谢谢

标签: flutterdartstatelesswidget

解决方案


您只需通过构造函数将数据/值从一个小部件类传递到另一个:

class RowStructure extends StatelessWidget {
  
  String text = "";
  VoidCallback onTap;
  
  RowStructure({ this.text, this.onTap });
  
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Container(
          child: FlatButton(
            onPressed: onTap,
            child: Text(text),
          ),

推荐阅读