从Flutter中的父目录导入 [英] Import from parent directory in Flutter
问题描述
我想在另一个文件夹中的自己文件中制作几个复杂的窗口小部件,这些文件将由帮助程序脚本导入和配置.这是文件树:
I want to make a couple of complicated widgets in their own files in another folder, which will be imported and configured by a helper script. Here is the file tree:
- lib/
- constants.dart
- file1.dart
- file2.dart
- main.dart
- utils.dart
- utils/
- complex_widget1.dart
- complex_widget2.dart
- complex_widget3.dart
这是utils.dart
import "utils/complex_widget1.dart";
import "utils/complex_widget2.dart";
import "utils/complex_widget3.dart";
class Utils {
final Widget1 widget1;
final Widget2 widget2;
final Widget3 widget3;
final String data_needed_by_widgets;
Utils (this.data_needed_by_widgets) :
widget1 = Widget1(data_needed_by_widgets),
widget2 = Widget2(data_needed_by_widgets),
widget3 = Widget3(data_needed_by_widgets);
}
这应该可以正常工作.但是问题出在我要访问小部件中的constants.dart
(它包含一堆const
字符串和我在所有文件中使用的其他东西)时
This should work fine. But the problem comes when I want to access constants.dart
in my widgets (It holds a bunch of const
Strings and other stuff that I use across all my files):
utils/complex_widget1.dart
:
// Pretend this has actually complicated stuff
import "constants.dart"; // How do I import this?
class Widget1 extends StatelessWidget {
@override
Widget build (BuildContext context) => Center (
child: Text (TITLE_TEXT) // From constants.dart
);
}
我不能只是从constants.dart
中导入各个变量,它们都是全局变量,没有作为参数传递的类或函数.如何从Widget1
(或其他任何complex_widget
)访问constants.dart
中的值?
I can't just import the individual variables from constants.dart
, they're all global and there are no classes or functions to pass as arguments. How do I access values from constants.dart
from Widget1
(or any other complex_widget
, for that matter)?
推荐答案
您可以使用相对路径
import '../../constants.dart';
但是您应该使用包路径,因此移动文件不需要编辑导入.
But you should use package paths so moving the files doesn't require editing the imports.
import 'package:YOUR_PACKAGE/constants.dart';
请注意,在package
路径中省略了lib/
目录.
Note the lib/
directory is omitted in package
paths.
这篇关于从Flutter中的父目录导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!