2
votes

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:

  • pubspec.yaml:
dependencies:
  mycommon:
    path: ../mycommon
  • some_class.dart:
import 'package:mycommon/models.dart';

the common lib/package:

  • pubspec.yaml
name: mycommon
  • lib/src/model/model_1.dart

  • lib/src/model/model_2.dart

  • ...

  • lib/src/model/model_50.dart

  • lib/models.dart:

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:

  • pubspec.yaml:
dependencies:
  mycommon:
    path: ../mycommon
  • some_class.dart:
import 'package:mycommon/model/model_1.dart';

the common lib/package:

  • pubspec.yaml
name: mycommon
  • lib/model/model_1.dart (no library keyword)

  • lib/model/model_2.dart

  • ...

  • lib/model/model_50.dart

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.

1
(no library keyword at all. just a normal class) What does that mean? Where did you get the idea of naming a file .class?Nate Bosch
@NateBosch thanks for the reply. That was just a typo. I have changed my question description now.sgon00

1 Answers

1
votes

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.