【问题标题】:Can I extract methods which modify the state in Dart?我可以提取修改 Dart 状态的方法吗?
【发布时间】:2020-04-24 02:28:48
【问题描述】:

我开始学习 Dart + Flutter,我开发了一个简单的应用程序,只有一个 .dart 文件。我的状态中有几个变量,有几个修改它们的方法,以及一些在调用onPressed 时修改这些变量的按钮。这是简化的示例:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  int a = 0;
  int b = 0;
  List<int> list = List.generate(/* something something */);
  ...
  void firstMethod() {
    a = 1;
    b = 2;
  }
  ...
  RaisedButton methodThatBuildsButton(){
    return RaisedButton(
      ...
      onPressed: () {
        setState((){
          list.add(1);
        });
      });
    );
  }
  ...
}

等等……

因为我想要一个干净的“主”文件(如果可能,只使用build 方法),我想知道是否有办法将所有这些方法提取到一个单独的类中,并调用它们来自主班?也许有办法以某种方式传递状态(可能作为参数?),所以它可以从另一个类修改?

【问题讨论】:

  • 你应该寻找全局/应用状态和状态管理工具

标签: flutter dart


【解决方案1】:

是的,您可以使用我们所说的“mixins”。

这是一个例子:

mixin MyMixin {
   // a variable defined on the modified class that this mixin uses
   //
   // It is voluntarily not a concrete implementation, as we don't want the mixin
   // to define those variables, but let the class that use it handle the definition instead
  int get count;
  set count(int value);

  void increment() {
    count += 1;
  }
}

// We apply the mixin using the `with` keyword
class Counter with MyMixin {
  int count = 0;
}

void main() {
  final counter = Counter();

  print(counter.count); // 0
  counter.increment();
  print(counter.count); // 1
}

【讨论】:

    猜你喜欢
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多