sumitsharansatsangi

unnecessary null checking removed

Showing 92 changed files with 2112 additions and 665 deletions

Too many changes to show.

To preserve performance only 92 of 92+ files are displayed.

## [5.0.0-release-candidate-4]
-Fix changeThemeMode and RxList
## [5.0.0-release-candidate-3]
-Fix changeTheme
## [5.0.0-release-candidate-2]
This version adds built-in support for animation in Flutter in an easy, clear way, and without having to create a StatefulWidget with controllers and animations. All you need to do is call the name of the animation.
If you want to add a "fadeIn" effect to any widget, simply add .fadeIn() to the end of it.
```dart
Container(
color: Colors.blue,
height: 100,
width: 100,
).fadeIn(),
```
https://user-images.githubusercontent.com/35742643/221383556-075a0b71-1617-4a31-a3c7-1acc68732f59.mp4
Maybe you want to merge two or more animations, just concatenate them at the end of the widget.
```dart
Container(
color: Colors.blue,
height: 100,
width: 100,
).fadeIn().bounce(begin: -0.8, end: 0.3),
```
https://user-images.githubusercontent.com/35742643/221383613-9044c92f-7c6b-48c4-aa79-0a0c20d4068a.mp4
Creating animation sequences in Flutter is one of the most painful things to do with the framework. You need to create tons of AnimationControllers. Well, using GetX 5 you just need to tell your animation that it is sequential. Just like that.
```dart
const FlutterLogo(size: 110)
.bounce(begin: -0.8, end: 0.4)
.fadeIn()
.spin(isSequential: true)
.wobble(isSequential: true, begin: 0, end: 8)
.flip(isSequential: true)
.fadeOut(isSequential: true),
```
Result:
https://user-images.githubusercontent.com/35742643/221393968-20cb2411-516b-44a7-8b85-45090bece532.mp4
## [5.0.0-release-candidate]
Refactor StateManager, RouteManager and InstanceManager from scratch
Fixed Bugs
Added a Scopped DI
Api now uses Navigator 2
Added new RouteOutlet
Added a new futurize method to StateMixin, that tracks updates, errors, and states programatically,
## [4.6.1]
Fix GetConnect on Flutter web
... ...
# Include option is buggy:
include: package:lints/recommended.yaml
include: package:flutter_lints/flutter.yaml
# In case the include issue gets fixed, lines below INCLUDE_FIX
# can be removed
... ...
... ... @@ -21,6 +21,8 @@ linter:
# `// ignore_for_file: name_of_lint` syntax on the line or in the file
# producing the lint.
rules:
camel_case_types: false
constant_identifier_names: false
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
... ...
... ... @@ -6,7 +6,7 @@ import 'pt_BR.dart';
class TranslationService extends Translations {
static Locale? get locale => Get.deviceLocale;
static final fallbackLocale = Locale('en', 'US');
static const fallbackLocale = Locale('en', 'US');
@override
Map<String, Map<String, String>> get keys => {
'en_US': en_US,
... ...
... ... @@ -6,7 +6,7 @@ import 'routes/app_pages.dart';
import 'shared/logger/logger_utils.dart';
void main() {
runApp(MyApp());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
... ... @@ -30,27 +30,27 @@ class MyApp extends StatelessWidget {
/// Nav 2 snippet
// void main() {
// runApp(MyApp());
// runApp(const MyApp());
// }
// class MyApp extends StatelessWidget {
// MyApp({Key? key}) : super(key: key);
// const MyApp({Key? key}) : super(key: key);
// @override
// Widget build(BuildContext context) {
// return GetMaterialApp.router(
// return GetMaterialApp(
// getPages: [
// GetPage(
// participatesInRootNavigator: true,
// name: '/first',
// page: () => First()),
// page: () => const First()),
// GetPage(
// name: '/second',
// page: () => Second(),
// page: () => const Second(),
// ),
// GetPage(
// name: '/third',
// page: () => Third(),
// page: () => const Third(),
// ),
// ],
// debugShowCheckedModeBanner: false,
... ... @@ -59,26 +59,32 @@ class MyApp extends StatelessWidget {
// }
// class First extends StatelessWidget {
// const First({Key? key}) : super(key: key);
// @override
// Widget build(BuildContext context) {
// print('First rebuild');
// return Scaffold(
// appBar: AppBar(
// title: Text('page one'),
// title: const Text('page one'),
// leading: IconButton(
// icon: Icon(Icons.more),
// icon: const Icon(Icons.more),
// onPressed: () {
// print('THEME CHANGED');
// Get.changeTheme(
// context.isDarkMode ? ThemeData.light() : ThemeData.dark());
// Get.isDarkMode ? ThemeData.light() : ThemeData.dark());
// },
// ),
// ),
// body: Center(
// child: Container(
// child: SizedBox(
// height: 300,
// width: 300,
// child: ElevatedButton(
// onPressed: () {},
// child: Text('next screen'),
// onPressed: () {
// Get.toNamed('/second?id=123');
// },
// child: const Text('next screen'),
// ),
// ),
// ),
... ... @@ -87,19 +93,22 @@ class MyApp extends StatelessWidget {
// }
// class Second extends StatelessWidget {
// const Second({Key? key}) : super(key: key);
// @override
// Widget build(BuildContext context) {
// print('second rebuild');
// return Scaffold(
// appBar: AppBar(
// title: Text('page two ${Get.parameters["id"]}'),
// ),
// body: Center(
// child: Container(
// child: SizedBox(
// height: 300,
// width: 300,
// child: ElevatedButton(
// onPressed: () {},
// child: Text('next screen'),
// child: const Text('next screen'),
// ),
// ),
// ),
... ... @@ -108,20 +117,22 @@ class MyApp extends StatelessWidget {
// }
// class Third extends StatelessWidget {
// const Third({Key? key}) : super(key: key);
// @override
// Widget build(BuildContext context) {
// return Scaffold(
// backgroundColor: Colors.red,
// appBar: AppBar(
// title: Text('page three'),
// title: const Text('page three'),
// ),
// body: Center(
// child: Container(
// child: SizedBox(
// height: 300,
// width: 300,
// child: ElevatedButton(
// onPressed: () {},
// child: Text('go to first screen'),
// child: const Text('go to first screen'),
// ),
// ),
// ),
... ...
... ... @@ -10,7 +10,7 @@ class CountryView extends GetView<HomeController> {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
decoration: const BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
colorFilter: ColorFilter.linearToSrgbGamma(),
... ... @@ -36,7 +36,7 @@ class CountryView extends GetView<HomeController> {
//Get.rootDelegate.toNamed('/home/country');
final data =
await Get.toNamed('/home/country/details?id=$index');
print(data);
Get.log(data);
},
trailing: CircleAvatar(
backgroundImage: NetworkImage(
... ...
... ... @@ -15,7 +15,7 @@ class DetailsView extends GetView<HomeController> {
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
colorFilter: ColorFilter.linearToSrgbGamma(),
colorFilter: const ColorFilter.linearToSrgbGamma(),
image: NetworkImage(
"https://flagpedia.net/data/flags/normal/${country.countryCode.toLowerCase()}.png"),
),
... ... @@ -35,53 +35,57 @@ class DetailsView extends GetView<HomeController> {
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'${country.country}',
style: TextStyle(fontSize: 45, fontWeight: FontWeight.bold),
country.country,
style:
const TextStyle(fontSize: 45, fontWeight: FontWeight.bold),
),
SizedBox(
const SizedBox(
height: 35,
),
Text(
'total_confirmed'.tr,
style: TextStyle(
style: const TextStyle(
fontSize: 25,
),
),
Text(
'${country.totalConfirmed}',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
style:
const TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
),
SizedBox(
const SizedBox(
height: 10,
),
Text(
'total_deaths'.tr,
style: TextStyle(
style: const TextStyle(
fontSize: 25,
),
),
Text(
'${country.totalDeaths}',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
style:
const TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
),
SizedBox(
const SizedBox(
height: 10,
),
Text(
'total_recovered'.tr,
style: TextStyle(
style: const TextStyle(
fontSize: 25,
),
),
Text(
'${country.totalRecovered}',
style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
style:
const TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
),
TextButton(
onPressed: () {
Get.back(result: 'djsoidjsoidj');
},
child: Text('back'))
child: const Text('back'))
],
)),
),
... ...
... ... @@ -9,7 +9,7 @@ class HomeView extends GetView<HomeController> {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
decoration: const BoxDecoration(
color: Colors.white,
image: DecorationImage(
fit: BoxFit.cover,
... ... @@ -22,7 +22,7 @@ class HomeView extends GetView<HomeController> {
backgroundColor: Colors.transparent,
appBar: AppBar(
leading: IconButton(
icon: Icon(Icons.add),
icon: const Icon(Icons.add),
onPressed: () {
Get.snackbar('title', 'message');
},
... ... @@ -38,43 +38,45 @@ class HomeView extends GetView<HomeController> {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(
const SizedBox(
height: 100,
),
Text(
'total_confirmed'.tr,
style: TextStyle(
style: const TextStyle(
fontSize: 30,
),
),
Text(
'${state!.global.totalConfirmed}',
style: TextStyle(fontSize: 45, fontWeight: FontWeight.bold),
style: const TextStyle(
fontSize: 45, fontWeight: FontWeight.bold),
),
SizedBox(
const SizedBox(
height: 10,
),
Text(
'total_deaths'.tr,
style: TextStyle(
style: const TextStyle(
fontSize: 30,
),
),
Text(
'${state.global.totalDeaths}',
style: TextStyle(fontSize: 45, fontWeight: FontWeight.bold),
style: const TextStyle(
fontSize: 45, fontWeight: FontWeight.bold),
),
SizedBox(
const SizedBox(
height: 10,
),
OutlinedButton(
style: OutlinedButton.styleFrom(
textStyle: TextStyle(color: Colors.black),
side: BorderSide(
textStyle: const TextStyle(color: Colors.black),
side: const BorderSide(
color: Colors.deepPurple,
width: 3,
),
shape: StadiumBorder(),
shape: const StadiumBorder(),
),
onPressed: () async {
//await Navigation Get.rootDelegate.toNamed('/home/country');
... ... @@ -82,7 +84,7 @@ class HomeView extends GetView<HomeController> {
},
child: Text(
'fetch_country'.tr,
style: TextStyle(
style: const TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
),
... ... @@ -90,17 +92,17 @@ class HomeView extends GetView<HomeController> {
),
OutlinedButton(
style: OutlinedButton.styleFrom(
textStyle: TextStyle(color: Colors.black),
side: BorderSide(
textStyle: const TextStyle(color: Colors.black),
side: const BorderSide(
color: Colors.deepPurple,
width: 3,
),
shape: StadiumBorder(),
shape: const StadiumBorder(),
),
onPressed: () {
Get.updateLocale(Locale('pt', 'BR'));
Get.updateLocale(const Locale('pt', 'BR'));
},
child: Text(
child: const Text(
'Update language to Portuguese',
style: TextStyle(
fontWeight: FontWeight.bold,
... ...
... ... @@ -14,16 +14,16 @@ class AppPages {
static final routes = [
GetPage(
name: Routes.HOME,
page: () => HomeView(),
page: () => const HomeView(),
binding: HomeBinding(),
children: [
GetPage(
name: Routes.COUNTRY,
page: () => CountryView(),
page: () => const CountryView(),
children: [
GetPage(
name: Routes.DETAILS,
page: () => DetailsView(),
page: () => const DetailsView(),
),
],
),
... ...
mixin Logger {
// Sample of abstract logging function
static void write(String text, {bool isError = false}) {
// ignore: avoid_print
Future.microtask(() => print('** $text. isError: [$isError]'));
}
}
... ...
... ... @@ -38,6 +38,7 @@ dev_dependencies:
flutter_test:
sdk: flutter
get_test: 4.0.1
flutter_lints: ^2.0.1
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
... ...
... ... @@ -3,13 +3,11 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
import 'package:get_demo/pages/home/domain/adapters/repository_adapter.dart';
import 'package:get_demo/pages/home/domain/entity/cases_model.dart';
import 'package:get_demo/pages/home/presentation/controllers/home_controller.dart';
// import 'package:get_demo/routes/app_pages.dart';
// import 'package:get_test/get_test.dart';
import 'package:matcher/matcher.dart' as m;
import '../lib/pages/home/domain/adapters/repository_adapter.dart';
import '../lib/pages/home/domain/entity/cases_model.dart';
import '../lib/pages/home/presentation/controllers/home_controller.dart';
class MockRepositorySuccess implements IHomeRepository {
@override
... ... @@ -57,7 +55,7 @@ void main() {
test('Test Controller', () async {
/// Controller can't be on memory
expect(() => Get.find<HomeController>(tag: 'success'),
throwsA(m.TypeMatcher<String>()));
throwsA(const TypeMatcher<String>()));
/// binding will put the controller on memory
binding.dependencies();
... ... @@ -72,7 +70,7 @@ void main() {
expect(controller.status.isLoading, true);
/// await time request
await Future.delayed(Duration(milliseconds: 100));
await Future.delayed(const Duration(milliseconds: 100));
/// test if status is success
expect(controller.status.isSuccess, true);
... ...
... ... @@ -8,7 +8,7 @@ class DashboardController extends GetxController {
void onReady() {
super.onReady();
Timer.periodic(
Duration(seconds: 1),
const Duration(seconds: 1),
(timer) {
now.value = DateTime.now();
},
... ...
... ... @@ -4,6 +4,8 @@ import 'package:get/get.dart';
import '../controllers/dashboard_controller.dart';
class DashboardView extends GetView<DashboardController> {
const DashboardView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
... ... @@ -12,7 +14,7 @@ class DashboardView extends GetView<DashboardController> {
() => Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
const Text(
'DashboardView is working',
style: TextStyle(fontSize: 20),
),
... ...
... ... @@ -14,7 +14,6 @@ class HomeView extends GetView<HomeController> {
final delegate = context.navigation;
//This router outlet handles the appbar and the bottom navigation bar
final currentLocation = context.location;
print(currentLocation);
var currentIndex = 0;
if (currentLocation.startsWith(Routes.products) == true) {
currentIndex = 2;
... ... @@ -46,7 +45,7 @@ class HomeView extends GetView<HomeController> {
default:
}
},
items: [
items: const [
// _Paths.HOME + [Empty]
BottomNavigationBarItem(
icon: Icon(Icons.home),
... ...
... ... @@ -6,6 +6,8 @@ import '../../../routes/app_pages.dart';
import '../controllers/login_controller.dart';
class LoginView extends GetView<LoginController> {
const LoginView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
... ... @@ -25,7 +27,7 @@ class LoginView extends GetView<LoginController> {
},
),
MaterialButton(
child: Text(
child: const Text(
'Do LOGIN !!',
style: TextStyle(color: Colors.blue, fontSize: 20),
),
... ...
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/product_details_controller.dart';
class ProductDetailsView extends GetWidget<ProductDetailsController> {
const ProductDetailsView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
... ... @@ -12,7 +13,7 @@ class ProductDetailsView extends GetWidget<ProductDetailsController> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
const Text(
'ProductDetailsView is working',
style: TextStyle(fontSize: 20),
),
... ...
... ... @@ -11,13 +11,13 @@ class ProductsView extends GetView<ProductsController> {
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
onPressed: () => controller.loadDemoProductsFromSomeWhere(),
label: Text('Add'),
label: const Text('Add'),
),
body: Column(
children: [
Hero(
const Hero(
tag: 'heroLogo',
child: const FlutterLogo(),
child: FlutterLogo(),
),
Expanded(
child: Obx(
... ...
... ... @@ -5,6 +5,8 @@ import '../../../routes/app_pages.dart';
import '../controllers/profile_controller.dart';
class ProfileView extends GetView<ProfileController> {
const ProfileView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
... ... @@ -13,16 +15,16 @@ class ProfileView extends GetView<ProfileController> {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
const Text(
'ProfileView is working',
style: TextStyle(fontSize: 20),
),
Hero(
const Hero(
tag: 'heroLogo',
child: const FlutterLogo(),
child: FlutterLogo(),
),
MaterialButton(
child: Text('Show a test dialog'),
child: const Text('Show a test dialog'),
onPressed: () {
//shows a dialog
Get.defaultDialog(
... ... @@ -32,7 +34,7 @@ class ProfileView extends GetView<ProfileController> {
},
),
MaterialButton(
child: Text('Show a test dialog in Home router outlet'),
child: const Text('Show a test dialog in Home router outlet'),
onPressed: () {
//shows a dialog
... ...
... ... @@ -19,7 +19,7 @@ class DrawerWidget extends StatelessWidget {
color: Colors.red,
),
ListTile(
title: Text('Home'),
title: const Text('Home'),
onTap: () {
Get.toNamed(Routes.home);
//to close the drawer
... ... @@ -28,7 +28,7 @@ class DrawerWidget extends StatelessWidget {
},
),
ListTile(
title: Text('Settings'),
title: const Text('Settings'),
onTap: () {
Get.toNamed(Routes.settings);
//to close the drawer
... ... @@ -38,7 +38,7 @@ class DrawerWidget extends StatelessWidget {
),
if (AuthService.to.isLoggedInValue)
ListTile(
title: Text(
title: const Text(
'Logout',
style: TextStyle(
color: Colors.red,
... ... @@ -54,7 +54,7 @@ class DrawerWidget extends StatelessWidget {
),
if (!AuthService.to.isLoggedInValue)
ListTile(
title: Text(
title: const Text(
'Login',
style: TextStyle(
color: Colors.blue,
... ...
... ... @@ -6,6 +6,8 @@ import '../controllers/root_controller.dart';
import 'drawer.dart';
class RootView extends GetView<RootController> {
const RootView({super.key});
@override
Widget build(BuildContext context) {
return RouterOutlet.builder(
... ... @@ -13,7 +15,7 @@ class RootView extends GetView<RootController> {
builder: (context) {
final title = context.location;
return Scaffold(
drawer: DrawerWidget(),
drawer: const DrawerWidget(),
appBar: AppBar(
title: Text(title),
centerTitle: true,
... ...
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/settings_controller.dart';
class SettingsView extends GetView<SettingsController> {
const SettingsView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
return const Scaffold(
body: Center(
child: Text(
'SettingsView is working',
... ...
... ... @@ -18,11 +18,11 @@ class SplashService extends GetxService {
Future<void> _initFunction() async {
final t = Timer.periodic(
Duration(milliseconds: 500),
const Duration(milliseconds: 500),
(t) => _changeActiveString(),
);
//simulate some long running operation
await Future.delayed(Duration(seconds: 5));
await Future.delayed(const Duration(seconds: 5));
//cancel the timer once we are done
t.cancel();
}
... ...
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/splash_service.dart';
class SplashView extends GetView<SplashService> {
const SplashView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
... ... @@ -15,10 +16,10 @@ class SplashView extends GetView<SplashService> {
Obx(
() => Text(
controller.welcomeStr[controller.activeStr.value],
style: TextStyle(fontSize: 20),
style: const TextStyle(fontSize: 20),
),
),
CircularProgressIndicator(),
const CircularProgressIndicator(),
],
),
),
... ...
... ... @@ -28,7 +28,7 @@ class AppPages {
static final routes = [
GetPage(
name: '/',
page: () => RootView(),
page: () => const RootView(),
bindings: [RootBinding()],
participatesInRootNavigator: true,
preventDuplicates: true,
... ... @@ -39,7 +39,7 @@ class AppPages {
EnsureNotAuthedMiddleware(),
],
name: _Paths.login,
page: () => LoginView(),
page: () => const LoginView(),
bindings: [LoginBinding()],
),
GetPage(
... ... @@ -53,7 +53,7 @@ class AppPages {
children: [
GetPage(
name: _Paths.dashboard,
page: () => DashboardView(),
page: () => const DashboardView(),
bindings: [
DashboardBinding(),
],
... ... @@ -64,7 +64,7 @@ class AppPages {
EnsureAuthMiddleware(),
],
name: _Paths.profile,
page: () => ProfileView(),
page: () => const ProfileView(),
title: 'Profile',
transition: Transition.size,
bindings: [ProfileBinding()],
... ... @@ -82,7 +82,7 @@ class AppPages {
name: _Paths.productDetails,
transition: Transition.cupertino,
showCupertinoParallax: true,
page: () => ProductDetailsView(),
page: () => const ProductDetailsView(),
bindings: const [],
middlewares: [
//only enter this route when authed
... ... @@ -95,7 +95,7 @@ class AppPages {
),
GetPage(
name: _Paths.settings,
page: () => SettingsView(),
page: () => const SettingsView(),
bindings: [
SettingsBinding(),
],
... ...
... ... @@ -3,6 +3,7 @@
/// injection, and route management in a quick and practical way.
library get;
export 'get_animations/index.dart';
export 'get_common/get_reset.dart';
export 'get_connect/connect.dart';
export 'get_core/get_core.dart';
... ...
import 'dart:math';
import 'dart:ui';
import 'package:flutter/widgets.dart';
import 'get_animated_builder.dart';
typedef OffsetBuilder = Offset Function(BuildContext, double);
class FadeInAnimation extends OpacityAnimation {
FadeInAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
super.begin = 0,
super.end = 1,
super.idleValue = 0,
});
}
class FadeOutAnimation extends OpacityAnimation {
FadeOutAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
super.begin = 1,
super.end = 0,
super.idleValue = 1,
});
}
class OpacityAnimation extends GetAnimatedBuilder<double> {
OpacityAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
required super.onComplete,
required double begin,
required double end,
required super.idleValue,
}) : super(
tween: Tween<double>(begin: begin, end: end),
builder: (context, value, child) {
return Opacity(
opacity: value,
child: child!,
);
},
);
}
class RotateAnimation extends GetAnimatedBuilder<double> {
RotateAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform.rotate(
angle: value,
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
class ScaleAnimation extends GetAnimatedBuilder<double> {
ScaleAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform.scale(
scale: value,
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
// class SlideAnimation extends GetAnimatedBuilder<Offset> {
// SlideAnimation({
// super.key,
// required super.duration,
// required super.delay,
// required super.child,
// super.onComplete,
// required Offset begin,
// required Offset end,
// super.idleValue = const Offset(0, 0),
// }) : super(
// builder: (context, value, child) => Transform.translate(
// offset: value,
// child: child,
// ),
// tween: Tween(begin: begin, end: end),
// );
// }
class BounceAnimation extends GetAnimatedBuilder<double> {
BounceAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
super.curve = Curves.bounceOut,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform.scale(
scale: 1 + value.abs(),
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
class SpinAnimation extends GetAnimatedBuilder<double> {
SpinAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform.rotate(
angle: value * pi / 180.0,
child: child,
),
tween: Tween<double>(begin: 0, end: 360),
);
}
class SizeAnimation extends GetAnimatedBuilder<double> {
SizeAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
super.idleValue = 0,
required double begin,
required double end,
}) : super(
builder: (context, value, child) => Transform.scale(
scale: value,
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
class BlurAnimation extends GetAnimatedBuilder<double> {
BlurAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => BackdropFilter(
filter: ImageFilter.blur(
sigmaX: value,
sigmaY: value,
),
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
class FlipAnimation extends GetAnimatedBuilder<double> {
FlipAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) {
final radians = value * pi;
return Transform(
transform: Matrix4.rotationY(radians),
alignment: Alignment.center,
child: child,
);
},
tween: Tween<double>(begin: begin, end: end),
);
}
class WaveAnimation extends GetAnimatedBuilder<double> {
WaveAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform(
transform: Matrix4.translationValues(
0.0,
20.0 * sin(value * pi * 2),
0.0,
),
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
class WobbleAnimation extends GetAnimatedBuilder<double> {
WobbleAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required double begin,
required double end,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.001)
..rotateZ(sin(value * pi * 2) * 0.1),
alignment: Alignment.center,
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
class SlideInLeftAnimation extends SlideAnimation {
SlideInLeftAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required super.begin,
required super.end,
super.idleValue = 0,
}) : super(
offsetBuild: (context, value) =>
Offset(value * MediaQuery.of(context).size.width, 0),
);
}
class SlideInRightAnimation extends SlideAnimation {
SlideInRightAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required super.begin,
required super.end,
super.idleValue = 0,
}) : super(
offsetBuild: (context, value) =>
Offset((1 - value) * MediaQuery.of(context).size.width, 0),
);
}
class SlideInUpAnimation extends SlideAnimation {
SlideInUpAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required super.begin,
required super.end,
super.idleValue = 0,
}) : super(
offsetBuild: (context, value) =>
Offset(0, value * MediaQuery.of(context).size.height),
);
}
class SlideInDownAnimation extends SlideAnimation {
SlideInDownAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required super.begin,
required super.end,
super.idleValue = 0,
}) : super(
offsetBuild: (context, value) =>
Offset(0, (1 - value) * MediaQuery.of(context).size.height),
);
}
class SlideAnimation extends GetAnimatedBuilder<double> {
SlideAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
required double begin,
required double end,
required OffsetBuilder offsetBuild,
super.onComplete,
super.idleValue = 0,
}) : super(
builder: (context, value, child) => Transform.translate(
offset: offsetBuild(context, value),
child: child,
),
tween: Tween<double>(begin: begin, end: end),
);
}
// class ZoomAnimation extends GetAnimatedBuilder<double> {
// ZoomAnimation({
// super.key,
// required super.duration,
// required super.delay,
// required super.child,
// super.onComplete,
// required double begin,
// required double end,
// super.idleValue = 0,
// }) : super(
// builder: (context, value, child) => Transform.scale(
// scale: lerpDouble(1, end, value)!,
// child: child,
// ),
// tween: Tween<double>(begin: begin, end: end),
// );
// }
class ColorAnimation extends GetAnimatedBuilder<Color?> {
ColorAnimation({
super.key,
required super.duration,
required super.delay,
required super.child,
super.onComplete,
required Color begin,
required Color end,
Color? idleColor,
}) : super(
builder: (context, value, child) => ColorFiltered(
colorFilter: ColorFilter.mode(
Color.lerp(begin, end, value!.value.toDouble())!,
BlendMode.srcIn,
),
child: child,
),
idleValue: idleColor ?? begin,
tween: ColorTween(begin: begin, end: end),
);
}
... ...
import 'package:flutter/material.dart';
import 'animations.dart';
import 'get_animated_builder.dart';
const _defaultDuration = Duration(seconds: 2);
const _defaultDelay = Duration.zero;
extension AnimationExtension on Widget {
GetAnimatedBuilder? get _currentAnimation =>
(this is GetAnimatedBuilder) ? this as GetAnimatedBuilder : null;
GetAnimatedBuilder fadeIn({
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
assert(isSequential || this is! FadeOutAnimation,
'Can not use fadeOut + fadeIn when isSequential is false');
return FadeInAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder fadeOut({
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
assert(isSequential || this is! FadeInAnimation,
'Can not use fadeOut() + fadeIn when isSequential is false');
return FadeOutAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder rotate({
required double begin,
required double end,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return RotateAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder scale({
required double begin,
required double end,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return ScaleAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder slide({
required OffsetBuilder offset,
double begin = 0,
double end = 1,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return SlideAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
offsetBuild: offset,
child: this,
);
}
GetAnimatedBuilder bounce({
required double begin,
required double end,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return BounceAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder spin({
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return SpinAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder size({
required double begin,
required double end,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return SizeAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder blur({
double begin = 0,
double end = 15,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return BlurAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder flip({
double begin = 0,
double end = 1,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return FlipAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
GetAnimatedBuilder wave({
double begin = 0,
double end = 1,
Duration duration = _defaultDuration,
Duration delay = _defaultDelay,
ValueSetter<AnimationController>? onComplete,
bool isSequential = false,
}) {
return WaveAnimation(
duration: duration,
delay: _getDelay(isSequential, delay),
begin: begin,
end: end,
onComplete: onComplete,
child: this,
);
}
Duration _getDelay(bool isSequential, Duration delay) {
assert(!(isSequential && delay != Duration.zero),
"Error: When isSequential is true, delay must be non-zero. Context: isSequential: $isSequential delay: $delay");
return isSequential
? (_currentAnimation?.totalDuration ?? Duration.zero)
: delay;
}
}
... ...
import 'package:flutter/material.dart';
import 'animations.dart';
class GetAnimatedBuilder<T> extends StatefulWidget {
final Duration duration;
final Duration delay;
final Widget child;
final ValueSetter<AnimationController>? onComplete;
final ValueSetter<AnimationController>? onStart;
final Tween<T> tween;
final T idleValue;
final ValueWidgetBuilder<T> builder;
final Curve curve;
Duration get totalDuration => duration + delay;
const GetAnimatedBuilder({
super.key,
this.curve = Curves.linear,
this.onComplete,
this.onStart,
required this.duration,
required this.tween,
required this.idleValue,
required this.builder,
required this.child,
required this.delay,
});
@override
GetAnimatedBuilderState<T> createState() => GetAnimatedBuilderState<T>();
}
class GetAnimatedBuilderState<T> extends State<GetAnimatedBuilder<T>>
with SingleTickerProviderStateMixin {
late final AnimationController _controller;
late final Animation<T> _animation;
// AnimationController get controller => _controller;
// Animation<T> get animation => _animation;
bool _wasStarted = false;
// bool get wasStarted => _wasStarted;
late T _idleValue;
bool _willResetOnDispose = false;
bool get willResetOnDispose => _willResetOnDispose;
void _listener(AnimationStatus status) {
switch (status) {
case AnimationStatus.completed:
widget.onComplete?.call(_controller);
if (_willResetOnDispose) {
_controller.reset();
}
break;
// case AnimationStatus.dismissed:
case AnimationStatus.forward:
widget.onStart?.call(_controller);
break;
// case AnimationStatus.reverse:
default:
break;
}
}
@override
void initState() {
super.initState();
if (widget is OpacityAnimation) {
final current =
context.findRootAncestorStateOfType<GetAnimatedBuilderState>();
final isLast = current == null;
if (widget is FadeInAnimation) {
_idleValue = 1.0 as dynamic;
} else {
if (isLast) {
_willResetOnDispose = false;
} else {
_willResetOnDispose = true;
}
_idleValue = widget.idleValue;
}
} else {
_idleValue = widget.idleValue;
}
_controller = AnimationController(
vsync: this,
duration: widget.duration,
);
_controller.addStatusListener(_listener);
_animation = widget.tween.animate(
CurvedAnimation(
parent: _controller,
curve: widget.curve,
),
);
Future.delayed(widget.delay, () {
if (mounted) {
setState(() {
_wasStarted = true;
_controller.forward();
});
}
});
}
@override
void dispose() {
_controller.removeStatusListener(_listener);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _animation,
builder: (context, child) {
final value = _wasStarted ? _animation.value : _idleValue;
return widget.builder(context, value, child);
},
child: widget.child,
);
}
}
... ...
export './animations.dart';
export './extensions.dart';
export './get_animated_builder.dart';
... ...
... ... @@ -268,9 +268,9 @@ class GetConnect extends GetConnectInterface {
}) {
_checkIfDisposed(isHttp: false);
final _socket = GetSocket(_concatUrl(url)!, ping: ping);
sockets.add(_socket);
return _socket;
final newSocket = GetSocket(_concatUrl(url)!, ping: ping);
sockets.add(newSocket);
return newSocket;
}
String? _concatUrl(String? url) {
... ...
... ... @@ -16,7 +16,8 @@ typedef Decoder<T> = T Function(dynamic data);
typedef Progress = Function(double percent);
typedef ResponseInterceptor<T> = Future<Response<T>?> Function(Request<T> request, Type targetType, HttpClientResponse response);
typedef ResponseInterceptor<T> = Future<Response<T>?> Function(
Request<T> request, Type targetType, HttpClientResponse response);
class GetHttpClient {
String userAgent;
... ... @@ -38,7 +39,7 @@ class GetHttpClient {
bool errorSafety = true;
final HttpRequestBase _httpClient;
final IClient _httpClient;
final GetModifier _modifier;
... ... @@ -57,12 +58,14 @@ class GetHttpClient {
List<TrustedCertificate>? trustedCertificates,
bool withCredentials = false,
String Function(Uri url)? findProxy,
}) : _httpClient = createHttp(
allowAutoSignedCert: allowAutoSignedCert,
trustedCertificates: trustedCertificates,
withCredentials: withCredentials,
findProxy: findProxy,
),
IClient? customClient,
}) : _httpClient = customClient ??
createHttp(
allowAutoSignedCert: allowAutoSignedCert,
trustedCertificates: trustedCertificates,
withCredentials: withCredentials,
findProxy: findProxy,
),
_modifier = GetModifier();
void addAuthenticator<T>(RequestModifier<T> auth) {
... ... @@ -85,7 +88,7 @@ class GetHttpClient {
_modifier.removeResponseModifier<T>(interceptor);
}
Uri _createUri(String? url, Map<String, dynamic>? query) {
Uri createUri(String? url, Map<String, dynamic>? query) {
if (baseUrl != null) {
url = baseUrl! + url!;
}
... ... @@ -154,18 +157,17 @@ class GetHttpClient {
bodyStream = _trackProgress(bodyBytes, uploadProgress);
}
final uri = _createUri(url, query);
final uri = createUri(url, query);
return Request<T>(
method: method,
url: uri,
headers: headers,
bodyBytes: bodyStream,
contentLength: bodyBytes?.length ?? 0,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
decoder: decoder,
responseInterceptor: responseInterceptor
);
method: method,
url: uri,
headers: headers,
bodyBytes: bodyStream,
contentLength: bodyBytes?.length ?? 0,
followRedirects: followRedirects,
maxRedirects: maxRedirects,
decoder: decoder,
responseInterceptor: responseInterceptor);
}
void _setContentLenght(Map<String, String> headers, int contentLength) {
... ... @@ -277,7 +279,7 @@ class GetHttpClient {
) {
final headers = <String, String>{};
_setSimpleHeaders(headers, contentType);
final uri = _createUri(url, query);
final uri = createUri(url, query);
return Future.value(Request<T>(
method: 'get',
... ... @@ -291,11 +293,14 @@ class GetHttpClient {
));
}
ResponseInterceptor<T>? _responseInterceptor<T>(ResponseInterceptor<T>? actual) {
if(actual != null) return actual;
ResponseInterceptor<T>? _responseInterceptor<T>(
ResponseInterceptor<T>? actual) {
if (actual != null) return actual;
final defaultInterceptor = defaultResponseInterceptor;
return defaultInterceptor != null
? (request, targetType, response) async => await defaultInterceptor(request, targetType, response) as Response<T>?
? (request, targetType, response) async =>
await defaultInterceptor(request, targetType, response)
as Response<T>?
: null;
}
... ... @@ -330,7 +335,7 @@ class GetHttpClient {
) {
final headers = <String, String>{};
_setSimpleHeaders(headers, contentType);
final uri = _createUri(url, query);
final uri = createUri(url, query);
return Request<T>(
method: 'delete',
... ... @@ -340,6 +345,7 @@ class GetHttpClient {
responseInterceptor: _responseInterceptor(responseInterceptor),
);
}
Future<Response<T>> send<T>(Request<T> request) async {
try {
var response = await _performRequest<T>(() => Future.value(request));
... ... @@ -521,78 +527,16 @@ class GetHttpClient {
}
}
// Future<Response<T>> download<T>(
// String url,
// String path, {
// Map<String, String> headers,
// String contentType = 'application/octet-stream',
// Map<String, dynamic> query,
// }) async {
// try {
// var response = await _performRequest<T>(
// () => _get<T>(url, contentType, query, null),
// headers: headers,
// );
// response.bodyBytes.listen((value) {});
// return response;
// } on Exception catch (e) {
// if (!errorSafety) {
// throw GetHttpException(e.toString());
// }
// return Future.value(Response<T>(
// statusText: 'Can not connect to server. Reason: $e',
// ));
// }
// int byteCount = 0;
// int totalBytes = httpResponse.contentLength;
// Directory appDocDir = await getApplicationDocumentsDirectory();
// String appDocPath = appDocDir.path;
// File file = File(path);
// var raf = file.openSync(mode: FileMode.write);
// Completer completer = Completer<String>();
// httpResponse.listen(
// (data) {
// byteCount += data.length;
// raf.writeFromSync(data);
// if (onDownloadProgress != null) {
// onDownloadProgress(byteCount, totalBytes);
// }
// },
// onDone: () {
// raf.closeSync();
// completer.complete(file.path);
// },
// onError: (e) {
// raf.closeSync();
// file.deleteSync();
// completer.completeError(e);
// },
// cancelOnError: true,
// );
// return completer.future;
// }
Future<Response<T>> delete<T>(
String url, {
Map<String, String>? headers,
String? contentType,
Map<String, dynamic>? query,
Decoder<T>? decoder,
ResponseInterceptor<T>? responseInterceptor
}) async {
Future<Response<T>> delete<T>(String url,
{Map<String, String>? headers,
String? contentType,
Map<String, dynamic>? query,
Decoder<T>? decoder,
ResponseInterceptor<T>? responseInterceptor}) async {
try {
var response = await _performRequest<T>(
() async => _delete<T>(url, contentType, query, decoder, responseInterceptor),
() async =>
_delete<T>(url, contentType, query, decoder, responseInterceptor),
headers: headers,
);
return response;
... ...
... ... @@ -4,7 +4,8 @@ List<int> fileToBytes(dynamic data) {
if (data is List<int>) {
return data;
} else {
throw FormatException('File is not "File" or "String" or "List<int>"');
throw const FormatException(
'File is not "File" or "String" or "List<int>"');
}
}
... ...
... ... @@ -9,8 +9,8 @@ import '../../response/response.dart';
import '../interface/request_base.dart';
import '../utils/body_decoder.dart';
/// A `dart:html` implementation of `HttpRequestBase`.
class HttpRequestImpl implements HttpRequestBase {
/// A `dart:html` implementation of `IClient`.
class HttpRequestImpl implements IClient {
HttpRequestImpl({
bool allowAutoSignedCert = true,
List<TrustedCertificate>? trustedCertificates,
... ... @@ -51,7 +51,7 @@ class HttpRequestImpl implements HttpRequestBase {
var reader = FileReader();
reader.onLoad.first.then((_) async {
var bodyBytes = BodyBytesStream.fromBytes(reader.result as List<int>);
var bodyBytes = (reader.result as List<int>).toStream();
final stringBody =
await bodyBytesToString(bodyBytes, xhr.responseHeaders);
... ...
... ... @@ -2,7 +2,7 @@ import '../../request/request.dart';
import '../../response/response.dart';
/// Abstract interface of [HttpRequestImpl].
abstract class HttpRequestBase {
abstract class IClient {
/// Sends an HTTP [Request].
Future<Response<T>> send<T>(Request<T> request);
... ...
... ... @@ -12,7 +12,8 @@ List<int> fileToBytes(dynamic data) {
} else if (data is List<int>) {
return data;
} else {
throw FormatException('File is not "File" or "String" or "List<int>"');
throw const FormatException(
'File is not "File" or "String" or "List<int>"');
}
}
... ...
... ... @@ -8,9 +8,8 @@ import '../../response/response.dart';
import '../interface/request_base.dart';
import '../utils/body_decoder.dart';
/// A `dart:io` implementation of `HttpRequestBase`.
class HttpRequestImpl extends HttpRequestBase {
/// A `dart:io` implementation of `IClient`.
class HttpRequestImpl extends IClient {
io.HttpClient? _httpClient;
io.SecurityContext? _securityContext;
... ... @@ -58,10 +57,11 @@ class HttpRequestImpl extends HttpRequestBase {
});
final bodyBytes = (response);
final interceptionResponse = await request.responseInterceptor?.call(request, T, response);
if(interceptionResponse != null) return interceptionResponse;
final interceptionResponse =
await request.responseInterceptor?.call(request, T, response);
if (interceptionResponse != null) return interceptionResponse;
final stringBody = await bodyBytesToString(bodyBytes, headers);
final body = bodyDecoded<T>(
... ...
... ... @@ -5,7 +5,7 @@ import '../utils/body_decoder.dart';
typedef MockClientHandler = Future<Response> Function(Request request);
class MockClient extends HttpRequestBase {
class MockClient extends IClient {
/// The handler for than transforms request on response
final MockClientHandler _handler;
... ... @@ -16,7 +16,7 @@ class MockClient extends HttpRequestBase {
@override
Future<Response<T>> send<T>(Request<T> request) async {
var requestBody = await request.bodyBytes.toBytes();
var bodyBytes = BodyBytesStream.fromBytes(requestBody);
var bodyBytes = requestBody.toStream();
var response = await _handler(request);
... ...
... ... @@ -3,7 +3,7 @@ import '../../request/request.dart';
import '../../response/response.dart';
import '../interface/request_base.dart';
class HttpRequestImpl extends HttpRequestBase {
class HttpRequestImpl extends IClient {
HttpRequestImpl({
bool allowAutoSignedCert = true,
List<TrustedCertificate>? trustedCertificates,
... ...
... ... @@ -25,9 +25,9 @@ class FormData {
static const int _maxBoundaryLength = 70;
static String _getBoundary() {
final _random = Random();
final newRandom = Random();
var list = List<int>.generate(_maxBoundaryLength - GET_BOUNDARY.length,
(_) => boundaryCharacters[_random.nextInt(boundaryCharacters.length)],
(_) => boundaryCharacters[newRandom.nextInt(boundaryCharacters.length)],
growable: false);
return '$GET_BOUNDARY${String.fromCharCodes(list)}';
}
... ...
import '../http/stub/file_decoder_stub.dart'
if (dart.library.html) '../http/html/file_decoder_html.dart'
if (dart.library.io) '../http/io/file_decoder_io.dart';
import '../request/request.dart';
class MultipartFile {
... ... @@ -11,7 +10,7 @@ class MultipartFile {
this.contentType = 'application/octet-stream',
}) : _bytes = fileToBytes(data) {
_length = _bytes.length;
_stream = BodyBytesStream.fromBytes(_bytes);
_stream = _bytes.toStream();
}
final List<int> _bytes;
... ...
... ... @@ -68,7 +68,7 @@ class Request<T> {
return Request._(
url: url,
method: method,
bodyBytes: bodyBytes ??= BodyBytesStream.fromBytes(const []),
bodyBytes: bodyBytes ??= <int>[].toStream(),
headers: Map.from(headers),
followRedirects: followRedirects,
maxRedirects: maxRedirects,
... ... @@ -113,9 +113,11 @@ class Request<T> {
}
}
extension BodyBytesStream on Stream<List<int>> {
static Stream<List<int>> fromBytes(List<int> bytes) => Stream.value(bytes);
extension StreamExt on List<int> {
Stream<List<int>> toStream() => Stream.value(this).asBroadcastStream();
}
extension BodyBytesStream on Stream<List<int>> {
Future<Uint8List> toBytes() {
var completer = Completer<Uint8List>();
var sink = ByteConversionSink.withCallback(
... ...
import 'package:flutter/widgets.dart';
class Engine{
static WidgetsBinding get instance {
class Engine {
static WidgetsBinding get instance {
return WidgetsFlutterBinding.ensureInitialized();
}
}
\ No newline at end of file
}
... ...
... ... @@ -161,11 +161,11 @@ extension Inst on GetInterface {
_InstanceBuilderFactory<S>? dep;
if (_singl.containsKey(key)) {
final _dep = _singl[key];
if (_dep == null || !_dep.isDirty) {
final newDep = _singl[key];
if (newDep == null || !newDep.isDirty) {
return;
} else {
dep = _dep as _InstanceBuilderFactory<S>;
dep = newDep as _InstanceBuilderFactory<S>;
}
}
_singl[key] = _InstanceBuilderFactory<S>(
... ...
... ... @@ -44,7 +44,7 @@ class GetModalBottomSheetRoute<T> extends PopupRoute<T> {
final bool removeTop;
@override
Duration get transitionDuration => Duration(milliseconds: 700);
Duration get transitionDuration => const Duration(milliseconds: 700);
@override
bool get barrierDismissible => isDismissible;
... ... @@ -66,12 +66,11 @@ class GetModalBottomSheetRoute<T> extends PopupRoute<T> {
@override
Animation<double> createAnimation() {
if (curve != null) {
return CurvedAnimation(
curve: curve!, parent: _animationController!.view);
return CurvedAnimation(curve: curve!, parent: _animationController!.view);
}
return _animationController!.view;
}
@override
AnimationController createAnimationController() {
assert(_animationController == null);
... ...
... ... @@ -51,9 +51,9 @@ class GetDialogRoute<T> extends PopupRoute<T> {
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return Semantics(
child: widget(context, animation, secondaryAnimation),
scopesRoute: true,
explicitChildNodes: true,
child: widget(context, animation, secondaryAnimation),
);
}
... ...
... ... @@ -187,7 +187,7 @@ extension ExtensionDialog on GetInterface {
actions.add(TextButton(
style: TextButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
shape: RoundedRectangleBorder(
side: BorderSide(
color: buttonColor ?? theme.colorScheme.secondary,
... ... @@ -230,8 +230,8 @@ extension ExtensionDialog on GetInterface {
}
Widget baseAlertDialog = AlertDialog(
titlePadding: titlePadding ?? EdgeInsets.all(8),
contentPadding: contentPadding ?? EdgeInsets.all(8),
titlePadding: titlePadding ?? const EdgeInsets.all(8),
contentPadding: contentPadding ?? const EdgeInsets.all(8),
backgroundColor: backgroundColor ?? theme.dialogBackgroundColor,
shape: RoundedRectangleBorder(
... ... @@ -244,7 +244,7 @@ extension ExtensionDialog on GetInterface {
content ??
Text(middleText,
textAlign: TextAlign.center, style: middleTextStyle),
SizedBox(height: 16),
const SizedBox(height: 16),
ButtonTheme(
minWidth: 78.0,
height: 34.0,
... ... @@ -395,6 +395,7 @@ extension ExtensionSnackbar on GetInterface {
Gradient? backgroundGradient,
TextButton? mainButton,
OnTap? onTap,
OnHover? onHover,
bool? isDismissible,
bool? showProgressIndicator,
DismissDirection? dismissDirection,
... ... @@ -433,14 +434,14 @@ extension ExtensionSnackbar on GetInterface {
),
snackPosition: snackPosition ?? SnackPosition.top,
borderRadius: borderRadius ?? 15,
margin: margin ?? EdgeInsets.symmetric(horizontal: 10),
margin: margin ?? const EdgeInsets.symmetric(horizontal: 10),
duration: duration,
barBlur: barBlur ?? 7.0,
backgroundColor: backgroundColor ?? Colors.grey.withOpacity(0.2),
icon: icon,
shouldIconPulse: shouldIconPulse ?? true,
maxWidth: maxWidth,
padding: padding ?? EdgeInsets.all(16),
padding: padding ?? const EdgeInsets.all(16),
borderColor: borderColor,
borderWidth: borderWidth,
leftBarIndicatorColor: leftBarIndicatorColor,
... ... @@ -448,6 +449,7 @@ extension ExtensionSnackbar on GetInterface {
backgroundGradient: backgroundGradient,
mainButton: mainButton,
onTap: onTap,
onHover: onHover,
isDismissible: isDismissible ?? true,
dismissDirection: dismissDirection,
showProgressIndicator: showProgressIndicator ?? false,
... ... @@ -457,7 +459,7 @@ extension ExtensionSnackbar on GetInterface {
snackStyle: snackStyle ?? SnackStyle.floating,
forwardAnimationCurve: forwardAnimationCurve ?? Curves.easeOutCirc,
reverseAnimationCurve: reverseAnimationCurve ?? Curves.easeOutCirc,
animationDuration: animationDuration ?? Duration(seconds: 1),
animationDuration: animationDuration ?? const Duration(seconds: 1),
overlayBlur: overlayBlur ?? 0.0,
overlayColor: overlayColor ?? Colors.transparent,
userInputForm: userInputForm);
... ... @@ -1082,14 +1084,14 @@ extension GetNavigationExt on GetInterface {
}
GetDelegate searchDelegate(dynamic k) {
GetDelegate _key;
GetDelegate key;
if (k == null) {
_key = Get.rootController.rootDelegate;
key = Get.rootController.rootDelegate;
} else {
if (!keys.containsKey(k)) {
throw 'Route id ($k) not found';
}
_key = keys[k]!;
key = keys[k]!;
}
// if (_key.listenersLength == 0 && !testMode) {
... ... @@ -1102,7 +1104,7 @@ extension GetNavigationExt on GetInterface {
// """;
// }
return _key;
return key;
}
/// give current arguments
... ... @@ -1156,11 +1158,11 @@ extension GetNavigationExt on GetInterface {
/// give access to Theme.of(context)
ThemeData get theme {
var _theme = ThemeData.fallback();
var theme = ThemeData.fallback();
if (context != null) {
_theme = Theme.of(context!);
theme = Theme.of(context!);
}
return _theme;
return theme;
}
/// The current null safe [WidgetsBinding]
... ... @@ -1283,8 +1285,8 @@ extension OverlayExt on GetInterface {
});
final overlayEntryLoader = OverlayEntry(builder: (context) {
return loadingWidget ??
Center(
child: Container(
const Center(
child: SizedBox(
height: 90,
width: 90,
child: Text('Loading...'),
... ...
... ... @@ -59,13 +59,14 @@ class GetCupertinoApp extends StatelessWidget {
final RouteInformationProvider? routeInformationProvider;
final RouteInformationParser<Object>? routeInformationParser;
final RouterDelegate<Object>? routerDelegate;
final RouterConfig<Object>? routerConfig;
final BackButtonDispatcher? backButtonDispatcher;
final CupertinoThemeData? theme;
final bool useInheritedMediaQuery;
final List<Bind> binds;
final ScrollBehavior? scrollBehavior;
GetCupertinoApp({
const GetCupertinoApp({
Key? key,
this.theme,
this.navigatorKey,
... ... @@ -123,25 +124,16 @@ class GetCupertinoApp extends StatelessWidget {
backButtonDispatcher = null,
routeInformationParser = null,
routerDelegate = null,
routerConfig = null,
super(key: key);
static String _cleanRouteName(String name) {
name = name.replaceAll('() => ', '');
/// uncommonent for URL styling.
// name = name.paramCase!;
if (!name.startsWith('/')) {
name = '/$name';
}
return Uri.tryParse(name)?.toString() ?? name;
}
GetCupertinoApp.router({
const GetCupertinoApp.router({
Key? key,
this.theme,
this.routeInformationProvider,
this.routeInformationParser,
this.routerDelegate,
this.routerConfig,
this.backButtonDispatcher,
this.builder,
this.title = '',
... ... @@ -233,6 +225,7 @@ class GetCupertinoApp extends StatelessWidget {
routeInformationParser: controller.config.routeInformationParser,
backButtonDispatcher: backButtonDispatcher,
routeInformationProvider: routeInformationProvider,
routerConfig: routerConfig,
key: controller.config.unikey,
builder: (context, child) => Directionality(
textDirection: textDirection ??
... ... @@ -240,8 +233,8 @@ class GetCupertinoApp extends StatelessWidget {
? TextDirection.rtl
: TextDirection.ltr),
child: builder == null
? (child ?? Material())
: builder!(context, child ?? Material()),
? (child ?? const Material())
: builder!(context, child ?? const Material()),
),
title: title,
onGenerateTitle: onGenerateTitle,
... ...
... ... @@ -63,6 +63,7 @@ class GetMaterialApp extends StatelessWidget {
final RouteInformationProvider? routeInformationProvider;
final RouteInformationParser<Object>? routeInformationParser;
final RouterDelegate<Object>? routerDelegate;
final RouterConfig<Object>? routerConfig;
final BackButtonDispatcher? backButtonDispatcher;
final bool useInheritedMediaQuery;
... ... @@ -127,14 +128,16 @@ class GetMaterialApp extends StatelessWidget {
backButtonDispatcher = null,
routeInformationParser = null,
routerDelegate = null,
routerConfig = null,
super(key: key);
GetMaterialApp.router({
const GetMaterialApp.router({
Key? key,
this.routeInformationProvider,
this.scaffoldMessengerKey,
this.routeInformationParser,
this.routerDelegate,
this.routerConfig,
this.backButtonDispatcher,
this.builder,
this.title = '',
... ... @@ -240,12 +243,12 @@ class GetMaterialApp extends StatelessWidget {
// ],
child: Builder(builder: (context) {
final controller = GetRoot.of(context);
print('ROUTERRRR ${controller.config.routerDelegate}');
return MaterialApp.router(
routerDelegate: controller.config.routerDelegate,
routeInformationParser: controller.config.routeInformationParser,
backButtonDispatcher: backButtonDispatcher,
routeInformationProvider: routeInformationProvider,
routerConfig: routerConfig,
key: controller.config.unikey,
builder: (context, child) => Directionality(
textDirection: textDirection ??
... ... @@ -253,8 +256,8 @@ class GetMaterialApp extends StatelessWidget {
? TextDirection.rtl
: TextDirection.ltr),
child: builder == null
? (child ?? Material())
: builder!(context, child ?? Material()),
? (child ?? const Material())
: builder!(context, child ?? const Material()),
),
title: title,
onGenerateTitle: onGenerateTitle,
... ...
... ... @@ -276,7 +276,7 @@ class ConfigData {
}
class GetRoot extends StatefulWidget {
GetRoot({
const GetRoot({
Key? key,
required this.config,
required this.child,
... ... @@ -438,7 +438,7 @@ class GetRootState extends State<GetRoot> with WidgetsBindingObserver {
}
Transition? getThemeTransition() {
final platform = Get.theme.platform;
final platform = context.theme.platform;
final matchingTransition =
Get.theme.pageTransitionsTheme.builders[platform];
switch (matchingTransition) {
... ... @@ -489,7 +489,10 @@ class GetRootState extends State<GetRoot> with WidgetsBindingObserver {
}
void update() {
setState(() {});
context.visitAncestorElements((element) {
element.markNeedsBuild();
return false;
});
}
GlobalKey<NavigatorState> get key => rootDelegate.navigatorKey;
... ...
... ... @@ -132,15 +132,15 @@ class GetPageRoute<T> extends PageRoute<T>
final dep = item.dependencies();
if (dep is List<Bind>) {
_child = Binds(
child: middlewareRunner.runOnPageBuilt(pageToBuild()),
binds: dep,
child: middlewareRunner.runOnPageBuilt(pageToBuild()),
);
}
}
} else if (bindingsToBind is List<Bind>) {
_child = Binds(
child: middlewareRunner.runOnPageBuilt(pageToBuild()),
binds: bindingsToBind,
child: middlewareRunner.runOnPageBuilt(pageToBuild()),
);
}
}
... ...
... ... @@ -89,7 +89,7 @@ class SlideDownTransition {
Widget child) {
return SlideTransition(
position: Tween<Offset>(
begin: Offset(0.0, 1.0),
begin: const Offset(0.0, 1.0),
end: Offset.zero,
).animate(animation),
child: child,
... ... @@ -107,7 +107,7 @@ class SlideLeftTransition {
Widget child) {
return SlideTransition(
position: Tween<Offset>(
begin: Offset(-1.0, 0.0),
begin: const Offset(-1.0, 0.0),
end: Offset.zero,
).animate(animation),
child: child,
... ... @@ -125,7 +125,7 @@ class SlideRightTransition {
Widget child) {
return SlideTransition(
position: Tween<Offset>(
begin: Offset(1.0, 0.0),
begin: const Offset(1.0, 0.0),
end: Offset.zero,
).animate(animation),
child: child,
... ... @@ -143,7 +143,7 @@ class SlideTopTransition {
Widget child) {
return SlideTransition(
position: Tween<Offset>(
begin: Offset(0.0, -1.0),
begin: const Offset(0.0, -1.0),
end: Offset.zero,
).animate(animation),
child: child,
... ...
... ... @@ -48,7 +48,7 @@ class GetNavigator extends Navigator {
);
GetNavigator({
GlobalKey<NavigatorState>? key,
Key? key,
bool Function(Route<dynamic>, dynamic)? onPopPage,
required List<GetPage> pages,
List<NavigatorObserver>? observers,
... ...
... ... @@ -164,19 +164,19 @@ class GetPage<T> extends Page<T> {
@override
Route<T> createRoute(BuildContext context) {
// return GetPageRoute<T>(settings: this, page: page);
final _page = PageRedirect(
final page = PageRedirect(
route: this,
settings: this,
unknownRoute: unknownRoute,
).getPageToRoute<T>(this, unknownRoute, context);
return _page;
return page;
}
static PathDecoded _nameToRegex(String path) {
var keys = <String?>[];
String _replace(Match pattern) {
String recursiveReplace(Match pattern) {
var buffer = StringBuffer('(?:');
if (pattern[1] != null) buffer.write('.');
... ... @@ -188,7 +188,7 @@ class GetPage<T> extends Page<T> {
}
var stringPath = '$path/?'
.replaceAllMapped(RegExp(r'(\.)?:(\w+)(\?)?'), _replace)
.replaceAllMapped(RegExp(r'(\.)?:(\w+)(\?)?'), recursiveReplace)
.replaceAll('//', '/');
return PathDecoded(RegExp('^$stringPath\$'), keys);
... ...
... ... @@ -93,7 +93,7 @@ class GetDelegate extends RouterDelegate<RouteDecoder>
}) : navigatorKey = navigatorKey ?? GlobalKey<NavigatorState>(),
notFoundRoute = notFoundRoute ??= GetPage(
name: '/404',
page: () => Scaffold(
page: () => const Scaffold(
body: Center(child: Text('Route not found')),
),
) {
... ...
... ... @@ -380,8 +380,8 @@ Cannot read the previousTitle for a route that has not yet been installed''',
? CurvedAnimation(parent: animation, curve: finalCurve)
: animation,
secondaryRouteAnimation: secondaryAnimation,
child: child,
linearTransition: linearTransition,
child: child,
);
} else {
if (route.customTransition != null) {
... ... @@ -636,7 +636,7 @@ Cannot read the previousTitle for a route that has not yet been installed''',
));
case Transition.fade:
return FadeUpwardsPageTransitionsBuilder().buildTransitions(
return const FadeUpwardsPageTransitionsBuilder().buildTransitions(
route,
context,
animation,
... ... @@ -656,7 +656,7 @@ Cannot read the previousTitle for a route that has not yet been installed''',
));
case Transition.topLevel:
return ZoomPageTransitionsBuilder().buildTransitions(
return const ZoomPageTransitionsBuilder().buildTransitions(
route,
context,
animation,
... ... @@ -676,7 +676,7 @@ Cannot read the previousTitle for a route that has not yet been installed''',
));
case Transition.native:
return PageTransitionsTheme().buildTransitions(
return const PageTransitionsTheme().buildTransitions(
route,
context,
iosAnimation,
... ...
... ... @@ -57,17 +57,17 @@ class Dependencies {
}
abstract class Module extends StatefulWidget {
Module({Key? key}) : super(key: key);
const Module({Key? key}) : super(key: key);
Widget view(BuildContext context);
void dependencies(Dependencies i);
@override
_ModuleState createState() => _ModuleState();
ModuleState createState() => ModuleState();
}
class _ModuleState extends State<Module> {
class ModuleState extends State<Module> {
@override
void initState() {
RouterReportManager.instance.reportCurrentRoute(this);
... ...
... ... @@ -57,10 +57,10 @@ class RouteDecoder {
}
void replaceArguments(Object? arguments) {
final _route = route;
if (_route != null) {
final index = currentTreeBranch.indexOf(_route);
currentTreeBranch[index] = _route.copyWith(arguments: arguments);
final newRoute = route;
if (newRoute != null) {
final index = currentTreeBranch.indexOf(newRoute);
currentTreeBranch[index] = newRoute.copyWith(arguments: arguments);
}
}
... ...
... ... @@ -130,8 +130,8 @@ class MiddlewareRunner {
final List<GetMiddleware>? _middlewares;
List<GetMiddleware> _getMiddlewares() {
final _m = _middlewares ?? <GetMiddleware>[];
return List.of(_m)
final newMiddleware = _middlewares ?? <GetMiddleware>[];
return List.of(newMiddleware)
..sort(
(a, b) => (a.priority ?? 0).compareTo(b.priority ?? 0),
);
... ... @@ -198,34 +198,33 @@ class PageRedirect {
GetPageRoute<T> getPageToRoute<T>(
GetPage rou, GetPage? unk, BuildContext context) {
while (needRecheck(context)) {}
final _r = (isUnknown ? unk : rou)!;
final r = (isUnknown ? unk : rou)!;
return GetPageRoute<T>(
page: _r.page,
parameter: _r.parameters,
alignment: _r.alignment,
title: _r.title,
maintainState: _r.maintainState,
routeName: _r.name,
settings: _r,
curve: _r.curve,
showCupertinoParallax: _r.showCupertinoParallax,
gestureWidth: _r.gestureWidth,
opaque: _r.opaque,
customTransition: _r.customTransition,
bindings: _r.bindings,
binding: _r.binding,
binds: _r.binds,
transitionDuration:
_r.transitionDuration ?? Get.defaultTransitionDuration,
page: r.page,
parameter: r.parameters,
alignment: r.alignment,
title: r.title,
maintainState: r.maintainState,
routeName: r.name,
settings: r,
curve: r.curve,
showCupertinoParallax: r.showCupertinoParallax,
gestureWidth: r.gestureWidth,
opaque: r.opaque,
customTransition: r.customTransition,
bindings: r.bindings,
binding: r.binding,
binds: r.binds,
transitionDuration: r.transitionDuration ?? Get.defaultTransitionDuration,
reverseTransitionDuration:
_r.reverseTransitionDuration ?? Get.defaultTransitionDuration,
r.reverseTransitionDuration ?? Get.defaultTransitionDuration,
// performIncomeAnimation: _r.performIncomeAnimation,
// performOutGoingAnimation: _r.performOutGoingAnimation,
transition: _r.transition,
popGesture: _r.popGesture,
fullscreenDialog: _r.fullscreenDialog,
middlewares: _r.middlewares,
transition: r.transition,
popGesture: r.popGesture,
fullscreenDialog: r.fullscreenDialog,
middlewares: r.middlewares,
);
}
... ...
... ... @@ -4,14 +4,14 @@ import '../router_report.dart';
import 'default_route.dart';
class RouteReport extends StatefulWidget {
RouteReport({Key? key, required this.builder}) : super(key: key);
const RouteReport({Key? key, required this.builder}) : super(key: key);
final WidgetBuilder builder;
@override
_RouteReportState createState() => _RouteReportState();
RouteReportState createState() => RouteReportState();
}
class _RouteReportState extends State<RouteReport> with RouteReportMixin {
class RouteReportState extends State<RouteReport> with RouteReportMixin {
@override
void initState() {
RouterReportManager.instance.reportCurrentRoute(this);
... ...
... ... @@ -9,12 +9,13 @@ class RouterOutlet<TDelegate extends RouterDelegate<T>, T extends Object>
//keys
RouterOutlet.builder({
super.key,
TDelegate? delegate,
required this.builder,
}) : routerDelegate = delegate ?? Get.delegate<TDelegate, T>()!,
super();
}) : routerDelegate = delegate ?? Get.delegate<TDelegate, T>()!;
RouterOutlet({
Key? key,
TDelegate? delegate,
required Iterable<GetPage> Function(T currentNavStack) pickPages,
required Widget Function(
... ... @@ -24,6 +25,7 @@ class RouterOutlet<TDelegate extends RouterDelegate<T>, T extends Object>
)
pageBuilder,
}) : this.builder(
key: key,
builder: (context) {
final currentConfig = context.delegate.currentConfiguration as T?;
final rDelegate = context.delegate as TDelegate;
... ... @@ -37,11 +39,11 @@ class RouterOutlet<TDelegate extends RouterDelegate<T>, T extends Object>
delegate: delegate,
);
@override
_RouterOutletState<TDelegate, T> createState() =>
_RouterOutletState<TDelegate, T>();
RouterOutletState<TDelegate, T> createState() =>
RouterOutletState<TDelegate, T>();
}
class _RouterOutletState<TDelegate extends RouterDelegate<T>, T extends Object>
class RouterOutletState<TDelegate extends RouterDelegate<T>, T extends Object>
extends State<RouterOutlet<TDelegate, T>> {
RouterDelegate? delegate;
late ChildBackButtonDispatcher _backButtonDispatcher;
... ... @@ -80,7 +82,7 @@ class _RouterOutletState<TDelegate extends RouterDelegate<T>, T extends Object>
}
}
// class _RouterOutletState<TDelegate extends RouterDelegate<T>,
// class RouterOutletState<TDelegate extends RouterDelegate<T>,
//T extends Object>
// extends State<RouterOutlet<TDelegate, T>> {
// TDelegate get delegate => context.delegate as TDelegate;
... ... @@ -152,11 +154,11 @@ class GetRouterOutlet extends RouterOutlet<GetDelegate, RouteDecoder> {
delegate: delegate,
);
GetRouterOutlet.pickPages({
super.key,
Widget Function(GetDelegate delegate)? emptyWidget,
GetPage Function(GetDelegate delegate)? emptyPage,
required Iterable<GetPage> Function(RouteDecoder currentNavStack) pickPages,
bool Function(Route<dynamic>, dynamic)? onPopPage,
GlobalKey<NavigatorState>? key,
GetDelegate? delegate,
}) : super(
pageBuilder: (context, rDelegate, pages) {
... ... @@ -179,13 +181,14 @@ class GetRouterOutlet extends RouterOutlet<GetDelegate, RouteDecoder> {
key: key,
);
}
return (emptyWidget?.call(rDelegate) ?? SizedBox.shrink());
return (emptyWidget?.call(rDelegate) ?? const SizedBox.shrink());
},
pickPages: pickPages,
delegate: delegate ?? Get.rootController.rootDelegate,
);
GetRouterOutlet.builder({
super.key,
required Widget Function(
BuildContext context,
)
... ...
... ... @@ -7,88 +7,10 @@ import '../../../get_core/get_core.dart';
import '../../get_navigation.dart';
typedef OnTap = void Function(GetSnackBar snack);
typedef OnHover = void Function(GetSnackBar snack, SnackHoverState snackHoverState);
typedef SnackbarStatusCallback = void Function(SnackbarStatus? status);
@Deprecated('use GetSnackBar')
class GetBar extends GetSnackBar {
GetBar({
Key? key,
String? title,
String? message,
Widget? titleText,
Widget? messageText,
Widget? icon,
bool shouldIconPulse = true,
double? maxWidth,
EdgeInsets margin = const EdgeInsets.all(0.0),
EdgeInsets padding = const EdgeInsets.all(16),
double borderRadius = 0.0,
Color? borderColor,
double borderWidth = 1.0,
Color backgroundColor = const Color(0xFF303030),
Color? leftBarIndicatorColor,
List<BoxShadow>? boxShadows,
Gradient? backgroundGradient,
Widget? mainButton,
OnTap? onTap,
Duration? duration,
bool isDismissible = true,
DismissDirection? dismissDirection,
bool showProgressIndicator = false,
AnimationController? progressIndicatorController,
Color? progressIndicatorBackgroundColor,
Animation<Color>? progressIndicatorValueColor,
SnackPosition snackPosition = SnackPosition.bottom,
SnackStyle snackStyle = SnackStyle.floating,
Curve forwardAnimationCurve = Curves.easeOutCirc,
Curve reverseAnimationCurve = Curves.easeOutCirc,
Duration animationDuration = const Duration(seconds: 1),
double barBlur = 0.0,
double overlayBlur = 0.0,
Color overlayColor = Colors.transparent,
Form? userInputForm,
SnackbarStatusCallback? snackbarStatus,
}) : super(
key: key,
title: title,
message: message,
titleText: titleText,
messageText: messageText,
icon: icon,
shouldIconPulse: shouldIconPulse,
maxWidth: maxWidth,
margin: margin,
padding: padding,
borderRadius: borderRadius,
borderColor: borderColor,
borderWidth: borderWidth,
backgroundColor: backgroundColor,
leftBarIndicatorColor: leftBarIndicatorColor,
boxShadows: boxShadows,
backgroundGradient: backgroundGradient,
mainButton: mainButton,
onTap: onTap,
duration: duration,
isDismissible: isDismissible,
dismissDirection: dismissDirection,
showProgressIndicator: showProgressIndicator,
progressIndicatorController: progressIndicatorController,
progressIndicatorBackgroundColor: progressIndicatorBackgroundColor,
progressIndicatorValueColor: progressIndicatorValueColor,
snackPosition: snackPosition,
snackStyle: snackStyle,
forwardAnimationCurve: forwardAnimationCurve,
reverseAnimationCurve: reverseAnimationCurve,
animationDuration: animationDuration,
barBlur: barBlur,
overlayBlur: overlayBlur,
overlayColor: overlayColor,
userInputForm: userInputForm,
snackbarStatus: snackbarStatus,
);
}
class GetSnackBar extends StatefulWidget {
/// A callback for you to listen to the different Snack status
final SnackbarStatusCallback? snackbarStatus;
... ... @@ -150,6 +72,9 @@ class GetSnackBar extends StatefulWidget {
/// An alternative to [mainButton]
final OnTap? onTap;
/// A callback that registers the user's hover anywhere over the Snackbar.
final OnHover? onHover;
/// How long until Snack will hide itself (be dismissed).
/// To make it indefinite, leave it null.
final Duration? duration;
... ... @@ -259,6 +184,7 @@ class GetSnackBar extends StatefulWidget {
this.backgroundGradient,
this.mainButton,
this.onTap,
this.onHover,
this.duration,
this.isDismissible = true,
this.dismissDirection,
... ... @@ -293,11 +219,11 @@ class GetSnackBarState extends State<GetSnackBar>
AnimationController? _fadeController;
late Animation<double> _fadeAnimation;
final Widget _emptyWidget = SizedBox(width: 0.0, height: 0.0);
final Widget _emptyWidget = const SizedBox(width: 0.0, height: 0.0);
final double _initialOpacity = 1.0;
final double _finalOpacity = 0.4;
final Duration _pulseAnimationDuration = Duration(seconds: 1);
final Duration _pulseAnimationDuration = const Duration(seconds: 1);
late bool _isTitlePresent;
late double _messageTopMargin;
... ... @@ -513,9 +439,9 @@ You need to either use message[String], or messageText[Widget] or define a userI
padding: const EdgeInsets.only(
left: 8.0, right: 8.0, bottom: 8.0, top: 16.0),
child: FocusScope(
child: widget.userInputForm!,
node: _focusNode,
autofocus: true,
child: widget.userInputForm!,
),
),
);
... ... @@ -581,7 +507,7 @@ You need to either use message[String], or messageText[Widget] or define a userI
child: widget.titleText ??
Text(
widget.title ?? "",
style: TextStyle(
style: const TextStyle(
fontSize: 16.0,
color: Colors.white,
fontWeight: FontWeight.bold,
... ... @@ -600,8 +526,8 @@ You need to either use message[String], or messageText[Widget] or define a userI
child: widget.messageText ??
Text(
widget.message ?? "",
style:
TextStyle(fontSize: 14.0, color: Colors.white),
style: const TextStyle(
fontSize: 14.0, color: Colors.white),
),
),
],
... ... @@ -657,3 +583,6 @@ enum SnackPosition { top, bottom }
/// Indicates if snack will be attached to the edge of the screen or not
enum SnackStyle { floating, grounded }
/// Indicates if the mouse entered or exited
enum SnackHoverState { entered, exited }
\ No newline at end of file
... ...
... ... @@ -220,15 +220,15 @@ class SnackbarController {
],
OverlayEntry(
builder: (context) => Semantics(
focused: false,
container: true,
explicitChildNodes: true,
child: AlignTransition(
alignment: _animation,
child: snackbar.isDismissible
? _getDismissibleSnack(child)
: _getSnackbarContainer(child),
),
focused: false,
container: true,
explicitChildNodes: true,
),
maintainState: false,
opaque: false,
... ... @@ -238,11 +238,15 @@ class SnackbarController {
Widget _getBodyWidget() {
return Builder(builder: (_) {
return GestureDetector(
child: snackbar,
onTap: snackbar.onTap != null
? () => snackbar.onTap?.call(snackbar)
: null,
return MouseRegion(
onEnter: (_) => snackbar.onHover?.call(snackbar, SnackHoverState.entered),
onExit: (_) => snackbar.onHover?.call(snackbar, SnackHoverState.exited),
child: GestureDetector(
child: snackbar,
onTap: snackbar.onTap != null
? () => snackbar.onTap?.call(snackbar)
: null,
),
);
});
}
... ...
... ... @@ -48,7 +48,7 @@ class RxList<E> extends GetListenable<List<E>>
@override
RxList<E> operator +(Iterable<E> val) {
addAll(val);
refresh();
// refresh();
return this;
}
... ... @@ -113,11 +113,11 @@ class RxList<E> extends GetListenable<List<E>>
@override
Iterable<E> get reversed => value.reversed;
@override
set value(List<E> val) {
value = val;
refresh();
}
// @override
// set value(List<E> val) {
// value = val;
// refresh();
// }
@override
Iterable<E> where(bool Function(E) test) {
... ...
... ... @@ -8,7 +8,7 @@ class RxSet<E> extends GetListenable<Set<E>>
/// inside the List,
RxSet<E> operator +(Set<E> val) {
addAll(val);
refresh();
//refresh();
return this;
}
... ... @@ -25,13 +25,13 @@ class RxSet<E> extends GetListenable<Set<E>>
// // return _value;
// }
@override
@protected
set value(Set<E> val) {
if (value == val) return;
value = val;
refresh();
}
// @override
// @protected
// set value(Set<E> val) {
// if (value == val) return;
// value = val;
// refresh();
// }
@override
bool add(E value) {
... ...
... ... @@ -226,11 +226,11 @@ Worker debounce<T>(
void Function()? onDone,
bool? cancelOnError,
}) {
final _debouncer =
final newDebouncer =
Debouncer(delay: time ?? const Duration(milliseconds: 800));
StreamSubscription sub = listener.listen(
(event) {
_debouncer(() {
newDebouncer(() {
callback(event);
});
},
... ...
... ... @@ -22,6 +22,7 @@ class GetX<T extends GetLifeCycleMixin> extends StatefulWidget {
final String? tag;
const GetX({
super.key,
this.tag,
required this.builder,
this.global = true,
... ...
... ... @@ -32,7 +32,7 @@ mixin StateMixin<T> on ListNotifier {
void _fillInitialStatus() {
_status = (_value == null || _value!._isEmpty())
? GetStatus<T>.loading()
: GetStatus<T>.success(_value!);
: GetStatus<T>.success(_value as T);
}
GetStatus<T> get status {
... ... @@ -71,7 +71,7 @@ mixin StateMixin<T> on ListNotifier {
}
}
void futurize(Future<T> Function() body,
void futurize(Future<T> Function() body,
{T? initialData, String? errorMessage, bool useEmpty = true}) {
final compute = body;
_value ??= initialData;
... ... @@ -231,12 +231,12 @@ extension StateExt<T> on StateMixin<T> {
: Center(child: Text('A error occurred: ${status.errorMessage}'));
} else if (status.isEmpty) {
return onEmpty ??
SizedBox.shrink(); // Also can be widget(null); but is risky
const SizedBox.shrink(); // Also can be widget(null); but is risky
} else if (status.isSuccess) {
return widget(value);
} else if (status.isCustom) {
return onCustom?.call(_) ??
SizedBox.shrink(); // Also can be widget(null); but is risky
const SizedBox.shrink(); // Also can be widget(null); but is risky
}
return widget(value);
});
... ...
... ... @@ -24,7 +24,7 @@ abstract class ObxWidget extends ObxStatelessWidget {
class Obx extends ObxWidget {
final WidgetCallback builder;
const Obx(this.builder);
const Obx(this.builder, {super.key});
@override
Widget build(BuildContext context) {
... ...
... ... @@ -482,7 +482,7 @@ class BindElement<T> extends InheritedElement {
/// setState "link" from the Controller.
void _subscribeToController() {
if (widget.filter != null) {
_filter = widget.filter!(_controller!);
_filter = widget.filter!(_controller as T);
}
final filter = _filter != null ? _filterUpdate : getUpdate;
final localController = _controller;
... ... @@ -510,7 +510,7 @@ class BindElement<T> extends InheritedElement {
}
void _filterUpdate() {
var newFilter = widget.filter!(_controller!);
var newFilter = widget.filter!(_controller as T);
if (newFilter != _filter) {
_filter = newFilter;
getUpdate();
... ...
... ... @@ -176,11 +176,11 @@ class Notifier {
_notifyData?.disposers.add(listener);
}
void read(ListNotifierSingleMixin _updaters) {
void read(ListNotifierSingleMixin updaters) {
final listener = _notifyData?.updater;
if (listener != null && !_updaters.containsListener(listener)) {
_updaters.addListener(listener);
add(() => _updaters.removeListener(listener));
if (listener != null && !updaters.containsListener(listener)) {
updaters.addListener(listener);
add(() => updaters.removeListener(listener));
}
}
... ... @@ -188,7 +188,7 @@ class Notifier {
_notifyData = data;
final result = builder();
if (data.disposers.isEmpty && data.throwException) {
throw ObxError();
throw const ObxError();
}
_notifyData = null;
return result;
... ...
... ... @@ -38,12 +38,16 @@ class ValueBuilder<T> extends StatefulWidget {
}) : super(key: key);
@override
_ValueBuilderState<T> createState() => _ValueBuilderState<T>(initialValue);
ValueBuilderState<T> createState() => ValueBuilderState<T>();
}
class _ValueBuilderState<T> extends State<ValueBuilder<T>> {
T value;
_ValueBuilderState(this.value);
class ValueBuilderState<T> extends State<ValueBuilder<T>> {
late T value;
@override
void initState() {
value = widget.initialValue;
super.initState();
}
@override
Widget build(BuildContext context) => widget.builder(value, updater);
... ...
import 'dart:math';
extension Precision on double {
extension DoubleExt on double {
double toPrecision(int fractionDigits) {
var mod = pow(10, fractionDigits.toDouble()).toDouble();
return ((this * mod).round().toDouble() / mod);
}
Duration get milliseconds => Duration(microseconds: (this * 1000).round());
Duration get ms => milliseconds;
Duration get seconds => Duration(milliseconds: (this * 1000).round());
Duration get minutes =>
Duration(seconds: (this * Duration.secondsPerMinute).round());
Duration get hours =>
Duration(minutes: (this * Duration.minutesPerHour).round());
Duration get days => Duration(hours: (this * Duration.hoursPerDay).round());
}
... ...
... ... @@ -3,10 +3,6 @@ import '../get_utils/get_utils.dart';
extension GetDynamicUtils on dynamic {
bool? get isBlank => GetUtils.isBlank(this);
@Deprecated(
'isNullOrBlank is deprecated and cannot be used, use "isBlank" instead')
bool? get isNullOrBlank => GetUtils.isNullOrBlank(this);
void printError(
{String info = '', Function logFunction = GetUtils.printFunction}) =>
// ignore: unnecessary_this
... ...
... ... @@ -3,6 +3,7 @@ export 'double_extensions.dart';
export 'duration_extensions.dart';
export 'dynamic_extensions.dart';
export 'event_loop_extensions.dart';
export 'int_extensions.dart';
export 'internacionalization.dart' hide FirstWhereExt;
export 'iterable_extensions.dart';
export 'num_extensions.dart';
... ...
extension DurationExt on int {
Duration get seconds => Duration(seconds: this);
Duration get days => Duration(days: this);
Duration get hours => Duration(hours: this);
Duration get minutes => Duration(minutes: this);
Duration get milliseconds => Duration(milliseconds: this);
Duration get microseconds => Duration(microseconds: this);
Duration get ms => milliseconds;
}
... ...
... ... @@ -28,41 +28,4 @@ extension GetNumUtils on num {
Duration(milliseconds: (this * 1000).round()),
callback,
);
/// Easy way to make Durations from numbers.
///
/// Sample:
/// ```
/// print(1.seconds + 200.milliseconds);
/// print(1.hours + 30.minutes);
/// print(1.5.hours);
///```
Duration get milliseconds => Duration(microseconds: (this * 1000).round());
Duration get seconds => Duration(milliseconds: (this * 1000).round());
Duration get minutes =>
Duration(seconds: (this * Duration.secondsPerMinute).round());
Duration get hours =>
Duration(minutes: (this * Duration.minutesPerHour).round());
Duration get days => Duration(hours: (this * Duration.hoursPerDay).round());
//final _delayMaps = <Function, Future>{};
// TODO: create a proper Future and control the Timer.
// Future delay([double seconds = 0, VoidCallback callback]) async {
// final ms = (seconds * 1000).round();
// return Future.delayed(Duration(milliseconds: ms), callback);
// return _delayMaps[callback];
// }
//killDelay(VoidCallback callback) {
// if (_delayMaps.containsKey(callback)) {
// _delayMaps[callback]?.timeout(Duration.zero, onTimeout: () {
// print('callbacl eliminado!');
// });
// _delayMaps.remove(callback);
// }
//}
}
... ...
... ... @@ -500,7 +500,6 @@ class GetUtils {
/// Capitalize each word inside string
/// Example: your name => Your Name, your name => Your name
static String? capitalize(String value) {
if (isNull(value)) return null;
if (isBlank(value)!) return value;
return value.split(' ').map(capitalizeFirst).join(' ');
}
... ... @@ -508,7 +507,6 @@ class GetUtils {
/// Uppercase first letter inside string and let the others lowercase
/// Example: your name => Your name
static String? capitalizeFirst(String s) {
if (isNull(s)) return null;
if (isBlank(s)!) return s;
return s[0].toUpperCase() + s.substring(1).toLowerCase();
}
... ...
// TODO: resolve platform/desktop by JS browser agent.
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;
... ...
name: get
description: Open screens/snackbars/dialogs without context, manage states and inject dependencies easily with GetX.
version: 5.0.0-release-candidate
version: 5.0.0-release-candidate-4
homepage: https://github.com/jonataslaw/getx
environment:
... ... @@ -15,7 +15,7 @@ dependencies:
dev_dependencies:
flutter_test:
sdk: flutter
lints: ^2.1.1
flutter_lints: ^2.0.2
# For information on the generic Dart part of this file, see the
... ...
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
void main() {
group('Animation Extension', () {
Widget buildWidget() {
return Container(
width: 100,
height: 100,
color: Colors.red,
);
}
testWidgets('fadeIn() and fadeOut() can not be used sequentially',
(WidgetTester tester) async {
final widget = buildWidget();
expect(() => widget.fadeIn().fadeOut(), throwsAssertionError);
expect(() => widget.fadeOut().fadeIn(), throwsAssertionError);
expect(() => widget.fadeIn(isSequential: true).fadeOut(),
throwsAssertionError);
expect(() => widget.fadeOut(isSequential: true).fadeIn(),
throwsAssertionError);
});
testWidgets('can not use delay when isSequential is true',
(WidgetTester tester) async {
final widget = buildWidget();
expect(
() => widget.fadeIn(
isSequential: true, delay: const Duration(seconds: 1)),
throwsAssertionError);
});
testWidgets(
'fadeIn() and fadeOut() can be used together when isSequential is true',
(WidgetTester tester) async {
final widget = buildWidget();
expect(
() => widget.fadeIn(isSequential: true).fadeOut(isSequential: true),
isNot(throwsException));
expect(() => widget.fadeIn().fadeOut(isSequential: true),
isNot(throwsException));
});
testWidgets('fadeIn() returns a FadeInAnimation',
(WidgetTester tester) async {
final widget = buildWidget();
const begin = 0.0;
const end = 1.0;
final animation = widget.fadeIn();
expect(animation, isA<FadeInAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('fadeOut() returns a animation', (WidgetTester tester) async {
final widget = buildWidget();
const begin = 1.0;
const end = 0.0;
final animation = widget.fadeOut();
expect(animation, isA<FadeOutAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('rotate() returns a RotateAnimation',
(WidgetTester tester) async {
const begin = 0.9;
const end = 1.1;
final widget = buildWidget();
final animation = widget.rotate(begin: begin, end: end);
expect(animation, isA<RotateAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('scale() returns a ScaleAnimation',
(WidgetTester tester) async {
const begin = 0.9;
const end = 1.1;
final widget = buildWidget();
final animation = widget.scale(begin: begin, end: end);
expect(animation, isA<ScaleAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('slide() returns a SlideAnimation',
(WidgetTester tester) async {
const begin = 0;
const end = 1;
final widget = buildWidget();
final animation = widget.slide(offset: (_, __) => const Offset(0, 0));
expect(animation, isA<SlideAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('bounce() returns a BounceAnimation',
(WidgetTester tester) async {
const begin = 0.9;
const end = 1.1;
final widget = buildWidget();
final animation = widget.bounce(begin: begin, end: end);
expect(animation, isA<BounceAnimation>());
_testDefaultValues(
animation: animation,
widget: widget,
begin: begin,
end: end,
curve: Curves.bounceOut,
);
});
testWidgets('spin() returns a SpinAnimation', (WidgetTester tester) async {
final widget = buildWidget();
const begin = 0.0;
const end = 360;
final animation = widget.spin();
expect(animation, isA<SpinAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('size() returns a SizeAnimation', (WidgetTester tester) async {
final widget = buildWidget();
const begin = 0.9;
const end = 1.1;
final animation = widget.size(begin: begin, end: end);
expect(animation, isA<SizeAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('blur() returns a BlurAnimation', (WidgetTester tester) async {
final widget = buildWidget();
const begin = 0.9;
const end = 1.1;
final animation = widget.blur(begin: begin, end: end);
expect(animation, isA<BlurAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('flip() returns a FlipAnimation', (WidgetTester tester) async {
final widget = buildWidget();
const begin = 0.9;
const end = 1.1;
final animation = widget.flip(begin: begin, end: end);
expect(animation, isA<FlipAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
testWidgets('wave() returns a FlipAnimation', (WidgetTester tester) async {
final widget = buildWidget();
const begin = 0.9;
const end = 1.1;
final animation = widget.wave(begin: begin, end: end);
expect(animation, isA<WaveAnimation>());
_testDefaultValues(
animation: animation, widget: widget, begin: begin, end: end);
});
});
}
void _testDefaultValues<T>({
required GetAnimatedBuilder animation,
required Widget widget,
required T begin,
required T end,
Curve curve = Curves.linear,
}) {
expect(animation.tween.begin, begin);
expect(animation.tween.end, end);
if (animation.idleValue is Offset) {
expect(animation.idleValue, Offset.zero);
} else if (animation is FadeOutAnimation) {
expect(animation.idleValue, 1);
} else {
expect(animation.idleValue, 0);
}
expect(animation.delay, Duration.zero);
expect(animation.child, widget);
expect(animation.curve, curve);
}
... ...
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:get/get.dart';
class _Wrapper extends StatelessWidget {
const _Wrapper({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(body: child),
);
}
}
void main() {
testWidgets('GetAnimatedBuilder defaults', (WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: GetAnimatedBuilder<int>(
duration: const Duration(milliseconds: 500),
tween: Tween(begin: 0, end: 10),
idleValue: 0,
builder: (_, value, __) => Text(value.toString()),
delay: Duration.zero,
child: Container(),
),
),
);
// Verify that the widget starts with the idle value.
expect(find.text('0'), findsOneWidget);
// Wait for the animation to complete.
await tester.pumpAndSettle(const Duration(milliseconds: 500));
// Verify that the widget ends with the final value.
expect(find.text('10'), findsOneWidget);
});
testWidgets('GetAnimatedBuilder changes value over time', (tester) async {
await tester.pumpWidget(
_Wrapper(
child: GetAnimatedBuilder<double>(
duration: const Duration(milliseconds: 500),
tween: Tween<double>(begin: 0.0, end: 1.0),
idleValue: 0.0,
builder: (context, value, child) {
return Opacity(opacity: value);
},
delay: const Duration(milliseconds: 500),
child: Container(
width: 100,
height: 100,
color: Colors.red,
),
),
),
);
// Initial state is idleValue
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 0.0);
// Wait for the delay to finish
await tester.pump(const Duration(milliseconds: 500));
// Verify that the value changes over time
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.2, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.4, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.6, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.8, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(1.0, 0.01));
});
testWidgets('onComplete callback is called when animation finishes',
(WidgetTester tester) async {
AnimationController? controller;
var onCompleteCalled = false;
await tester.pumpWidget(
_Wrapper(
child: GetAnimatedBuilder<int>(
duration: const Duration(milliseconds: 500),
tween: Tween(begin: 0, end: 10),
idleValue: 0,
builder: (_, value, __) => Text(value.toString()),
delay: Duration.zero,
onComplete: (c) {
onCompleteCalled = true;
controller = c;
},
child: Container(),
),
),
);
expect(onCompleteCalled, isFalse);
// Wait for the animation to complete.
await tester.pumpAndSettle(const Duration(milliseconds: 500));
// Verify that the onComplete callback was called.
expect(controller, isNotNull);
expect(onCompleteCalled, isTrue);
});
testWidgets('onStart callback is called when animation starts',
(WidgetTester tester) async {
var onStartCalled = false;
await tester.pumpWidget(
_Wrapper(
child: GetAnimatedBuilder(
duration: const Duration(seconds: 1),
delay: Duration.zero,
tween: Tween<double>(begin: 0, end: 1),
idleValue: 0,
builder: (context, value, child) => Container(),
child: Container(),
onStart: (_) {
onStartCalled = true;
},
),
),
);
expect(onStartCalled, isFalse);
await tester.pump(const Duration(milliseconds: 500));
expect(onStartCalled, isTrue);
});
testWidgets('GetAnimatedBuilder delay', (WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: GetAnimatedBuilder<int>(
duration: const Duration(milliseconds: 500),
tween: Tween(begin: 0, end: 10),
idleValue: 0,
builder: (_, value, __) => Text(value.toString()),
delay: const Duration(milliseconds: 500),
child: Container(),
),
),
);
// Verify that the widget starts with the idle value.
expect(find.text('0'), findsOneWidget);
// Wait for the delay to pass.
await tester.pump(const Duration(milliseconds: 500));
// Verify that the animation has started.
expect(find.text('0'), findsOneWidget);
// Wait for the animation to complete.
await tester.pumpAndSettle(const Duration(milliseconds: 500));
// Verify that the widget ends with the final value.
expect(find.text('10'), findsOneWidget);
});
testWidgets(
'FadeInAnimation in idle should be visible, but not visible when the animation starts',
(WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: FadeInAnimation(
delay: const Duration(milliseconds: 500),
duration: const Duration(milliseconds: 500),
idleValue: 0,
child: const Text('Hello'),
),
),
);
// in idle, the opacity should be 1.0
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 1.0);
// Wait for the delay to finish
await tester.pump(const Duration(milliseconds: 500));
// When the animation starts the opacity should not be visible
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity, 0.0);
// Verify that the value changes over time
await tester.pump(const Duration(milliseconds: 100));
// The value should be updated
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.2, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.4, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.6, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(0.8, 0.01));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.widget<Opacity>(find.byType(Opacity)).opacity,
closeTo(1.0, 0.01));
});
testWidgets(
'willResetOnDispose should false when fadeOut is the last animation in a sequential animation',
(WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: const Text('Hello')
.fadeIn(
isSequential: true,
duration: const Duration(milliseconds: 500),
)
.fadeOut(
isSequential: true,
duration: const Duration(milliseconds: 500),
),
),
);
// The variable starts as false
expect(
tester
.state<GetAnimatedBuilderState>(find.byType(FadeOutAnimation))
.willResetOnDispose,
false);
// Jump to middle of next animation
await tester.pump(const Duration(milliseconds: 500));
// The value should be false
expect(
tester
.state<GetAnimatedBuilderState>(find.byType(FadeOutAnimation))
.willResetOnDispose,
false);
await tester.pumpAndSettle();
});
testWidgets(
'willResetOnDispose should true when fadeOut is not last animation in a sequential animation',
(WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: const Text('Hello')
.fadeOut(
isSequential: true,
duration: const Duration(milliseconds: 500),
)
.fadeIn(
isSequential: true,
duration: const Duration(milliseconds: 500),
),
),
);
// The variable starts as true
expect(
tester
.state<GetAnimatedBuilderState>(find.byType(FadeOutAnimation))
.willResetOnDispose,
true);
// Jump to middle of next animation
await tester.pump(const Duration(milliseconds: 500));
// The value should be true
expect(
tester
.state<GetAnimatedBuilderState>(find.byType(FadeOutAnimation))
.willResetOnDispose,
true);
await tester.pumpAndSettle();
});
testWidgets('RotateAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
RotateAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 0.0,
end: 360.0,
child: Container(),
),
);
expect(find.byType(RotateAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('ScaleAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
ScaleAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
);
expect(find.byType(ScaleAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('WaveAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
WaveAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
);
expect(find.byType(WaveAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('WobbleAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
WobbleAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
);
expect(find.byType(WobbleAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SlideAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
SlideAnimation(
offsetBuild: (p0, p1) => const Offset(1.0, 1.0),
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 0,
end: 1,
child: Container(),
),
);
expect(find.byType(SlideAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SlideInLeftAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: SlideInLeftAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
),
);
expect(find.byType(SlideInLeftAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SlideInRightAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: SlideInRightAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
),
);
expect(find.byType(SlideInRightAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SlideInUpAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: SlideInUpAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
),
);
expect(find.byType(SlideInUpAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SlideInDownAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
_Wrapper(
child: SlideInDownAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
),
);
expect(find.byType(SlideInDownAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('BounceAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
BounceAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 0.0,
end: 1.0,
child: Container(),
),
);
expect(find.byType(BounceAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SpinAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
SpinAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
child: Container(),
),
);
expect(find.byType(SpinAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('ColorAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
ColorAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: Colors.blue,
end: Colors.red,
child: Container(),
),
);
expect(find.byType(ColorAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('SizeAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
SizeAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
);
expect(find.byType(SizeAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('BlurAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
BlurAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
);
expect(find.byType(BlurAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
testWidgets('FlipAnimation', (WidgetTester tester) async {
await tester.pumpWidget(
FlipAnimation(
duration: const Duration(seconds: 1),
delay: Duration.zero,
begin: 1.0,
end: 2.0,
child: Container(),
),
);
expect(find.byType(FlipAnimation), findsOneWidget);
await tester.pumpAndSettle();
});
}
... ...
... ... @@ -6,6 +6,11 @@ import 'package:get/state_manager.dart';
int times = 30;
void printValue(String value) {
// ignore: avoid_print
print(value);
}
Future<int> valueNotifier() {
final c = Completer<int>();
final value = ValueNotifier<int>(0);
... ... @@ -15,7 +20,7 @@ Future<int> valueNotifier() {
value.addListener(() {
if (times == value.value) {
timer.stop();
print(
printValue(
"""${value.value} listeners notified | [VALUE_NOTIFIER] time: ${timer.elapsedMicroseconds}ms""");
c.complete(timer.elapsedMicroseconds);
}
... ... @@ -37,7 +42,7 @@ Future<int> getValue() {
value.addListener(() {
if (times == value.value) {
timer.stop();
print(
printValue(
"""${value.value} listeners notified | [GETX_VALUE] time: ${timer.elapsedMicroseconds}ms""");
c.complete(timer.elapsedMicroseconds);
}
... ... @@ -60,7 +65,7 @@ Future<int> stream() {
value.stream.listen((v) {
if (times == v) {
timer.stop();
print(
printValue(
"""$v listeners notified | [STREAM] time: ${timer.elapsedMicroseconds}ms""");
c.complete(timer.elapsedMicroseconds);
value.close();
... ... @@ -84,7 +89,7 @@ Future<int> stream() {
// value.listen((v) {
// if (times == v) {
// timer.stop();
// print(
// printValue(
// """$v listeners notified |
// [GET_STREAM] time: ${timer.elapsedMicroseconds}ms""");
// c.complete(timer.elapsedMicroseconds);
... ... @@ -108,7 +113,7 @@ Future<int> miniStream() {
value.listen((v) {
if (times == v) {
timer.stop();
print(
printValue(
"""$v listeners notified | [MINI_STREAM] time: ${timer.elapsedMicroseconds}ms""");
c.complete(timer.elapsedMicroseconds);
}
... ... @@ -123,49 +128,49 @@ Future<int> miniStream() {
void main() {
test('percentage test', () {
print('============================================');
print('PERCENTAGE TEST');
printValue('============================================');
printValue('PERCENTAGE TEST');
final referenceValue = 200;
final requestedValue = 100;
const referenceValue = 200;
const requestedValue = 100;
print('''
printValue('''
referenceValue is ${calculePercentage(referenceValue, requestedValue)}% more than requestedValue''');
expect(calculePercentage(referenceValue, requestedValue), 100);
});
test('run benchmarks from ValueNotifier', () async {
times = 30;
print('============================================');
print('VALUE_NOTIFIER X GETX_VALUE TEST');
print('-----------');
printValue('============================================');
printValue('VALUE_NOTIFIER X GETX_VALUE TEST');
printValue('-----------');
await getValue();
await valueNotifier();
print('-----------');
printValue('-----------');
times = 30000;
final getx = await getValue();
final dart = await valueNotifier();
print('-----------');
printValue('-----------');
print('ValueNotifier delay $dart ms to made $times requests');
print('GetValue delay $getx ms to made $times requests');
print('-----------');
print('''
printValue('ValueNotifier delay $dart ms to made $times requests');
printValue('GetValue delay $getx ms to made $times requests');
printValue('-----------');
printValue('''
GetValue is ${calculePercentage(dart, getx).round()}% faster than Default ValueNotifier with $times requests''');
});
test('run benchmarks from Streams', () async {
times = 30;
print('============================================');
print('DART STREAM X GET_STREAM X GET_MINI_STREAM TEST');
print('-----------');
printValue('============================================');
printValue('DART STREAM X GET_STREAM X GET_MINI_STREAM TEST');
printValue('-----------');
// var getx = await getStream();
var mini = await miniStream();
var dart = await stream();
print('-----------');
print('''
printValue('-----------');
printValue('''
GetStream is ${calculePercentage(dart, mini).round()}% faster than Default Stream with $times requests''');
print('-----------');
printValue('-----------');
times = 30000;
dart = await stream();
... ... @@ -176,12 +181,12 @@ GetStream is ${calculePercentage(dart, mini).round()}% faster than Default Strea
dart = await stream();
// getx = await getStream();
mini = await miniStream();
print('-----------');
print('dart_stream delay $dart ms to made $times requests');
// print('getx_stream delay $getx ms to made $times requests');
print('getx_mini_stream delay $mini ms to made $times requests');
print('-----------');
print('''
printValue('-----------');
printValue('dart_stream delay $dart ms to made $times requests');
// printValue('getx_stream delay $getx ms to made $times requests');
printValue('getx_mini_stream delay $mini ms to made $times requests');
printValue('-----------');
printValue('''
GetStream is ${calculePercentage(dart, mini).round()}% faster than Default Stream with $times requests''');
});
}
... ...
... ... @@ -101,7 +101,8 @@ void main() {
expect(Get.find<Controller>().count, 1);
Get.delete<Controller>();
expect(() => Get.find<Controller>(), throwsA(m.TypeMatcher<String>()));
expect(
() => Get.find<Controller>(), throwsA(const m.TypeMatcher<String>()));
Get.reset();
});
... ... @@ -162,7 +163,7 @@ void main() {
// Get.put(DisposableController());
expect(Get.delete<DisposableController>(), true);
expect(() => Get.find<DisposableController>(),
throwsA(m.TypeMatcher<String>()));
throwsA(const m.TypeMatcher<String>()));
});
test('Get.put test after delete with disposable controller and init check',
... ... @@ -192,7 +193,7 @@ void main() {
});
test('tagged temporary', () async {
final tag = 'tag';
const tag = 'tag';
Get.put(DisposableController(), tag: tag);
Get.replace<DisposableController>(Controller(), tag: tag);
final instance = Get.find<DisposableController>(tag: tag);
... ... @@ -201,7 +202,7 @@ void main() {
});
test('tagged permanent', () async {
final tag = 'tag';
const tag = 'tag';
Get.put(DisposableController(), permanent: true, tag: tag);
Get.replace<DisposableController>(Controller(), tag: tag);
final instance = Get.find<DisposableController>(tag: tag);
... ... @@ -210,7 +211,7 @@ void main() {
});
test('a generic parent type', () async {
final tag = 'tag';
const tag = 'tag';
Get.put<MyController>(DisposableController(), permanent: true, tag: tag);
Get.replace<MyController>(Controller(), tag: tag);
final instance = Get.find<MyController>(tag: tag);
... ...
... ... @@ -27,10 +27,10 @@
import 'package:flutter_test/flutter_test.dart';
class _FunctionMatcher<T> extends CustomMatcher {
class FunctionMatcher<T> extends CustomMatcher {
final Object Function(T value) _feature;
_FunctionMatcher(String name, this._feature, matcher)
FunctionMatcher(String name, this._feature, matcher)
: super('`$name`:', '`$name`', matcher);
@override
... ... @@ -39,15 +39,15 @@ class _FunctionMatcher<T> extends CustomMatcher {
class HavingMatcher<T> implements TypeMatcher<T> {
final TypeMatcher<T> _parent;
final List<_FunctionMatcher<T>> _functionMatchers;
final List<FunctionMatcher<T>> _functionMatchers;
HavingMatcher(TypeMatcher<T> parent, String description,
Object Function(T) feature, dynamic matcher,
[Iterable<_FunctionMatcher<T>>? existing])
[Iterable<FunctionMatcher<T>>? existing])
: _parent = parent,
_functionMatchers = [
...?existing,
_FunctionMatcher<T>(description, feature, matcher)
FunctionMatcher<T>(description, feature, matcher)
];
@override
... ...
... ... @@ -16,7 +16,7 @@ void main() {
expect('total_confirmed'.tr, 'Total Confirmed');
expect('total_deaths'.tr, 'Total Deaths');
Get.updateLocale(Locale('pt', 'BR'));
Get.updateLocale(const Locale('pt', 'BR'));
await tester.pumpAndSettle();
... ... @@ -24,7 +24,7 @@ void main() {
expect('total_confirmed'.tr, 'Total confirmado');
expect('total_deaths'.tr, 'Total de mortes');
Get.updateLocale(Locale('en', 'EN'));
Get.updateLocale(const Locale('en', 'EN'));
await tester.pumpAndSettle();
... ...
... ... @@ -12,16 +12,14 @@ void main() {
await tester.pump();
Get.bottomSheet(Container(
child: Wrap(
children: <Widget>[
ListTile(
leading: Icon(Icons.music_note),
title: Text('Music'),
onTap: () {},
),
],
),
Get.bottomSheet(Wrap(
children: <Widget>[
ListTile(
leading: const Icon(Icons.music_note),
title: const Text('Music'),
onTap: () {},
),
],
));
await tester.pumpAndSettle();
... ... @@ -36,16 +34,14 @@ void main() {
await tester.pump();
Get.bottomSheet(Container(
child: Wrap(
children: <Widget>[
ListTile(
leading: Icon(Icons.music_note),
title: Text('Music'),
onTap: () {},
),
],
),
Get.bottomSheet(Wrap(
children: <Widget>[
ListTile(
leading: const Icon(Icons.music_note),
title: const Text('Music'),
onTap: () {},
),
],
));
await tester.pumpAndSettle();
... ...
... ... @@ -13,8 +13,7 @@ void main() {
await tester.pump();
Get.defaultDialog(
onConfirm: () => print("Ok"),
middleText: "Dialog made in 3 lines of code");
onConfirm: () {}, middleText: "Dialog made in 3 lines of code");
await tester.pumpAndSettle();
... ... @@ -28,7 +27,7 @@ void main() {
await tester.pump();
Get.dialog(YourDialogWidget());
Get.dialog(const YourDialogWidget());
await tester.pumpAndSettle();
... ... @@ -42,7 +41,7 @@ void main() {
await tester.pump();
Get.dialog(YourDialogWidget());
Get.dialog(const YourDialogWidget());
await tester.pumpAndSettle();
expect(find.byType(YourDialogWidget), findsOneWidget);
... ...
... ... @@ -13,7 +13,7 @@ void main() {
expect(Get.isRegistered<Controller2>(), false);
expect(Get.isRegistered<Controller>(), false);
Get.to(() => First());
Get.to(() => const First());
await tester.pumpAndSettle();
... ... @@ -21,7 +21,7 @@ void main() {
expect(Get.isRegistered<Controller>(), true);
Get.to(() => Second());
Get.to(() => const Second());
await tester.pumpAndSettle();
... ... @@ -53,20 +53,24 @@ class Controller extends GetxController {}
class Controller2 extends GetxController {}
class First extends StatelessWidget {
const First({super.key});
@override
Widget build(BuildContext context) {
Get.put(Controller());
return Center(
return const Center(
child: Text("first"),
);
}
}
class Second extends StatelessWidget {
const Second({super.key});
@override
Widget build(BuildContext context) {
Get.put(Controller2());
return Center(
return const Center(
child: Text("second"),
);
}
... ...
... ... @@ -8,7 +8,7 @@ void main() {
testWidgets("Get.to navigates to provided route", (tester) async {
await tester.pumpWidget(Wrapper(child: Container()));
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -19,9 +19,9 @@ void main() {
await tester.pumpWidget(GetMaterialApp(
initialRoute: '/first',
getPages: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -35,11 +35,11 @@ void main() {
testWidgets("unknowroute", (tester) async {
await tester.pumpWidget(GetMaterialApp(
initialRoute: '/first',
unknownRoute: GetPage(name: '/404', page: () => Scaffold()),
unknownRoute: GetPage(name: '/404', page: () => const Scaffold()),
getPages: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -52,10 +52,10 @@ void main() {
});
testWidgets("Get.off navigates to provided route", (tester) async {
await tester.pumpWidget(Wrapper(child: FirstScreen()));
await tester.pumpWidget(const Wrapper(child: FirstScreen()));
// await tester.pump();
Get.off(() => SecondScreen());
Get.off(() => const SecondScreen());
await tester.pumpAndSettle();
... ... @@ -63,10 +63,10 @@ void main() {
});
testWidgets("Get.off removes current route", (tester) async {
await tester.pumpWidget(Wrapper(child: FirstScreen()));
await tester.pumpWidget(const Wrapper(child: FirstScreen()));
await tester.pump();
Get.off(() => SecondScreen());
Get.off(() => const SecondScreen());
Get.back();
await tester.pumpAndSettle();
... ... @@ -78,9 +78,9 @@ void main() {
await tester.pumpWidget(GetMaterialApp(
initialRoute: '/first',
getPages: [
GetPage(name: '/first', page: () => FirstScreen()),
GetPage(name: '/second', page: () => SecondScreen()),
GetPage(name: '/third', page: () => ThirdScreen()),
GetPage(name: '/first', page: () => const FirstScreen()),
GetPage(name: '/second', page: () => const SecondScreen()),
GetPage(name: '/third', page: () => const ThirdScreen()),
],
));
... ... @@ -97,9 +97,9 @@ void main() {
await tester.pumpWidget(GetMaterialApp(
initialRoute: '/first',
getPages: [
GetPage(name: '/first', page: () => FirstScreen()),
GetPage(name: '/second', page: () => SecondScreen()),
GetPage(name: '/third', page: () => ThirdScreen()),
GetPage(name: '/first', page: () => const FirstScreen()),
GetPage(name: '/second', page: () => const SecondScreen()),
GetPage(name: '/third', page: () => const ThirdScreen()),
],
));
... ... @@ -118,9 +118,9 @@ void main() {
await tester.pumpWidget(GetMaterialApp(
initialRoute: '/first',
getPages: [
GetPage(name: '/first', page: () => FirstScreen()),
GetPage(name: '/second', page: () => SecondScreen()),
GetPage(name: '/third', page: () => ThirdScreen()),
GetPage(name: '/first', page: () => const FirstScreen()),
GetPage(name: '/second', page: () => const SecondScreen()),
GetPage(name: '/third', page: () => const ThirdScreen()),
],
));
... ... @@ -138,10 +138,10 @@ void main() {
});
testWidgets("Get.offAll navigates to provided route", (tester) async {
await tester.pumpWidget(Wrapper(child: FirstScreen()));
await tester.pumpWidget(const Wrapper(child: FirstScreen()));
await tester.pump();
Get.offAll(() => SecondScreen());
Get.offAll(() => const SecondScreen());
await tester.pumpAndSettle();
... ... @@ -149,12 +149,12 @@ void main() {
});
testWidgets("Get.offAll removes all previous routes", (tester) async {
await tester.pumpWidget(Wrapper(child: FirstScreen()));
await tester.pumpWidget(const Wrapper(child: FirstScreen()));
await tester.pump();
Get.to(() => SecondScreen());
Get.to(() => const SecondScreen());
await tester.pumpAndSettle();
Get.offAll(() => ThirdScreen());
Get.offAll(() => const ThirdScreen());
await tester.pumpAndSettle();
Get.back();
await tester.pumpAndSettle();
... ... @@ -173,9 +173,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -192,9 +192,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -220,9 +220,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -237,9 +237,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -256,11 +256,12 @@ void main() {
testWidgets("Get.offUntil navigates to provided route", (tester) async {
await tester.pumpWidget(Wrapper(child: Container()));
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
Get.offUntil(() => ThirdScreen(), (route) => route.name == '/FirstScreen');
Get.offUntil(
() => const ThirdScreen(), (route) => route.name == '/FirstScreen');
await tester.pumpAndSettle();
... ... @@ -272,11 +273,12 @@ void main() {
(tester) async {
await tester.pumpWidget(Wrapper(child: Container()));
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
Get.to(() => SecondScreen());
Get.to(() => const SecondScreen());
await tester.pumpAndSettle();
Get.offUntil(() => ThirdScreen(), (route) => route.name == '/FirstScreen');
Get.offUntil(
() => const ThirdScreen(), (route) => route.name == '/FirstScreen');
await tester.pumpAndSettle();
Get.back();
... ... @@ -290,11 +292,12 @@ void main() {
(tester) async {
await tester.pumpWidget(Wrapper(child: Container()));
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
Get.to(() => SecondScreen());
Get.to(() => const SecondScreen());
await tester.pumpAndSettle();
Get.offUntil(() => ThirdScreen(), (route) => route.name == '/FirstScreen');
Get.offUntil(
() => const ThirdScreen(), (route) => route.name == '/FirstScreen');
await tester.pumpAndSettle();
Get.back();
... ... @@ -307,9 +310,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -326,9 +329,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third')
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third')
],
));
... ... @@ -347,9 +350,9 @@ void main() {
await tester.pumpWidget(WrapperNamed(
initialRoute: '/first',
namedRoutes: [
GetPage(page: () => FirstScreen(), name: '/first'),
GetPage(page: () => SecondScreen(), name: '/second'),
GetPage(page: () => ThirdScreen(), name: '/third'),
GetPage(page: () => const FirstScreen(), name: '/first'),
GetPage(page: () => const SecondScreen(), name: '/second'),
GetPage(page: () => const ThirdScreen(), name: '/third'),
],
));
... ... @@ -367,17 +370,17 @@ void main() {
testWidgets("Get.back navigates back", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.circularReveal,
child: Container(),
),
);
// await tester.pump();
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
Get.to(() => SecondScreen());
Get.to(() => const SecondScreen());
await tester.pumpAndSettle();
Get.back();
... ... @@ -391,16 +394,16 @@ void main() {
(tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.circularReveal,
child: Container(),
),
);
// await tester.pump();
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
Get.to(() => SecondScreen());
Get.to(() => const SecondScreen());
await tester.pumpAndSettle();
Get.snackbar('title', "message");
await tester.pumpAndSettle();
... ... @@ -417,12 +420,12 @@ void main() {
testWidgets("fadeIn", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.fadeIn,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -432,12 +435,12 @@ void main() {
testWidgets("downToUp", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.downToUp,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -447,12 +450,12 @@ void main() {
testWidgets("fade", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.fade,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -462,12 +465,12 @@ void main() {
testWidgets("leftToRight", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.leftToRight,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -477,12 +480,12 @@ void main() {
testWidgets("leftToRightWithFade", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.leftToRightWithFade,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -492,12 +495,12 @@ void main() {
testWidgets("leftToRightWithFade", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.rightToLeft,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -507,12 +510,12 @@ void main() {
testWidgets("defaultTransition", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.rightToLeft,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -522,12 +525,12 @@ void main() {
testWidgets("rightToLeftWithFade", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.rightToLeftWithFade,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -537,12 +540,12 @@ void main() {
testWidgets("cupertino", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.cupertino,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -552,12 +555,12 @@ void main() {
testWidgets("size", (tester) async {
await tester.pumpWidget(
Wrapper(
child: Container(),
defaultTransition: Transition.size,
child: Container(),
),
);
Get.to(() => FirstScreen());
Get.to(() => const FirstScreen());
await tester.pumpAndSettle();
... ... @@ -571,7 +574,8 @@ class FirstScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(child: Text('FirstScreen'));
// ignore: avoid_unnecessary_containers
return Container(child: const Text('FirstScreen'));
}
}
... ...
... ... @@ -35,11 +35,14 @@ void main() {
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => Container()),
GetPage(name: '/first', page: () => FirstScreen(), middlewares: [
RedirectMiddleware(),
]),
GetPage(name: '/second', page: () => SecondScreen()),
GetPage(name: '/third', page: () => ThirdScreen()),
GetPage(
name: '/first',
page: () => const FirstScreen(),
middlewares: [
RedirectMiddleware(),
]),
GetPage(name: '/second', page: () => const SecondScreen()),
GetPage(name: '/third', page: () => const ThirdScreen()),
],
),
);
... ... @@ -47,7 +50,6 @@ void main() {
Get.toNamed('/first');
await tester.pumpAndSettle();
print(Get.rootController.rootDelegate.currentConfiguration?.route?.name);
expect(find.byType(SecondScreen), findsOneWidget);
});
... ... @@ -57,11 +59,14 @@ void main() {
initialRoute: '/',
getPages: [
GetPage(name: '/', page: () => Container()),
GetPage(name: '/first', page: () => FirstScreen(), middlewares: [
RedirectMiddlewareNull(),
]),
GetPage(name: '/second', page: () => SecondScreen()),
GetPage(name: '/third', page: () => ThirdScreen()),
GetPage(
name: '/first',
page: () => const FirstScreen(),
middlewares: [
RedirectMiddlewareNull(),
]),
GetPage(name: '/second', page: () => const SecondScreen()),
GetPage(name: '/third', page: () => const ThirdScreen()),
],
),
);
... ... @@ -71,7 +76,6 @@ void main() {
Get.toNamed('/first');
await tester.pumpAndSettle();
print(Get.rootController.rootDelegate.currentConfiguration?.route?.name);
expect(find.byType(FirstScreen), findsOneWidget);
});
}
... ...
... ... @@ -64,7 +64,7 @@ void main() {
tree.addRoute(pageTree);
// tree.addRoute(pageTree);
final searchRoute = '/city/work/office/pen';
const searchRoute = '/city/work/office/pen';
final match = tree.matchRoute(searchRoute);
expect(match, isNotNull);
expect(match.route!.name, searchRoute);
... ... @@ -120,7 +120,7 @@ void main() {
// tree.addRoute(p);
// }
final searchRoute = '/city/work/office/pen';
const searchRoute = '/city/work/office/pen';
final match = tree.matchRoute(searchRoute);
expect(match, isNotNull);
expect(match.route!.name, searchRoute);
... ... @@ -166,7 +166,6 @@ void main() {
testWidgets(
'params in url by parameters',
(tester) async {
print("Iniciando test");
await tester.pumpWidget(GetMaterialApp(
initialRoute: '/first/juan',
getPages: [
... ...