7
votes

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)?

1
import '../constants.dart';Richard Heap

1 Answers

20
votes

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.