我可以提取修改 Dart 中状态的方法吗?



我开始学习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方法(,我想知道是否有办法将所有这些方法提取到单独的类中,并从主类调用它们?也许有一种方法可以以某种方式传递状态(也许作为参数?(,因此可以从另一个类修改它?

是的,您可以使用我们所说的"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
}

最新更新