Home > Software design >  Share model class between custom packages dart
Share model class between custom packages dart

Time:05-04

I have created 2 packages outside lib folder called : authentication_repository and user_repository to handle network requests.

This is my project structure :

├── lib
├── packages
│ ├── authentication_repository
│ └── user_repository

Since both repo needs User class I would like to provide them the same source file but I don't know how to do it.

Now each repo has its own User class and this is a problem because when I import them inside the same file Flutter doesn't know which user.dart file to use, if the one defined inside authentication_repository or the other one defined in user_repository . Each repo has its own pubspec.yaml file so maybe I could start from here?

Some suggested me to create a new repo called models and define here the User class, then both authentication_repository and user_repository will depend from models so they should be able to access the same file. This idea sounds good to me but I don't know how to do it.

EDIT :

I created a new repo called models with User class and models file :

class User extends Equatable {
  const User(this.id);

  final String id;

  @override
  List<Object> get props => [id];
}

And models file :

library models;

export './src/user.dart' show User;

Now how can I add this package to the other 2 repo? This is models/pubspec.yaml :

name: models
description: Dart package which manages the user domain.
version : ^1.0.0
publish_to: none

environment:
  sdk: ">=2.16.0 <3.0.0"

dependencies:
  equatable: ^2.0.0

Now I think I should be able to add it to other pubspec.yaml file like this one inside user_repository :

name: user_repository
description: Dart package which manages the user domain.
publish_to: none

environment:
  sdk: ">=2.16.0 <3.0.0"

dependencies:
  models: ^1.0.0

But receiving this error on models/pubspec.yaml : Error on line 3, column 11 of pubspec.yaml: Invalid version number: Could not parse "^1.0.0".

CodePudding user response:

It is simpler than you think. Just create a new package models in the same way you created other packages. In created package you will see models.dart. This file will imported by other packages like

import 'package:models/models.dart

In the lib folder create new folder src and add user.dart file with your User class into user.dart. To make it accessible from package in your root file models.dart add these lines

library models;
export './src/user.dart' show User;

Do not forget to add the package as a dependency for other packages in their pubspec.yaml:

dependencies:
  flutter:
    sdk: flutter
  models:
    path: [RELATIVE_PATH_TO_PACKAGE]

RELATIVE_PATH_TO_PACKAGE - is the path relatively to your other packages. If you place models package in your packages folder, then in pubspec.yaml of authentication_repository:

dependencies:
  flutter:
    sdk: flutter
  models:
    path: '../models'
  • Related