Augustin R
Augustin R

Reputation: 7799

Any difference between importing whole file and importing only class with show in Dart?

Instead of writing :

import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';

which exports a dozen of files, I would like to write :

import 'package:flutter_platform_widgets/flutter_platform_widgets.dart'
    show
        PlatformAlertDialog,
        PlatformCircularProgressIndicator,
        PlatformDialogAction,
        PlatformText,
        showPlatformDialog;

because I'm only using these components. However this is quite tidious (reminds me of Typescript's endless imports) and goes against Dart's principle of briefness.

Imports snippets in VSCode uses the first solution, but is there any notable difference, for example in terms of performance? Is there some kind of good practice? I cannot find anything in official guidelines.

Upvotes: 18

Views: 6468

Answers (2)

CopsOnRoad
CopsOnRoad

Reputation: 267614

There is no impact on performance. The reason of using show is to reduce chances of confusion when importing classes from different packages.

For instance: Let's say

abc.dart has 2 classes

class One {}

class Two {}

And xyz.dart also has 2 classes:

class One {}

class Three {}

And you are importing both package in your file

import 'abc.dart';
import 'xyz.dart';

Say, you only want to use class One from abc.dart, so when you use One it could be from abc.dart or xyz.dart. So to prevent One coming from xyz.dart you'd use:

import `xyz.dart` show Three // which means only `Three` class can be used in your current file from xyz.dart package

Upvotes: 16

Peter Haddad
Peter Haddad

Reputation: 80914

When you use the keyword show basically what you are saying that I only want to use this specific class from this package in your dart file, from the docs:

Importing only part of a library

If you want to use only part of a library, you can selectively import the library. For example:

// Import only foo.
import 'package:lib1/lib1.dart' show foo;

// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;

Now if you try to use anything from this package other than foo you will get an error because you specified that you only want to use foo.

Upvotes: 8

Related Questions