How do you create a namespace for a Dart class? I come from a C# background, where one would just use namespace SampleNamespace { }.
How do you achieve the same in Dart?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Dart doesn’t have the concept of namespaces, but instead it has libraries. You can consider a library to be sort of equivalent to a namespace, in that a library can be made of multiple files, and contain multiple classes and functions.
Privacy in Dart is also at the library, rather than the class level (anything prefixed with an underscore is private to that library).
An example of defining a library (using the example of a utilities library:
You can make other files part of the same library by using the
partkeyword. Part files are only used to help organize your code; you can put all your classes in a single library file, or split them among several part files (or part files and the library file) – it has no effect on the execution. It is stylistic to put the main library file in a parent folder, and part files in asrc/folder.Expanding the example to show Part files.
Those part files then link back to the library they are part of by using the
part ofstatement:Now that you have a library containing a function, you can make use of that library elsewhere by
importing the library:If you want to alias your library to avoid clashes (where you might import two libraries, both containing a
reverseString()function, you use theaskeyword:The import statement also makes use of packages, as imported by pub, Dart’s package manager, so you can also host your library on github or elsewhere, and reference your library as so:
The pub dependency is defined in a
pubspec.yamlfile, which tells pub where to find the library. You can find out more at pub.dartlang.orgIt is important to note that only the library file can:
importstatements. Part files cannot.librarykeyword. Part files cannot.partfiles. Part files cannot.One final point is that a runnable app file can (and is likely to be) a library file, and can also be made of part files