Open In App

How to reference another file in Dart?

Last Updated : 14 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Dart is a programming language developed by Google. It is generally used for client-side development in web and mobile apps or we can say that it is used to create single-page websites and web applications for example Gmail. Dart has become popular with Flutter for developing cross-platform applications. It is an open-source and object-oriented programming language. 

In this article, we are going to see how we can refer one file to another dart file. We will see this, step by step with the help of a Flutter project on VSCode. Let us assume that we have our main screen named as main.dart and we want to add another screen to the project. So for that, we need to create another file and add a reference to that file into our main.dart so that we can use any functionality from that screen. 

Add a reference to another file

You can add another file as a reference with the help of the below-mentioned steps.

Step 1: Create your file that is needed to be referred, by double-clicking on the lib folder and then on “New File“. Give a filename to it and the extension should be .dart.

Creating-a-file-for-reference

Step 2: Go to your main file where you want to refer to your second file.

Goto-main-file-to-refer-second-file

Step 3: Now start writing “import” on the top of your “main.dart” file. VSCode should give you suggestions for the rest of the syntax. If otherwise, write “import ‘filename.dart’;”.

Import-another-file-as-a-reference-file

Note: If your file is in another directory or inside a package, then you have to include the path to that file also inside the single quote. Like in this case material.dart has been included, so we have mentioned the package name to which the file belongs like this:

Give-the-reference-of-the-file-from-another-directory

That’s it! Now you can do any operation in between both the files or call a method from the second file or pass data, however, it may require.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads