【问题标题】:Call function from one build to another从一个构建调用函数到另一个构建
【发布时间】:2020-05-04 09:43:04
【问题描述】:

在我的主页.dart 中,我有这段代码。当有文本时,我想调用在页面 B 构建函数中声明的过滤函数。我怎样才能做到这一点?

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: _appBarTitle,
          actions: <Widget>[
            IconButton(
              onPressed: () {
                setState(() {
                                 ....
                      decoration: new InputDecoration(
                      onChanged: (value) {
                         // call filter function in pageB
                      },
                    );
                      ....
               }

【问题讨论】:

  • 你试过了吗 - PageB pageB = new pageB(); pageB.myFunction();
  • @Sukhi 是的,它说没有定义。
  • 是公共功能吗?
  • @Sukhi 是的。我刚刚宣布它们为无效。
  • 将pageA中的dart文件导入为“import pageb.dart”。您将能够访问pageB中的功能。这不是理想的方式,但应该有效。

标签: listview flutter dart


【解决方案1】:

有几种方法可以做到这一点。

正如聊天中所讨论的,PageB().filterSearch(value) 是一种方法。

另一种方法是导入页面b dart文件并访问该功能。类似的东西:

PageA.dart:

import "pageb.dart"



decoration: new InputDecoration(
                      onChanged: (value) {
                         // call filter function in pageB
                         filterSearch(value);
                      },

【讨论】:

    【解决方案2】:

    您可以通过检查下面的代码来实现这一点

    需要两个步骤:

    1. 创建 PageB 类的实例
    2. 在创建的 PageB 实例上调用函数 ```filter()

    检查下面的代码,它运行良好:

      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: _appBarTitle,
              actions: <Widget>[
                IconButton(
                  onPressed: () {
                    setState(() {
                                     ....
                          decoration: new InputDecoration(
                          onChanged: (value) {
                             // call filter function in pageB
                             //create an object of Page B
                             PageB _pageb = PageB();
                             // call the filter function in PageB using the object above
                             _pageb.filter();
                          },
                        );
                          ....
                   }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2016-01-30
      • 1970-01-01
      • 2020-03-14
      • 2011-03-24
      • 2014-03-12
      • 1970-01-01
      • 2014-06-25
      • 2018-05-05
      相关资源
      最近更新 更多