├── .gitignore
├── .metadata
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── analysis_options.yaml
├── example
├── bubble_cards_example.dart
└── main.dart
├── lib
├── controller.dart
└── widget_slider.dart
├── pubspec.yaml
└── test
└── widget_slider_test.dart
/.gitignore:
--------------------------------------------------------------------------------
1 | # Miscellaneous
2 | *.class
3 | *.log
4 | *.pyc
5 | *.swp
6 | .DS_Store
7 | .atom/
8 | .buildlog/
9 | .history
10 | .svn/
11 |
12 | # IntelliJ related
13 | *.iml
14 | *.ipr
15 | *.iws
16 | .idea/
17 |
18 | # The .vscode folder contains launch configuration and tasks you configure in
19 | # VS Code which you may wish to be included in version control, so this line
20 | # is commented out by default.
21 | #.vscode/
22 |
23 | # Flutter/Dart/Pub related
24 | # Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
25 | /pubspec.lock
26 | **/doc/api/
27 | .dart_tool/
28 | .packages
29 | build/
30 | coverage/
31 |
--------------------------------------------------------------------------------
/.metadata:
--------------------------------------------------------------------------------
1 | # This file tracks properties of this Flutter project.
2 | # Used by Flutter tool to assess capabilities and perform upgrades etc.
3 | #
4 | # This file should be version controlled and should not be manually edited.
5 |
6 | version:
7 | revision: c860cba910319332564e1e9d470a17074c1f2dfd
8 | channel: stable
9 |
10 | project_type: package
11 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # v0.1.0 - (18/04/22)
2 |
3 | ## Very first release of `widget_slider`
4 |
5 |
6 |
7 | - See the official installing guidline from [widget_slider/install](https://github.com/theiskaa/widget_slider/wiki/Installing)
8 | - Read the official documentation from [widget_slider/wiki](https://github.com/theiskaa/widget_slider/wiki)
9 | - For information regarding contributions, please refer to [CONTRIBUTING.md](https://github.com/theiskaa/widget_slider/blob/main/CONTRIBUTING.md) file.
10 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | First of all, thank you for considering contributing! :tada:
4 |
5 | Here you will find some guidelines on how to contribute. Feel free to propose changes to this document if you think something is missing or needs to be clarified.
6 |
7 | ## Contributing Guides
8 |
9 | First time contributing? You can learn more about contributing to open source projects through GitHub's [wonderful open source guides](https://opensource.guide/how-to-contribute/).
10 |
11 | ### :bug: Reporting a Problem
12 |
13 | Before you open a new issue, check to see if the problem has [already been reported](https://github.com/theiskaa/widget_slider/issues). If it has and **the issue is still open**, add a comment to the existing issue instead of creating a new one.
14 |
15 | > **Note:** If you fid a **closed** issue that seems to address the same thing that you've found, open a new issue and include a link to the original one.
16 |
17 | When you open an issue, try to be as descriptive as possible. Add any relevant screenshots so that the problem can be identified quickly.
18 |
19 | ### :sparkles: Opening a Pull Request
20 |
21 | > A lot of the following information was inspired by [opensource.guide](https://opensource.guide/how-to-contribute/), a great site to learn all about open source software.
22 |
23 | If you've fixed a bug, started working on an enhancement, or done something else, you can [create a pull request](https://github.com/theiskaa/widget_slider/pulls) to start a conversation about your changes.
24 |
25 | A pull request doesn't necessarily have to include finished work. It may be better to open a PR early on so that you can get feedback on your contribution. Just mention that it's a work in progress and keep adding commits.
26 |
27 | Here's how to contribute and submit your pull request:
28 |
29 | 1. [**Fork the repository**](https://help.github.com/articles/fork-a-repo/) and clone it locally. Add the original repository as a remote and pull in changes every so often so that you stay up to date with the project.
30 | 2. [**Create a branch**](https://guides.github.com/introduction/flow/) from `develop` for your changes.
31 | 3. **Add, commit, and push** your changes to your branch.
32 | 4. **Test out your changes.** Make sure that they work as you intended.
33 | 5. [**Open a pull request**](https://github.com/theiskaa/widget_slider/pulls) to merge your branch into `develop`.
34 | - Reference any issues related to your PR (e.g. "Resolves #17").
35 | - Describe your changes in detail and include screenshots if necessary.
36 | 6. :sunglasses: Sit back, relax, and wait for your PR to be reviewed. You might have to tweak your contribution or elaborate on your changes. That's OK, don't be afraid to justify your reasoning and ask questions.
37 |
38 | Thank you for reading through this contributing guide and welcome to the community! :tada:
39 |
40 | > We gonna make something easy to do :v:
41 | n
42 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright (c) 2019 Giorgi Beriashvili
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | ### Installing
12 | - See the official installing guidline from [widget_slider/install](https://github.com/theiskaa/widget_slider/wiki/Installing)
13 |
14 | ### Official Documentation (Wiki)
15 | - Read the official documentation from [widget_slider/wiki](https://github.com/theiskaa/widget_slider/wiki)
16 |
17 | ### Contributing
18 | - For information regarding contributions, please refer to [CONTRIBUTING.md](https://github.com/theiskaa/widget_slider/blob/main/CONTRIBUTING.md) file.
19 |
--------------------------------------------------------------------------------
/analysis_options.yaml:
--------------------------------------------------------------------------------
1 | include: package:flutter_lints/flutter.yaml
2 |
3 | # Additional information about this file can be found at
4 | # https://dart.dev/guides/language/analysis-options
5 |
--------------------------------------------------------------------------------
/example/bubble_cards_example.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter/cupertino.dart';
3 | import 'package:widget_slider/widget_slider.dart';
4 |
5 | void main() => runApp(const App());
6 |
7 | class App extends StatelessWidget {
8 | const App({Key? key}) : super(key: key);
9 |
10 | @override
11 | Widget build(BuildContext context) {
12 | return MaterialApp(
13 | home: const Home(),
14 | theme: ThemeData.dark(),
15 | );
16 | }
17 | }
18 |
19 | class Home extends StatefulWidget {
20 | const Home({Key? key}) : super(key: key);
21 |
22 | @override
23 | State createState() => _HomeState();
24 | }
25 |
26 | class _HomeState extends State {
27 | final controller = SliderController();
28 | final indexes = List.generate(10, (index) => index+1);
29 |
30 | @override
31 | Widget build(BuildContext context) {
32 | return Scaffold(
33 | body: Center(
34 | child: WidgetSlider(
35 | controller: controller,
36 | itemCount: indexes .length,
37 | onMove: (i) {/*...*/},
38 | itemBuilder: (context, index, activeIndex) {
39 | return CupertinoButton(
40 | padding: EdgeInsets.zero,
41 | onPressed: () async {
42 | if (index == activeIndex) return;
43 | await controller.moveTo?.call(index);
44 | },
45 | child: AnimatedContainer(
46 | duration: const Duration(milliseconds: 300),
47 | decoration: BoxDecoration(
48 | color: index == activeIndex ? Colors.green : Colors.red,
49 | shape: BoxShape.circle,
50 | border: index == activeIndex
51 | ? Border.all(color: Colors.white, width: 3)
52 | : null,
53 | ),
54 | child: Center(
55 | child: Text(
56 | indexes[index].toString(),
57 | style: const TextStyle(
58 | fontWeight: FontWeight.bold,
59 | color: Colors.white,
60 | ),
61 | ),
62 | ),
63 | ),
64 | );
65 | },
66 | ),
67 | ),
68 | );
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/example/main.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/cupertino.dart';
2 | import 'package:flutter/material.dart';
3 | import 'package:widget_slider/widget_slider.dart';
4 |
5 | void main() => runApp(const App());
6 |
7 | class App extends StatelessWidget {
8 | const App({Key? key}) : super(key: key);
9 |
10 | @override
11 | Widget build(BuildContext context) {
12 | return const MaterialApp(home: Home());
13 | }
14 | }
15 |
16 | class Home extends StatefulWidget {
17 | const Home({Key? key}) : super(key: key);
18 |
19 | @override
20 | State createState() => _HomeState();
21 | }
22 |
23 | class _HomeState extends State {
24 | final controller = SliderController(
25 | duration: const Duration(milliseconds: 600),
26 | );
27 |
28 | final images = const [
29 | 'https://i.picsum.photos/id/816/200/300.jpg?hmac=4O5XSGjimzcjZYOXpVb_--v3rGzmS-3chmG2L1MS-mc',
30 | 'https://i.picsum.photos/id/436/200/300.jpg?hmac=OuJRsPTZRaNZhIyVFbzDkMYMyORVpV86q5M8igEfM3Y',
31 | 'https://i.picsum.photos/id/645/200/300.jpg?hmac=fiKW3Nj8r0CWJQY3S-kkeT8PAfvKhA8igd9GIRk41Yw',
32 | 'https://i.picsum.photos/id/281/200/300.jpg?hmac=KCN8F5QTgxHdeQxLpZ5BOuUEVQEp8jAedlLSRERW7CY',
33 | 'https://i.picsum.photos/id/816/200/300.jpg?hmac=4O5XSGjimzcjZYOXpVb_--v3rGzmS-3chmG2L1MS-mc',
34 | ];
35 |
36 | @override
37 | Widget build(BuildContext context) {
38 | return Scaffold(
39 | body: Center(
40 | child: WidgetSlider(
41 | fixedSize: 300,
42 | controller: controller,
43 | itemCount: images.length,
44 | itemBuilder: (context, index, activeIndex) {
45 | return CupertinoButton(
46 | onPressed: () async => await controller.moveTo?.call(index),
47 | child: Container(
48 | margin: const EdgeInsets.all(5),
49 | decoration: BoxDecoration(
50 | borderRadius: BorderRadius.circular(10),
51 | image: DecorationImage(
52 | fit: BoxFit.fill,
53 | image: NetworkImage(images[index]),
54 | ),
55 | boxShadow: [
56 | BoxShadow(
57 | color: Colors.grey.shade50,
58 | offset: const Offset(0, 8),
59 | spreadRadius: 5,
60 | blurRadius: 10,
61 | ),
62 | BoxShadow(
63 | color: Colors.grey.shade100,
64 | offset: const Offset(0, 8),
65 | spreadRadius: 5,
66 | blurRadius: 10,
67 | ),
68 | ],
69 | ),
70 | ),
71 | );
72 | },
73 | ),
74 | ),
75 | );
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/lib/controller.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 |
3 | /// The external controller for [WidgetSlider].
4 | class SliderController {
5 | /// Duration value of sub-function's animations.
6 | ///
7 | /// If unset, defaults to the [milliseconds: 350].
8 | final Duration duration;
9 |
10 | /// Curve style of sub-function's animations.
11 | ///
12 | /// If unset, defaults to the [Curves.easeOut].
13 | final Curve curve;
14 |
15 | SliderController({
16 | this.duration = const Duration(milliseconds: 350),
17 | this.curve = Curves.easeOut,
18 | });
19 |
20 | /// Navigates to item at given index(i).
21 | ///
22 | /// If given index is exceeds min/max length, nothing will happen.
23 | Future Function(int i)? moveTo;
24 |
25 | /// Navigates to next(current+1) item.
26 | ///
27 | /// If next(current+1) is exceeds max length, nothing will happen.
28 | Future Function()? moveToNext;
29 |
30 | /// Navigates to previous(current-1) item.
31 | ///
32 | /// If back(current-1) is exceeds min length, nothing will happen.
33 | Future Function()? moveToPrevious;
34 | }
35 |
--------------------------------------------------------------------------------
/lib/widget_slider.dart:
--------------------------------------------------------------------------------
1 | library widget_slider;
2 |
3 | import 'package:flutter/material.dart';
4 | import 'package:widget_slider/controller.dart';
5 |
6 | export 'package:widget_slider/controller.dart';
7 |
8 | /// A simple wrapper widget, used to generate size of [WidgetSlider].
9 | class _FlexdSizedBox extends StatelessWidget {
10 | final Widget? child;
11 | final double? aspectRatio;
12 | final double? fixedSize;
13 |
14 | const _FlexdSizedBox({Key? key, this.child, this.aspectRatio, this.fixedSize}) : super(key: key);
15 |
16 | @override
17 | Widget build(BuildContext context) {
18 | if (fixedSize != null) return SizedBox(height: fixedSize, child: child);
19 | return AspectRatio(aspectRatio: aspectRatio ?? 1, child: child);
20 | }
21 | }
22 |
23 | /// A simple carousel type component-slider widget for Flutter.
24 | ///
25 | /// Example:
26 | /// ```dart
27 | /// WidgetSlider(
28 | /// fixedSize: 300,
29 | /// itemCount: images.length,
30 | /// itemBuilder: (context, index, isActive) {
31 | /// return Container(
32 | /// decoration: const BoxDecoration(
33 | /// image: DecorationImage(
34 | /// image: NetworkImage('https://picsum.photos/200/300')
35 | /// ),
36 | /// ),
37 | /// );
38 | // },
39 | /// ),
40 | /// ```
41 | class WidgetSlider extends StatefulWidget {
42 | /// Length of items that'd be built via [itemBuilder].
43 | final int itemCount;
44 |
45 | /// Widget generator of the list. Generated widgets are represented as [PageView] pages.
46 | ///
47 | /// First index is each elements real index, but second index is active page's(item's) index.
48 | final Widget Function(BuildContext, int, int) itemBuilder;
49 |
50 | /// A function to execute on each page move.
51 | /// {i} represents the index of moved page.
52 | final Function(int i)? onMove;
53 |
54 | /// A external controller to manipulate widget from outside of it.
55 | ///
56 | /// next() | navigates to next(current+1) item.
57 | /// back() | navigates to back(current-1) item.
58 | /// moveTo(i) | navigates to item at given index(i).
59 | final SliderController? controller;
60 |
61 | /// The proximity between items.
62 | /// Value should be given as basic representation of percentages from (0 to 1) as
63 | /// | 0.1 -> 10%
64 | /// | 0.2 -> 20%
65 | /// ...
66 | ///
67 | /// If unset, defaults to the [0.5] -> 50%
68 | final double proximity;
69 |
70 | /// Decides differences of active & non-active item sizes .
71 | /// Value should be given as basic representation of percentages from (0 to 1) as
72 | /// | 0.1 -> 10%
73 | /// | 0.2 -> 20%
74 | /// ...
75 | ///
76 | /// s:1
77 | /// 0.5 ╭────────╮ 0.5
78 | /// ╭───╮ │ │ ╭───╮
79 | /// │ 6 │ │ 47 │ │ 7 │
80 | /// ╰───╯ │ │ ╰───╯
81 | /// ╰────────╯
82 | ///
83 | /// If unset, defaults to [0.5](non-active item will 50% smaller than active one).
84 | /// If set to [null], size distinction animation will be disabled.
85 | final double? sizeDistinction;
86 |
87 | /// The scroll direction of list widget.
88 | ///
89 | /// If unset, defaults to the [Axis.horizontal].
90 | final Axis scrollDirection;
91 |
92 | /// Ratio is of whole list widget.
93 | ///
94 | /// If unset, defaults to the -> [2].
95 | final double aspectRatio;
96 |
97 | /// Concrete fixed size for whole list widget.
98 | ///
99 | /// If not null, [aspectRatio]'s value will be ignored.
100 | final double? fixedSize;
101 |
102 | /// Animation curve style of widget's distinction.
103 | ///
104 | /// If unset defaults to the [Curves.easeOut].
105 | final Curve transformCurve;
106 |
107 | /// Reverse initializes list as reversed.
108 | /// [1, 2, 3] --> [3, 2, 1] (But remains at same page index(0)).
109 | ///
110 | /// If unset, defaults to the [false].
111 | final bool reverse;
112 |
113 | /// Enables/Disables snapping physics animation of widget.
114 | ///
115 | /// If unset, defaults to the [true](enabled).
116 | final bool pageSnapping;
117 |
118 | /// TODO: implement functionality to the widget.
119 | ///
120 | /// Enables/Disables infinite scrolling of list widget.
121 | /// If set, itemCount value will be ignored,
122 | /// Note: infinite scroll functionality could be enabled by setting [itemCount] to `null`.
123 | ///
124 | /// If unset, defaults to the [false](disabled).
125 | final bool infiniteScroll;
126 |
127 | /// Physics of the list widget.
128 | /// The physics are modified to snap to page boundaries using
129 | /// [PageScrollPhysics] prior to being used.
130 | ///
131 | /// If an explicit [ScrollBehavior] is provided to [scrollBehavior], the
132 | /// [ScrollPhysics] provided by that behavior will take precedence after
133 | /// [physics].
134 | ///
135 | /// Defaults to matching platform conventions.
136 | final ScrollPhysics? physics;
137 |
138 | /// Whether to add padding to both ends of the list.
139 | ///
140 | /// If this is set to true and [sizeDistinction] < 1.0, padding will be added
141 | /// such that the first and last child slivers will be in the center of
142 | /// the viewport when scrolled all the way to the start or end, respectively.
143 | ///
144 | /// If [sizeDistinction] >= 1.0, this property has no effect.
145 | ///
146 | /// If unset, defaults to the [true].
147 | final bool padEnds;
148 |
149 | const WidgetSlider({
150 | Key? key,
151 | required this.itemCount,
152 | required this.itemBuilder,
153 | this.onMove,
154 | this.controller,
155 | this.proximity = .5,
156 | this.sizeDistinction = 0.5,
157 | this.scrollDirection = Axis.horizontal,
158 | this.aspectRatio = 2,
159 | this.fixedSize,
160 | this.transformCurve = Curves.easeOut,
161 | this.reverse = false,
162 | this.pageSnapping = true,
163 | this.infiniteScroll = false,
164 | this.physics,
165 | this.padEnds = true,
166 | }) : super(key: key);
167 |
168 | @override
169 | // ignore: no_logic_in_create_state
170 | State createState() => _WidgetSliderState(controller);
171 | }
172 |
173 | class _WidgetSliderState extends State {
174 | _WidgetSliderState(SliderController? controller) {
175 | if (controller == null) return;
176 | _controller = controller;
177 |
178 | controller.moveTo = moveTo;
179 | controller.moveToNext = moveToNext;
180 | controller.moveToPrevious = moveToPrevious;
181 | }
182 |
183 | // Exact current page address, it's calculated from offsett.
184 | double page = 0;
185 |
186 | // Concrete current page adress, it's rounded variant of [page].
187 | // Used as [activeIndex] in [widget.itemBuilder].
188 | int activePage = 0;
189 |
190 | SliderController _controller = SliderController();
191 | late PageController pageController;
192 |
193 | @override
194 | void initState() {
195 | _reInitEssentials();
196 | super.initState();
197 | }
198 |
199 | @override
200 | void didUpdateWidget(covariant WidgetSlider oldWidget) {
201 | _reInitEssentials();
202 | super.didUpdateWidget(oldWidget);
203 | }
204 |
205 | void _reInitEssentials() {
206 | pageController = PageController(
207 | initialPage: activePage,
208 | viewportFraction: widget.proximity,
209 | );
210 |
211 | // Used to avoid [Page value is only available after content dimensions are established] error.
212 | // Taking page's value via listener causes no error. Instead of [pageController.page] we use [currentPage]
213 | pageController.addListener(() {
214 | if (pageController.page == null) return;
215 | page = pageController.page!;
216 | });
217 | }
218 |
219 | // Closure(callback) of controller's moveTo function.
220 | Future moveTo(i) async {
221 | return await pageController.animateToPage(
222 | i,
223 | duration: _controller.duration,
224 | curve: _controller.curve,
225 | );
226 | }
227 |
228 | // Closure(callback) of controller's moveToNext function.
229 | Future moveToNext() async {
230 | return await pageController.nextPage(
231 | duration: _controller.duration,
232 | curve: _controller.curve,
233 | );
234 | }
235 |
236 | // Closure(callback) of controller's moveToPrevious function.
237 | Future moveToPrevious() async {
238 | return await pageController.previousPage(
239 | duration: _controller.duration,
240 | curve: _controller.curve,
241 | );
242 | }
243 |
244 | // Generates a valid scale for each item.
245 | double _generateScale(int index, Size size) {
246 | if (widget.sizeDistinction == null) return 1;
247 |
248 | final offset = (page - index).abs();
249 | final ratio = (1 - (widget.sizeDistinction! * offset)).clamp(0, 1);
250 |
251 | return widget.transformCurve.transform(ratio.toDouble());
252 | }
253 |
254 | @override
255 | Widget build(BuildContext context) {
256 | return _FlexdSizedBox(
257 | fixedSize: widget.fixedSize,
258 | aspectRatio: widget.aspectRatio,
259 | child: PageView.builder(
260 | controller: pageController,
261 | reverse: widget.reverse,
262 | itemCount: widget.itemCount,
263 | pageSnapping: widget.pageSnapping,
264 | physics: widget.physics,
265 | padEnds: widget.padEnds,
266 | scrollDirection: widget.scrollDirection,
267 | onPageChanged: (i) {
268 | // update static active page on each move.
269 | setState(() => activePage = i);
270 |
271 | widget.onMove?.call(i);
272 | },
273 | itemBuilder: (context, i) => AnimatedBuilder(
274 | animation: pageController,
275 | child: widget.itemBuilder(context, i, activePage),
276 | builder: (context, child) {
277 | final size = MediaQuery.of(context).size;
278 | final scale = _generateScale(i, size);
279 |
280 | return Transform.scale(
281 | scale: scale,
282 | child: Builder(
283 | builder: (context) {
284 | if (widget.scrollDirection == Axis.horizontal) {
285 | return SizedBox(child: child, width: scale * size.width);
286 | }
287 |
288 | return SizedBox(child: child, height: size.height);
289 | },
290 | ),
291 | );
292 | },
293 | ),
294 | ),
295 | );
296 | }
297 | }
298 |
--------------------------------------------------------------------------------
/pubspec.yaml:
--------------------------------------------------------------------------------
1 | name: widget_slider
2 | description: A simple carousel type component-slider widget for Flutter.
3 | version: 0.1.0
4 | homepage: https://github.com/theiskaa/widget_slider
5 | issue_tracker: https://github.com/theiskaa/widget_slider/issues
6 | documentation: https://github.com/theiskaa/widget_slider/wiki
7 |
8 | environment:
9 | sdk: ">=2.16.2 <3.0.0"
10 | flutter: ">=1.17.0"
11 |
12 | dependencies:
13 | flutter:
14 | sdk: flutter
15 |
16 | dev_dependencies:
17 | flutter_test:
18 | sdk: flutter
19 | flutter_lints: ^1.0.0
20 |
21 | flutter:
22 |
--------------------------------------------------------------------------------
/test/widget_slider_test.dart:
--------------------------------------------------------------------------------
1 | import 'package:flutter/material.dart';
2 | import 'package:flutter_test/flutter_test.dart';
3 | import 'package:widget_slider/widget_slider.dart';
4 |
5 | void main() {
6 | late Widget horizontalSlider, verticalSlider;
7 | late SliderController controller;
8 |
9 | final items = List.generate(5, (index) => 'Test $index');
10 |
11 | setUpAll(() {
12 | controller = SliderController();
13 |
14 | horizontalSlider = WidgetSlider(
15 | controller: controller,
16 | itemCount: items.length,
17 | onMove: (_) {},
18 | itemBuilder: (context, index, activeIndex) {
19 | final value = index == activeIndex ? 'active' : 'non-active';
20 | return Text(value, key: Key(value));
21 | },
22 | );
23 |
24 | verticalSlider = WidgetSlider(
25 | itemCount: items.length,
26 | scrollDirection: Axis.vertical,
27 | onMove: (_) {},
28 | itemBuilder: (context, index, activeIndex) {
29 | return Text(index == activeIndex ? 'active' : 'non-active');
30 | },
31 | );
32 | });
33 |
34 | group('[WidgetSlider]', () {
35 | testWidgets('should build horizontal-widget properly', (tester) async {
36 | await tester.pumpWidget(
37 | MaterialApp(home: Scaffold(body: horizontalSlider)),
38 | );
39 |
40 | // Stable widgets.
41 | expect(find.byType(PageView), findsOneWidget);
42 | expect(find.byType(AnimatedBuilder), findsNWidgets(items.length + 3));
43 | expect(find.byType(Transform), findsNWidgets(8));
44 | expect(find.byType(Builder), findsNWidgets(items.length));
45 | expect(find.byType(SizedBox), findsNWidgets(2));
46 |
47 | // User provided.
48 | expect(find.byType(Text), findsNWidgets(2));
49 |
50 | // State actions.
51 | controller.moveToNext?.call();
52 | controller.moveToPrevious?.call();
53 | controller.moveTo?.call(items.length - 1);
54 | });
55 |
56 | testWidgets(
57 | 'should build vertical-widget properly',
58 | (WidgetTester tester) async {
59 | await tester.pumpWidget(
60 | MaterialApp(home: Scaffold(body: verticalSlider)),
61 | );
62 |
63 | // Stable widgets.
64 | expect(find.byType(PageView), findsOneWidget);
65 | expect(find.byType(AnimatedBuilder), findsNWidgets(items.length + 3));
66 | expect(find.byType(Transform), findsNWidgets(8));
67 | expect(find.byType(Builder), findsNWidgets(items.length));
68 | expect(find.byType(SizedBox), findsNWidgets(2));
69 |
70 | // User provided.
71 | expect(find.byType(Text), findsNWidgets(2));
72 | },
73 | );
74 | });
75 | }
76 |
--------------------------------------------------------------------------------