从另一个有状态小部件调用一个有状态小部件中的方法 - Flutter [英] call method in one stateful widget from another stateful widget - Flutter

查看:37
本文介绍了从另一个有状态小部件调用一个有状态小部件中的方法 - Flutter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在处理的 flutter 项目,因为它有 500 多行代码,所以我无法放置整个代码,所以我将尝试像使用 imp 一样简单地提出我的问题.代码部分.

I have a flutter project that I am working on I can't put the whole code cause its more than 500 lines of code so I will try to ask my question as simply as I acn using the imp. section of the code .

我有一个有状态的小部件,并且在扩展 State

I am having a stateful widget and having some functions inside that stateful widget under the class that extends State<MusicPlayer>

文件 libmain.dart

只需要一个简单的函数

class MyAppState extends State<MyApp>{
...
void printSample (){
  print("Sample text");
}
...

这个函数在主类中的有状态小部件内.

this function is inside the stateful widget inside main class .

还有另一个文件 libMyApplication.dart

这个文件也有一个有状态的小部件,我可以做些什么,以便我可以在这里调用函数 printSample() ..

this file also has a stateful widget can I do something so that I can call the function printSample() here ..

class MyApplicationState extends State<MyApplication>{
...
@override
  Widget build(BuildContext context) {
    return new FlatButton(
      child: new Text("Print Sample Text"),
      onPressed :(){
       // i want to cal the function here how is it possible to call the 
       // function 
       // printSample()  from here??  
      }
    );
  }
}

推荐答案

要调用父级的函数,可以使用回调模式.在这个例子中,一个函数 (onColorSelected) 被传递给孩子.当一个按钮被按下时孩子会调用这个函数:

To call a function of a parent, you can use the callback pattern. In this example, a function (onColorSelected) is passed to the child. The child calls the function when a button is pressed:

import 'package:flutter/material.dart';

class Parent extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ParentState();
  }
}

class ParentState extends State<Parent> {
  Color selectedColor = Colors.grey;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          color: selectedColor,
          height: 200.0,
        ),
        ColorPicker(
          onColorSelect: (Color color) {
            setState(() {
              selectedColor = color;
            });
          },
        )
      ],
    );
  }
}

class ColorPicker extends StatelessWidget {
  const ColorPicker({this.onColorSelect});

  final ColorCallback onColorSelect;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        RaisedButton(
          child: Text('red'),
          color: Colors.red,
          onPressed: () {
            onColorSelect(Colors.red);
          },
        ),
        RaisedButton(
          child: Text('green'),
          color: Colors.green,
          onPressed: () {
            onColorSelect(Colors.green);
          },
        ),
        RaisedButton(
          child: Text('blue'),
          color: Colors.blue,
          onPressed: () {
            onColorSelect(Colors.blue);
          },
        )
      ],
    );
  }
}

typedef ColorCallback = void Function(Color color);

内部 Flutter 小部件(如按钮或表单字段)使用完全相同的模式.如果你只想调用一个没有任何参数的函数,你可以使用 VoidCallback 类型来代替定义你自己的回调类型.

Internal Flutter widgets like buttons or form fields use exactly the same pattern. If you only want to call a function without any arguments, you can use the VoidCallback type instead defining your own callback type.

如果你想通知上级的父母,你可以在每个层级重复这个模式:

If you want to notify a higher up parent, you can just repeat this pattern on every hierarchy level:

class ColorPickerWrapper extends StatelessWidget {
  const ColorPickerWrapper({this.onColorSelect});

  final ColorCallback onColorSelect;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(20.0),
      child: ColorPicker(onColorSelect: onColorSelect),
    )
  }
}

<小时>

在 Flutter 中不鼓励从父小部件调用子小部件的方法.相反,Flutter 鼓励您将子项的状态作为构造函数参数传递.您只需在父小部件中调用 setState 来更新其子部件,而不是调用子部件的方法.


Calling a method of child widget from a parent widget is discouraged in Flutter. Instead, Flutter encourages you to pass down the state of a child as constructor parameters. Instead of calling a method of the child, you just call setState in the parent widget to update its children.

另一种方法是 Flutter 中的 controller 类(ScrollControllerAnimationController、...).这些也作为构造函数参数传递给子级,它们包含控制子级状态的方法,而无需在父级上调用 setState.示例:

One alternative approach are the controller classes in Flutter (ScrollController, AnimationController, ...). These are also passed to the children as constructor parameters, and they contain methods to control the state of the child without calling setState on the parent. Example:

scrollController.animateTo(200.0, duration: Duration(seconds: 1), curve: Curves.easeInOut);

然后要求孩子们聆听这些变化以更新他们的内部状态.当然,您也可以实现自己的控制器类.如果需要,我建议您查看 Flutter 的源代码以了解其工作原理.

The children are then required to listen to these changes to update their internal state. Of course, you can also implement your own controller class. If you need to, I recommend you to look at the source code of Flutter to understand how that works.

期货和流是传递状态的另一种选择,也可用于调用子函数.

Futures and streams are another alternative to pass down state, and could also be used to call a function of a child.

但我真的不推荐它.如果你需要调用子widget的方法,那很像是你的应用架构有缺陷.尝试将状态向上移动到共同祖先!

But I really don't recommend it. If you need to call a method of a child widget, it is very like that your application architecture is flawed. Try to move the state up to the common ancestor!

这篇关于从另一个有状态小部件调用一个有状态小部件中的方法 - Flutter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆