Compare commits

..

No commits in common. "master" and "1.0.4" have entirely different histories.

30 changed files with 725 additions and 1024 deletions

View file

@ -1,14 +0,0 @@
name: Iconica Standard Component CI Workflow
# Workflow Caller version: 2.0.0
on:
pull_request:
workflow_dispatch:
jobs:
call-global-iconica-workflow:
uses: Iconica-Development/.github/.github/workflows/component-ci.yml@master
secrets: inherit
permissions: write-all
with:
subfolder: "." # add optional subfolder to run workflow in

View file

@ -1,14 +0,0 @@
name: Iconica Standard Component Documentation Workflow
# Workflow Caller version: 1.0.0
on:
release:
types: [published]
workflow_dispatch:
jobs:
call-iconica-component-documentation-workflow:
uses: Iconica-Development/.github/.github/workflows/component-documentation.yml@master
secrets: inherit
permissions: write-all

7
.gitignore vendored
View file

@ -23,7 +23,7 @@ migrate_working_dir/
# Flutter/Dart/Pub related # Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
pubspec.lock /pubspec.lock
**/doc/api/ **/doc/api/
.dart_tool/ .dart_tool/
.packages .packages
@ -37,8 +37,3 @@ example/windows/
example/web/ example/web/
.flutter-plugins .flutter-plugins
.flutter-plugins-dependencies .flutter-plugins-dependencies
.metadata
# FVM Version Cache
.fvm/
.fvmrc

10
.metadata Normal file
View file

@ -0,0 +1,10 @@
# 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.
version:
revision: f1875d570e39de09040c8f79aa13cc56baab8db1
channel: stable
project_type: package

View file

@ -1,75 +1,39 @@
## 1.6.0 # 1.0.4
* Upgraded flutter_input_library to 3.6.0
## 1.5.0 * Fixed a nullcheck being done on the nullable user in Avatar
- Updated flutter_input_library to 3.2.1
- Added the option to give a `BoxFit` to the avatar image
## 1.4.0
- Added CONTRIBUTING.md, documentation and updated flutter_input_library to 3.2.1
## 1.3.0
- Field has been added so the user can provide it's current password for reauthentication.
## 1.2.1
- Added Iconica CI and Iconica Linter
## 1.2.0
- Added the posibilty to enable the user to change it's password.
## 1.1.6
- Fixed avatar image zooming when constrained beyond it's size
## 1.1.5
- Added custom background color for avatar
## 1.0.5
- Added TextStyle option for all text fields
## 1.0.4
- Fixed a nullcheck being done on the nullable user in Avatar
## 1.0.3 ## 1.0.3
- No longer crashes without profile data * No longer crashes without profile data
## 1.0.2 ## 1.0.2
- Added form key and more customizability for web * Added form key and more customizability for web
## 1.0.1 ## 1.0.1
- Added a default wrap instead of column * Added a default wrap instead of column
## 0.0.11 ## 0.0.11
- Fixed bug where some field wouldn't update when submitted. * Fixed bug where some field wouldn't update when submitted.
## 0.0.10 ## 0.0.10
- Fixed bug where keyboard would close on selecting custom input fields. * Fixed bug where keyboard would close on selecting custom input fields.
## 0.0.7 ## 0.0.7
- Submit all edited fields on submit of one field * Submit all edited fields on submit of one field
## 0.0.3 ## 0.0.3
- Add support for image URL (instead of in-memory image using image parameter from User model) * Add support for image URL (instead of in-memory image using image parameter from User model)
## 0.0.2 ## 0.0.2
- Add prioritizedItems option to display items at the top of the page. * Add prioritizedItems option to display items at the top of the page.
## 0.0.1 ## 0.0.1
- Initial release. * Initial release.

View file

@ -1,198 +0,0 @@
# Contributing
First off, thanks for taking the time to contribute! ❤️
All types of contributions are encouraged and valued.
See the [Table of Contents](#table-of-contents) for different ways to help and details about how we handle them.
Please make sure to read the relevant section before making your contribution.
It will make it a lot easier for us maintainers and smooth out the experience for all involved.
Iconica looks forward to your contributions. 🎉
## Table of contents
- [Code of conduct](#code-of-conduct)
- [I Have a Question](#i-have-a-question)
- [I Want To Contribute](#i-want-to-contribute)
- [Reporting Bugs](#reporting-bugs)
- [Contributing code](#contributing-code)
## Code of conduct
### Legal notice
When contributing to this project, you must agree that you have authored 100% of the content, that you have the necessary rights to the content and that the content you contribute may be provided under the project license.
All accepted pull requests and other additions to this project will be considered intellectual property of Iconica.
All repositories should be kept clean of jokes, easter eggs and other unnecessary additions.
## I have a question
If you want to ask a question, we assume that you have read the available documentation found within the code.
Before you ask a question, it is best to search for existing issues that might help you.
In case you have found a suitable issue but still need clarification, you can ask your question
It is also advisable to search the internet for answers first.
If you then still feel the need to ask a question and need clarification, we recommend the following:
- Open an issue.
- Provide as much context as you can about what you're running into.
We will then take care of the issue as soon as possible.
## I want to contribute
### Reporting bugs
<!-- omit in toc -->
**Before submitting a bug report**
A good bug report shouldn't leave others needing to chase you up for more information.
Therefore, we ask you to investigate carefully, collect information and describe the issue in detail in your report.
Please complete the following steps in advance to help us fix any potential bug as fast as possible.
- Make sure that you are using the latest version.
- Determine if your bug is really a bug and not an error on your side e.g. using incompatible environment components/versions (If you are looking for support, you might want to check [this section](#i-have-a-question)).
- To see if other users have experienced (and potentially already solved) the same issue you are having, check if there is not already a bug report existing for your bug or error.
- Also make sure to search the internet (including Stack Overflow) to see if users outside of Iconica have discussed the issue.
- Collect information about the bug:
- Stack trace (Traceback)
- OS, Platform and Version (Windows, Linux, macOS, x86, ARM)
- Version of the interpreter, compiler, SDK, runtime environment, package manager, depending on what seems relevant.
- Time and date of occurance
- Describe the expected result and actual result
- Can you reliably reproduce the issue? And can you also reproduce it with older versions? Describe all steps that lead to the bug.
Once it's filed:
- The project team will label the issue accordingly.
- A team member will try to reproduce the issue with your provided steps.
If there are no reproduction steps or no obvious way to reproduce the issue, the team will ask you for additional information.
- If the team is able to reproduce the issue, it will be moved into the backlog, as well as marked with a priority, and the issue will be left to be [implemented by someone](#contributing-code).
### Contributing code
When you start working on your contribution, make sure you are aware of the relevant documentation and the functionality of the component you are working on.
When writing code, follow the style guidelines set by Dart: [Effective Dart](https://Dart.dev/guides/language/effective-Dart). This contains most information you will need to write clean Dart code that is well documented.
**Documentation**
As Effective Dart indicates, documenting your public methods with Dart doc comments is recommended.
Aside from Effective Dart, we require specific information in the documentation of a method:
At the very least, your documentation should first name what the code does, then followed below by requirements for calling the method, the result of the method.
Any references to internal variables or other methods should be done through [var] to indicate a reference.
If the method or class is complex enough (determined by the reviewers) an example is required.
If unsure, add an example in the docs using code blocks.
For classes and methods, document the individual parameters with their implications.
> Tip: Remember that the shortest documentation can be written by having good descriptive names in the first place.
An example:
````Dart
library iconica_utilities.bidirectional_sorter;
part 'sorter.Dart';
part 'enum.Dart';
/// Generic sort method, allow sorting of list with primitives or complex types.
/// Uses [SortDirection] to determine the direction, either Ascending or Descending,
/// Gets called on [List] toSort of type [T] which cannot be shorter than 2.
/// Optionally for complex types a [Comparable] [Function] can be given to compare complex types.
/// ```
/// List<TestObject> objects = [];
/// for (int i = 0; i < 10; i++) {
/// objects.add(TestObject(name: "name", id: i));
/// }
///
/// sort<TestObject>(
/// SortDirection.descending, objects, (object) => object.id);
///
/// ```
/// In the above example a list of TestObjects is created, and then sorted in descending order.
/// If the implementation of TestObject is as following:
/// ```
/// class TestObject {
/// final String name;
/// final int id;
///
/// TestObject({required this.name, required this.id});
/// }
/// ```
/// And the list is logged to the console, the following will appear:
/// ```
/// [name9, name8, name7, name6, name5, name4, name3, name2, name1, name0]
/// ```
void sort<T>(
/// Determines the sorting direction, can be either Ascending or Descending
SortDirection sortDirection,
/// Incoming list, which gets sorted
List<T> toSort, [
/// Optional comparable, which is only necessary for complex types
SortFieldGetter<T>? sortValueCallback,
]) {
if (toSort.length < 2) return;
assert(
toSort.whereType<Comparable>().isNotEmpty || sortValueCallback != null);
BidirectionalSorter<T>(
sortInstructions: <SortInstruction<T>>[
SortInstruction(
sortValueCallback ?? (t) => t as Comparable, sortDirection),
],
).sort(toSort);
}
/// same functionality as [sort] but with the added functionality
/// of sorting multiple values
void sortMulti<T>(
/// Incoming list, which gets sorted
List<T> toSort,
/// list of comparables to sort multiple values at once,
/// priority based on index
List<SortInstruction<T>> sortValueCallbacks,
) {
if (toSort.length < 2) return;
assert(sortValueCallbacks.isNotEmpty);
BidirectionalSorter<T>(
sortInstructions: sortValueCallbacks,
).sort(toSort);
}
````
**Tests**
For each public method that was created, excluding widgets, which contains any form of logic (e.g. Calculations, predicates or major side-effects) tests are required.
A set of tests is written for each method, covering at least each path within the method. For example:
```Dart
void foo() {
try {
var bar = doSomething();
if (bar) {
doSomethingElse();
} else {
doSomethingCool();
}
} catch (_) {
displayError();
}
}
```
The method above should result in 3 tests:
1. A test for the path leading to displayError by the cause of an exception
2. A test for if bar is true, resulting in doSomethingElse()
3. A test for if bar is false, resulting in the doSomethingCool() method being called.
This means that we require 100% coverage of each method you test.

View file

@ -31,7 +31,6 @@ Underneath are all paramters, of the 'ProfilePage' widget, listed with an explan
| itemBuilderOptions | The options used by the standard itemBuilder to alter the function and style of the textfields | | itemBuilderOptions | The options used by the standard itemBuilder to alter the function and style of the textfields |
| prioritizedItems | The items that are displayed at the top of the page. Before all the other items in the list and the default items | | prioritizedItems | The items that are displayed at the top of the page. Before all the other items in the list and the default items |
By default input fields are saved after pressing 'enter' inside of the input field.
## Issues ## Issues
@ -39,7 +38,7 @@ Please file any issues, bugs or feature request as an issue on our [GitHub](http
## Want to contribute ## Want to contribute
If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug or adding a cool new feature), please carefully review our [contribution guide](./CONTRIBUTING.md) and send us your [pull request](https://github.com/Iconica-Development/flutter_profile/pulls). If you would like to contribute to the plugin (e.g. by improving the documentation, solving a bug or adding a cool new feature), please carefully review our [contribution guide](../CONTRIBUTING.md) and send us your [pull request](https://github.com/Iconica-Development/flutter_profile/pulls).
## Author ## Author

View file

@ -1,9 +1,4 @@
include: package:flutter_iconica_analysis/analysis_options.yaml include: package:flutter_lints/flutter.yaml
# Possible to overwrite the rules from the package # Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
analyzer:
exclude:
linter:
rules:

45
example/.metadata Normal file
View file

@ -0,0 +1,45 @@
# 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.
version:
revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
channel: stable
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
- platform: android
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
- platform: ios
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
- platform: linux
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
- platform: macos
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
- platform: web
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
- platform: windows
create_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
base_revision: b8f7f1f9869bb2d116aa6a70dbeac61000b52849
# 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'

View file

@ -2,6 +2,8 @@
// //
// SPDX-License-Identifier: BSD-3-Clause // SPDX-License-Identifier: BSD-3-Clause
import 'dart:typed_data';
import 'package:example/utils/example_profile_service.dart'; import 'package:example/utils/example_profile_service.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@ -42,6 +44,9 @@ class _ProfileExampleState extends State<ProfileExample> {
_user = User( _user = User(
firstName: 'Firstname', firstName: 'Firstname',
lastName: 'Lastname', lastName: 'Lastname',
image: Uint8List.fromList(
[],
),
profileData: profileData, profileData: profileData,
); );
} }
@ -52,68 +57,58 @@ class _ProfileExampleState extends State<ProfileExample> {
var width = MediaQuery.of(context).size.width; var width = MediaQuery.of(context).size.width;
return Scaffold( return Scaffold(
body: ProfilePage( body: Center(
changePasswordConfig: child: Column(
const ChangePasswordConfig(enablePasswordChange: true), children: [
wrapViewOptions: WrapViewOptions( SizedBox(
spacing: 8, height: 400,
direction: Axis.vertical, width: 800,
), child: ProfilePage(
bottomActionText: 'Log out', showItems: false,
itemBuilderOptions: ItemBuilderOptions( prioritizedItems: const ['remarks', 'about'],
//no label for email wrapViewOptions: WrapViewOptions(
validators: { direction: Axis.horizontal,
'first_name': (String? value) { spacing: 16,
if (value == null || value.isEmpty) {
return 'Field empty';
}
return null;
},
'last_name': (String? value) {
if (value == null || value.isEmpty) {
return 'Field empty';
}
return null;
},
'email': (String? value) {
if (value == null || value.isEmpty) {
return 'Field empty';
}
return null;
},
},
inputDecorationField: {
'current_password': const InputDecoration(
constraints: BoxConstraints(
maxHeight: 60,
maxWidth: 250,
), ),
hintText: 'Current password'), bottomActionText: 'Log out',
'password_1': const InputDecoration( itemBuilderOptions: ItemBuilderOptions(
constraints: BoxConstraints( //no label for email
maxHeight: 60, validators: {
maxWidth: 250, 'first_name': (String? value) {
if (value == null || value.isEmpty) {
return 'Field empty';
}
return null;
},
'last_name': (String? value) {
if (value == null || value.isEmpty) {
return 'Field empty';
}
return null;
},
'email': (String? value) {
if (value == null || value.isEmpty) {
return 'Field empty';
}
return null;
},
},
), ),
hintText: 'New password'), user: _user,
'password_2': const InputDecoration( service: ExampleProfileService(),
constraints: BoxConstraints( style: ProfileStyle(
maxHeight: 60, avatarTextStyle: const TextStyle(fontSize: 20),
maxWidth: 250, pagePadding: EdgeInsets.only(
top: 50,
bottom: 50,
left: width * 0.1,
right: width * 0.1,
),
), ),
hintText: 'Repeat new password'), ),
}, ),
), const Text('test')
user: _user, ],
service: ExampleProfileService(),
style: ProfileStyle(
avatarTextStyle: const TextStyle(fontSize: 20),
pagePadding: EdgeInsets.only(
top: 50,
bottom: 50,
left: width * 0.1,
right: width * 0.1,
),
), ),
), ),
); );
@ -145,7 +140,6 @@ class CustomItemBuilderExample extends ItemBuilder {
key: formFieldKey, key: formFieldKey,
controller: controller, controller: controller,
decoration: inputDecoration, decoration: inputDecoration,
style: options.inputTextStyle,
readOnly: options.readOnly, readOnly: options.readOnly,
onFieldSubmitted: (value) { onFieldSubmitted: (value) {
updateItem(value); updateItem(value);

View file

@ -17,7 +17,7 @@ class ExampleProfileData extends ProfileData {
String? remarks; String? remarks;
@override @override
Map<String, Widget?> mapWidget( Map<String, dynamic> mapWidget(
VoidCallback update, VoidCallback update,
BuildContext context, BuildContext context,
) { ) {
@ -38,7 +38,7 @@ class ExampleProfileData extends ProfileData {
} }
@override @override
Map<String, String?> toMap() { Map<String, dynamic> toMap() {
return {'email': email, 'about': about, 'remarks': remarks}; return {'email': email, 'about': about, 'remarks': remarks};
} }

View file

@ -28,12 +28,4 @@ class ExampleProfileService extends ProfileService {
{required Function(bool isUploading) onUploadStateChanged}) { {required Function(bool isUploading) onUploadStateChanged}) {
debugPrint('Updating avatar'); debugPrint('Updating avatar');
} }
@override
FutureOr<bool> changePassword(
BuildContext context, String currentPassword, String newPassword) {
debugPrint('$currentPassword -> $newPassword');
return true;
}
} }

378
example/pubspec.lock Normal file
View file

@ -0,0 +1,378 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
url: "https://pub.dartlang.org"
source: hosted
version: "2.9.0"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
cached_network_image:
dependency: transitive
description:
name: cached_network_image
url: "https://pub.dartlang.org"
source: hosted
version: "3.2.2"
cached_network_image_platform_interface:
dependency: transitive
description:
name: cached_network_image_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.0"
cached_network_image_web:
dependency: transitive
description:
name: cached_network_image_web
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.2"
characters:
dependency: transitive
description:
name: characters
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.1"
clock:
dependency: transitive
description:
name: clock
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.1"
collection:
dependency: transitive
description:
name: collection
url: "https://pub.dartlang.org"
source: hosted
version: "1.16.0"
crypto:
dependency: transitive
description:
name: crypto
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.2"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.5"
fake_async:
dependency: transitive
description:
name: fake_async
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.1"
ffi:
dependency: transitive
description:
name: ffi
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
file:
dependency: transitive
description:
name: file
url: "https://pub.dartlang.org"
source: hosted
version: "6.1.4"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_blurhash:
dependency: transitive
description:
name: flutter_blurhash
url: "https://pub.dartlang.org"
source: hosted
version: "0.7.0"
flutter_cache_manager:
dependency: transitive
description:
name: flutter_cache_manager
url: "https://pub.dartlang.org"
source: hosted
version: "3.3.0"
flutter_lints:
dependency: "direct dev"
description:
name: flutter_lints
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.1"
flutter_profile:
dependency: "direct main"
description:
path: ".."
relative: true
source: path
version: "1.0.4"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
http:
dependency: transitive
description:
name: http
url: "https://pub.dartlang.org"
source: hosted
version: "0.13.5"
http_parser:
dependency: transitive
description:
name: http_parser
url: "https://pub.dartlang.org"
source: hosted
version: "4.0.2"
lints:
dependency: transitive
description:
name: lints
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.0"
matcher:
dependency: transitive
description:
name: matcher
url: "https://pub.dartlang.org"
source: hosted
version: "0.12.12"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.5"
meta:
dependency: transitive
description:
name: meta
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0"
octo_image:
dependency: transitive
description:
name: octo_image
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.2"
path:
dependency: transitive
description:
name: path
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.2"
path_provider:
dependency: transitive
description:
name: path_provider
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.11"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.22"
path_provider_ios:
dependency: transitive
description:
name: path_provider_ios
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.11"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.7"
path_provider_macos:
dependency: transitive
description:
name: path_provider_macos
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.6"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "2.0.5"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.3"
pedantic:
dependency: transitive
description:
name: pedantic
url: "https://pub.dartlang.org"
source: hosted
version: "1.11.1"
platform:
dependency: transitive
description:
name: platform
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.0"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.3"
process:
dependency: transitive
description:
name: process
url: "https://pub.dartlang.org"
source: hosted
version: "4.2.4"
rxdart:
dependency: transitive
description:
name: rxdart
url: "https://pub.dartlang.org"
source: hosted
version: "0.27.7"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.99"
source_span:
dependency: transitive
description:
name: source_span
url: "https://pub.dartlang.org"
source: hosted
version: "1.9.0"
sqflite:
dependency: transitive
description:
name: sqflite
url: "https://pub.dartlang.org"
source: hosted
version: "2.2.0+3"
sqflite_common:
dependency: transitive
description:
name: sqflite_common
url: "https://pub.dartlang.org"
source: hosted
version: "2.4.0+2"
stack_trace:
dependency: transitive
description:
name: stack_trace
url: "https://pub.dartlang.org"
source: hosted
version: "1.10.0"
stream_channel:
dependency: transitive
description:
name: stream_channel
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
string_scanner:
dependency: transitive
description:
name: string_scanner
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.1"
synchronized:
dependency: transitive
description:
name: synchronized
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.0+3"
term_glyph:
dependency: transitive
description:
name: term_glyph
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.1"
test_api:
dependency: transitive
description:
name: test_api
url: "https://pub.dartlang.org"
source: hosted
version: "0.4.12"
typed_data:
dependency: transitive
description:
name: typed_data
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.1"
uuid:
dependency: transitive
description:
name: uuid
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.7"
vector_math:
dependency: transitive
description:
name: vector_math
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.2"
win32:
dependency: transitive
description:
name: win32
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.1"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.0+2"
sdks:
dart: ">=2.18.0 <3.0.0"
flutter: ">=3.3.0"

View file

@ -1,15 +1,14 @@
// SPDX-FileCopyrightText: 2022 Iconica // SPDX-FileCopyrightText: 2022 Iconica
// //
// SPDX-License-Identifier: BSD-3-Clause // SPDX-License-Identifier: BSD-3-Clause
///
library flutter_profile; library flutter_profile;
export 'src/models/change_password_config.dart';
export 'src/models/user.dart';
export 'src/services/profile_service.dart';
export 'src/widgets/avatar/avatar.dart';
export 'src/widgets/avatar/avatar_wrapper.dart';
export 'src/widgets/item_builder/item_builder.dart';
export 'src/widgets/item_builder/item_builder_options.dart';
export 'src/widgets/profile/profile_page.dart'; export 'src/widgets/profile/profile_page.dart';
export 'src/widgets/profile/profile_style.dart'; export 'src/widgets/profile/profile_style.dart';
export 'src/widgets/avatar/avatar_wrapper.dart';
export 'src/widgets/avatar/avatar.dart';
export 'src/services/profile_service.dart';
export 'src/widgets/item_builder/item_builder.dart';
export 'src/models/user.dart';
export 'src/widgets/item_builder/item_builder_options.dart';

View file

@ -1,45 +0,0 @@
import 'package:flutter/material.dart';
/// Configuration to enable to user to change his password in the profilescreen.
class ChangePasswordConfig {
const ChangePasswordConfig({
required this.enablePasswordChange,
this.title = 'Change password',
this.titleStyle,
this.underTitle =
'You van make the password more secure using upper and lower case '
'letter, numbers and special characters.',
this.underTitleStyle,
this.saveButtonBuilder,
this.fieldRequiredErrorText = 'Field required',
this.notEqualErrorText = 'Password have to be equal',
});
/// Enables the textfields for the user to provide a new password.
final bool enablePasswordChange;
/// Text for the title above the textfields.
final String title;
/// Textstyle of the title.
final TextStyle? titleStyle;
/// Text for the undertitle just above the textfields.
final String underTitle;
/// Textstyle for the undertitle
final TextStyle? underTitleStyle;
/// Ability to override the standard 'save password' button.
final Widget Function(
BuildContext context,
void Function() onTap,
)? saveButtonBuilder;
/// Error text to be shown when either of the textfields is empty.
final String fieldRequiredErrorText;
/// Error text to be shown when the second password isn't equal
/// to the first password.
final String notEqualErrorText;
}

View file

@ -10,6 +10,12 @@ import 'package:flutter/material.dart';
/// ///
/// For additional data profileData can be used. /// For additional data profileData can be used.
class User { class User {
String? firstName;
String? lastName;
Uint8List? image;
String? imageUrl;
ProfileData? profileData;
User({ User({
this.firstName, this.firstName,
this.lastName, this.lastName,
@ -18,6 +24,10 @@ class User {
this.profileData, this.profileData,
}); });
String get displayName => '${firstName ?? ''} ${lastName ?? ''}';
String get initials =>
'${(firstName?.isNotEmpty ?? false) ? firstName![0] : ''}${(lastName?.isNotEmpty ?? false) ? lastName![0] : ''}';
factory User.fromMap(Map<String, dynamic> data) => User( factory User.fromMap(Map<String, dynamic> data) => User(
firstName: data['first_name'], firstName: data['first_name'],
lastName: data['last_name'], lastName: data['last_name'],
@ -26,35 +36,6 @@ class User {
profileData: data['profile_data'], profileData: data['profile_data'],
); );
/// The first name of the user.
String? firstName;
/// The last name of the user.
String? lastName;
/// The image of the user, stored as Uint8List.
Uint8List? image;
/// The URL of the user's image.
String? imageUrl;
/// Additional profile data for the user.
ProfileData? profileData;
/// The display name of the user, which is a combination of
/// the first name and the last name.
/// If the first name or the last name is null,
/// an empty string is used instead.
String get displayName => '${firstName ?? ''} ${lastName ?? ''}';
/// The initials of the user, which are the first characters
/// of the first name and the last name.
/// If the first name or the last name is null or empty,
/// an empty string is used instead.
String get initials =>
'${(firstName?.isNotEmpty ?? false) ? firstName![0] : ''}'
'${(lastName?.isNotEmpty ?? false) ? lastName![0] : ''}';
Map<String, dynamic> toMap() => { Map<String, dynamic> toMap() => {
'first_name': firstName, 'first_name': firstName,
'last_name': lastName, 'last_name': lastName,
@ -66,19 +47,17 @@ class User {
/// ProfileData is used to store custom/addintional data for a user. /// ProfileData is used to store custom/addintional data for a user.
/// ///
/// The MapWidget method is used to bind a [Widget] to one of the keys. /// The MapWidget method is used to bind a [Widget] to one of the keys. This will override the standard textfield.
/// This will override the standard textfield.
/// ///
/// The Builditems method is used to make the list of /// The Builditems method is used to make the list of field to house the user data.
/// field to house the user data.
abstract class ProfileData { abstract class ProfileData {
const ProfileData(); const ProfileData();
ProfileData fromMap(Map<String, dynamic> data); ProfileData fromMap(Map<String, dynamic> data);
Map<String, String?> toMap(); Map<String, dynamic> toMap();
Map<String, Widget?> mapWidget(VoidCallback update, BuildContext context); Map<String, dynamic> mapWidget(VoidCallback update, BuildContext context);
ProfileData create(); ProfileData create();
} }

View file

@ -6,18 +6,13 @@ import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_profile/src/models/user.dart'; import 'package:flutter_profile/src/models/user.dart';
/// ProfileService can be extended and set for the profilePage. /// ProfileService can be extended and set for the profilePage. The following method can be overriden.
/// The following method can be overriden.
/// ///
/// BottompageAction is called when the [InkWell] at the bottom of /// BottompageAction is called when the [InkWell] at the bottom of the page is tapped.
/// the page is tapped.
/// ///
/// EditProfile is called when a user changes and submits a standard textfields. /// EditProfile is called when a user changes and submits a standard textfields.
/// ///
/// UploadImage is called when te user presses the avatar. /// UploadImage is called when te user presses the avatar.
///
/// changePassword is called when the user requests to change his password.
/// Return true to clear the inputfields.
abstract class ProfileService { abstract class ProfileService {
const ProfileService(); const ProfileService();
@ -27,13 +22,6 @@ abstract class ProfileService {
FutureOr<void> uploadImage( FutureOr<void> uploadImage(
BuildContext context, { BuildContext context, {
// ignore: avoid_positional_boolean_parameters
required Function(bool isUploading) onUploadStateChanged, required Function(bool isUploading) onUploadStateChanged,
}); });
FutureOr<bool> changePassword(
BuildContext context,
String currentPassword,
String newPassword,
);
} }

View file

@ -8,24 +8,14 @@ import 'package:flutter_profile/src/models/user.dart';
class Avatar extends StatelessWidget { class Avatar extends StatelessWidget {
const Avatar({ const Avatar({
super.key, Key? key,
this.user, this.user,
this.size = 100, this.size = 100,
this.avatarBackgroundColor, }) : super(key: key);
this.boxfit = BoxFit.contain,
});
/// The user object containing user information.
final User? user; final User? user;
/// Size of the avatar.
final double size; final double size;
/// Background color of the avatar.
final Color? avatarBackgroundColor;
final BoxFit boxfit;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
var imageProvider = _getImageProvider(user); var imageProvider = _getImageProvider(user);
@ -38,14 +28,13 @@ class Avatar extends StatelessWidget {
height: size, height: size,
decoration: BoxDecoration( decoration: BoxDecoration(
shape: BoxShape.circle, shape: BoxShape.circle,
color: avatarBackgroundColor ?? color: !hasImage && hasNames
(!hasImage && hasNames ? _generateColorWithIntials(user!.firstName, user!.lastName)
? _generateColorWithIntials(user!.firstName, user!.lastName) : null,
: null),
image: hasImage image: hasImage
? DecorationImage( ? DecorationImage(
image: imageProvider, image: imageProvider,
fit: boxfit, fit: BoxFit.cover,
) )
: null, : null,
), ),
@ -62,7 +51,6 @@ class Avatar extends StatelessWidget {
); );
} }
/// Returns the image provider based on user's image or image URL.
ImageProvider? _getImageProvider(User? user) { ImageProvider? _getImageProvider(User? user) {
if (user?.image != null) { if (user?.image != null) {
return MemoryImage(user!.image!); return MemoryImage(user!.image!);
@ -72,8 +60,6 @@ class Avatar extends StatelessWidget {
return null; return null;
} }
/// Generates a color based on the initials of the user's
/// first name and last name.
Color _generateColorWithIntials(String? firstName, String? lastName) { Color _generateColorWithIntials(String? firstName, String? lastName) {
var idFirstName = 0; var idFirstName = 0;
var idLastName = 0; var idLastName = 0;

View file

@ -8,36 +8,21 @@ import 'package:flutter_profile/src/widgets/avatar/avatar.dart';
class AvatarWrapper extends StatelessWidget { class AvatarWrapper extends StatelessWidget {
const AvatarWrapper({ const AvatarWrapper({
Key? key,
required this.user, required this.user,
super.key,
this.showName = false, this.showName = false,
this.padding = const EdgeInsets.only(top: 16), this.padding = const EdgeInsets.only(top: 16),
this.size = 100, this.size = 100,
this.textStyle, this.textStyle,
this.customAvatar, this.customAvatar,
this.avatarBackgroundColor, }) : super(key: key);
});
/// The user object containing user information.
final User user; final User user;
/// Custom widget to be used as an avatar.
final Widget? customAvatar; final Widget? customAvatar;
/// Background color of the avatar.
final Color? avatarBackgroundColor;
/// Whether to show the user's name beneath the avatar.
final bool showName; final bool showName;
/// Padding around the avatar and the name.
final EdgeInsets padding; final EdgeInsets padding;
/// Size of the avatar.
final double size;
/// Style for the user's name.
final TextStyle? textStyle; final TextStyle? textStyle;
final double size;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@ -45,7 +30,6 @@ class AvatarWrapper extends StatelessWidget {
Avatar( Avatar(
user: user, user: user,
size: size, size: size,
avatarBackgroundColor: avatarBackgroundColor,
); );
return showName return showName
@ -56,8 +40,8 @@ class AvatarWrapper extends StatelessWidget {
padding: padding, padding: padding,
child: Flexible( child: Flexible(
child: Text( child: Text(
user.displayName,
style: textStyle, style: textStyle,
user.displayName,
), ),
), ),
), ),

View file

@ -3,11 +3,9 @@
// SPDX-License-Identifier: BSD-3-Clause // SPDX-License-Identifier: BSD-3-Clause
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_input_library/flutter_input_library.dart';
import 'package:flutter_profile/src/widgets/item_builder/item_builder_options.dart'; import 'package:flutter_profile/src/widgets/item_builder/item_builder_options.dart';
/// ItemBuilder is used to set the standard textfield for each undefined /// ItemBuilder is used to set the standard textfield for each undefined users data item.
/// users data item.
/// ///
/// Options sets options for the textfield. /// Options sets options for the textfield.
class ItemBuilder { class ItemBuilder {
@ -17,24 +15,19 @@ class ItemBuilder {
final ItemBuilderOptions options; final ItemBuilderOptions options;
Widget build( Widget build(String key, dynamic value, Widget? widget,
String key, Function(String) updateItem, Function(String?) saveItem) {
String? value,
Widget? widget,
void Function(String) updateItem,
void Function(String?) saveItem,
) {
if (widget == null) { if (widget == null) {
var controller = TextEditingController( var controller = TextEditingController(
text: value ?? '', text: '${value ?? ''}',
); );
var inputDecoration = late InputDecoration inputDecoration;
options.inputDecorationField?[key] ?? options.inputDecoration;
inputDecoration =
options.inputDecorationField?[key] ?? options.inputDecoration;
var formFieldKey = GlobalKey<FormFieldState>(); var formFieldKey = GlobalKey<FormFieldState>();
return TextFormField( return TextFormField(
style: options.inputTextStyle,
keyboardType: options.keyboardType?[key], keyboardType: options.keyboardType?[key],
key: formFieldKey, key: formFieldKey,
controller: controller, controller: controller,
@ -46,29 +39,11 @@ class ItemBuilder {
onSaved: (newValue) { onSaved: (newValue) {
saveItem(newValue); saveItem(newValue);
}, },
validator: (value) => options.validators?[key]?.call(value), validator: (value) {
return options.validators?[key]?.call(value);
},
); );
} }
return widget; return widget;
} }
Widget buildPassword(
String key,
TextEditingController controller,
void Function(String?) onChanged,
String? Function(String?) validator,
) {
var inputDecoration =
options.inputDecorationField?[key] ?? options.inputDecoration;
return FlutterFormInputPassword(
controller: controller,
style: options.inputTextStyle,
decoration: inputDecoration,
onChanged: onChanged,
enabled: !options.readOnly,
validator: (value) =>
validator(value) ?? options.validators?[key]?.call(value),
);
}
} }

View file

@ -4,32 +4,24 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// ItemBuilderOptions is a class to store all settings for a field in the /// ItemBuilderOptions is a class to store all settings for a field in the profile page.
/// profile page.
/// ///
/// InputDecoration sets the decoration for all standard textfields. /// InputDecoration sets the decoration for all standard textfields. This is overridden if a field specific decoration is set by inputDecorationField.
/// This is overridden if a field specific decoration is set by
/// inputDecorationField.
/// ///
/// inputDecorationField sets the inputdecoration by key of the user data field. /// inputDecorationField sets the inputdecoration by key of the user data field. So a field can have its own specific decoration.
/// So a field can have its own specific decoration.
/// ///
/// Validator can be used to set a validator for the standard textfield. /// Validator can be used to set a validator for the standard textfield.
class ItemBuilderOptions { class ItemBuilderOptions {
ItemBuilderOptions({ ItemBuilderOptions({
this.inputDecoration = const InputDecoration( this.inputDecoration = const InputDecoration(
constraints: BoxConstraints(maxWidth: 200, maxHeight: 40), constraints: BoxConstraints(maxWidth: 200, maxHeight: 40)),
),
this.inputDecorationField, this.inputDecorationField,
this.readOnly = false, this.readOnly = false,
this.validators, this.validators,
this.keyboardType, this.keyboardType,
this.inputTextStyle,
}); });
final InputDecoration inputDecoration;
/// TextStyle for the input fields final InputDecoration inputDecoration;
final TextStyle? inputTextStyle;
final Map<String, InputDecoration>? inputDecorationField; final Map<String, InputDecoration>? inputDecorationField;
final bool readOnly; final bool readOnly;
final Map<String, String? Function(String?)>? validators; final Map<String, String? Function(String?)>? validators;

View file

@ -16,56 +16,46 @@ class ItemList {
this.itemBuilder, this.itemBuilder,
this.itemBuilderOptions, this.itemBuilderOptions,
}) { }) {
var itemBuilder = this.itemBuilder ?? builder; for (var item in items.entries) {
widgets.addAll({
widgets = { item.key: itemBuilder == null
for (var item in items.entries) ...{ ? builder.build(
item.key: itemBuilder.build( item.key,
item.key, item.value,
item.value, typeMap[item.key],
typeMap[item.key], (value) {
(value) { saveProfile();
saveProfile(); },
}, (value) {
(value) { updateProfile(item.key, value);
updateProfile(item.key, value); },
}, )
), : itemBuilder!.build(
}, item.key,
}; item.value,
typeMap[item.key],
(value) {
saveProfile();
},
(value) {
updateProfile(item.key, value);
},
)
});
}
} }
/// Gets the map of item keys and their corresponding widgets.
Map<String, Widget> getItemList() => widgets; Map<String, Widget> getItemList() => widgets;
/// Map containing item keys and their values. final Map<String, dynamic> items;
final Map<String, String?> items; final Map<String, dynamic> typeMap;
final Function(String, String?) updateProfile;
/// Map containing item keys and their types. final Function() saveProfile;
final Map<String, Widget?> typeMap;
/// Function to update the profile with a specific item's value.
final void Function(String, String?) updateProfile;
/// Function to save the profile after an item value is updated.
final void Function() saveProfile;
/// Builder for custom item widgets.
final ItemBuilder? itemBuilder; final ItemBuilder? itemBuilder;
/// Options for the item builder.
final ItemBuilderOptions? itemBuilderOptions; final ItemBuilderOptions? itemBuilderOptions;
/// Global key for the form associated with the item list.
final GlobalKey<FormState> formKey; final GlobalKey<FormState> formKey;
/// Map containing item keys and their corresponding widgets. Map<String, Widget> widgets = {};
late final Map<String, Widget> widgets;
/// `builder` is an instance of `ItemBuilder` which is used
/// to build the items in the list.
/// If `itemBuilderOptions` is not provided, a default
/// `ItemBuilderOptions` instance is used.
late ItemBuilder builder = ItemBuilder( late ItemBuilder builder = ItemBuilder(
options: itemBuilderOptions ?? ItemBuilderOptions(), options: itemBuilderOptions ?? ItemBuilderOptions(),
); );

View file

@ -1,178 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_profile/flutter_profile.dart';
class ChangePassword extends StatefulWidget {
const ChangePassword({
required this.config,
required this.service,
this.wrapViewOptions,
this.wrapItemsBuilder,
this.itemBuilder,
this.itemBuilderOptions,
this.style = const ProfileStyle(),
super.key,
});
/// Configuration for changing password.
final ChangePasswordConfig config;
/// Options for wrapping the items.
final WrapViewOptions? wrapViewOptions;
/// Builder for wrapping items.
final Widget Function(BuildContext context, Widget child)? wrapItemsBuilder;
/// Builder for creating items.
final ItemBuilder? itemBuilder;
/// Options for item builder.
final ItemBuilderOptions? itemBuilderOptions;
/// Styling options for the widget.
final ProfileStyle style;
/// Profile service for managing user profile.
final ProfileService service;
@override
State<ChangePassword> createState() => _ChangePasswordState();
}
class _ChangePasswordState extends State<ChangePassword> {
late var config = widget.config;
late final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
late final Widget? changePasswordChild;
late var currentPasswordController = TextEditingController();
late var password1Controller = TextEditingController();
late var password2Controller = TextEditingController();
String? currentPassword;
String? password1;
String? password2;
late var builder = widget.itemBuilder ??
ItemBuilder(
options: widget.itemBuilderOptions ?? ItemBuilderOptions(),
);
@override
void initState() {
super.initState();
var changePasswordItems = Wrap(
alignment: widget.wrapViewOptions?.wrapAlignment ?? WrapAlignment.start,
direction: widget.wrapViewOptions?.direction ?? Axis.vertical,
spacing: widget.wrapViewOptions?.spacing ?? 0,
runSpacing: widget.wrapViewOptions?.runSpacing ?? 0,
clipBehavior: widget.wrapViewOptions?.clipBehavior ?? Clip.none,
children: [
builder.buildPassword(
'current_password',
currentPasswordController,
(value) => currentPassword = value,
(value) {
if (currentPassword?.isEmpty ?? true) {
return config.fieldRequiredErrorText;
}
return null;
},
),
builder.buildPassword(
'password_1',
password1Controller,
(value) => password1 = value,
(value) {
if (password1?.isEmpty ?? true) {
return config.fieldRequiredErrorText;
}
return null;
},
),
builder.buildPassword(
'password_2',
password2Controller,
(value) => password2 = value,
(value) {
if (password2?.isEmpty ?? true) {
return config.fieldRequiredErrorText;
}
if (password2 != password1) {
return config.notEqualErrorText;
}
return null;
},
),
],
);
changePasswordChild =
widget.wrapItemsBuilder?.call(context, changePasswordItems) ??
changePasswordItems;
}
@override
Widget build(BuildContext context) {
var theme = Theme.of(context);
Future<void> onTapSave() async {
if ((_formKey.currentState?.validate() ?? false) &&
currentPassword != null &&
password2 != null) {
if (await widget.service
.changePassword(context, currentPassword!, password2!)) {
currentPasswordController.clear();
password1Controller.clear();
password2Controller.clear();
currentPassword = null;
password1 = null;
password2 = null;
}
}
}
return Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
height: widget.style.betweenDefaultItemPadding * 2.5,
),
Text(
config.title,
style: config.titleStyle ?? theme.textTheme.titleMedium,
textAlign: TextAlign.center,
),
Text(
config.underTitle,
style: config.underTitleStyle ?? theme.textTheme.bodyMedium,
textAlign: TextAlign.center,
),
SizedBox(
height: widget.style.betweenDefaultItemPadding,
),
changePasswordChild!,
SizedBox(
height: widget.style.betweenDefaultItemPadding * 2,
),
config.saveButtonBuilder?.call(
context,
onTapSave,
) ??
FilledButton(
onPressed: onTapSave,
child: const Text('Save password'),
),
],
),
);
}
}

View file

@ -3,7 +3,6 @@
// SPDX-License-Identifier: BSD-3-Clause // SPDX-License-Identifier: BSD-3-Clause
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_profile/src/models/change_password_config.dart';
import 'package:flutter_profile/src/models/user.dart'; import 'package:flutter_profile/src/models/user.dart';
import 'package:flutter_profile/src/services/profile_service.dart'; import 'package:flutter_profile/src/services/profile_service.dart';
import 'package:flutter_profile/src/widgets/item_builder/item_builder.dart'; import 'package:flutter_profile/src/widgets/item_builder/item_builder.dart';
@ -11,41 +10,31 @@ import 'package:flutter_profile/src/widgets/item_builder/item_builder_options.da
import 'package:flutter_profile/src/widgets/profile/profile_style.dart'; import 'package:flutter_profile/src/widgets/profile/profile_style.dart';
import 'package:flutter_profile/src/widgets/profile/profile_wrapper.dart'; import 'package:flutter_profile/src/widgets/profile/profile_wrapper.dart';
/// The ProfilePage widget is able to show the data of a user. By default the /// The ProfilePage widget is able to show the data of a user. By default the user is able to change this data. The widget has a couple of parameters listed below:
/// user is able to change this data. The widget has a couple of
/// parameters listed below:
/// ///
/// User will contain the data of the user which atleast contain a first name, last name and an avatar/image. Besides this information the [ProfileData] can be used to set custom user fields. /// User will contain the data of the user which atleast contain a first name, last name and an avatar/image. Besides this information the [ProfileData] can be used to set custom user fields.
/// ///
/// With the use of the service set by a [ProfileService] some actions can be determined what should occur when the user does the following actions: Deleting/editing the profile or uploading an image. /// With the use of the service set by a [ProfileService] some actions can be determined what should occur when the user does the following actions: Deleting/editing the profile or uploading an image.
/// ///
/// The style can be used the set some style options regarding the whole form. /// The style can be used the set some style options regarding the whole form. This is done by setting a [ProfileStyle]. The following styling can be set: The style of the avatar, the padding of the page and default padding between items.
/// This is done by setting a [ProfileStyle]. The following styling can be set:
/// The style of the avatar, the padding of the page and default
/// padding between items.
/// ///
/// CustomAvatar can be set to override the standard avatar using any [Widget]. /// CustomAvatar can be set to override the standard avatar using any [Widget].
/// ///
/// ShowAvatar can be set using a [bool] to determine whether the avatar should /// ShowAvatar can be set using a [bool] to determine whether the avatar should be shown and be able to be set by the user. Default set to true.
/// be shown and be able to be set by the user. Default set to true.
/// ///
/// BottomActionText sets the text for the inkwell at the bottom of the page. /// BottomActionText sets the text for the inkwell at the bottom of the page. If this is set the null then the [InkWell] is disabled.
/// If this is set the null then the [InkWell] is disabled.
/// ///
/// ItemBuilder is used to determine how the user data is represented. /// ItemBuilder is used to determine how the user data is represented.
/// ///
/// ItemBuilderOptions can be used to just set the settings for fields instead /// ItemBuilderOptions can be used to just set the settings for fields instead of defining the field itself and how it is used. This field should not be used when the itemBuilder is set.
/// of defining the field itself and how it is used. This field should not
/// be used when the itemBuilder is set.
class ProfilePage extends StatefulWidget { class ProfilePage extends StatefulWidget {
const ProfilePage({ const ProfilePage({
Key? key,
required this.user, required this.user,
required this.service, required this.service,
super.key,
this.style = const ProfileStyle(), this.style = const ProfileStyle(),
this.customAvatar, this.customAvatar,
this.showAvatar = true, this.showAvatar = true,
this.avatarBackgroundColor,
this.showItems = true, this.showItems = true,
this.itemBuilder, this.itemBuilder,
this.itemBuilderOptions, this.itemBuilderOptions,
@ -56,9 +45,7 @@ class ProfilePage extends StatefulWidget {
this.wrapViewOptions, this.wrapViewOptions,
this.extraWidgets, this.extraWidgets,
this.formKey, this.formKey,
this.changePasswordConfig = }) : super(key: key);
const ChangePasswordConfig(enablePasswordChange: false),
});
/// User containing all the user data. /// User containing all the user data.
final User user; final User user;
@ -75,15 +62,10 @@ class ProfilePage extends StatefulWidget {
/// Whether to show the users avatar. /// Whether to show the users avatar.
final bool showAvatar; final bool showAvatar;
///The background color of the avatar when no image is available. /// Whether you want to show the input fields, sometimes you just want to edit the avatar.
final Color? avatarBackgroundColor;
/// Whether you want to show the input fields, sometimes you just want
/// to edit the avatar.
final bool showItems; final bool showItems;
/// Sets the text for the [InkWell] at the bottom of the profile page. /// Sets the text for the [InkWell] at the bottom of the profile page. The [InkWell] is disabled when null.
/// The [InkWell] is disabled when null.
final String? bottomActionText; final String? bottomActionText;
/// Itembuilder is used the build each field in the user. /// Itembuilder is used the build each field in the user.
@ -95,8 +77,7 @@ class ProfilePage extends StatefulWidget {
/// Customize the parent widget for all fields /// Customize the parent widget for all fields
final Widget Function(BuildContext context, Widget child)? wrapItemsBuilder; final Widget Function(BuildContext context, Widget child)? wrapItemsBuilder;
/// Map keys of items that should be shown first before the default /// Map keys of items that should be shown first before the default items and the rest of the items.
/// items and the rest of the items.
final List<String> prioritizedItems; final List<String> prioritizedItems;
/// Shows textfields for firstname and lastname if is set to true /// Shows textfields for firstname and lastname if is set to true
@ -105,67 +86,52 @@ class ProfilePage extends StatefulWidget {
/// Edit the direction and spacing between every item /// Edit the direction and spacing between every item
final WrapViewOptions? wrapViewOptions; final WrapViewOptions? wrapViewOptions;
/// The map of extra widgets that might want to be added like empty /// The map of extra widgets that might want to be added like empty SizedBoxes for styling.
/// SizedBoxes for styling.
final Map<String, Widget>? extraWidgets; final Map<String, Widget>? extraWidgets;
/// Use the form key to save on any custom callback /// Use the form key to save on any custom callback
final GlobalKey<FormState>? formKey; final GlobalKey<FormState>? formKey;
/// Configuration to give the user the option to change his/her password.
final ChangePasswordConfig changePasswordConfig;
@override @override
State<ProfilePage> createState() => _ProfilePageState(); State<ProfilePage> createState() => _ProfilePageState();
} }
class _ProfilePageState extends State<ProfilePage> { class _ProfilePageState extends State<ProfilePage> {
@override @override
Widget build(BuildContext context) => ProfileWrapper( Widget build(BuildContext context) {
service: widget.service, return ProfileWrapper(
user: widget.user, service: widget.service,
rebuild: () { user: widget.user,
setState(() {}); rebuild: () {
}, setState(() {});
style: widget.style, },
customAvatar: widget.customAvatar, style: widget.style,
showAvatar: widget.showAvatar, customAvatar: widget.customAvatar,
showItems: widget.showItems, showAvatar: widget.showAvatar,
bottomActionText: widget.bottomActionText, showItems: widget.showItems,
itemBuilder: widget.itemBuilder, bottomActionText: widget.bottomActionText,
itemBuilderOptions: widget.itemBuilderOptions, itemBuilder: widget.itemBuilder,
prioritizedItems: widget.prioritizedItems, itemBuilderOptions: widget.itemBuilderOptions,
showDefaultItems: widget.showDefaultItems, prioritizedItems: widget.prioritizedItems,
wrapItemsBuilder: widget.wrapItemsBuilder, showDefaultItems: widget.showDefaultItems,
wrapViewOptions: widget.wrapViewOptions, wrapItemsBuilder: widget.wrapItemsBuilder,
extraWidgets: widget.extraWidgets, wrapViewOptions: widget.wrapViewOptions,
formKey: widget.formKey, extraWidgets: widget.extraWidgets,
avatarBackgroundColor: widget.avatarBackgroundColor, formKey: widget.formKey,
changePasswordConfig: widget.changePasswordConfig, );
); }
} }
class WrapViewOptions { class WrapViewOptions {
WrapViewOptions({ WrapViewOptions(
this.direction, {this.direction,
this.spacing, this.spacing,
this.wrapAlignment, this.wrapAlignment,
this.runSpacing, this.runSpacing,
this.clipBehavior, this.clipBehavior});
});
/// The direction to use as the main axis.
Axis? direction; Axis? direction;
/// The distance between adjacent children in the cross axis.
double? spacing; double? spacing;
/// How the children should be placed along the main axis.
WrapAlignment? wrapAlignment;
/// The distance between adjacent children in the main axis.
double? runSpacing; double? runSpacing;
/// Determines how visual overflow should be handled.
Clip? clipBehavior; Clip? clipBehavior;
WrapAlignment? wrapAlignment;
} }

View file

@ -4,13 +4,11 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
/// ProfielStyle is used to set a couple of style paramaters for the /// ProfielStyle is used to set a couple of style paramaters for the whole profile page.
/// whole profile page.
/// ///
/// AvatarStyle is used to set some styling for the avatar using [AvatarStyle]. /// AvatarStyle is used to set some styling for the avatar using [AvatarStyle].
/// ///
/// PagePaddign is used to set the padding around the whole profile page /// PagePaddign is used to set the padding around the whole profile page with its parent.
/// with its parent.
/// ///
/// BetweenDefaultitemPadding sets te padding between each user data item. /// BetweenDefaultitemPadding sets te padding between each user data item.
class ProfileStyle { class ProfileStyle {
@ -24,8 +22,7 @@ class ProfileStyle {
/// AvatarStyle can be used to set some avatar styling parameters. /// AvatarStyle can be used to set some avatar styling parameters.
final TextStyle avatarTextStyle; final TextStyle avatarTextStyle;
/// PagePadding can be set to determine the padding of the whole page /// PagePadding can be set to determine the padding of the whole page againt the profile page parent.
/// againt the profile page parent.
final EdgeInsetsGeometry pagePadding; final EdgeInsetsGeometry pagePadding;
/// BetweenDefaultItemPadding sets the /// BetweenDefaultItemPadding sets the

View file

@ -3,14 +3,12 @@
// SPDX-License-Identifier: BSD-3-Clause // SPDX-License-Identifier: BSD-3-Clause
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_profile/src/models/change_password_config.dart';
import 'package:flutter_profile/src/models/user.dart'; import 'package:flutter_profile/src/models/user.dart';
import 'package:flutter_profile/src/services/profile_service.dart'; import 'package:flutter_profile/src/services/profile_service.dart';
import 'package:flutter_profile/src/widgets/avatar/avatar_wrapper.dart'; import 'package:flutter_profile/src/widgets/avatar/avatar_wrapper.dart';
import 'package:flutter_profile/src/widgets/item_builder/item_builder.dart'; import 'package:flutter_profile/src/widgets/item_builder/item_builder.dart';
import 'package:flutter_profile/src/widgets/item_builder/item_builder_options.dart'; import 'package:flutter_profile/src/widgets/item_builder/item_builder_options.dart';
import 'package:flutter_profile/src/widgets/item_builder/item_list.dart'; import 'package:flutter_profile/src/widgets/item_builder/item_list.dart';
import 'package:flutter_profile/src/widgets/profile/change_password_widget.dart';
import 'package:flutter_profile/src/widgets/profile/profile_page.dart'; import 'package:flutter_profile/src/widgets/profile/profile_page.dart';
import 'package:flutter_profile/src/widgets/profile/profile_style.dart'; import 'package:flutter_profile/src/widgets/profile/profile_style.dart';
@ -22,7 +20,6 @@ class ProfileWrapper extends StatefulWidget {
this.style = const ProfileStyle(), this.style = const ProfileStyle(),
this.customAvatar, this.customAvatar,
this.showAvatar = true, this.showAvatar = true,
this.avatarBackgroundColor,
this.itemBuilder, this.itemBuilder,
this.itemBuilderOptions, this.itemBuilderOptions,
this.wrapViewOptions, this.wrapViewOptions,
@ -33,64 +30,26 @@ class ProfileWrapper extends StatefulWidget {
this.wrapItemsBuilder, this.wrapItemsBuilder,
this.formKey, this.formKey,
this.extraWidgets, this.extraWidgets,
this.changePasswordConfig =
const ChangePasswordConfig(enablePasswordChange: false),
super.key, super.key,
}); });
/// The user object containing user information.
final User user; final User user;
/// The service for managing user profile.
final ProfileService service; final ProfileService service;
/// The styling options for the profile.
final ProfileStyle style; final ProfileStyle style;
/// Custom avatar widget.
final Widget? customAvatar; final Widget? customAvatar;
/// Flag to show or hide the avatar.
final bool showAvatar; final bool showAvatar;
/// Background color for the avatar.
final Color? avatarBackgroundColor;
/// Text for the bottom action.
final String? bottomActionText; final String? bottomActionText;
/// Builder for creating items.
final ItemBuilder? itemBuilder; final ItemBuilder? itemBuilder;
/// Options for item builder.
final ItemBuilderOptions? itemBuilderOptions;
/// Options for wrapping the view.
final WrapViewOptions? wrapViewOptions; final WrapViewOptions? wrapViewOptions;
final Function rebuild;
/// Callback to rebuild the widget. final ItemBuilderOptions? itemBuilderOptions;
final Function() rebuild;
/// Flag to show default items.
final bool showDefaultItems; final bool showDefaultItems;
/// Flag to show items.
final bool showItems; final bool showItems;
/// Builder for wrapping items.
final Widget Function(BuildContext context, Widget child)? wrapItemsBuilder; final Widget Function(BuildContext context, Widget child)? wrapItemsBuilder;
final Map<String, Widget>? extraWidgets;
/// Key for the form.
final GlobalKey<FormState>? formKey; final GlobalKey<FormState>? formKey;
/// Additional widgets to be displayed. /// Map keys of items that should be shown first before the default items and the rest of the items.
final Map<String, Widget>? extraWidgets;
/// Configuration for changing password.
final ChangePasswordConfig changePasswordConfig;
/// Map keys of items that should be shown first before the default items and
/// the rest of the items.
final List<String> prioritizedItems; final List<String> prioritizedItems;
@override @override
@ -107,12 +66,12 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
@override @override
void initState() { void initState() {
super.initState();
_formKey = widget.formKey ?? GlobalKey<FormState>(); _formKey = widget.formKey ?? GlobalKey<FormState>();
super.initState();
if (widget.showDefaultItems) { if (widget.showDefaultItems) {
if (widget.itemBuilder == null) { if (widget.itemBuilder == null) {
var builder = ItemBuilder( ItemBuilder builder = ItemBuilder(
options: widget.itemBuilderOptions ?? ItemBuilderOptions(), options: widget.itemBuilderOptions ?? ItemBuilderOptions(),
); );
defaultItems.addAll({ defaultItems.addAll({
@ -123,7 +82,7 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
(value) { (value) {
submitAllChangedFields(); submitAllChangedFields();
}, },
(v) async { (v) {
if (widget.user.firstName != v) { if (widget.user.firstName != v) {
widget.user.firstName = v; widget.user.firstName = v;
widget.service.editProfile(widget.user, 'first_name', v); widget.service.editProfile(widget.user, 'first_name', v);
@ -137,7 +96,7 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
(value) { (value) {
submitAllChangedFields(); submitAllChangedFields();
}, },
(v) async { (v) {
if (widget.user.lastName != v) { if (widget.user.lastName != v) {
widget.user.lastName = v; widget.user.lastName = v;
widget.service.editProfile(widget.user, 'last_name', v); widget.service.editProfile(widget.user, 'last_name', v);
@ -154,7 +113,7 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
(value) { (value) {
submitAllChangedFields(); submitAllChangedFields();
}, },
(v) async { (v) {
if (widget.user.firstName != v) { if (widget.user.firstName != v) {
widget.user.firstName = v; widget.user.firstName = v;
widget.service.editProfile(widget.user, 'first_name', v); widget.service.editProfile(widget.user, 'first_name', v);
@ -168,7 +127,7 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
(value) { (value) {
submitAllChangedFields(); submitAllChangedFields();
}, },
(v) async { (v) {
if (widget.user.lastName != v) { if (widget.user.lastName != v) {
widget.user.lastName = v; widget.user.lastName = v;
widget.service.editProfile(widget.user, 'last_name', v); widget.service.editProfile(widget.user, 'last_name', v);
@ -181,28 +140,28 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
widgets.addAll(widget.extraWidgets ?? {}); widgets.addAll(widget.extraWidgets ?? {});
widgets.addAll(defaultItems); widgets.addAll(defaultItems);
if (widget.user.profileData != null) { if (widget.user.profileData != null) {
widgets.addAll( widgets.addAll(ItemList(
ItemList( Map.fromEntries(widget.user.profileData!.toMap().entries),
Map.fromEntries(widget.user.profileData!.toMap().entries), widget.user.profileData!.mapWidget(
widget.user.profileData!.mapWidget( () {
() { widget.rebuild();
widget.rebuild();
},
context,
),
(key, value) async {
if (widget.user.profileData?.toMap()[key] == null) {
widget.service.editProfile(widget.user, key, value);
} else if (widget.user.profileData?.toMap()[key] != value) {
widget.service.editProfile(widget.user, key, value);
}
}, },
submitAllChangedFields, context,
itemBuilder: widget.itemBuilder, ),
itemBuilderOptions: widget.itemBuilderOptions, (key, value) {
formKey: _formKey, if (widget.user.toMap()['profile_data'][key] == null) {
).getItemList(), widget.service.editProfile(widget.user, key, value);
); } else if (widget.user.toMap()['profile_data'][key] != value) {
widget.service.editProfile(widget.user, key, value);
}
},
() {
submitAllChangedFields();
},
itemBuilder: widget.itemBuilder,
itemBuilderOptions: widget.itemBuilderOptions,
formKey: _formKey,
).getItemList());
} }
var items = Wrap( var items = Wrap(
@ -229,76 +188,53 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
} }
@override @override
Widget build(BuildContext context) => Stack( Widget build(BuildContext context) {
children: [ return Material(
SizedBox( color: Colors.transparent,
height: MediaQuery.of(context).size.height, child: Padding(
width: MediaQuery.of(context).size.width, padding: widget.style.pagePadding,
child: SingleChildScrollView( child: Column(
child: Padding( children: [
padding: widget.style.pagePadding, if (widget.showAvatar) ...[
child: Column( InkWell(
children: [ onTap: () => widget.service.uploadImage(
if (widget.showAvatar) ...[ context,
InkWell( onUploadStateChanged: (isUploading) => setState(
onTap: () async => widget.service.uploadImage( () {
context, _isUploadingImage = isUploading;
onUploadStateChanged: (isUploading) => setState( },
() { ),
_isUploadingImage = isUploading; ),
}, child: AvatarWrapper(
user: widget.user,
textStyle: widget.style.avatarTextStyle,
customAvatar: _isUploadingImage
? Container(
width: 100,
height: 100,
decoration: const BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
), ),
), child: const CircularProgressIndicator(),
child: AvatarWrapper( )
avatarBackgroundColor: widget.avatarBackgroundColor, : widget.customAvatar,
user: widget.user,
textStyle: widget.style.avatarTextStyle,
customAvatar: _isUploadingImage
? Container(
width: 100,
height: 100,
decoration: const BoxDecoration(
color: Colors.black,
shape: BoxShape.circle,
),
child: const CircularProgressIndicator(),
)
: widget.customAvatar,
),
),
SizedBox(
height: widget.style.betweenDefaultItemPadding,
),
],
if (widget.showItems) ...[
Form(
key: _formKey,
child: child,
),
],
if (widget.changePasswordConfig.enablePasswordChange) ...[
ChangePassword(
config: widget.changePasswordConfig,
service: widget.service,
wrapViewOptions: widget.wrapViewOptions,
wrapItemsBuilder: widget.wrapItemsBuilder,
itemBuilder: widget.itemBuilder,
itemBuilderOptions: widget.itemBuilderOptions,
style: widget.style,
),
],
],
), ),
), ),
), SizedBox(
), height: widget.style.betweenDefaultItemPadding,
if (widget.bottomActionText != null && ),
MediaQuery.of(Scaffold.of(context).context).viewInsets.bottom == ],
0.0) ...[ if (widget.showItems) Form(key: _formKey, child: child),
Align( if (widget.bottomActionText != null) ...[
alignment: Alignment.bottomCenter, SizedBox(
child: InkWell( height: widget.style.betweenDefaultItemPadding,
onTap: () async => await widget.service.pageBottomAction(), ),
const Spacer(),
InkWell(
onTap: () {
widget.service.pageBottomAction();
},
child: Padding( child: Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
child: Text( child: Text(
@ -307,14 +243,18 @@ class _ProfileWrapperState extends State<ProfileWrapper> {
), ),
), ),
), ),
), ] else ...[
const Spacer(),
],
], ],
], ),
); ),
);
}
/// This calls onSaved on all the fiels which check if they have a new value /// This calls onSaved on all the fiels which check if they have a new value
void submitAllChangedFields() { void submitAllChangedFields() {
if (_formKey.currentState?.validate() ?? false) { if (_formKey.currentState!.validate()) {
_formKey.currentState!.save(); _formKey.currentState!.save();
} }
} }

View file

@ -1,29 +1,20 @@
name: flutter_profile name: flutter_profile
description: Flutter profile package description: Flutter profile package
version: 1.6.0 version: 1.0.4
repository: https://github.com/Iconica-Development/flutter_profile repository: https://github.com/Iconica-Development/flutter_profile
publish_to: https://forgejo.internal.iconica.nl/api/packages/internal/pub
environment: environment:
sdk: ">=3.0.0 <4.0.0" sdk: ">=2.17.6 <3.0.0"
flutter: ">=1.17.0" flutter: ">=1.17.0"
dependencies: dependencies:
cached_network_image: ^3.3.0 cached_network_image: ^3.2.2
flutter_input_library:
hosted: https://forgejo.internal.iconica.nl/api/packages/internal/pub
version: ^3.6.0
flutter: flutter:
sdk: flutter sdk: flutter
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:
sdk: flutter sdk: flutter
flutter_iconica_analysis: flutter_lints: ^2.0.0
git:
url: https://github.com/Iconica-Development/flutter_iconica_analysis
ref: 6.0.0
flutter: flutter:

View file

@ -25,9 +25,9 @@ void main() {
), ),
); );
var firstNameFinder = find.text('Firstname'); final firstNameFinder = find.text('Firstname');
var lastNameFinder = find.text('Lastname'); final lastNameFinder = find.text('Lastname');
var emailFinder = find.text('test@email.com'); final emailFinder = find.text('test@email.com');
expect(firstNameFinder, findsOneWidget); expect(firstNameFinder, findsOneWidget);
expect(lastNameFinder, findsOneWidget); expect(lastNameFinder, findsOneWidget);
@ -74,13 +74,13 @@ void main() {
await tester.testTextInput.receiveAction(TextInputAction.send); await tester.testTextInput.receiveAction(TextInputAction.send);
await tester.pump(); await tester.pump();
var firstNameFinder = find.text('Firstname'); final firstNameFinder = find.text('Firstname');
var firstNameEditedFinder = find.text('FirstEditedName'); final firstNameEditedFinder = find.text('FirstEditedName');
var lastNameFinder = find.text('Lastname'); final lastNameFinder = find.text('Lastname');
var emailFinder = find.text('test@email.com'); final emailFinder = find.text('test@email.com');
var emailEditedFinder = find.text('edited@emial.com'); final emailEditedFinder = find.text('edited@emial.com');
expect(firstNameFinder, findsNothing); expect(firstNameFinder, findsNothing);
expect(firstNameEditedFinder, findsOneWidget); expect(firstNameEditedFinder, findsOneWidget);

View file

@ -13,7 +13,7 @@ class TestProfileData extends ProfileData {
String? email; String? email;
@override @override
Map<String, Widget?> mapWidget( Map<String, dynamic> mapWidget(
VoidCallback update, VoidCallback update,
BuildContext context, BuildContext context,
) => ) =>
@ -27,7 +27,7 @@ class TestProfileData extends ProfileData {
); );
@override @override
Map<String, String?> toMap() => { Map<String, dynamic> toMap() => {
'email': email, 'email': email,
}; };

View file

@ -23,15 +23,6 @@ class TestProfileService extends ProfileService {
@override @override
FutureOr<void> uploadImage( FutureOr<void> uploadImage(
BuildContext context, { BuildContext context, {
// ignore: avoid_positional_boolean_parameters
required Function(bool isUploading) onUploadStateChanged, required Function(bool isUploading) onUploadStateChanged,
}) {} }) {}
@override
FutureOr<bool> changePassword(
BuildContext context,
String currentPassword,
String newPassword,
) =>
true;
} }