我做了以下测试,但是没有用:
//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'
}
Run Code Online (Sandbox Code Playgroud)
我想将flutter教程中的类拆分为多个文件。例如:_buildSuggestions在单独的文件中,_buildRow在单独的文件中,等等。
更新:
我的解决方案:
之前:
//main.dart
class RandomWordsState extends State<RandomWords> {
{
final _var1;
final _var2;
@override
Widget build(BuildContext context) {
...
body: _buildList(),
);
Widget _buildList() { ... }
Widget _buildRow() { ... }
}
Run Code Online (Sandbox Code Playgroud)
后:
//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 ...
}
Run Code Online (Sandbox Code Playgroud)
我面临同样的问题。我的基于扩展的变体:
页面.dart
part 'section.dart';
class _PageState extends State<Page> {
build(BuildContext context) {
// ...
_buildSection(context);
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
段.dart
part of 'page.dart';
extension Section on _PageState {
_buildSection(BuildContext context) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
Dart不支持部分类。part并将part of一个库拆分为多个文件,而不是一个类。
_Dart中的私有(以开头的标识符)是每个库的*.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;
}
Run Code Online (Sandbox Code Playgroud)
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'
}
Run Code Online (Sandbox Code Playgroud)
在Dart的许多代码生成方案中都使用了类似的模式,例如
和其他许多人。
我只是用像 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
}
}
Run Code Online (Sandbox Code Playgroud)
请忽略编码约定,这只是一个示例。
| 归档时间: |
|
| 查看次数: |
4196 次 |
| 最近记录: |