Menu
Coddy logo textTech

External Files

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 1 of 110.

External files let you organize your classes in separate Dart files and import them into your main program.

Create a separate Dart file called my_class.dart

class MyClass {
  // class body
}

Import the file into your main file using the import directive

import 'my_class.dart';

Now you can use the class in your main file

void main() {
  MyClass obj = MyClass();
  print(obj.runtimeType);
}

Output:

MyClass

The import 'my_class.dart'; statement connects the my_class.dart file to your program. The filename must include the .dart extension and be wrapped in single quotes. Dart resolves the path relative to the current file.

challenge icon

Challenge

Medium

You are given two Dart files (my_class.dart and driver.dart). Add the correct import statement in driver.dart to connect the files so that MyClass can be used!

Cheat sheet

To use classes from external files, create separate Dart files and import them using the import directive:

Create a separate file (e.g., my_class.dart):

class MyClass {
  // class body
}

Import the file in your main program:

import 'my_class.dart';

The filename must include the .dart extension and be wrapped in single quotes. Dart resolves the path relative to the current file.

Use the imported class:

void main() {
  MyClass obj = MyClass();
  print(obj.runtimeType);
}

Try it yourself

// TODO: Import my_class.dart

import 'dart:io';

void main() {
  String testCase = stdin.readLineSync()!;
  MyClass obj = MyClass();
  print('Test completed');
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming