如何在颤动中分割飞镖类?

时间:2018-04-01 02:42:16

标签: dart flutter

我做了以下测试,但它不起作用:

//main.dart
class Test
{
  static const   a = 10;
  final b = 20;
  final c = a+1;

}

//part.dart
part of 'main.dart';
class Test
{
  final d = a +1;   //<---undefined name 'a'
} 

我想将flutter tutorial中的类拆分为多个文件。例如:单独文件中的_buildSuggestions,单独文件中的_buildRow等。

更新

我的解决方案:

之前:

//main.dart
class RandomWordsState extends State<RandomWords> {
{
    final _var1;
    final _var2;
    @override
    Widget build(BuildContext context) {
      ...
      body: _buildList(),
    );

    Widget _buildList() { ... }
    Widget _buildRow() { ... }
}

后:

//main.dart
import 'buildlist.dart';
class RandomWordsState extends State<RandomWords> {
{
    final var1;
    final var2;
    @override
    Widget build(BuildContext context) {
      ...
      body: buildList(this),
    );

}

//buildlist.dart
import 'main.dart';

  Widget buildList(RandomWordsState obj) {
     ... obj.var1 ...
  }

3 个答案:

答案 0 :(得分:5)

Dart不支持部分课程。 partpart of拆分为多个文件,而不是类。

Dart中的

私有(以_开头的标识符)是每个库,通常是*.dart文件。

<强> main.dart

part 'part.dart';

class Test {
  /// When someone tries to create an instance of this class
  /// Create an instance of _Test instead
  factory Test() = _Test;

  /// private constructor that can only be accessed within the same library
  Test._(); 

  static const   a = 10;
  final b = 20;
  final c = a+1;
}

<强> part.dart

part of 'main.dart';
class _Test extends Test {
  /// private constructor can only be called from within the same library
  /// Call the private constructor of the super class
  _Test() : super._();

  /// static members of other classes need to be prefixed with
  /// the class name, even when it is the super class
  final d = Test.a +1;   //<---undefined name 'a'
} 

在Dart中的许多代码生成场景中使用了类似的模式,如

和其他许多人。

答案 1 :(得分:2)

我面临着同样的问题。我的基于扩展的变体:

page.dart

part 'section.dart';

class _PageState extends State<Page> {
    build(BuildContext context) {
        // ...
        _buildSection(context);
        // ...
    }
}

section.dart

part of 'page.dart';

extension Section on _PageState {
    _buildSection(BuildContext context) {
        // ...
    }
}

答案 2 :(得分:2)

我只是使用诸如Swift之类的扩展关键字对其进行扩展。

// class_a.dart
class ClassA {}

// class_a+feature_a.dart
import 'class_a.dart';    

extension ClassA_FeatureA on ClassA {
  String separatedFeatureA() {
    // do your job here
  }
}

请忽略编码约定,这只是一个示例。