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
Here is what is in 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);
}
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
);
}
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)?
So to import something to "somefile. dart" you add the import to "lib. dart". All imports are then available in all the lib files.
Run the command "Fix Imports" from the Command Palette; all imports from your own package will become relative. Also, the "Organize Import" command will be called. The only command added (so far) is "dart-import. fix"; you can bind it as desired.
To list all the files or folders, you have to use flutter_file_manager, path, and path_provider_ex flutter package. Add the following lines in your pubspec. yaml file to add this package in your dependency. Add read / write permissions in your android/app/src/main/AndroidManifest.
You can use relative paths
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';
Note the lib/
directory is omitted in package
paths.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With