简体   繁体   English

Flutter:如何使用变量将 arguments 传递给 Widget?

[英]Flutter: how to pass arguments to a Widget using a variable?

Here's some pseudo code showing what I'm trying to achieve:这是一些伪代码,显示了我要实现的目标:

Text txt(text, [subtitle = false]) {
  final params = subtitle
      ? {
          'textAlign': TextAlign.center,
          'style': TextStyle(color: Colors.purple)
        }
      : {
          'textAlign': TextAlign.left,
          'style': TextStyle(color: Colors.black54)
        };

  return Text(
    text,
    ...params,
  );
}

Is it possible to pass variable arguments to a Flutter widget?是否可以将变量 arguments 传递给 Flutter 小部件? Please keep in mind that the Text widget is just an example and not the focus of my question, it could be any other Flutter widget, like Container, or SizedBox, for example.请记住,Text 小部件只是一个示例,而不是我问题的重点,它可以是任何其他 Flutter 小部件,例如 Container 或 SizedBox。

In one of my apps在我的一个应用程序中

      Text(listItem.name,
          style: TextStyle(
              decoration: listItem.checked
                  ? TextDecoration.lineThrough
                  : TextDecoration.none)),

works perfectly fine, listItem.checked is of boolean type.工作得很好, listItem.checked是 boolean 类型。

This question has more examples: How to use conditional statement within child attribute of a Flutter Widget (Center Widget)这个问题有更多的例子: How to use conditional statement within a Flutter Widget (Center Widget)

How to pass arguments to a widget using a variable:如何使用变量将 arguments 传递给小部件:

tldr; tldr; We have to turn our thinking on its head a bit.我们必须稍微改变一下思路。 Data can be passed to the called widget when you navigate to it by using final arguments with default values in the destination widget.当您使用最终 arguments 和目标小部件中的默认值导航到被调用小部件时,可以将数据传递给它。 Using an optional function you can get data back from the 'child' (destination) widget.使用可选的 function 您可以从“子”(目标)小部件获取数据。

In the destination stateful widget you create a final variable;在目标状态小部件中,您创建一个最终变量;

 final int boxIndex;

In the destination constructor give your final variable a constant default value在目标构造函数中,为您的最终变量提供一个常量默认值

DestinationClassConstructor({Key? key, this.boxIndex = -1}): super(key: key);

You can add methods to the stateful widget class that use the value in some significant way:您可以将方法添加到有状态小部件 class 以某种重要方式使用该值:

eg例如

  bool isEditing() {
    return this.boxIndex != -1;
  }

In the source widget that calls the destination widget, you can pass in a value other than the default.在调用目标小部件的源小部件中,您可以传入默认值以外的值。

DestinationClassConstructor(boxIndex: 123),

In the destination widgets state content class you could use the value directly or call the method above:在目标小部件 state 内容 class 中,您可以直接使用该值或调用上述方法:

eg例如

widget.isEditing()
widget.boxIndex,

The real power of this method happens when you decide that you can pass Functions as parameters:当您决定可以将函数作为参数传递时,此方法的真正威力就会出现:

eg例如

In your destination stateful widget create the nullable function call with its constructor argument:在您的目标有状态小部件中,使用其构造函数参数创建可为空的 function 调用:

final Function()? destinationWidgetTapped;

DestinationClassConstructor({Key? key, this.destinationWidgetTapped}): super(key: key);

Note: In this case the function variable is assigned a default value of null.注意:在这种情况下,function 变量的默认值是 null。

Somewhere in your destination content state widget call the function:在您的目标内容 state 小部件中的某处调用 function:

if (widget.destinationTapped != null) widget.destinationWidgetTapped!();

Then in your source widget make the call as follows:然后在您的源小部件中进行如下调用:

DestinationClassConstructor(destinationWidgetTapped: () {
                        print('this code from the source widget executes after the child widget event is invoked');

                        Navigator.of(context).pop(); //pop the child widget
                      },

Which is fine and very useful when you consider that you can also pass back a value along with the function call.当您考虑到您还可以将值与 function 调用一起传回时,这很好并且非常有用。

final Function(String)? destinationWidgetTapped;

DestinationClassConstructor({Key? key, this.destinationWidgetTapped}): super(key: key);

Somewhere in your destination content state widget call the function:在您的目标内容 state 小部件中的某处调用 function:

if (widget.destinationTapped != null) widget.destinationWidgetTapped!('Hello from the Destination Content State Widget');

Then you can receive data like this:然后你可以收到这样的数据:

DestinationClassConstructor(destinationWidgetTapped: (value) { 
    print('Data is passed from the destination widget with a string value of : $value');
    Navigator.of(context).pop();
},

Nota Bene:注意事项:

Function(String) can also be written as ValueChanged<String> Function(String)也可以写成ValueChanged<String>

We can further extrapolate that any object may be passed:我们可以进一步推断任何 object 都可以通过:

Function(Object?) written as ValueChanged<Object?> Function(Object?)写成ValueChanged<Object?>

And the argument might be better written as:这个论点可能更好地写成:

 final ValueChanged<Object?>? onValueChanged; DestinationClassConstructor({Key? key, this.onValueChanged}): super(key: key);

Which would allow one to send any data object, array, json, map, string, int, bool, etc. while maintaining access to a completion handler so that one could access the variable data in both directions.这将允许发送任何数据 object、数组、json、map、字符串、int、bool 等,同时保持对完成处理程序的访问,以便可以在两个方向上访问变量数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 flutter 中通过 2 个 Arguments? - How to pass 2 Arguments in flutter? 在 Flutter 如何将值传递给小部件 - In Flutter How to pass value to the widget 如何使用 flutter 将动态值传递给其他小部件 - How to pass dynamic value to other widget using flutter 如何在颤振中使用导航器将用户传递到带有状态小部件的命名路由? - How to pass user to named route with a stateful widget using Navigator in flutter? 如何在Flutter中将额外的参数传递给ListView.builder Widget的itemBuilder函数? - How to pass extra arguments to itemBuilder function of ListView.builder Widget in Flutter? 如何将 arguments 传递给 flutter 中的 function? - How to pass arguments to a function in flutter? 将 arguments 传递给 pushnamed 但在接收器小部件中在 flutter 中给出 null - Pass arguments to pushnamed but in receiver widget give null in flutter 如何使用 flutter 中的提供程序或 valuenotifier 将数据从子小部件传递到父小部件 - How to pass data from child widget to parent widget using provider or valuenotifier in flutter Flutter/Dart FutureBuilder - 如何将快照数据存储在变量中并将值传递给其他小部件? - Flutter/Dart FutureBuilder - How to store a snapshot.data in a variable and pass the value to other widget? 如何将JSON数据传递到Flutter小部件 - How to pass json data to flutter widget
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM