Compare commits

..
Author SHA1 Message Date
hugo 2a4e29f38c chore(release): publish packages
- wyatt_architecture@0.1.0
 - wyatt_authentication_bloc@0.4.0+2
 - wyatt_crud_bloc@0.1.0+1
 - wyatt_form_bloc@0.2.0+1
2022-12-03 20:40:23 -05:00
hugo ca70f2eb1d feat(authentication)!: add repo in callback usecases (close #55) 2022-12-03 18:53:20 -05:00
hugo f123e537ae fix(authentication): allow email/password validators customization (closes #57) 2022-12-03 18:41:04 -05:00
AN12345 c3315d968c refactor(bloc_helper)!: update onWrap label (close #46) 2022-11-24 18:16:20 -05:00
AN12345 45312473d1 feat: add gen-class-models in melos scripts 2022-11-24 17:55:07 -05:00
AN12345 17e7bce9e6 refactor(architecture): update naming methodes (close #47) 2022-11-24 17:25:44 -05:00
hugo 3886ef080e fix(crud)!: use FutureOrResult extension (close #42) 2022-11-24 15:24:59 -05:00
hugo 626d951443 fix(authentication)!: use FutureOrResult extension (close #41) 2022-11-24 11:18:16 -05:00
hugo f36e0b51e0 feat(type): add Result extension on FutureOr type (close #40) 2022-11-23 19:13:04 -05:00
AN12345 80ce7aff91 fix(architecture): fix execute method on error handler. (#38) 2022-11-23 23:11:04 +00:00
AN12345 a9121b6862 refactor(architecture): update example. (close #38) 2022-11-23 23:11:04 +00:00
AN12345 54f92e8042 docs(architecture): generate class model. (#38) 2022-11-23 23:11:04 +00:00
AN12345 00393a6ba7 docs(architecture): update Readme. (#38) 2022-11-23 23:11:04 +00:00
AN12345 136e0e8c98 chore(architecture)!: update exports. (#38) 2022-11-23 23:11:04 +00:00
AN12345 500a6ae51d feat(architecture): update usecase en add & sepcific case. (#38) 2022-11-23 23:11:04 +00:00
AN12345 79fdde25fc feat(architecture): add obsevers for alternative usecase scenarions (#38) 2022-11-23 23:11:04 +00:00
Malo Léon 742bf1d614 Merge pull request 'config/update_project_management' (#32) from config/update_project_management into master
Reviewed-on: #32
Reviewed-by: Hugo Pointcheval <hugo@noreply@wyatt-studio.fr>
2022-11-22 02:33:48 +00:00
AN12345 0dbde68d7d typo: fix readme typo error 2022-11-21 21:32:36 -05:00
AN12345 cd881da072 doc: update readme 2022-11-21 21:20:25 -05:00
AN12345 5918a5cf1f doc: add simple workflow diagramm 2022-11-21 21:20:01 -05:00
AN12345 775d766d14 build: update melos configuration and update targets 2022-11-21 20:59:36 -05:00
AN12345 383098b147 build: add mason configuration files 2022-11-21 20:59:02 -05:00
AN12345 4d51e2b786 build: add coverage script 2022-11-21 20:58:18 -05:00
AN12345 32cc1f55d9 chore: update gitignore 2022-11-21 20:57:52 -05:00
AN12345 6ee101bf36 doc: update readme 2022-11-21 20:54:57 -05:00
hugo f0ed08bd49 feat(auth): add reloadCache method in AuthenticationCubit 2022-11-16 19:52:24 -05:00
hugo 390fb81b1e fix(auth): fix stream account, now including correctly extra data 2022-11-16 19:51:45 -05:00
hugo 279d451cd8 fix(auth): fix mock isNewUser 2022-11-16 19:48:03 -05:00
hugo a66db23ace chore(release): publish packages
- wyatt_authentication_bloc@0.4.0+1
2022-11-16 17:20:57 -05:00
hugo 3d7af98ac9 fix(auth): add sort of mutex on onAuthChanges callback trigger 2022-11-16 17:16:41 -05:00
AN12345 b033b97917 feat(notification_bloc) add new package for push notification management 2022-11-16 16:58:19 -05:00
hugo 14b7f31b53 chore(form): use hard link for vscode folder 2022-11-16 16:32:05 -05:00
hugo 403bcafe93 chore(form): remove vscode symlink 2022-11-16 16:30:49 -05:00
hugo 21ab6f6021 chore(auth): use hardlink for vscode folder 2022-11-16 16:27:51 -05:00
hugo 198ecac5da chore(auth): remove vscode symlink to fix publish 2022-11-16 16:18:23 -05:00
hugo c945cd435e chore(release): publish packages
- wyatt_authentication_bloc@0.4.0
 - wyatt_form_bloc@0.2.0
2022-11-16 16:03:13 -05:00
hugo 852d29ef0a refactor(auth): update example with new input builders 2022-11-16 16:02:18 -05:00
hugo 08383ec03b refactor(form)!: input builders provides FormInput 2022-11-16 16:00:13 -05:00
hugo ee8ce76839 fix(form): disable status selection and rebuild SubmitBuilder on every state changes #28 2022-11-16 15:51:34 -05:00
hugo f05f2230e9 fix(auth): add initial null account event in stream in the mock authentication 2022-11-16 15:46:07 -05:00
hugo 54002beaab test(auth): add tests for the SignUpCubit update method 2022-11-16 15:45:11 -05:00
hugo d5698fbffc test(form): add formReplace test case #27 2022-11-16 15:43:52 -05:00
hugo 31ad460757 fix(auth)!: add signInWithEmailAndPassword and signInAnonymously methods in SignInCubit #26 2022-11-15 19:25:20 -05:00
hugo 4fd2a2a16c chore(auth): remove old example and rename actual 2022-11-15 18:52:10 -05:00
hugo 6eb40de72c feat(form): add metadata tag to bypass validation #29 2022-11-15 18:48:02 -05:00
hugo cecbc94a95 chore(auth): add global vscode folder symlink 2022-11-15 18:13:56 -05:00
hugo 3820fc4764 chore(auth): remove local vscode folder 2022-11-15 18:13:30 -05:00
hugo 1b893a5b84 test(form): add some tests 2022-11-15 18:10:50 -05:00
hugo 72661a343f fix(form): fix set operations behaviors 2022-11-15 18:10:30 -05:00
hugo 9ebe8e21dc fix(form): add nullable validator on boolean value 2022-11-15 18:09:39 -05:00
hugo 141f15b444 feat(form): add shorthands to access validator status 2022-11-15 18:09:13 -05:00
hugo 3a8a604a48 chore(form): add vscode folder symlink 2022-11-15 18:06:13 -05:00
hugo 41493207b3 chore(form): remove local vscode folder 2022-11-15 18:05:18 -05:00
hugo cbc4a2e149 chore: change vscode global settings 2022-11-15 18:03:30 -05:00
hugo 7345e415a7 chore(release): publish packages
- wyatt_crud_bloc@0.1.0
2022-11-13 20:29:19 -05:00
hugo ff680614aa typo(crud): fix line length 2022-11-13 20:21:20 -05:00
hugo 3e110e2eb5 fix(crud): update example 2022-11-13 20:19:21 -05:00
hugo 1ccb0a540e refactor(crud)!: migrate to wyatt architecture 2022-11-13 20:19:10 -05:00
hugo f9da719b91 refactor(crud): add vscode config 2022-11-13 20:18:10 -05:00
hugo 95f41025f4 chore(release): publish packages
- wyatt_authentication_bloc@0.3.0+1
2022-11-11 19:09:01 -05:00
hugo eceda684f0 fix(auth): fix some bugs to validate publishing 2022-11-11 19:08:28 -05:00
hugo 291c195ceb chore(release): publish packages
- wyatt_authentication_bloc@0.3.0
2022-11-11 19:01:49 -05:00
hugo 1896497c1a refactor(auth): use correct deps 2022-11-11 19:01:00 -05:00
hugo 87254ef547 feat(auth): add fully functionnal mock data source 2022-11-11 18:48:30 -05:00
hugo da34acd35b fix(auth): return exception and not throwing it anymore 2022-11-11 18:47:59 -05:00
hugo d9d0625c67 fix(auth): exception returns msg as message 2022-11-11 18:47:16 -05:00
hugo 08f789725b feat(auth): add toString and equality on entities and models 2022-11-11 18:46:37 -05:00
hugo 33ac5c6280 doc(auth): update pubspec and readme 2022-11-11 16:54:58 -05:00
hugo 762b9bcd11 refactor(auth): update example with new listeners 2022-11-11 16:54:40 -05:00
hugo 38480d84f4 test(auth): add tests for all features 2022-11-11 16:54:08 -05:00
hugo 03a51b97ad feat(auth)!: add email verification, password reset support 2022-11-11 16:53:36 -05:00
hugo 1dd49fa080 chore(release): publish packages
- wyatt_architecture@0.0.2
 - wyatt_authentication_bloc@0.2.1+6
 - wyatt_form_bloc@0.1.0+1
2022-11-10 22:59:51 -05:00
hugo 0219e3d557 doc(arch): update readme 2022-11-10 22:58:35 -05:00
hugo 3de7d01173 feat(arch): add new typedef for stream and simple result 2022-11-10 22:58:19 -05:00
hugo 4183da6259 feat(arch): make base class const 2022-11-10 22:57:51 -05:00
hugo 1f24a76717 chore(form): add hosted dependecy 2022-11-10 13:51:37 -05:00
362 changed files with 10265 additions and 3209 deletions
+4 -1
View File
@@ -197,4 +197,7 @@ $RECYCLE.BIN/
.idea/
*.iml
google-services.json
pubspec_overrides.yaml
pubspec_overrides.yaml
# Mason
.mason/
+7 -2
View File
@@ -1,4 +1,10 @@
{
// Dart
"dart.runPubGetOnPubspecChanges": "never",
// Gitea
"gitea.owner": "Wyatt-FOSS",
"gitea.repo": "wyatt-packages",
// Header
"psi-header.changes-tracking": {
"isActive": true
},
@@ -67,5 +73,4 @@
],
}
],
"dart.runPubGetOnPubspecChanges": false,
}
}
+195
View File
@@ -3,6 +3,201 @@
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2022-12-03
### Changes
---
Packages with breaking changes:
- [`wyatt_architecture` - `v0.1.0`](#wyatt_architecture---v010)
Packages with other changes:
- [`wyatt_authentication_bloc` - `v0.4.0+2`](#wyatt_authentication_bloc---v0402)
- [`wyatt_crud_bloc` - `v0.1.0+1`](#wyatt_crud_bloc---v0101)
- [`wyatt_form_bloc` - `v0.2.0+1`](#wyatt_form_bloc---v0201)
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `wyatt_authentication_bloc` - `v0.4.0+2`
- `wyatt_crud_bloc` - `v0.1.0+1`
- `wyatt_form_bloc` - `v0.2.0+1`
---
#### `wyatt_architecture` - `v0.1.0`
- **REFACTOR**: update naming methodes (close #47).
- **REFACTOR**: update example. (close #38).
- **FIX**: fix execute method on error handler. (#38).
- **FEAT**: update usecase en add & sepcific case. (#38).
- **FEAT**: add obsevers for alternative usecase scenarions (#38).
- **DOCS**: generate class model. (#38).
- **DOCS**: update Readme. (#38).
- **BREAKING** **CHORE**: update exports. (#38).
## 2022-11-16
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`wyatt_authentication_bloc` - `v0.4.0+1`](#wyatt_authentication_bloc---v0401)
---
#### `wyatt_authentication_bloc` - `v0.4.0+1`
- **FIX**: add sort of mutex on onAuthChanges callback trigger.
## 2022-11-16
### Changes
---
Packages with breaking changes:
- [`wyatt_authentication_bloc` - `v0.4.0`](#wyatt_authentication_bloc---v040)
- [`wyatt_form_bloc` - `v0.2.0`](#wyatt_form_bloc---v020)
Packages with other changes:
- There are no other changes in this release.
---
#### `wyatt_authentication_bloc` - `v0.4.0`
- **REFACTOR**: update example with new input builders.
- **FIX**: add initial null account event in stream in the mock authentication.
- **BREAKING** **FIX**: add signInWithEmailAndPassword and signInAnonymously methods in SignInCubit #26.
#### `wyatt_form_bloc` - `v0.2.0`
- **FIX**: disable status selection and rebuild SubmitBuilder on every state changes #28.
- **FIX**: fix set operations behaviors.
- **FIX**: add nullable validator on boolean value.
- **FEAT**: add metadata tag to bypass validation #29.
- **FEAT**: add shorthands to access validator status.
- **BREAKING** **REFACTOR**: input builders provides FormInput.
## 2022-11-13
### Changes
---
Packages with breaking changes:
- [`wyatt_crud_bloc` - `v0.1.0`](#wyatt_crud_bloc---v010)
Packages with other changes:
- There are no other changes in this release.
---
#### `wyatt_crud_bloc` - `v0.1.0`
- **REFACTOR**: add vscode config.
- **FIX**: update example.
- **BREAKING** **REFACTOR**: migrate to wyatt architecture.
## 2022-11-11
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`wyatt_authentication_bloc` - `v0.3.0+1`](#wyatt_authentication_bloc---v0301)
---
#### `wyatt_authentication_bloc` - `v0.3.0+1`
- **FIX**: fix some bugs to validate publishing.
## 2022-11-11
### Changes
---
Packages with breaking changes:
- [`wyatt_authentication_bloc` - `v0.3.0`](#wyatt_authentication_bloc---v030)
Packages with other changes:
- There are no other changes in this release.
---
#### `wyatt_authentication_bloc` - `v0.3.0`
- **REFACTOR**: use correct deps.
- **REFACTOR**: update example with new listeners.
- **FIX**: return exception and not throwing it anymore.
- **FIX**: exception returns msg as message.
- **FEAT**: add fully functionnal mock data source.
- **FEAT**: add toString and equality on entities and models.
- **BREAKING** **FEAT**: add email verification, password reset support.
## 2022-11-10
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`wyatt_architecture` - `v0.0.2`](#wyatt_architecture---v002)
- [`wyatt_authentication_bloc` - `v0.2.1+6`](#wyatt_authentication_bloc---v0216)
- [`wyatt_form_bloc` - `v0.1.0+1`](#wyatt_form_bloc---v0101)
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
- `wyatt_architecture` - `v0.0.2`
Packages with dependency updates only:
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
- `wyatt_authentication_bloc` - `v0.2.1+6`
- `wyatt_form_bloc` - `v0.1.0+1`
---
#### `wyatt_architecture` - `v0.0.2`
## 2022-11-10
### Changes
+131 -23
View File
@@ -1,17 +1,17 @@
<!--
* Copyright (C) 2022 WYATT GROUP
* Please see the AUTHORS file for details.
*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
@@ -51,39 +51,54 @@ and open source.
---
## Development
## Contribution
Clone this repo.
You have to install [melos](https://github.com/invertase/melos).
```shell
git clone ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-packages.git
```
### Prerequisite
- [Flutter](https://github.com/flutter/flutter).
- [Melos](https://github.com/invertase/melos). Used to manage Dart projects with multiple packages.
```shell
dart pub global activate melos
```
Then bootstrap with `melos bs`.
- [Mason](https://github.com/felangel/mason). Used for code generation.
```shell
dart pub global activate mason_cli
```
- [Lcov](https://github.com/linux-test-project/lcov). Used to generate coverage data.
```shell
# on macos
brew install lcov
```
- genhtml. Used to convert coverage data into html pages.
After installing all these packages, bootstrap with `melos bs`.
### Create a new package
Create a new package in `packages/` folder.
```shell
dart create -t package-simple wyatt_<name>
```
Remove any `example/` subfolder. Then create a new sample project.
```shell
flutter create --platforms android --project-name <name>_example example
mason make wyatt_package --package_name wyatt_<name> --description A new Wyatt package --flutter_only false
```
Then bootstrap project with `melos bs` command.
### Convention
#### Naming
In the previous instructions `<name>` variable is important.
In the previous instructions `<name>` variable is important.
It have to be clear and intelligible.
You **MUST** use underscores.
@@ -93,15 +108,44 @@ You **MUST** use `wyatt` prefix for package.
You **MUST** name example with specific name.
For example, if name is CRUD BLOC
- name will be crud_bloc
- so the package will be: `wyatt_crud_bloc`
- and the example will be: `crud_bloc_example`
#### Commits
### Create issues
Add the issues directly related to what you want to develop and label them correctly.
```
Type(scope): issue.
```
For example, on notification bloc package :
- `Feature(notification_bloc): add firebase messaging data source.`
- `Test(notification_bloc): add test for pushwoosh datasource.`
### Branches
Master is protected. You can't push on it. Please develop your feature on another branch. The name of your branch has to match with the issue opened.
`type(scope):issue`
Example :
Issue :
- `Feature(notification_bloc): add firebase messaging data source.`
Branch related to this issue :
- `feature(notification_bloc)/add_firebase_messaging_data_source`
### Commits
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
tl;dr : `type(scope): description`.
tl;dr : `type(scope): description #issue`.
Here allowed <type> values:
- **feat** for a new feature for the user, not a new feature for build script. Such commit will trigger a release bumping a MINOR version.
@@ -115,11 +159,68 @@ Here allowed <type> values:
Some examples :
- `feat(auth): add AWS support.` = add a feature in authentication_bloc package.
- `feat(auth): add AWS support. (#31)` = add a feature in authentication_bloc package, linked to the 31st issue.
- `docs: update readme.` = update **this** readme file.
- `fix(crud)!: fix bug in awesome() function.` = fix a bug, `!` is important and indicate `BREAKING CHANGES`.
- `fix(crud)!: fix bug in awesome() function. (#32)` = fix a bug, `!` is important and indicate `BREAKING CHANGES` linked with the 32nd issue.
Conventional commits are important for `melos version` command !
When you have finished developing, and are ready to close the issue, close it via your commit :
`feat(auth): add AWS support. (close #31)`
Note that your issue will be close after merging on master.
Before closing the issue, please check tests and update coverage. You might run :
```shell
melos run test
melos run gen_coverage
```
#### Merge your work
After closing your issue, some work may have been done on master in the meantime. To keep a clean git history, please rebase before opening a change request.
Two situations :
- You have not yet created your branch and have committed locally :
```shell
git pull --rebase
```
- You are already working on your branch :
```shell
git rebase -i master
```
If possible, please use `--fixup` on your commit in interactive rebase.
Then, opend your PR, get the necessary approval and merge your work. Then you're done ✅.
#### Update version.
Once your work is on the master, you can update your package version. Please filter packages to update only your package. `--scope` is used to do it.
For example, after merging changes on `wyatt_otification_bloc` package, you might run :
```shell
melos version --scope="*wyatt_notification_bloc*"
```
In fact, melos will filter all packages that match the `wyatt_notification_block` pattern.
You can update check all packages tests by running :
```shell
melos run test
```
#### Publish your package
If package is ready for procution, publish it runnig :
```shell
melos publish --scope"*package*"
```
#### Badging
@@ -130,7 +231,8 @@ In the package `readme.md` file, please specify the supported SDK:
```markdown
![SDK: Dart & Flutter](https://img.shields.io/badge/SDK-Dart%20%7C%20Flutter-blue?style=flat-square)
```
or
or
![SDK: Dart](https://img.shields.io/badge/SDK-Dart-blue?style=flat-square)
@@ -161,4 +263,10 @@ Here you can change `package name` and `package version`.
![Status: Experimental](https://img.shields.io/badge/Status-WIP-red?style=flat-square)
This repository is maintained by Wyatt Studio but work is in progress.
This repository is maintained by Wyatt Studio but work is in progress.
## Simple work flow diagramm
To sum up, here a simple work flow diagramm.
![Dev Wokflow](doc/workflow.svg)
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env bash
escapedPath="$(echo `pwd` | sed 's/\//\\\//g')"
if grep flutter pubspec.yaml > /dev/null; then
if [ -d "coverage" ]; then
# combine line coverage info from package tests to a common file
if [ ! -d "$MELOS_ROOT_PATH/coverage" ]; then
mkdir "$MELOS_ROOT_PATH/coverage"
fi
sed "s/^SF:lib/SF:$escapedPath\/lib/g" coverage/lcov.info >> "$MELOS_ROOT_PATH/coverage/lcov.info"
rm -rf "coverage"
fi
fi
+15
View File
@@ -0,0 +1,15 @@
@startuml Simple Developpment Workflow
start
:Create an issue;
:Create branch related to the issue;
repeat :Commit related to the issue;
repeat while (feature is done)
:Update coverage;
:Close issue via last commit;
:Rebase from `master`;
:Create pull request;
:Merge branches;
:Update version;
:Publish package;
stop
@enduml
+25
View File
File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 7.5 KiB

+1
View File
@@ -0,0 +1 @@
{"bricks":{"wyatt_clean_code":{"git":{"url":"ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git","path":"bricks/wyatt_clean_code","ref":"033baa65408ec6b68e6a2ef43e64c24708ef16a1"}},"wyatt_feature_brick":{"git":{"url":"ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git","path":"bricks/wyatt_feature_brick","ref":"033baa65408ec6b68e6a2ef43e64c24708ef16a1"}},"wyatt_package":{"git":{"url":"ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git","path":"bricks/wyatt_package","ref":"033baa65408ec6b68e6a2ef43e64c24708ef16a1"}}}}
+13
View File
@@ -0,0 +1,13 @@
bricks:
wyatt_clean_code:
git:
url: ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git
path: bricks/wyatt_clean_code
wyatt_feature_brick:
git:
url: ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git
path: bricks/wyatt_feature_brick
wyatt_package:
git:
url: ssh://git@git.wyatt-studio.fr:993/Wyatt-FOSS/wyatt-bricks.git
path: bricks/wyatt_package
+14
View File
@@ -36,6 +36,20 @@ scripts:
clean:deep:
run: git clean -x -d -f -q
description: Clean things very deeply with `git clean`.
test:selective_unit_test:
run: melos exec --dir-exists="test" -- flutter test --no-pub --coverage
description: Run Flutter tests for a specific package in this project.
select-package:
flutter: true
test:
run: melos run test:selective_unit_test --no-select
description: Run all Flutter tests in this project.
gen-coverage: melos exec -- sh "\$MELOS_ROOT_PATH/combine_coverage.sh" && genhtml coverage/lcov.info -o coverage/html
gen-class-models: melos exec --scope="*wyatt_*" -- dart pub global run dcdg -o models/class-models.puml
# Additional cleanup lifecycle script, executed when `melos clean` is run.
postclean: >
+17
View File
@@ -1,3 +1,20 @@
## 0.1.0
> Note: This release has breaking changes.
- **REFACTOR**: update naming methodes (close #47).
- **REFACTOR**: update example. (close #38).
- **FIX**: fix execute method on error handler. (#38).
- **FEAT**: update usecase en add & sepcific case. (#38).
- **FEAT**: add obsevers for alternative usecase scenarions (#38).
- **DOCS**: generate class model. (#38).
- **DOCS**: update Readme. (#38).
- **BREAKING** **CHORE**: update exports. (#38).
## 0.0.2
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 0.0.2-dev.0
- **FEAT**: add exceptions, datasources, repositories, and usecases.
+186 -9
View File
@@ -16,19 +16,18 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
-->
# Flutter - Wyatt Architecture
<p align="left">
<a href="https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages/src/branch/master/packages/wyatt_analysis">
<img src="https://img.shields.io/badge/Style-Wyatt%20Analysis-blue.svg?style=flat-square" alt="Style: Wyatt Analysis" />
</a>
<img src="https://img.shields.io/badge/SDK-Flutter-blue?style=flat-square" alt="SDK: Flutter" />
</p>
Architecture for Flutter.
Following: <https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html>
The Wyatt Architecture for Flutter.
## Features
@@ -37,10 +36,188 @@ Following: <https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architect
- DataSource
- Entity
## Getting started
<!-- TODO -->
## Usage
<!-- TODO -->
### Domain
Create your entities by extending `Entity` :
```dart
class Photo extends Entity {
final int id;
final String url;
const Photo({
required this.id,
required this.url,
});
}
```
Then create the data sources by extending `BaseLocalDataSource` or `BaseRemoteDataSource` depending the type of data source.
```dart
abstract class PhotoRemoteDataSource extends BaseRemoteDataSource {
Future<Photo> getPhoto(int id);
Future<List<Photo>> getAllPhotos({int? start, int? limit});
}
```
Then you can create your repositories by extenting `BaseRepository` :
```dart
abstract class PhotoRepository extends BaseRepository {
FutureResult<Photo> getPhoto(int id);
FutureResult<List<Photo>> getAllPhotos({int? start, int? limit});
}
```
> Here the repository is just a proxy of the data sources with result type (to have beautiful error handling).
And finaly create your different usecases :
Several use cases are supported :
- Classic usecase :
```dart
class Test extends AsyncUseCase<QueryParameters, List<Photo>>> {
@override
FuturOrResult<List<Photo>>> call(QueryParameters? params) {
final photos = _photoRepository.getAllPhotos(
start: params.start,
limit: params.limit,
);
return photos;
}
}
```
You can add alternatve scenarios and check pre/post conditions using our extensions :
```dart
class SearchPhotos extends AsyncUseCase<QueryParameters, List<Photo>>> {
@override
FutureOrResult<List<Photo>>> call(QueryParameters? params) {
final photos = _photoRepository.getAllPhotos(
start: params.start,
limit: params.limit,
);
return photos;
}
@override
FutureOr<void> onStart(QueryParameters? params) {
if(params.start == null || params.limit == null){
throw ClientException('Préconndition non valides');
}
}
}
```
You can implement error scenarios overriding `onError`, or check postconditions by overriding `onComplete` .
- Stream usecase :
```dart
class SearchPhotos extends StreamUseCase<QueryParameters, List<Photo>>> {
@override
FutureOrResult<Stream<List<Photo>>>> call(QueryParameters? params) {
final photos = _photoRepository.getAllPhotos(
start: params.start,
limit: params.limit,
);
return photos;
}
}
```
On this case, observers allow you to add alternative scénarios when data changed, overriding `onData` or `onDone`.
Please note that to use handlers, call `call` method and not `execute`.
> In fact, here we need a new parameter object, so let's create it:
```dart
class QueryParameters {
final int? start;
final int? limit;
QueryParameters(this.start, this.limit);
}
```
### Data
We start by creating models for photos and list of photos. You can use `freezed`. The `PhotoModel` extends `Photo` with some de/serializer capabilities. And those are used only in data layer.
Then implements your data sources:
```dart
class PhotoApiDataSourceImpl extends PhotoRemoteDataSource {
final MiddlewareClient _client;
PhotoApiDataSourceImpl(this._client);
@override
Future<Photo> getPhoto(int id) async {
final response = await _client.get(Uri.parse('/photos/$id'));
final photo =
PhotoModel.fromJson(jsonDecode(response.body) as Map<String, Object?>);
return photo;
}
@override
Future<List<Photo>> getAllPhotos({int? start, int? limit}) async {
final startQuery = start.isNotNull ? '_start=$start' : '';
final limitQuery = limit.isNotNull ? '_limit=$limit' : '';
final delimiter1 =
(startQuery.isNotEmpty || limitQuery.isNotEmpty) ? '?' : '';
final delimiter2 =
(startQuery.isNotEmpty && limitQuery.isNotEmpty) ? '&' : '';
final url = '/photos$delimiter1$startQuery$delimiter2$limitQuery';
final response = await _client.get(Uri.parse(url));
final photos =
ListPhotoModel.fromJson({'photos': jsonDecode(response.body)});
return photos.photos;
}
}
```
> 1: Note that here we use `MiddlewareClient` from our http package.
> 2: You can create multiple implementations (one real and one mock for example).
And implement the repositories:
```dart
class PhotoRepositoryImpl extends PhotoRepository {
final PhotoRemoteDataSource _photoRemoteDataSource;
PhotoRepositoryImpl(
this._photoRemoteDataSource,
);
@override
FutureResult<Photo> getPhoto(int id) => Result.tryCatchAsync(
() => _photoRemoteDataSource.getPhoto(id),
(error) => ServerException('Cannot retrieve photo $id.'),
);
@override
FutureResult<List<Photo>> getAllPhotos({int? start, int? limit}) async =>
Result.tryCatchAsync(
() => _photoRemoteDataSource.getAllPhotos(start: start, limit: limit),
(error) => ServerException('Cannot retrieve all photos.'),
);
}
```
That's all.
@@ -35,46 +35,47 @@ class PhotoRepositoryImpl extends PhotoRepository {
);
@override
FutureResult<void> addPhotoToFavorites(Photo photo) => Result.tryCatchAsync(
FutureOrResult<void> addPhotoToFavorites(Photo photo) => Result.tryCatchAsync(
() => _favoriteLocalDataSource.addPhotoToFavorites(photo),
(error) => ClientException('Cannot add photo to favorites.'),
);
@override
FutureResult<bool> checkIfPhotoIsInFavorites(int id) => Result.tryCatchAsync(
FutureOrResult<bool> checkIfPhotoIsInFavorites(int id) =>
Result.tryCatchAsync(
() => _favoriteLocalDataSource.checkIfPhotoIsInFavorites(id),
(error) =>
ClientException('Cannot check if photo `$id` is in favorites.'),
);
@override
FutureResult<void> deletePhotoFromFavorites(int id) => Result.tryCatchAsync(
FutureOrResult<void> deletePhotoFromFavorites(int id) => Result.tryCatchAsync(
() => _favoriteLocalDataSource.deletePhotoFromFavorites(id),
(error) => ClientException('Cannot delete photo `$id` from favorites.'),
);
@override
FutureResult<Album> getAlbum(int id) => Result.tryCatchAsync(
FutureOrResult<Album> getAlbum(int id) => Result.tryCatchAsync(
() => _albumRemoteDataSource.getAlbum(id),
(error) => ServerException('Cannot retrieve album $id.'),
);
@override
FutureResult<List<Album>> getAllAlbums({int? start, int? limit}) =>
FutureOrResult<List<Album>> getAllAlbums({int? start, int? limit}) =>
Result.tryCatchAsync(
() => _albumRemoteDataSource.getAllAlbums(start: start, limit: limit),
(error) => ServerException('Cannot retrieve all albums.'),
);
@override
FutureResult<List<Photo>> getAllPhotos({int? start, int? limit}) async =>
FutureOrResult<List<Photo>> getAllPhotos({int? start, int? limit}) async =>
Result.tryCatchAsync(
() => _photoRemoteDataSource.getAllPhotos(start: start, limit: limit),
(error) => ServerException('Cannot retrieve all photos.'),
);
@override
FutureResult<List<Photo>> getAllPhotosFromFavorites() async {
FutureOrResult<List<Photo>> getAllPhotosFromFavorites() async {
try {
final response = <Photo>[];
final favorites =
@@ -95,13 +96,13 @@ class PhotoRepositoryImpl extends PhotoRepository {
}
@override
FutureResult<Photo> getPhoto(int id) => Result.tryCatchAsync(
FutureOrResult<Photo> getPhoto(int id) => Result.tryCatchAsync(
() => _photoRemoteDataSource.getPhoto(id),
(error) => ServerException('Cannot retrieve photo $id.'),
);
@override
FutureResult<List<Photo>> getPhotosFromAlbum(
FutureOrResult<List<Photo>> getPhotosFromAlbum(
int albumId, {
int? start,
int? limit,
@@ -19,17 +19,17 @@ import 'package:architecture_example/domain/entities/photo.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
abstract class PhotoRepository extends BaseRepository {
FutureResult<Album> getAlbum(int id);
FutureResult<List<Album>> getAllAlbums({int? start, int? limit});
FutureResult<Photo> getPhoto(int id);
FutureResult<List<Photo>> getAllPhotos({int? start, int? limit});
FutureResult<List<Photo>> getPhotosFromAlbum(
FutureOrResult<Album> getAlbum(int id);
FutureOrResult<List<Album>> getAllAlbums({int? start, int? limit});
FutureOrResult<Photo> getPhoto(int id);
FutureOrResult<List<Photo>> getAllPhotos({int? start, int? limit});
FutureOrResult<List<Photo>> getPhotosFromAlbum(
int albumId, {
int? start,
int? limit,
});
FutureResult<void> addPhotoToFavorites(Photo photo);
FutureResult<void> deletePhotoFromFavorites(int id);
FutureResult<List<Photo>> getAllPhotosFromFavorites();
FutureResult<bool> checkIfPhotoIsInFavorites(int id);
FutureOrResult<void> addPhotoToFavorites(Photo photo);
FutureOrResult<void> deletePhotoFromFavorites(int id);
FutureOrResult<List<Photo>> getAllPhotosFromFavorites();
FutureOrResult<bool> checkIfPhotoIsInFavorites(int id);
}
@@ -1,31 +1,40 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class AddPhotoToFavorites extends UseCase<Photo, List<Photo>> {
class AddPhotoToFavorites extends AsyncUseCase<Photo, List<Photo>> {
final PhotoRepository _photoRepository;
AddPhotoToFavorites(this._photoRepository);
@override
FutureResult<List<Photo>> call(Photo params) async {
await _photoRepository.addPhotoToFavorites(params);
FutureOrResult<List<Photo>> execute(Photo? params) async {
await _photoRepository.addPhotoToFavorites(params!);
return _photoRepository.getAllPhotosFromFavorites();
}
@override
FutureOr<void> onStart(Photo? params) {
if (params == null) {
throw ClientException('Photo cannot be null');
}
}
}
@@ -14,15 +14,24 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class CheckIfPhotoIsInFavorites extends UseCase<int, bool> {
class CheckIfPhotoIsInFavorites extends AsyncUseCase<int, bool> {
final PhotoRepository _photoRepository;
CheckIfPhotoIsInFavorites(this._photoRepository);
@override
FutureResult<bool> call(int params) async =>
_photoRepository.checkIfPhotoIsInFavorites(params);
FutureOrResult<bool> execute(int? params) async =>
_photoRepository.checkIfPhotoIsInFavorites(params!);
@override
FutureOr<void> onStart(int? params) {
if (params == null) {
throw ClientException('id cannot be null');
}
}
}
@@ -1,16 +1,16 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
@@ -18,13 +18,13 @@ import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class DisplayFavorites extends UseCase<void, List<Photo>> {
class DisplayFavorites extends AsyncUseCase<NoParam, List<Photo>> {
final PhotoRepository _photoRepository;
DisplayFavorites(this._photoRepository);
@override
FutureResult<List<Photo>> call(void params) {
FutureOrResult<List<Photo>> execute(void params) {
final photos = _photoRepository.getAllPhotosFromFavorites();
return photos;
}
@@ -14,18 +14,27 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class DisplayPhoto extends UseCase<int, Photo> {
class DisplayPhoto extends AsyncUseCase<int, Photo> {
final PhotoRepository _photoRepository;
DisplayPhoto(this._photoRepository);
@override
FutureResult<Photo> call(int params) {
final photo = _photoRepository.getPhoto(params);
FutureOrResult<Photo> execute(int? params) {
final photo = _photoRepository.getPhoto(params!);
return photo;
}
@override
FutureOr<void> onStart(int? params) {
if (params == null) {
throw ClientException('id cannot be null');
}
}
}
@@ -14,24 +14,33 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:architecture_example/domain/usecases/photos/params/query_parameters.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class OpenAlbum extends UseCase<QueryParameters, List<Photo>> {
class OpenAlbum extends AsyncUseCase<QueryParameters, List<Photo>> {
final PhotoRepository _photoRepository;
OpenAlbum(this._photoRepository);
@override
FutureResult<List<Photo>> call(QueryParameters params) {
FutureOrResult<List<Photo>> execute(QueryParameters? params) {
final photos = _photoRepository.getPhotosFromAlbum(
params.albumId,
params!.albumId,
start: params.start,
limit: params.limit,
);
return photos;
}
@override
FutureOr<void> onStart(QueryParameters? params) {
if (params == null) {
throw ClientException('params cannot be null');
}
}
}
@@ -14,18 +14,27 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/photo.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class RemovePhotoFromFavorites extends UseCase<int, List<Photo>> {
class RemovePhotoFromFavorites extends AsyncUseCase<int, List<Photo>> {
final PhotoRepository _photoRepository;
RemovePhotoFromFavorites(this._photoRepository);
@override
FutureResult<List<Photo>> call(int params) async {
await _photoRepository.deletePhotoFromFavorites(params);
FutureOrResult<List<Photo>> execute(int? params) async {
await _photoRepository.deletePhotoFromFavorites(params!);
return _photoRepository.getAllPhotosFromFavorites();
}
@override
FutureOr<void> onStart(int? params) {
if (params == null) {
throw ClientException('id cannot be null');
}
}
}
@@ -14,22 +14,31 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:architecture_example/domain/entities/album.dart';
import 'package:architecture_example/domain/repositories/photo_repository.dart';
import 'package:architecture_example/domain/usecases/photos/params/query_parameters.dart';
import 'package:wyatt_architecture/wyatt_architecture.dart';
class RetrieveAllAlbums extends UseCase<QueryParameters, List<Album>> {
class RetrieveAllAlbums extends AsyncUseCase<QueryParameters, List<Album>> {
final PhotoRepository _photoRepository;
RetrieveAllAlbums(this._photoRepository);
@override
FutureResult<List<Album>> call(QueryParameters params) {
FutureOrResult<List<Album>> execute(QueryParameters? params) {
final albums = _photoRepository.getAllAlbums(
start: params.start,
start: params!.start,
limit: params.limit,
);
return albums;
}
@override
FutureOr<void> onStart(QueryParameters? params) {
if (params == null) {
throw ClientException('params cannot be null');
}
}
}
@@ -14,4 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
abstract class BaseDataSource {}
abstract class BaseDataSource {
const BaseDataSource();
}
@@ -16,4 +16,6 @@
import 'package:wyatt_architecture/src/domain/data_sources/base_data_source.dart';
abstract class BaseLocalDataSource extends BaseDataSource {}
abstract class BaseLocalDataSource extends BaseDataSource {
const BaseLocalDataSource();
}
@@ -16,4 +16,6 @@
import 'package:wyatt_architecture/src/domain/data_sources/base_data_source.dart';
abstract class BaseRemoteDataSource extends BaseDataSource {}
abstract class BaseRemoteDataSource extends BaseDataSource {
const BaseRemoteDataSource();
}
@@ -14,4 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
class BaseRepository {}
abstract class BaseRepository {
const BaseRepository();
}
@@ -0,0 +1,44 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/wyatt_architecture.dart';
/// Usecase observers
mixin Observer<Parameters, ReturnType> {
/// Called before usecase is runned.
/// Usefull to check the preconditions
FutureOr<void> onStart(Parameters? params) {}
/// Called when error occures during main scenario
/// Usefull to run alternative scenario
FutureOr<void> onError(AppException? error) {}
}
/// Specific observer for classic usecase
mixin AsyncObserver<ReturnType> {
FutureOr<void> onComplete(ReturnType? data) {}
}
/// Specific observer for stream case usecase
mixin StreamObserver<ReturnType> {
/// Replaces the data event handler of this subscription.
void onDone() {}
/// Replaces the done event handler of this subscription.
void onData(ReturnType? data) {}
}
@@ -1,25 +1,80 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:async';
import 'package:wyatt_architecture/src/core/exceptions/exceptions.dart';
import 'package:wyatt_architecture/src/domain/usecases/observers.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';
typedef FutureResult<T> = Future<Result<T, AppException>>;
typedef FutureOrResult<T> = FutureOr<Result<T, AppException>>;
typedef StreamResult<T> = Stream<Result<T, AppException>>;
// ignore: one_member_abstracts
abstract class UseCase<Parameters, ReturnType> {
FutureResult<ReturnType> call(Parameters params);
/// Abstract class of a use case
abstract class BaseUseCase<Parameters, ReturnType> {
/// Run use case scenarios
ReturnType call(Parameters parameters);
/// Private function to implement main scenario
/// of your usecase.
ReturnType execute(Parameters params);
}
/// Abstract class of a use case that deals specifically
/// with the response and its state.
abstract class UseCase<Parameters, ReturnType>
extends BaseUseCase<Parameters?, FutureOrResult<ReturnType>>
with Observer<Parameters, ReturnType> {
FutureOr<void> _onSuccess(ReturnType data);
/// Supports the result of the main scenario and integrates
/// some alternative scenarios if necessary.
@override
FutureOrResult<ReturnType> call(Parameters? parameters) async {
try {
await onStart(parameters);
final response = await execute(parameters);
if (response.isErr) {
await onError(response.err);
} else if (response.isOk && response.ok != null) {
await _onSuccess(response.ok as ReturnType);
}
return response;
} catch (e) {
return Err(ClientException(e.toString()));
}
}
}
/// Abtstract classic usecase.
abstract class AsyncUseCase<Parameters, ReturnType>
extends UseCase<Parameters?, ReturnType> with AsyncObserver<ReturnType> {
@override
FutureOr<void> _onSuccess(ReturnType data) => onComplete(data);
}
/// Abstract specific usecase bases on streams
abstract class StreamUseCase<Parameters, ReturnType>
extends UseCase<Parameters?, Stream<ReturnType>>
with StreamObserver<ReturnType> {
@override
FutureOr<void> _onSuccess(Stream<ReturnType> data) {
data.listen(
onData,
onDone: onDone,
);
}
}
@@ -14,4 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
export 'no_param.dart';
export 'observers.dart';
export 'usecase.dart';
Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

@@ -0,0 +1,86 @@
@startuml
set namespaceSeparator ::
abstract class "wyatt_architecture::src::core::exceptions::exceptions.dart::AppException" {
+String? message
+String toString()
}
"dart::core::Exception" <|-- "wyatt_architecture::src::core::exceptions::exceptions.dart::AppException"
class "wyatt_architecture::src::core::exceptions::exceptions.dart::ClientException" {
}
"wyatt_architecture::src::core::exceptions::exceptions.dart::AppException" <|-- "wyatt_architecture::src::core::exceptions::exceptions.dart::ClientException"
class "wyatt_architecture::src::core::exceptions::exceptions.dart::ServerException" {
}
"wyatt_architecture::src::core::exceptions::exceptions.dart::AppException" <|-- "wyatt_architecture::src::core::exceptions::exceptions.dart::ServerException"
abstract class "wyatt_architecture::src::domain::repositories::base_repository.dart::BaseRepository" {
}
abstract class "wyatt_architecture::src::domain::data_sources::local::base_local_data_source.dart::BaseLocalDataSource" {
}
"wyatt_architecture::src::domain::data_sources::base_data_source.dart::BaseDataSource" <|-- "wyatt_architecture::src::domain::data_sources::local::base_local_data_source.dart::BaseLocalDataSource"
abstract class "wyatt_architecture::src::domain::data_sources::base_data_source.dart::BaseDataSource" {
}
abstract class "wyatt_architecture::src::domain::data_sources::remote::base_remote_data_source.dart::BaseRemoteDataSource" {
}
"wyatt_architecture::src::domain::data_sources::base_data_source.dart::BaseDataSource" <|-- "wyatt_architecture::src::domain::data_sources::remote::base_remote_data_source.dart::BaseRemoteDataSource"
class "wyatt_architecture::src::domain::usecases::no_param.dart::NoParam" {
}
"wyatt_architecture::src::domain::entities::entity.dart::Entity" <|-- "wyatt_architecture::src::domain::usecases::no_param.dart::NoParam"
abstract class "wyatt_architecture::src::domain::usecases::observers.dart::Observer" {
+FutureOr<void> onStart()
+FutureOr<void> onError()
}
abstract class "wyatt_architecture::src::domain::usecases::observers.dart::AsyncObserver" {
+FutureOr<void> onComplete()
}
abstract class "wyatt_architecture::src::domain::usecases::observers.dart::StreamObserver" {
+void onDone()
+void onData()
}
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::BaseUseCase" {
+ReturnType execute()
+ReturnType call()
}
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::UseCase" {
-FutureOr<void> _onSuccess()
+FutureOr<Result<ReturnType, AppException>> execute()
}
"wyatt_architecture::src::domain::usecases::usecase.dart::BaseUseCase" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::UseCase"
"wyatt_architecture::src::domain::usecases::observers.dart::Observer" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::UseCase"
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::AsyncUseCase" {
-FutureOr<void> _onSuccess()
}
"wyatt_architecture::src::domain::usecases::usecase.dart::UseCase" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::AsyncUseCase"
"wyatt_architecture::src::domain::usecases::observers.dart::AsyncObserver" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::AsyncUseCase"
abstract class "wyatt_architecture::src::domain::usecases::usecase.dart::StreamUseCase" {
-FutureOr<void> _onSuccess()
}
"wyatt_architecture::src::domain::usecases::usecase.dart::UseCase" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::StreamUseCase"
"wyatt_architecture::src::domain::usecases::observers.dart::StreamObserver" <|-- "wyatt_architecture::src::domain::usecases::usecase.dart::StreamUseCase"
abstract class "wyatt_architecture::src::domain::entities::entity.dart::Entity" {
}
@enduml
+1 -1
View File
@@ -1,7 +1,7 @@
name: wyatt_architecture
description: A new Wyatt package
repository: https://git.wyatt-studio.fr/Wyatt-FOSS/wyatt-packages/src/branch/master/packages/wyatt_architecture
version: 0.0.2-dev.0
version: 0.1.0
publish_to: https://git.wyatt-studio.fr/api/packages/Wyatt-FOSS/pub
@@ -14,4 +14,4 @@
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// TODO(wyatt): Add some tests
// Nothing to test as there is no logic in this package.
@@ -0,0 +1,2 @@
firebase_options.dart
.vscode
+7 -2
View File
@@ -1,4 +1,10 @@
{
// Dart
"dart.runPubGetOnPubspecChanges": "never",
// Gitea
"gitea.owner": "Wyatt-FOSS",
"gitea.repo": "wyatt-packages",
// Header
"psi-header.changes-tracking": {
"isActive": true
},
@@ -67,5 +73,4 @@
],
}
],
"dart.runPubGetOnPubspecChanges": false,
}
}
@@ -1,3 +1,39 @@
## 0.4.0+2
- Update a dependency to the latest release.
## 0.4.0+1
- **FIX**: add sort of mutex on onAuthChanges callback trigger.
## 0.4.0
> Note: This release has breaking changes.
- **REFACTOR**: update example with new input builders.
- **FIX**: add initial null account event in stream in the mock authentication.
- **BREAKING** **FIX**: add signInWithEmailAndPassword and signInAnonymously methods in SignInCubit #26.
## 0.3.0+1
- **FIX**: fix some bugs to validate publishing.
## 0.3.0
> Note: This release has breaking changes.
- **REFACTOR**: use correct deps.
- **REFACTOR**: update example with new listeners.
- **FIX**: return exception and not throwing it anymore.
- **FIX**: exception returns msg as message.
- **FEAT**: add fully functionnal mock data source.
- **FEAT**: add toString and equality on entities and models.
- **BREAKING** **FEAT**: add email verification, password reset support.
## 0.2.1+6
- Update a dependency to the latest release.
## 0.2.1+5
- Update a dependency to the latest release.
+20 -258
View File
@@ -29,43 +29,28 @@ Authentication Bloc for Flutter.
## Features
- UserInterface
* UserFirebase : FirebaseAuth user implementation
- AuthenticationRepositoryInterface
* AuthenticationRepositoryFirebase : FirebaseAuth implementation
- ExceptionsInterface
* ExceptionsFirebase : FirebaseAuth Exception parsing implementation
- AuthenticationBloc
* Tracks every user changes
- Right after the listener has been registered.
- When a user is signed in.
- When the current user is signed out.
- When there is a change in the current user's token.
- On `refresh()`
* Start/Stop listening on demand
- `start()` to listen to user changes
- `stop()` to cancel listener
- SignUpCubit
* Handles email/password validation and password confirmation
* Handles register with email/password
* Handles custom form fields thanks `wyatt_form_bloc`
- Use `entries` to pass a `FormData` object
- You can use several pre configured `FormInput` for validation
- You can use `updateFormData()` to change FormData and validators during runtime (intersection, union, difference or replace)
- SignInCubit
* Handles email/password validation
* Handles login with email/password
- EmailVerificationCubit
* Handles send email verification process
* Handles email verification check
- PasswordResetCubit
* Handles send password reset email process
- Builders
* AuthenticationBuilder to build widgets on user state changes
- Wyatt Architecture
- Entities:
- Account : AccountModel -> Contains account information from provider
- AccountWrapper : AccountWrapperModel -> Contains account and extra data.
- Data Sources:
- Local:
- Cached Authentication Data : AuthenticationCacheDataSourceImpl -> Provides a cache implementation
- Remote:
- Remote Authentication Data : AuthenticationFirebaseDataSourceImpl -> Provides a proxy to FirebaseAuth
- Repositories:
- AuthenticationRepository : AuthenticationRepositoryImpl -> Provides all authentication methods
- Features:
- Authentication:
- AuthenticationBuilder : widget to build reactive view from authentication state
- AuthenticationCubit : tracks every auth changes, have sign out capability.
- SignUp:
- SignUpCubit: implementation of a FormDataCubit from `wyatt_form_bloc` for the sign up
- SignIn:
- SignUpCubit: implementation of a FormDataCubit from `wyatt_form_bloc` for the sign in
- Consistent
* Every class have same naming convention
- Tested
* Partially tested with *bloc_test*
## Getting started
@@ -77,227 +62,4 @@ import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
## Usage
Create an authentication repository:
```dart
final AuthenticationRepositoryInterface _authenticationRepository = AuthenticationRepositoryFirebase();
```
Create an authentication cubit:
```dart
final AuthenticationCubit _authenticationCubit = AuthenticationCubit(
authenticationRepository: _authenticationRepository,
);
```
Create a sign up cubit:
```dart
final SignUpCubit _signUpCubit = SignUpCubit(
authenticationRepository: _authenticationRepository,
authenticationCubit: _authenticationCubit,
);
```
You can use `AuthenticationBloc` to route your app.
```dart
return MultiRepositoryProvider(
providers: [
RepositoryProvider<AuthenticationRepositoryInterface>(
create: (context) => _authenticationRepository,
),
],
child: MultiBlocProvider(
providers: [
BlocProvider<AuthenticationCubit>(
create: (context) => _authenticationCubit..init(),
),
BlocProvider<SignUpCubit>(
create: (context) => _signUpCubit,
),
],
child: const AppView(),
),
);
```
> Don't forget to call `init()` on authentication cubit.
And in `AppView` use an `AuthenticationBuilder`:
```dart
AuthenticationBuilder(
unknown: (context) => const LoadingPage(),
unauthenticated: (context) => const LoginPage(),
authenticated: (context, user, userData) => const HomePage(),
)
```
To create a `SignInCubit` you'll need the same `AuthenticationRepository`, you can use the `context`:
```dart
BlocProvider(
create: (_) => SignInCubit(context.read<AuthenticationRepositoryInterface>()),
child: const LoginForm(),
),
```
> In practice it's better to create it in the main `MultiBlocProvider` because the LoginPage can be destroyed, and cubit closed, before login flow ends
## Recipes
### Password confirmation
In this recipe we'll se how to create a custom `FormEntry` to confirm password.
First, create an entry at the SignUpCubit creation:
```dart
SignUpCubit _signUpCubit = SignUpCubit(
authenticationRepository: _authenticationRepository,
authenticationCubit: _authenticationCubit,
entries: const FormData([
FormEntry('form_field_confirmPassword', ConfirmedPassword.pure()),
]),
);
```
Then, in the sign up form, create an input for password confirmation:
- `ConfirmedPassword` validator need password value and confirm password value to compare.
```dart
return BlocBuilder<SignUpCubit, SignUpState>(
builder: (context, state) {
return TextField(
onChanged: (confirmPassword) => context
.read<SignUpCubit>()
.dataChanged(
'form_field_confirmPassword',
ConfirmedPassword.dirty(
password: context.read<SignUpCubit>().state.password.value,
value: confirmPassword,
),
),
obscureText: true,
decoration: InputDecoration(
labelText: 'confirm password',
errorText: state.data!.input('form_field_confirmPassword').invalid
? 'passwords do not match'
: null,
),
);
},
);
```
> `form_field_confirmPassword` is the field identifier used in all application to retrieve data. You can use a constant to avoid typos.
You'll need to update password input to update confirm state on password update !
```dart
return BlocBuilder<SignUpCubit, SignUpState>(
builder: (context, state) {
return TextField(
onChanged: (password) {
context.read<SignUpCubit>().passwordChanged(password);
context.read<SignUpCubit>().dataChanged(
'form_field_confirmPassword',
ConfirmedPassword.dirty(
password: password,
value: context
.read<SignUpCubit>()
.state
.data!
.input('form_field_confirmPassword')
.value,
),
);
},
obscureText: true,
decoration: InputDecoration(
labelText: 'password',
errorText: state.password.invalid ? 'invalid password' : null,
),
);
},
);
```
> Here you call standard `passwordChanged()` AND `dataChanged()`.
And voilà !
### Create Firestore Document on Sign Up
In this recipe we'll se how to create a Firestore Document on sign up success.
First create a callback function:
```dart
Future<void> onSignUpSuccess(SignUpState state, String? uid) async {
if (uid != null) {
final user = {
'uid': uid,
'email': state.email.value,
...state.data.toMap(),
};
await FirebaseFirestore.instance.collection('users').doc(uid).set(user);
}
}
```
Then create SignUpCubit with custom entries and register callback:
```dart
SignUpCubit _signUpCubit = SignUpCubit(
authenticationRepository: _authenticationRepository,
authenticationCubit: _authenticationCubit,
entries: const FormData([
FormEntry('form_field_name', Name.pure(), fieldName: 'name'),
FormEntry('form_field_phone', Phone.pure(), fieldName: 'phone'),
FormEntry('form_field_confirmPassword', ConfirmedPassword.pure(), export: false),
]),
onSignUpSuccess: onSignUpSuccess,
);
```
> Use `fieldName` and `export` to control `.toMap()` result on FormData ! Useful to disable exportation of sensible data like passwords.
Create widgets for each inputs:
```dart
class _PhoneInput extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<SignUpCubit, SignUpState>(
builder: (context, state) {
return TextField(
onChanged: (phone) => context
.read<SignUpCubit>()
.dataChanged('form_field_phone', Phone.dirty(phone)),
keyboardType: TextInputType.phone,
decoration: InputDecoration(
labelText: 'phone',
helperText: '',
errorText: state.data!.input('form_field_phone').invalid
? 'invalid phone'
: null,
),
);
},
);
}
}
```
> Create widgets for Name and ConfirmedPassword too.
Then add a sign up button with:
```dart
context.read<SignUpCubit>().signUpFormSubmitted()
```
And voilà, a document with `uid` as id, and fields `email`, `name`, `phone`, `uid` will be create in `users` collection.
// TODO
@@ -1 +1,4 @@
include: package:wyatt_analysis/analysis_options.flutter.yaml
include: package:wyatt_analysis/analysis_options.flutter.yaml
analyzer:
exclude: "!example/**"
@@ -8,6 +8,7 @@
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
@@ -45,4 +46,4 @@ app.*.map.json
/android/app/profile
/android/app/release
lib/firebase_options.dart
firebase_options.dart
@@ -1,10 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
# This file should be version controlled.
version:
revision: 5464c5bac742001448fe4fc0597be939379f88ea
revision: e99c9c7cd9f6c0b2f8ae6e3ebfd585239f5568f4
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: e99c9c7cd9f6c0b2f8ae6e3ebfd585239f5568f4
base_revision: e99c9c7cd9f6c0b2f8ae6e3ebfd585239f5568f4
- platform: ios
create_revision: e99c9c7cd9f6c0b2f8ae6e3ebfd585239f5568f4
base_revision: e99c9c7cd9f6c0b2f8ae6e3ebfd585239f5568f4
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
@@ -1,4 +0,0 @@
## 1.0.1
- Update a dependency to the latest release.
@@ -1,4 +1,4 @@
# authentication_bloc_example
# example_router
A new Flutter project.
@@ -8,9 +8,9 @@ This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
For help getting started with Flutter development, view the
[online documentation](https://docs.flutter.dev/), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
@@ -30,6 +30,7 @@ apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion flutter.compileSdkVersion
ndkVersion flutter.ndkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
@@ -46,7 +47,9 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.authentication_bloc_example"
applicationId "com.example.example_router"
// You can update the following values to match your application needs.
// For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
minSdkVersion 21
targetSdkVersion flutter.targetSdkVersion
versionCode flutterVersionCode.toInteger()
@@ -1,91 +0,0 @@
{
"project_info": {
"project_number": "136771801992",
"firebase_url": "https://tchat-beta.firebaseio.com",
"project_id": "tchat-beta",
"storage_bucket": "tchat-beta.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:136771801992:android:4ff419f07afdad6097203d",
"android_client_info": {
"package_name": "com.example.authentication_bloc_example"
}
},
"oauth_client": [
{
"client_id": "136771801992-nps7ic22shstvgdv0c2ojvbkj3dkntum.apps.googleusercontent.com",
"client_type": 1,
"android_info": {
"package_name": "com.example.authentication_bloc_example",
"certificate_hash": "5d8790309e13b68c35e5d4d8437c35c6d15e6131"
}
},
{
"client_id": "136771801992-ncuib3rbu7p4ro4eo5su4vaudn2u4qrv.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAYS14uXupkS158Q5QAFP1864UrUN_yDSk"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "136771801992-ncuib3rbu7p4ro4eo5su4vaudn2u4qrv.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "136771801992-e585bm1n9b3lv89t4phrl9u0glsg52ua.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "com.example.example"
}
}
]
}
}
},
{
"client_info": {
"mobilesdk_app_id": "1:136771801992:android:8482c9b90bc29de697203d",
"android_client_info": {
"package_name": "com.example.crud_bloc_example"
}
},
"oauth_client": [
{
"client_id": "136771801992-ncuib3rbu7p4ro4eo5su4vaudn2u4qrv.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyAYS14uXupkS158Q5QAFP1864UrUN_yDSk"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "136771801992-ncuib3rbu7p4ro4eo5su4vaudn2u4qrv.apps.googleusercontent.com",
"client_type": 3
},
{
"client_id": "136771801992-e585bm1n9b3lv89t4phrl9u0glsg52ua.apps.googleusercontent.com",
"client_type": 2,
"ios_info": {
"bundle_id": "com.example.example"
}
}
]
}
}
}
],
"configuration_version": "1"
}
@@ -1,6 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.authentication_bloc_example">
<!-- Flutter needs it to communicate with the running application
package="com.example.example_router">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
@@ -1,7 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.authentication_bloc_example">
package="com.example.example_router">
<application
android:label="authentication_bloc_example"
android:label="example_router"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
@@ -3,7 +3,7 @@
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
@@ -3,7 +3,7 @@
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
@@ -1,6 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.authentication_bloc_example">
<!-- Flutter needs it to communicate with the running application
package="com.example.example_router">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
@@ -6,7 +6,7 @@ buildscript {
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath 'com.android.tools.build:gradle:7.1.2'
// START: FlutterFire Configuration
classpath 'com.google.gms:google-services:4.3.10'
// END: FlutterFire Configuration
@@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip
@@ -1,182 +0,0 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'dart:developer';
import 'package:authentication_bloc_example/constants.dart';
import 'package:authentication_bloc_example/home/home_page.dart';
import 'package:authentication_bloc_example/login/login_page.dart';
import 'package:authentication_bloc_example/model.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
static FormData getNormalFormData() {
return const FormData([
FormInput(formFieldName, Name.pure()),
FormInput(formFieldPhone, Phone.pure()),
FormInput(formFieldPro, Boolean.pure()),
FormInput(
formFieldConfirmedPassword,
ConfirmedPassword.pure(),
metadata: FormInputMetadata(export: false),
),
]);
}
static FormData getProFormData() {
return const FormData([
FormInput(formFieldName, Name.pure()),
FormInput(formFieldPhone, Phone.pure()),
FormInput(formFieldPro, Boolean.pure()),
FormInput(formFieldSiren, Siren.pure()),
FormInput(formFieldIban, Iban.pure()),
FormInput(
formFieldConfirmedPassword,
ConfirmedPassword.pure(),
metadata: FormInputMetadata(export: false),
),
]);
}
// On Authentication Success. (Authenticated or Anonymous)
// User callback.
Future<Map<String, dynamic>> onAuthSuccess(UserInterface user) async {
if (user.isNotEmpty && !user.isAnonymous) {
// Check if user is register in Firesore.
DocumentSnapshot firestoreUser = await FirebaseFirestore.instance
.collection(firestoreCollectionUsers)
.doc(user.uid)
.get();
if (!firestoreUser.exists) {
// Register user in Firestore when sign in with social account.
final uid = user.uid;
final u = {'uid': uid, 'email': user.email};
await FirebaseFirestore.instance
.collection(firestoreCollectionUsers)
.doc(uid)
.set(u);
return {
'user': UserFirestore(
uid: uid,
email: user.email ?? '',
name: user.displayName ?? '',
phone: user.phoneNumber ?? ''),
};
} else {
return {
'user': UserFirestore.fromMap(
firestoreUser.data() as Map<String, dynamic>),
...firestoreUser.data() as Map<String, dynamic>? ?? {}
};
}
} else {
return {};
}
}
// On Sign Up Success.
Future<void> onSignUpSuccess(SignUpState state, String? uid) async {
if (uid != null) {
final data = state.data.toMap();
final user = {'uid': uid, 'email': state.email.value, ...data};
log('onSignUpSuccess: $user');
await FirebaseFirestore.instance
.collection(firestoreCollectionUsers)
.doc(uid)
.set(user);
}
}
@override
Widget build(BuildContext context) {
AuthenticationRepositoryInterface authenticationRepository =
AuthenticationRepositoryFirebase();
AuthenticationCubit authenticationCubit = AuthenticationCubit(
authenticationRepository: authenticationRepository,
onAuthSuccess: onAuthSuccess,
);
SignUpCubit signUpCubit = SignUpCubit(
authenticationRepository: authenticationRepository,
authenticationCubit: authenticationCubit,
entries: getNormalFormData(),
onSignUpSuccess: onSignUpSuccess,
);
SignInCubit signInCubit = SignInCubit(
authenticationRepository: authenticationRepository,
authenticationCubit: authenticationCubit,
);
return MultiRepositoryProvider(
providers: [
RepositoryProvider<AuthenticationRepositoryInterface>(
create: (context) => authenticationRepository,
),
],
child: MultiBlocProvider(
providers: [
BlocProvider<AuthenticationCubit>(
create: (context) => authenticationCubit..init(),
),
BlocProvider<SignUpCubit>(
create: (context) => signUpCubit,
),
BlocProvider<SignInCubit>(
create: (context) => signInCubit,
),
],
child: const AppView(),
),
);
}
}
class AppView extends StatelessWidget {
const AppView({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
buttonTheme: const ButtonThemeData(
buttonColor: Colors.blue,
textTheme: ButtonTextTheme.primary,
),
),
home: AuthenticationBuilder(
unknown: (context) {
return const Scaffold(
body: Center(
child: CircularProgressIndicator(),
),
);
},
authenticated: (context, user, userData) => const HomePage(),
unauthenticated: (context) => const LoginPage(),
),
);
}
}
@@ -3,7 +3,7 @@
// -----
// File: bootstrap.dart
// Created Date: 19/08/2022 15:05:17
// Last Modified: Wed Nov 09 2022
// Last Modified: Fri Nov 11 2022
// -----
// Copyright (c) 2022
@@ -11,8 +11,6 @@ import 'dart:async';
import 'package:example_router/core/dependency_injection/get_it.dart';
import 'package:example_router/core/utils/app_bloc_observer.dart';
import 'package:example_router/firebase_options.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
@@ -25,11 +23,6 @@ Future<void> bootstrap(FutureOr<Widget> Function() builder) async {
FlutterError.onError = (details) {
debugPrint(details.toString());
};
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
await GetItInitializer.init();
runApp(await builder());
@@ -16,6 +16,7 @@
import 'package:get_it/get_it.dart';
import 'package:wyatt_authentication_bloc/wyatt_authentication_bloc.dart';
import 'package:wyatt_type_utils/wyatt_type_utils.dart';
final getIt = GetIt.I;
@@ -23,12 +24,33 @@ abstract class GetItInitializer {
static Future<void> init() async {
getIt
..registerLazySingleton<AuthenticationRemoteDataSource>(
() => AuthenticationFirebaseDataSourceImpl(),
() => AuthenticationMockDataSourceImpl(registeredAccounts: [
Pair(
AccountModel(
uid: '1',
emailVerified: true,
isAnonymous: false,
providerId: 'wyatt',
email: 'toto@test.fr',
),
'toto1234',
),
Pair(
AccountModel(
uid: '2',
emailVerified: false,
isAnonymous: false,
providerId: 'wyatt',
email: 'tata@test.fr',
),
'tata1234',
),
]),
)
..registerLazySingleton<AuthenticationCacheDataSource<int>>(
() => AuthenticationCacheDataSourceImpl<int>(),
);
await getIt.allReady();
}
}
@@ -0,0 +1,30 @@
// Copyright (C) 2022 WYATT GROUP
// Please see the AUTHORS file for details.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
import 'package:wyatt_form_bloc/wyatt_form_bloc.dart';
class CustomPassword extends RegexValidator<ValidationStandardError> {
const CustomPassword.pure([super.value]) : super.pure();
const CustomPassword.dirty([super.value]) : super.dirty();
@override
ValidationStandardError get onEmpty => ValidationStandardError.empty;
@override
ValidationStandardError get onError => ValidationStandardError.invalid;
@override
RegExp get regex => RegExp(r'^(?=.*[A-Za-z\w\s])(?=.*\d).{6,}$');
}

Some files were not shown because too many files have changed in this diff Show More