how to split dart class in flutter?
Dart doesn't support partial classes. part
and part of
are to split a library into multiple files, not a class.
Private (identifiers starting with _
) in Dart is per library which is usually a *.dart
file.
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'
}
A similar pattern is used in many code-generation scenarios in Dart like in
- https://pub.dartlang.org/packages/built_value
- https://pub.dartlang.org/packages/built_redux
- https://pub.dartlang.org/packages/json_serializable
and many others.
I am faced with same problem. My variant based on extensions:
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) {
// ...
}
}