简体   繁体   中英

What is the purpose of a classless dart file?

I was wondering why there are .dart files without classes. Does it have any advantage?

For example:

import 'package:http/http.dart' as http;

You have to reference it with an "as" and then you can use it like this:

 response = await http
          .post(
            url,
            headers: header,
            body: dataToSend,
          )

Please consider me as a basic flutter developer, probably the answer is out there in a website.

Dart libraries can contain both classes and other top-level declarations, unlike, say, Java where classes are the only top-level declarations allowed, and all other declarations are inside classes.

There is nothing magical about a library which happens to export only non-class declarations. It's just a library. You don't have to import such a library with a prefix (like as http ), you can import it directly as well, and then you can reference the imported names without the prefix:

import "package:http/http.dart";
...
   response = await post(url, headers: headers, body: dataToSend);

Likewise, libraries with classes can also be imported with a prefix:

import "dart:convert" as convert;
... 
   Uint8List utf8 = ...;
   String result = convert.utf8.decode(utf8);

That allows you to avoid name conflicts, like the utf8 name here. In fact, the package:http/http.dart library does export classes , like Response or Client .

The only difference here is that a library which is intended to be imported with a prefix can choose to have shorter names for its top-level members without risking conflicts or ambiguities. Because the name will always be used adjacent to the prefix, extra context from the prefix does not need to be in the name exported from the library.

The post above might conflict with other things named post , but http.post makes it explicit what kind of post we are talking about.

Dart allows you to specify an import prefix In your case its as . With as you are giving the imported library or file a name and you use that name to access properties. It's usually done to prevent a library from polluting your namespace or make the code readable.

and we use dart files without classes mostly to declare constants or function that will repeat in our code so we can access it whenever we want without defining it over and over

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM