sgon00
sgon00

Reputation: 5757

Common Package instead of Library in Dart?

I have some model classes shared between different dart projects.

Option 1

First, I followed the dart Library convention to do the following:

In the project/package which imports the common lib/package:

dependencies:
  mycommon:
    path: ../mycommon
import 'package:mycommon/models.dart';

the common lib/package:

name: mycommon
library mycommon;

export 'src/model/model_1.dart';
export 'src/model/model_2.dart';
...
export 'src/model/model_50.dart';

Option 2

Treat the common lib as a normal package

In the project/package which imports the common lib/package:

dependencies:
  mycommon:
    path: ../mycommon
import 'package:mycommon/model/model_1.dart';

the common lib/package:

name: mycommon

I don't find anywhere using Option 2 yet. This is just what I came up with by myself.

My question is simply if the Option 2 way is recommended? I prefer using the Option 2 because I can just import what class I actually want instead of everything. And most of time, I will only need one class model per dart file.

Upvotes: 2

Views: 560

Answers (1)

Nate Bosch
Nate Bosch

Reputation: 10915

lib/src/model/model_a.class isn't a file name you should ever use for Dart code. The file should be lib/src/model/model_a.dart regardless of what type of Dart code it has.

It's perfectly fine to use lib/model/model_a.dart and import as package:mycommon/model/model_a.dart. The usual case is that a package is published with a single library that gets imported, and then implementation detail in lib/src, but that isn't a requirement. If there are bits of implementation that are useful on their own, having them outside of lib/src and imported directly is fine.

I'd recommend not following that pattern if there are many such files, or if a bunch of them commonly need to be imported together. import 'package:mycommon/models.dart'; is going to be a lot nicer than dozens of imports in a row for each individual model. Dart is not Java and every class you import does not need to be in it's own library.

Upvotes: 1

Related Questions