Jonny Borges
Committed by GitHub

New Release - Get 2.5

## [2.5.0]
- Added List.obs
- Now you can transform any class on obs
## [2.4.0]
- Added GetX, state manager rxDart based.
- Fix error on add for non global controllers
## [2.3.2]
- Fix close method called on not root GetBuilder
## [2.3.1]
- Auto close stream inside close method
- Added docs
## [2.3.0]
- Added interface to GetX support
## [2.2.8]
- Added api to platform brightness
## [2.2.7]
- Fix typos
## [2.2.6]
- Fix cancel button on defaultDialog don't appear when widget implementation usage
... ...
... ... @@ -183,7 +183,7 @@ With Get, all you have to do is call your Get.snackbar from anywhere in your cod
///////////////////////////////////
```
If you prefer the traditional snackbar, or want to customize it from scratch, including adding just one line (Get.snackbar makes use of a mandatory title and message), you can use
`GetBar().show();` which provides the RAW API on which Get.snackbar was built.
`Get.rawSnackbar();` which provides the RAW API on which Get.snackbar was built.
### Dialogs
... ... @@ -244,7 +244,7 @@ What performance improvements does Get bring?
2- Does not use changeNotifier, it is the state manager that uses less memory (close to 0mb).
3- Forget StatefulWidget! With Get you will never need it again. With the other state managers, you will probably have to use a StatefulWidget to get the instance of your Provider, BLoC, MobX Controller, etc. But have you ever stopped to think that your appBar, your scaffold, and most of the widgets that are in your class are stateless? So why save the state of an entire class, if you can only save the state of the Widget that is stateful? Get solves that, too. Create a Stateless class, make everything stateless. If you need to update a single component, wrap it with GetBuilder, and its state will be maintained.
3- Forget StatefulWidget! With Get you will never need it again (if you need to use it, you are using Get incorrectly). With the other state managers, you will probably have to use a StatefulWidget to get the instance of your Provider, BLoC, MobX Controller, etc. But have you ever stopped to think that your appBar, your scaffold, and most of the widgets that are in your class are stateless? So why save the state of an entire class, if you can only save the state of the Widget that is stateful? Get solves that, too. Create a Stateless class, make everything stateless. If you need to update a single component, wrap it with GetBuilder, and its state will be maintained.
4- Organize your project for real! Controllers must not be in your UI, place your TextEditController, or any controller you use within your Controller class.
... ... @@ -261,7 +261,7 @@ What performance improvements does Get bring?
In class A the controller is not yet in memory, because you have not used it yet (Get is lazyLoad). In class B you used the controller, and it entered memory. In class C you used the same controller as in class B, Get will share the state of controller B with controller C, and the same controller is still in memory. If you close screen C and screen B, Get will automatically take controller X out of memory and free up resources, because Class a is not using the controller. If you navigate to B again, controller X will enter memory again, if instead of going to class C, you return to class A again, Get will take the controller out of memory in the same way. If class C didn't use the controller, and you took class B out of memory, no class would be using controller X and likewise it would be disposed of. The only exception that can mess with Get, is if you remove B from the route unexpectedly, and try to use the controller in C. In this case, the creator ID of the controller that was in B was deleted, and Get was programmed to remove it from memory every controller that has no creator ID. If you intend to do this, add the "autoRemove: false" flag to class B's GetBuilder and use adoptID = true; in class C's GetBuilder.
### State manager usage
### Simple state manager usage
```dart
// Create controller class and extends GetController
... ... @@ -283,8 +283,6 @@ GetBuilder<Controller>(
**Done!**
- You have already learned how to manage states with Get.
### Global State manager
If you navigate many routes and need data that was in your previously used controller, you just need to use GetBuilder Again (with no init):
```dart
... ... @@ -330,6 +328,39 @@ FloatingActionButton(
```
When you press FloatingActionButton, all widgets that are listening to the 'counter' variable will be updated automatically.
##### No StatefulWidget:
Using StatefulWidgets means storing the state of entire screens unnecessarily. With Get the use of StatefulWidget is optional. Avoid them and save your users' RAM.
If you need to call initState() or dispose() method, you can call them directly from GetBuilder();
```dart
GetBuilder<Controller>(
initState(_) => Controller.to.fetchApi(),
dispose(_) => Controller.to.closeStreams(),
builder: (s) => Text('${s.username}'),
),
```
- NOTE: If you are working with reactive programming with Get, know that it automatically closes your streams, as long as you close them correctly inside the close() method;
Do not call a dispose method inside GetController, it will not do anything, remember that the controller is not a Widget, you should not "dispose" it, and it will be automatically and intelligently removed from memory by Get. If you used any stream on it and want to close it, just insert it into the close method. Example:
```dart
class Controller extends GetController {
StreamController<User> user = StreamController<User>();
StreamController<String> name = StreamController<String>();
/// close stream = close method, not dispose.
@override
void close() {
user.close();
name.close();
super.close();
}
```
##### Forms of use:
- Recommended usage:
... ... @@ -384,6 +415,130 @@ GetBuilder( // you dont need to type on this way
```
If you want to refine a widget's update control, you can assign them unique IDs:
```dart
GetBuilder<Controller>(
id: 'text'
init: Controller(), // use it only first time on each controller
builder: (_) => Text(
'${Get.find<Controller>().counter}', //here
)),
```
And update it fis form:
```dart
update(this,['text']);
You can also impose conditions for the update:
```
update(this,['text'], counter < 10);
Why use the update method and why don't we use ChangeNotifier?
## Reactive State Manager
If you want power, Get gives you the most advanced state manager you could ever have.
GetX was built 100% based on Streams, and give you all the firepower that BLoC gave you, with an easier facility than using MobX.
Without decorations, you can turn anything into Observable with just a ".obs".
Maximum performance: In addition to having a smart algorithm for minimal reconstruction, Get uses comparators to make sure the state has changed. If you experience any errors in your application, and send a duplicate change of state, Get will ensure that your application does not collapse.
The state only changes if the values ​​change. That's the main difference between Get, and using Computed from MobX. When joining two observables, when one is changed, the hearing of that observable will change. With Get, if you join two variables (which is unnecessary computed for that), GetX (similar to Observer) will only change if it implies a real change of state. Example:
```dart
final count1 = 0.obs;
final count2 = 0.obs;
int get soma => count1.value + count2.value;
```
```dart
GetX<Controller>(
builder: (_) {
print("count 1 rebuild");
return Text('${_.count1.value}');
},
),
GetX<Controller>(
builder: (_) {
print("count 2 rebuild");
return Text('${_.count2.value}');
},
),
GetX<Controller>(
builder: (_) {
print("count 3 rebuild");
return Text('${_.soma}');
},
),
```
If we increment the number of count 1, only count 1 and count 3 are reconstructed, because count 1 now has a value of 1, and 1 + 0 = 1, changing the sum value.
If we change count 2, only count2 and 3 are reconstructed, because the value of 2 has changed, and the result of the sum is now 2.
If we add the number 1 to count 1, which already contains 1, no widget is reconstructed. If we add a value of 1 for count 1 and a value of 2 for count 2, only 2 and 3 will be reconstructed, simply because GetX not only changes what is necessary, it avoids duplicating events.
In addition, Get provides refined state control. You can condition an event (such as adding an object to a list), on a certain condition.
```dart
list.addIf(item<limit, item);
```
Without decorations, without a code generator, without complications, GetX will change the way you manage your states in Flutter, and that is not a promise, it is a certainty!
Do you know Flutter's counter app? Your Controller class might look like this:
```dart
class CountCtl extends RxController {
int count = 0.obs;
}
```
With a simple:
```dart
ctl.count.value++
```
You could update the counter variable in your UI, regardless of where it is stored.
You can transform anything on obs:
```dart
class RxUser {
final name = "Camila".obs;
final age = 18.obs;
}
class User {
User({String name, int age});
final rx = RxUser();
String get name => rx.name.value;
set name(String value) => rx.name.value = value;
int get age => rx.age.value;
set age(int value) => rx.age.value = value;
}
```
```dart
void main() {
final user = User();
print(user.name);
user.age = 23;
user.rx.age.listen((int age) => print(age));
user.age = 24;
user.age = 25;
}
___________
out:
Camila
23
24
25
## Simple Instance Manager
Are you already using Get and want to make your project as lean as possible? Get has a simple and powerful dependency manager that allows you to retrieve the same class as your Bloc or Controller with just 1 lines of code, no Provider context, no inheritedWidget:
... ... @@ -409,6 +564,12 @@ And then you will be able to recover your controller data that was obtained back
Text(controller.textFromApi);
```
Looking for lazy loading? You can declare all your controllers, and it will be called only when someone needs it. You can do this with:
```dart
Get.lazyPut<Service>(()=> ApiMock());
/// ApiMock will only be called when someone uses Get.find<Service> for the first time
```
To remove a instance of Get:
```dart
Get.delete<Controller>();
... ... @@ -718,7 +879,7 @@ See how simple it is:
child: FlatButton(
color: Colors.blue,
onPressed: () {
Get.toNamed('/second', 1); // navigate by your nested route by index
Get.toNamed('/second', id:1); // navigate by your nested route by index
},
child: Text("Go to second")),
),
... ...
... ... @@ -6,6 +6,10 @@ export 'src/snackbar/snack.dart';
export 'src/bottomsheet/bottomsheet.dart';
export 'src/snackbar/snack_route.dart';
export 'src/state/get_state.dart';
export 'src/rx/rx_interface.dart';
export 'src/rx/rx_impl.dart';
export 'src/rx/rx_getbuilder.dart';
export 'src/rx/rx_listview_builder.dart';
export 'src/root/root_widget.dart';
export 'src/routes/default_route.dart';
export 'src/routes/get_route.dart';
... ...
... ... @@ -6,24 +6,10 @@ import 'root/root_controller.dart';
import 'routes/default_route.dart';
import 'routes/observers/route_observer.dart';
import 'routes/transitions_type.dart';
import 'rx/rx_interface.dart';
import 'snackbar/snack.dart';
class Get {
static Get _get;
static GlobalKey<NavigatorState> _key;
static GlobalKey<NavigatorState> addKey(GlobalKey<NavigatorState> newKey) {
_key = newKey;
return _key;
}
static GlobalKey<NavigatorState> get key {
if (_key == null) {
_key = GlobalKey<NavigatorState>();
}
return _key;
}
///Use Get.to instead of Navigator.push, Get.off instead of Navigator.pushReplacement,
///Get.offAll instead of Navigator.pushAndRemoveUntil. For named routes just add "named"
///after them. Example: Get.toNamed, Get.offNamed, and Get.AllNamed.
... ... @@ -35,6 +21,15 @@ class Get {
return _get;
}
bool _enableLog = true;
bool _defaultPopGesture = GetPlatform.isIOS;
bool _defaultOpaqueRoute = true;
Transition _defaultTransition =
(GetPlatform.isIOS ? Transition.cupertino : Transition.fade);
Duration _defaultDurationTransition = Duration(milliseconds: 400);
bool _defaultGlobalState = true;
RouteSettings _settings;
///Use Get.to instead of Navigator.push, Get.off instead of Navigator.pushReplacement,
///Get.offAll instead of Navigator.pushAndRemoveUntil. For named routes just add "named"
///after them. Example: Get.toNamed, Get.offNamed, and Get.AllNamed.
... ... @@ -43,14 +38,21 @@ class Get {
///the parentheses and the magic will occur.
Get._();
static bool _enableLog = true;
static bool _defaultPopGesture = GetPlatform.isIOS;
static bool _defaultOpaqueRoute = true;
static Transition _defaultTransition =
(GetPlatform.isIOS ? Transition.cupertino : Transition.fade);
static Duration _defaultDurationTransition = Duration(milliseconds: 400);
static bool _defaultGlobalState = true;
static RouteSettings _settings;
static Get _get;
GlobalKey<NavigatorState> _key;
static GlobalKey<NavigatorState> addKey(GlobalKey<NavigatorState> newKey) {
_get._key = newKey;
return _get._key;
}
static GlobalKey<NavigatorState> get key {
if (_get._key == null) {
_get._key = GlobalKey<NavigatorState>();
}
return _get._key;
}
/// It replaces Navigator.push, but needs no context, and it doesn't have the Navigator.push
/// routes rebuild bug present in Flutter. If for some strange reason you want the default behavior
... ... @@ -60,13 +62,18 @@ class Get {
Transition transition,
Duration duration,
int id,
bool fullscreenDialog = false,
Object arguments,
bool popGesture}) {
return global(id).currentState.push(GetRouteBase(
return _get.global(id).currentState.push(GetRouteBase(
opaque: opaque ?? true,
page: page,
popGesture: popGesture ?? _defaultPopGesture,
transition: transition ?? _defaultTransition,
transitionDuration: duration ?? _defaultDurationTransition));
settings: RouteSettings(
name: '/' + page.toString().toLowerCase(), arguments: arguments),
popGesture: popGesture ?? _get._defaultPopGesture,
transition: transition ?? _get._defaultTransition,
fullscreenDialog: fullscreenDialog,
transitionDuration: duration ?? _get._defaultDurationTransition));
}
/// It replaces Navigator.pushNamed, but needs no context, and it doesn't have the Navigator.pushNamed
... ... @@ -75,14 +82,15 @@ class Get {
static Future<T> toNamed<T>(String page, {arguments, int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id).currentState.pushNamed(page, arguments: arguments);
return _get.global(id).currentState.pushNamed(page, arguments: arguments);
}
/// It replaces Navigator.pushReplacementNamed, but needs no context.
static Future<T> offNamed<T>(String page, {arguments, int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id)
return _get
.global(id)
.currentState
.pushReplacementNamed(page, arguments: arguments);
}
... ... @@ -91,24 +99,35 @@ class Get {
static void until(predicate, {int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id).currentState.popUntil(predicate);
return _get.global(id).currentState.popUntil(predicate);
}
/// It replaces Navigator.pushAndRemoveUntil, but needs no context.
static Future<T> offUntil<T>(page, predicate, {int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id).currentState.pushAndRemoveUntil(page, predicate);
return _get.global(id).currentState.pushAndRemoveUntil(page, predicate);
}
/// It replaces Navigator.pushNamedAndRemoveUntil, but needs no context.
static Future<T> offNamedUntil<T>(page, predicate, {int id}) {
return global(id).currentState.pushNamedAndRemoveUntil(page, predicate);
return _get
.global(id)
.currentState
.pushNamedAndRemoveUntil(page, predicate);
}
/// It replaces Navigator.popAndPushNamed, but needs no context.
static Future<T> offAndToNamed<T>(String page, {arguments, int id, result}) {
return _get
.global(id)
.currentState
.popAndPushNamed(page, arguments: arguments, result: result);
}
/// It replaces Navigator.removeRoute, but needs no context.
static void removeRoute(route, {int id}) {
return global(id).currentState.removeRoute(route);
return _get.global(id).currentState.removeRoute(route);
}
/// It replaces Navigator.pushNamedAndRemoveUntil, but needs no context.
... ... @@ -116,7 +135,7 @@ class Get {
{RoutePredicate predicate, arguments, int id}) {
var route = (Route<dynamic> rota) => false;
return global(id).currentState.pushNamedAndRemoveUntil(
return _get.global(id).currentState.pushNamedAndRemoveUntil(
newRouteName, predicate ?? route,
arguments: arguments);
}
... ... @@ -134,7 +153,7 @@ class Get {
return (isOverlaysClosed);
});
}
global(id).currentState.pop(result);
_get.global(id).currentState.pop(result);
}
// /// Experimental API to back from overlay
... ... @@ -148,7 +167,7 @@ class Get {
times = 1;
}
int count = 0;
void back = global(id).currentState.popUntil((route) {
void back = _get.global(id).currentState.popUntil((route) {
return count++ == times;
});
return back;
... ... @@ -162,13 +181,18 @@ class Get {
Transition transition,
bool popGesture,
int id,
Object arguments,
bool fullscreenDialog = false,
Duration duration}) {
return global(id).currentState.pushReplacement(GetRouteBase(
return _get.global(id).currentState.pushReplacement(GetRouteBase(
opaque: opaque ?? true,
page: page,
popGesture: popGesture ?? _defaultPopGesture,
transition: transition ?? _defaultTransition,
transitionDuration: duration ?? _defaultDurationTransition));
settings: RouteSettings(
name: '/' + page.toString().toLowerCase(), arguments: arguments),
fullscreenDialog: fullscreenDialog,
popGesture: popGesture ?? _get._defaultPopGesture,
transition: transition ?? _get._defaultTransition,
transitionDuration: duration ?? _get._defaultDurationTransition));
}
/// It replaces Navigator.pushAndRemoveUntil, but needs no context
... ... @@ -177,15 +201,20 @@ class Get {
bool opaque = false,
bool popGesture,
int id,
Object arguments,
bool fullscreenDialog = false,
Transition transition}) {
var route = (Route<dynamic> rota) => false;
return global(id).currentState.pushAndRemoveUntil(
return _get.global(id).currentState.pushAndRemoveUntil(
GetRouteBase(
opaque: opaque ?? true,
popGesture: popGesture ?? _defaultPopGesture,
popGesture: popGesture ?? _get._defaultPopGesture,
page: page,
transition: transition ?? _defaultTransition,
settings: RouteSettings(
name: '/' + page.toString().toLowerCase(), arguments: arguments),
fullscreenDialog: fullscreenDialog,
transition: transition ?? _get._defaultTransition,
),
predicate ?? route);
}
... ... @@ -537,7 +566,7 @@ class Get {
}
/// change default config of Get
static void config(
Get.config(
{bool enableLog,
bool defaultPopGesture,
bool defaultOpaqueRoute,
... ... @@ -545,45 +574,47 @@ class Get {
bool defaultGlobalState,
Transition defaultTransition}) {
if (enableLog != null) {
_enableLog = enableLog;
_get._enableLog = enableLog;
}
if (defaultPopGesture != null) {
_defaultPopGesture = defaultPopGesture;
_get._defaultPopGesture = defaultPopGesture;
}
if (defaultOpaqueRoute != null) {
_defaultOpaqueRoute = defaultOpaqueRoute;
_get._defaultOpaqueRoute = defaultOpaqueRoute;
}
if (defaultTransition != null) {
_defaultTransition = defaultTransition;
_get._defaultTransition = defaultTransition;
}
if (defaultDurationTransition != null) {
_defaultDurationTransition = defaultDurationTransition;
_get._defaultDurationTransition = defaultDurationTransition;
}
if (defaultGlobalState != null) {
_defaultGlobalState = defaultGlobalState;
_get._defaultGlobalState = defaultGlobalState;
}
}
static GetMaterialController getController = GetMaterialController();
GetMaterialController _getController = GetMaterialController();
GetMaterialController get getController => _getController;
static changeTheme(ThemeData theme) {
getController.setTheme(theme);
Get.changeTheme(ThemeData theme) {
_get._getController.setTheme(theme);
}
static restartApp() {
getController.restartApp();
Get.restartApp() {
_get._getController.restartApp();
}
static Map<int, GlobalKey<NavigatorState>> _keys = {};
Map<int, GlobalKey<NavigatorState>> _keys = {};
static GlobalKey<NavigatorState> nestedKey(int key) {
_keys.putIfAbsent(key, () => GlobalKey<NavigatorState>());
return _keys[key];
_get._keys.putIfAbsent(key, () => GlobalKey<NavigatorState>());
return _get._keys[key];
}
static GlobalKey<NavigatorState> global(int k) {
GlobalKey<NavigatorState> global(int k) {
if (k == null) {
return key;
}
... ... @@ -713,70 +744,78 @@ class Get {
Get()._singl.containsKey(_getKey(S, name));
/// give access to Routing API from GetObserver
static Routing get routing => _routing;
static Routing get routing => _get._routing;
static RouteSettings get routeSettings => _settings;
static RouteSettings get routeSettings => _get._settings;
static Routing _routing;
Routing _routing;
static Map<String, String> _parameters = {};
Map<String, String> _parameters = {};
static setParameter(Map<String, String> param) {
_parameters = param;
Get.setParameter(Map<String, String> param) {
_get._parameters = param;
}
static setRouting(Routing rt) {
_routing = rt;
Get.setRouting(Routing rt) {
_get._routing = rt;
}
static setSettings(RouteSettings settings) {
_settings = settings;
Get.setSettings(RouteSettings settings) {
_get._settings = settings;
}
/// give current arguments
static get arguments => _routing.args;
static Object get arguments => _get._routing.args;
/// give current arguments
static Map<String, String> get parameters => _parameters;
static Map<String, String> get parameters => _get._parameters;
/// interface to GetX
RxInterface _obs;
static RxInterface get obs => _get._obs;
static set obs(RxInterface observer) => _get._obs = observer;
/// give arguments from previous route
static get previousArguments => _routing.previousArgs;
static get previousArguments => _get._routing.previousArgs;
/// give name from current route
static get currentRoute => _routing.current;
static get currentRoute => _get._routing.current;
/// give name from previous route
static get previousRoute => _routing.previous;
static get previousRoute => _get._routing.previous;
/// check if snackbar is open
static bool get isSnackbarOpen => _routing.isSnackbar;
static bool get isSnackbarOpen => _get._routing.isSnackbar;
/// check if dialog is open
static bool get isDialogOpen => _routing.isDialog;
static bool get isDialogOpen => _get._routing.isDialog;
/// check if bottomsheet is open
static bool get isBottomSheetOpen => _routing.isBottomSheet;
static bool get isBottomSheetOpen => _get._routing.isBottomSheet;
/// check a raw current route
static Route<dynamic> get rawRoute => _routing.route;
static Route<dynamic> get rawRoute => _get._routing.route;
/// check if log is enable
static bool get isLogEnable => _enableLog;
static bool get isLogEnable => _get._enableLog;
/// default duration of transition animation
/// default duration work only API 2.0
static Duration get defaultDurationTransition => _defaultDurationTransition;
static Duration get defaultDurationTransition =>
_get._defaultDurationTransition;
/// give global state of all GetState by default
static bool get defaultGlobalState => _defaultGlobalState;
static bool get defaultGlobalState => _get._defaultGlobalState;
/// check if popGesture is enable
static bool get isPopGestureEnable => _defaultPopGesture;
static bool get isPopGestureEnable => _get._defaultPopGesture;
/// check if default opaque route is enable
static bool get isOpaqueRouteDefault => _defaultOpaqueRoute;
static bool get isOpaqueRouteDefault => _get._defaultOpaqueRoute;
static Transition get defaultTransition => _defaultTransition;
static Transition get defaultTransition => _get._defaultTransition;
/// give access to currentContext
static BuildContext get context => key.currentContext;
... ... @@ -793,6 +832,13 @@ class Get {
/// give access to Mediaquery.of(context)
static MediaQueryData get mediaQuery => MediaQuery.of(context);
/// Check if dark mode theme is enable
static get isDarkMode => (theme.brightness == Brightness.dark);
/// Check if dark mode theme is enable on platform on android Q+
static get isPlatformDarkMode =>
(mediaQuery.platformBrightness == Brightness.dark);
/// give access to Theme.of(context).iconTheme.color
static Color get iconColor => Theme.of(context).iconTheme.color;
... ...
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'bottomsheet/bottomsheet.dart';
import 'platform/platform.dart';
import 'root/root_controller.dart';
import 'routes/default_route.dart';
import 'routes/observers/route_observer.dart';
import 'routes/transitions_type.dart';
import 'rx/rx_interface.dart';
import 'snackbar/snack.dart';
class Get {
static Get _get;
static GlobalKey<NavigatorState> _key;
static GlobalKey<NavigatorState> addKey(GlobalKey<NavigatorState> newKey) {
_key = newKey;
return _key;
}
static GlobalKey<NavigatorState> get key {
if (_key == null) {
_key = GlobalKey<NavigatorState>();
}
return _key;
}
///Use Get.to instead of Navigator.push, Get.off instead of Navigator.pushReplacement,
///Get.offAll instead of Navigator.pushAndRemoveUntil. For named routes just add "named"
///after them. Example: Get.toNamed, Get.offNamed, and Get.AllNamed.
///To return to the previous screen, use Get.back().
///No need to pass any context to Get, just put the name of the route inside
///the parentheses and the magic will occur.
factory Get() {
if (_get == null) _get = Get._();
return _get;
}
///Use Get.to instead of Navigator.push, Get.off instead of Navigator.pushReplacement,
///Get.offAll instead of Navigator.pushAndRemoveUntil. For named routes just add "named"
///after them. Example: Get.toNamed, Get.offNamed, and Get.AllNamed.
///To return to the previous screen, use Get.back().
///No need to pass any context to Get, just put the name of the route inside
///the parentheses and the magic will occur.
Get._();
static bool _enableLog = true;
static bool _defaultPopGesture = GetPlatform.isIOS;
static bool _defaultOpaqueRoute = true;
static Transition _defaultTransition =
(GetPlatform.isIOS ? Transition.cupertino : Transition.fade);
static Duration _defaultDurationTransition = Duration(milliseconds: 400);
static bool _defaultGlobalState = true;
static RouteSettings _settings;
/// It replaces Navigator.push, but needs no context, and it doesn't have the Navigator.push
/// routes rebuild bug present in Flutter. If for some strange reason you want the default behavior
/// of rebuilding every app after a route, use opaque = true as the parameter.
static Future<T> to<T>(Widget page,
{bool opaque,
Transition transition,
Duration duration,
int id,
bool fullscreenDialog = false,
Object arguments,
bool popGesture}) {
return global(id).currentState.push(GetRouteBase(
opaque: opaque ?? true,
page: page,
settings: RouteSettings(
name: '/' + page.toString().toLowerCase(), arguments: arguments),
popGesture: popGesture ?? _defaultPopGesture,
transition: transition ?? _defaultTransition,
fullscreenDialog: fullscreenDialog,
transitionDuration: duration ?? _defaultDurationTransition));
}
/// It replaces Navigator.pushNamed, but needs no context, and it doesn't have the Navigator.pushNamed
/// routes rebuild bug present in Flutter. If for some strange reason you want the default behavior
/// of rebuilding every app after a route, use opaque = true as the parameter.
static Future<T> toNamed<T>(String page, {arguments, int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id).currentState.pushNamed(page, arguments: arguments);
}
/// It replaces Navigator.pushReplacementNamed, but needs no context.
static Future<T> offNamed<T>(String page, {arguments, int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id)
.currentState
.pushReplacementNamed(page, arguments: arguments);
}
/// It replaces Navigator.popUntil, but needs no context.
static void until(predicate, {int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id).currentState.popUntil(predicate);
}
/// It replaces Navigator.pushAndRemoveUntil, but needs no context.
static Future<T> offUntil<T>(page, predicate, {int id}) {
// if (key.currentState.mounted) // add this if appear problems on future with route navigate
// when widget don't mounted
return global(id).currentState.pushAndRemoveUntil(page, predicate);
}
/// It replaces Navigator.pushNamedAndRemoveUntil, but needs no context.
static Future<T> offNamedUntil<T>(page, predicate, {int id}) {
return global(id).currentState.pushNamedAndRemoveUntil(page, predicate);
}
/// It replaces Navigator.popAndPushNamed, but needs no context.
static Future<T> offAndToNamed<T>(String page, {arguments, int id, result}) {
return global(id)
.currentState
.popAndPushNamed(page, arguments: arguments, result: result);
}
/// It replaces Navigator.removeRoute, but needs no context.
static void removeRoute(route, {int id}) {
return global(id).currentState.removeRoute(route);
}
/// It replaces Navigator.pushNamedAndRemoveUntil, but needs no context.
static Future<T> offAllNamed<T>(String newRouteName,
{RoutePredicate predicate, arguments, int id}) {
var route = (Route<dynamic> rota) => false;
return global(id).currentState.pushNamedAndRemoveUntil(
newRouteName, predicate ?? route,
arguments: arguments);
}
static bool get isOverlaysOpen =>
(isSnackbarOpen || isDialogOpen || isBottomSheetOpen);
static bool get isOverlaysClosed =>
(!Get.isSnackbarOpen && !Get.isDialogOpen && !Get.isBottomSheetOpen);
/// It replaces Navigator.pop, but needs no context.
static void back({dynamic result, bool closeOverlays = false, int id}) {
if (closeOverlays && isOverlaysOpen) {
navigator.popUntil((route) {
return (isOverlaysClosed);
});
}
global(id).currentState.pop(result);
}
// /// Experimental API to back from overlay
// static void backE({dynamic result}) {
// Navigator.pop(overlayContext);
// }
/// It will close as many screens as you define. Times must be> 0;
static void close(int times, [int id]) {
if ((times == null) || (times < 1)) {
times = 1;
}
int count = 0;
void back = global(id).currentState.popUntil((route) {
return count++ == times;
});
return back;
}
/// It replaces Navigator.pushReplacement, but needs no context, and it doesn't have the Navigator.pushReplacement
/// routes rebuild bug present in Flutter. If for some strange reason you want the default behavior
/// of rebuilding every app after a route, use opaque = true as the parameter.
static Future<T> off<T>(Widget page,
{bool opaque = false,
Transition transition,
bool popGesture,
int id,
Object arguments,
bool fullscreenDialog = false,
Duration duration}) {
return global(id).currentState.pushReplacement(GetRouteBase(
opaque: opaque ?? true,
page: page,
settings: RouteSettings(
name: '/' + page.toString().toLowerCase(), arguments: arguments),
fullscreenDialog: fullscreenDialog,
popGesture: popGesture ?? _defaultPopGesture,
transition: transition ?? _defaultTransition,
transitionDuration: duration ?? _defaultDurationTransition));
}
/// It replaces Navigator.pushAndRemoveUntil, but needs no context
static Future<T> offAll<T>(Widget page,
{RoutePredicate predicate,
bool opaque = false,
bool popGesture,
int id,
Object arguments,
bool fullscreenDialog = false,
Transition transition}) {
var route = (Route<dynamic> rota) => false;
return global(id).currentState.pushAndRemoveUntil(
GetRouteBase(
opaque: opaque ?? true,
popGesture: popGesture ?? _defaultPopGesture,
page: page,
settings: RouteSettings(
name: '/' + page.toString().toLowerCase(), arguments: arguments),
fullscreenDialog: fullscreenDialog,
transition: transition ?? _defaultTransition,
),
predicate ?? route);
}
/// Show a dialog
static Future<T> dialog<T>(
Widget child, {
bool barrierDismissible = true,
bool useRootNavigator = true,
// RouteSettings routeSettings
}) {
return showDialog(
barrierDismissible: barrierDismissible,
useRootNavigator: useRootNavigator,
routeSettings: RouteSettings(name: 'dialog'),
context: overlayContext,
builder: (_) {
return child;
},
);
}
/// Api from showGeneralDialog with no context
static Future<T> generalDialog<T>({
@required RoutePageBuilder pageBuilder,
bool barrierDismissible,
String barrierLabel,
Color barrierColor,
Duration transitionDuration,
RouteTransitionsBuilder transitionBuilder,
bool useRootNavigator = true,
RouteSettings routeSettings,
// RouteSettings routeSettings
}) {
return showGeneralDialog(
pageBuilder: pageBuilder,
barrierDismissible: barrierDismissible,
barrierLabel: barrierLabel,
barrierColor: barrierColor,
transitionDuration: transitionDuration,
transitionBuilder: transitionBuilder,
useRootNavigator: useRootNavigator,
routeSettings: RouteSettings(name: 'dialog'),
context: overlayContext,
);
}
static Future<T> defaultDialog<T>({
String title = "Alert",
Widget content,
VoidCallback onConfirm,
VoidCallback onCancel,
VoidCallback onCustom,
String textConfirm,
String textCancel,
String textCustom,
Widget confirm,
Widget cancel,
Widget custom,
Color backgroundColor,
Color buttonColor,
String middleText = "Dialog made in 3 lines of code",
double radius = 20.0,
List<Widget> actions,
}) {
bool leanCancel = onCancel != null || textCancel != null;
bool leanConfirm = onConfirm != null || textConfirm != null;
actions ??= [];
if (cancel != null) {
actions.add(cancel);
} else {
if (leanCancel) {
actions.add(FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
onPressed: () {
onCancel?.call();
Get.back();
},
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
child: Text(textCancel ?? "Cancel"),
shape: RoundedRectangleBorder(
side: BorderSide(
color: buttonColor ?? Get.theme.accentColor,
width: 2,
style: BorderStyle.solid),
borderRadius: BorderRadius.circular(100)),
));
}
}
if (confirm != null) {
actions.add(confirm);
} else {
if (leanConfirm) {
actions.add(FlatButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
color: buttonColor ?? Get.theme.accentColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100)),
child: Text(textConfirm ?? "Ok"),
onPressed: () {
onConfirm?.call();
}));
}
}
return Get.dialog(AlertDialog(
titlePadding: EdgeInsets.all(8),
contentPadding: EdgeInsets.all(8),
backgroundColor: backgroundColor ?? Get.theme.dialogBackgroundColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(radius))),
title: Text(title, textAlign: TextAlign.center),
content: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
content ?? Text(middleText ?? "", textAlign: TextAlign.center),
SizedBox(height: 16),
ButtonTheme(
minWidth: 78.0,
height: 34.0,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 8,
runSpacing: 8,
children: actions,
),
)
],
),
// actions: actions, // ?? <Widget>[cancelButton, confirmButton],
buttonPadding: EdgeInsets.zero,
));
}
static Future<T> bottomSheet<T>(
Widget bottomsheet, {
Color backgroundColor,
double elevation,
ShapeBorder shape,
Clip clipBehavior,
Color barrierColor,
bool ignoreSafeArea,
bool isScrollControlled = false,
bool useRootNavigator = false,
bool isDismissible = true,
bool enableDrag = true,
}) {
assert(bottomsheet != null);
assert(isScrollControlled != null);
assert(useRootNavigator != null);
assert(isDismissible != null);
assert(enableDrag != null);
return navigator.push<T>(GetModalBottomSheetRoute<T>(
builder: (_) => bottomsheet,
theme: Theme.of(Get.key.currentContext, shadowThemeOnly: true),
isScrollControlled: isScrollControlled,
barrierLabel: MaterialLocalizations.of(Get.key.currentContext)
.modalBarrierDismissLabel,
backgroundColor: backgroundColor ?? Colors.transparent,
elevation: elevation,
shape: shape,
removeTop: ignoreSafeArea ?? true,
clipBehavior: clipBehavior,
isDismissible: isDismissible,
modalBarrierColor: barrierColor,
settings: RouteSettings(name: "bottomsheet"),
enableDrag: enableDrag,
));
}
static void rawSnackbar(
{String title,
String message,
Widget titleText,
Widget messageText,
Widget icon,
bool instantInit = false,
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,
FlatButton mainButton,
OnTap onTap,
Duration duration = const Duration(seconds: 3),
bool isDismissible = true,
SnackDismissDirection dismissDirection = SnackDismissDirection.VERTICAL,
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),
SnackStatusCallback onStatusChanged,
double barBlur = 0.0,
double overlayBlur = 0.0,
Color overlayColor = Colors.transparent,
Form userInputForm}) {
GetBar getBar = GetBar(
title: title,
message: message,
titleText: titleText,
messageText: messageText,
snackPosition: snackPosition,
borderRadius: borderRadius,
margin: margin,
duration: duration,
barBlur: barBlur,
backgroundColor: backgroundColor,
icon: icon,
shouldIconPulse: shouldIconPulse,
maxWidth: maxWidth,
padding: padding,
borderColor: borderColor,
borderWidth: borderWidth,
leftBarIndicatorColor: leftBarIndicatorColor,
boxShadows: boxShadows,
backgroundGradient: backgroundGradient,
mainButton: mainButton,
onTap: onTap,
isDismissible: isDismissible,
dismissDirection: dismissDirection,
showProgressIndicator: showProgressIndicator ?? false,
progressIndicatorController: progressIndicatorController,
progressIndicatorBackgroundColor: progressIndicatorBackgroundColor,
progressIndicatorValueColor: progressIndicatorValueColor,
snackStyle: snackStyle,
forwardAnimationCurve: forwardAnimationCurve,
reverseAnimationCurve: reverseAnimationCurve,
animationDuration: animationDuration,
overlayBlur: overlayBlur,
overlayColor: overlayColor,
userInputForm: userInputForm);
if (instantInit) {
getBar.show();
} else {
SchedulerBinding.instance.addPostFrameCallback((_) {
getBar.show();
});
}
}
static void snackbar(title, message,
{Color colorText,
Duration duration,
/// with instantInit = false you can put Get.snackbar on initState
bool instantInit = false,
SnackPosition snackPosition,
Widget titleText,
Widget messageText,
Widget icon,
bool shouldIconPulse,
double maxWidth,
EdgeInsets margin,
EdgeInsets padding,
double borderRadius,
Color borderColor,
double borderWidth,
Color backgroundColor,
Color leftBarIndicatorColor,
List<BoxShadow> boxShadows,
Gradient backgroundGradient,
FlatButton mainButton,
OnTap onTap,
bool isDismissible,
bool showProgressIndicator,
SnackDismissDirection dismissDirection,
AnimationController progressIndicatorController,
Color progressIndicatorBackgroundColor,
Animation<Color> progressIndicatorValueColor,
SnackStyle snackStyle,
Curve forwardAnimationCurve,
Curve reverseAnimationCurve,
Duration animationDuration,
double barBlur,
double overlayBlur,
Color overlayColor,
Form userInputForm}) {
GetBar getBar = GetBar(
titleText: (title == null)
? null
: titleText ??
Text(
title,
style: TextStyle(
color: colorText ?? theme.iconTheme.color,
fontWeight: FontWeight.w800,
fontSize: 16),
),
messageText: messageText ??
Text(
message,
style: TextStyle(
color: colorText ?? theme.iconTheme.color,
fontWeight: FontWeight.w300,
fontSize: 14),
),
snackPosition: snackPosition ?? SnackPosition.TOP,
borderRadius: borderRadius ?? 15,
margin: margin ?? EdgeInsets.symmetric(horizontal: 10),
duration: duration ?? Duration(seconds: 3),
barBlur: barBlur ?? 7.0,
backgroundColor: backgroundColor ?? Colors.grey.withOpacity(0.2),
icon: icon,
shouldIconPulse: shouldIconPulse ?? true,
maxWidth: maxWidth,
padding: padding ?? EdgeInsets.all(16),
borderColor: borderColor,
borderWidth: borderWidth,
leftBarIndicatorColor: leftBarIndicatorColor,
boxShadows: boxShadows,
backgroundGradient: backgroundGradient,
mainButton: mainButton,
onTap: onTap,
isDismissible: isDismissible ?? true,
dismissDirection: dismissDirection ?? SnackDismissDirection.VERTICAL,
showProgressIndicator: showProgressIndicator ?? false,
progressIndicatorController: progressIndicatorController,
progressIndicatorBackgroundColor: progressIndicatorBackgroundColor,
progressIndicatorValueColor: progressIndicatorValueColor,
snackStyle: snackStyle ?? SnackStyle.FLOATING,
forwardAnimationCurve: forwardAnimationCurve ?? Curves.easeOutCirc,
reverseAnimationCurve: reverseAnimationCurve ?? Curves.easeOutCirc,
animationDuration: animationDuration ?? Duration(seconds: 1),
overlayBlur: overlayBlur ?? 0.0,
overlayColor: overlayColor ?? Colors.transparent,
userInputForm: userInputForm);
if (instantInit) {
getBar.show();
} else {
SchedulerBinding.instance.addPostFrameCallback((_) {
getBar.show();
});
}
}
/// change default config of Get
static void config(
{bool enableLog,
bool defaultPopGesture,
bool defaultOpaqueRoute,
Duration defaultDurationTransition,
bool defaultGlobalState,
Transition defaultTransition}) {
if (enableLog != null) {
_enableLog = enableLog;
}
if (defaultPopGesture != null) {
_defaultPopGesture = defaultPopGesture;
}
if (defaultOpaqueRoute != null) {
_defaultOpaqueRoute = defaultOpaqueRoute;
}
if (defaultTransition != null) {
_defaultTransition = defaultTransition;
}
if (defaultDurationTransition != null) {
_defaultDurationTransition = defaultDurationTransition;
}
if (defaultGlobalState != null) {
_defaultGlobalState = defaultGlobalState;
}
}
static GetMaterialController getController = GetMaterialController();
static changeTheme(ThemeData theme) {
getController.setTheme(theme);
}
static restartApp() {
getController.restartApp();
}
static Map<int, GlobalKey<NavigatorState>> _keys = {};
static GlobalKey<NavigatorState> nestedKey(int key) {
_keys.putIfAbsent(key, () => GlobalKey<NavigatorState>());
return _keys[key];
}
static GlobalKey<NavigatorState> global(int k) {
if (k == null) {
return key;
}
if (!_keys.containsKey(k)) {
throw 'route id not found';
}
return _keys[k];
}
//////////// INSTANCE MANAGER
Map<dynamic, dynamic> _singl = {};
Map<dynamic, _FcBuilderFunc> _factory = {};
static void lazyPut<S>(_FcBuilderFunc function) {
Get()._factory.putIfAbsent(S, () => function);
}
/// Inject class on Get Instance Manager
static S put<S>(
S dependency, {
String name,
bool overrideAbstract = false,
_FcBuilderFunc<S> builder,
}) {
_insert(
isSingleton: true,
replace: overrideAbstract,
//?? (("$S" == "${dependency.runtimeType}") == false),
name: name,
builder: builder ?? (() => dependency));
return find<S>(name: name);
}
/// Create a new instance from builder class
/// Example
/// Get.create(() => Repl());
/// Repl a = Get.find();
/// Repl b = Get.find();
/// print(a==b); (false)
static void create<S>(
_FcBuilderFunc<S> builder, {
String name,
}) {
_insert(isSingleton: false, name: name, builder: builder);
}
static void _insert<S>({
bool isSingleton,
String name,
bool replace = true,
_FcBuilderFunc<S> builder,
}) {
assert(builder != null);
String key = _getKey(S, name);
if (replace) {
Get()._singl[key] = _FcBuilder<S>(isSingleton, builder);
} else {
Get()._singl.putIfAbsent(key, () => _FcBuilder<S>(isSingleton, builder));
}
}
/// Find a instance from required class
static S find<S>({String name}) {
if (Get.isRegistred<S>()) {
String key = _getKey(S, name);
_FcBuilder builder = Get()._singl[key];
if (builder == null) {
if (name == null) {
throw "class ${S.toString()} is not register";
} else {
throw "class ${S.toString()} with name '$name' is not register";
}
}
return Get()._singl[key].getSependency();
} else {
if (!Get()._factory.containsKey(S))
throw " $S not found. You need call Get.put<$S>($S()) before";
if (isLogEnable) print('[GET] $S instance was created at that time');
S _value = Get.put<S>(Get()._factory[S].call() as S);
Get()._factory.remove(S);
return _value;
}
}
/// Remove dependency of [S] on dependency abstraction. For concrete class use Get.delete
static void remove<S>({String name}) {
String key = _getKey(S, name);
_FcBuilder builder = Get()._singl[key];
if (builder != null) builder.dependency = null;
if (Get()._singl.containsKey(key)) {
print('error on remove $key');
} else {
if (isLogEnable) print('[GET] $key removed from memory');
}
}
static String _getKey(Type type, String name) {
return name == null ? type.toString() : type.toString() + name;
}
static bool reset() {
Get()._singl.clear();
return true;
}
/// Delete class instance on [S] and clean memory
static bool delete<S>({String name}) {
String key = _getKey(S, name);
if (!Get()._singl.containsKey(key)) {
print('Instance $key not found');
return false;
}
Get()._singl.removeWhere((oldkey, value) => (oldkey == key));
if (Get()._singl.containsKey(key)) {
print('error on remove object $key');
} else {
if (isLogEnable) print('[GET] $key deleted from memory');
}
return true;
}
/// check if instance is registred
static bool isRegistred<S>({String name}) =>
Get()._singl.containsKey(_getKey(S, name));
/// give access to Routing API from GetObserver
static Routing get routing => _routing;
static RouteSettings get routeSettings => _settings;
static Routing _routing;
static Map<String, String> _parameters = {};
static setParameter(Map<String, String> param) {
_parameters = param;
}
static setRouting(Routing rt) {
_routing = rt;
}
static setSettings(RouteSettings settings) {
_settings = settings;
}
/// give current arguments
static get arguments => _routing.args;
/// give current arguments
static Map<String, String> get parameters => _parameters;
/// interface to GetX
RxInterface _obs;
static RxInterface get obs => _get._obs;
static set obs(RxInterface observer) => _get._obs = observer;
/// give arguments from previous route
static get previousArguments => _routing.previousArgs;
/// give name from current route
static get currentRoute => _routing.current;
/// give name from previous route
static get previousRoute => _routing.previous;
/// check if snackbar is open
static bool get isSnackbarOpen => _routing.isSnackbar;
/// check if dialog is open
static bool get isDialogOpen => _routing.isDialog;
/// check if bottomsheet is open
static bool get isBottomSheetOpen => _routing.isBottomSheet;
/// check a raw current route
static Route<dynamic> get rawRoute => _routing.route;
/// check if log is enable
static bool get isLogEnable => _enableLog;
/// default duration of transition animation
/// default duration work only API 2.0
static Duration get defaultDurationTransition => _defaultDurationTransition;
/// give global state of all GetState by default
static bool get defaultGlobalState => _defaultGlobalState;
/// check if popGesture is enable
static bool get isPopGestureEnable => _defaultPopGesture;
/// check if default opaque route is enable
static bool get isOpaqueRouteDefault => _defaultOpaqueRoute;
static Transition get defaultTransition => _defaultTransition;
/// give access to currentContext
static BuildContext get context => key.currentContext;
/// give access to current Overlay Context
static BuildContext get overlayContext => key.currentState.overlay.context;
/// give access to Theme.of(context)
static ThemeData get theme => Theme.of(context);
/// give access to TextTheme.of(context)
static TextTheme get textTheme => Theme.of(context).textTheme;
/// give access to Mediaquery.of(context)
static MediaQueryData get mediaQuery => MediaQuery.of(context);
/// Check if dark mode theme is enable
static get isDarkMode => (theme.brightness == Brightness.dark);
/// Check if dark mode theme is enable on platform on android Q+
static get isPlatformDarkMode =>
(mediaQuery.platformBrightness == Brightness.dark);
/// give access to Theme.of(context).iconTheme.color
static Color get iconColor => Theme.of(context).iconTheme.color;
/// give access to MediaQuery.of(context).size.height
static double get height => MediaQuery.of(context).size.height;
/// give access to MediaQuery.of(context).size.width
static double get width => MediaQuery.of(context).size.width;
}
/// It replaces the Flutter Navigator, but needs no context.
/// You can to use navigator.push(YourRoute()) rather Navigator.push(context, YourRoute());
NavigatorState get navigator => Get.key.currentState;
class _FcBuilder<S> {
bool isSingleton;
_FcBuilderFunc builderFunc;
S dependency;
_FcBuilder(this.isSingleton, this.builderFunc);
S getSependency() {
if (isSingleton) {
if (dependency == null) {
dependency = builderFunc() as S;
}
return dependency;
} else {
return builderFunc() as S;
}
}
}
typedef _FcBuilderFunc<S> = S Function();
... ...
... ... @@ -5,6 +5,7 @@ import 'package:get/src/routes/utils/parse_arguments.dart';
import 'root_controller.dart';
class GetMaterialApp extends StatelessWidget {
const GetMaterialApp({
Key key,
this.navigatorKey,
... ... @@ -99,13 +100,12 @@ class GetMaterialApp extends StatelessWidget {
Route<dynamic> namedRoutesGenerate(RouteSettings settings) {
Get.setSettings(settings);
// final parsedString = parse.split(settings.name);
/// onGenerateRoute to FlutterWeb is Broken on Dev/Master. This is a temporary
/// workaround until they fix it, because the problem is with the 'Flutter engine',
/// which changes the initial route for an empty String, not the main Flutter,
/// so only Team can fix it.
var parsedString = Get.getController.parse.split(
var parsedString = Get().getController.parse.split(
(settings.name == '' || settings.name == null)
? (initialRoute ?? '/')
: settings.name);
... ... @@ -119,7 +119,7 @@ class GetMaterialApp extends StatelessWidget {
Map<String, GetRoute> newNamedRoutes = {};
namedRoutes.forEach((key, value) {
String newName = Get.getController.parse.split(key).route;
String newName = Get().getController.parse.split(key).route;
newNamedRoutes.addAll({newName: value});
});
... ... @@ -171,7 +171,7 @@ class GetMaterialApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return GetBuilder<GetMaterialController>(
init: Get.getController,
init: Get().getController,
dispose: (d) {
onDispose?.call();
},
... ... @@ -179,7 +179,7 @@ class GetMaterialApp extends StatelessWidget {
onInit?.call();
if (namedRoutes != null) {
namedRoutes.forEach((key, value) {
Get.getController.parse.addRoute(key);
Get().getController.parse.addRoute(key);
});
}
Get.config(
... ... @@ -212,7 +212,7 @@ class GetMaterialApp extends StatelessWidget {
title: title ?? '',
onGenerateTitle: onGenerateTitle,
color: color,
theme: theme ?? _.theme ?? ThemeData.fallback(),
theme: _.theme ?? theme ?? ThemeData.fallback(),
darkTheme: darkTheme,
themeMode: themeMode ?? ThemeMode.system,
locale: locale,
... ...
typedef void ValueCallback<T>(T v);
... ...
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:get/src/get_main.dart';
import 'rx_impl.dart';
import 'rx_interface.dart';
class GetX<T extends RxController> extends StatefulWidget {
final Widget Function(T) builder;
final bool global;
final Stream Function(T) stream;
final StreamController Function(T) streamController;
final bool autoRemove;
final void Function(State state) initState, dispose, didChangeDependencies;
final T init;
GetX(
{this.builder,
this.global = true,
this.autoRemove = true,
this.initState,
this.stream,
this.dispose,
this.didChangeDependencies,
this.init,
this.streamController});
_GetXState<T> createState() => _GetXState<T>();
}
class _GetXState<T extends RxController> extends State<GetX<T>> {
RxInterface _observer;
StreamSubscription _listenSubscription;
T controller;
_GetXState() {
_observer = Rx();
}
@override
void initState() {
if (widget.global) {
if (Get.isRegistred<T>()) {
controller = Get.find<T>();
} else {
controller = widget.init;
Get.put<T>(controller);
}
} else {
controller = widget.init;
}
if (widget.initState != null) widget.initState(this);
try {
controller?.onInit();
} catch (e) {
if (Get.isLogEnable) print("Failure on call onInit");
}
_listenSubscription = _observer.subject.stream.listen((data) {
setState(() {});
});
super.initState();
}
@override
void dispose() {
controller?.close();
_listenSubscription?.cancel();
_observer?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
_observer.close();
final observer = Get.obs;
Get.obs = this._observer;
final result = widget.builder(controller);
Get.obs = observer;
return result;
}
}
... ...
import 'dart:async';
import 'package:get/src/get_main.dart';
import 'rx_callbacks.dart';
import 'rx_interface.dart';
import 'rx_model.dart';
import 'utils/delegate_list.dart';
class _StoredValue<T> implements RxInterface<T> {
StreamController<Change<T>> subject = StreamController<Change<T>>.broadcast();
StreamController<Change<T>> _changeCtl = StreamController<Change<T>>();
Map<Stream<Change<T>>, StreamSubscription> _subscriptions = Map();
T _value;
T get value {
if (Get.obs != null) {
Get.obs.addListener(subject.stream);
}
return _value;
}
String get string => value.toString();
close() {
_subscriptions.forEach((observable, subscription) {
subscription.cancel();
});
_subscriptions.clear();
_changeCtl.close();
}
addListener(Stream<Change<T>> rxGetx) {
if (_subscriptions.containsKey(rxGetx)) {
return;
}
_subscriptions[rxGetx] = rxGetx.listen((data) {
subject.add(data);
});
}
set value(T val) {
if (_value == val) return;
T old = _value;
_value = val;
subject.add(Change<T>($new: val, $old: old, batch: _cb));
}
int _cb = 0;
_StoredValue([T initial]) : _value = initial {
_onChange = subject.stream.asBroadcastStream();
}
void setCast(dynamic /* T */ val) => value = val;
Stream<Change<T>> _onChange;
Stream<Change<T>> get onChange {
_cb++;
_changeCtl.add(Change<T>($new: value, $old: null, batch: _cb));
_changeCtl.addStream(_onChange.skipWhile((v) => v.batch < _cb));
return _changeCtl.stream.asBroadcastStream();
}
Stream<T> get stream => onChange.map((c) => c.$new);
void bind(RxInterface<T> reactive) {
value = reactive.value;
reactive.stream.listen((v) => value = v);
}
void bindStream(Stream<T> stream) => stream.listen((v) => value = v);
void bindOrSet(/* T | Stream<T> | Reactive<T> */ other) {
if (other is RxInterface<T>) {
bind(other);
} else if (other is Stream<T>) {
bindStream(other.cast<T>());
} else {
value = other;
}
}
StreamSubscription<T> listen(ValueCallback<T> callback) =>
stream.listen(callback);
Stream<R> map<R>(R mapper(T data)) => stream.map(mapper);
}
class StringX<String> extends _StoredValue<String> {
StringX([String initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
class IntX<int> extends _StoredValue<int> {
IntX([int initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
class MapX<Map> extends _StoredValue<Map> {
MapX([Map initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
// class ListX<List> extends _StoredValue<List> {
// ListX([List initial]) {
// _value = initial;
// _onChange = subject.stream.asBroadcastStream();
// }
// }
class ListX<E> extends DelegatingList<E> implements List<E>, RxInterface<E> {
/// Create a list similar to `List<T>`
ListX([int length]) : super(length != null ? List<E>(length) : List<E>()) {
_onChange = subject.stream.asBroadcastStream();
}
ListX.filled(int length, E fill, {bool growable: false})
: super(List<E>.filled(length, fill, growable: growable)) {
_onChange = subject.stream.asBroadcastStream();
}
ListX.from(Iterable<E> items, {bool growable: true})
: super(List<E>.from(items, growable: growable)) {
_onChange = subject.stream.asBroadcastStream();
}
ListX.union(Iterable<E> items, [E item]) : super(items?.toList() ?? <E>[]) {
if (item != null) add(item);
_onChange = subject.stream.asBroadcastStream();
}
ListX.of(Iterable<E> items, {bool growable: true})
: super(List<E>.of(items, growable: growable));
ListX.generate(int length, E generator(int index), {bool growable: true})
: super(List<E>.generate(length, generator, growable: growable));
Map<Stream<Change<E>>, StreamSubscription> _subscriptions = Map();
final _changeCtl = StreamController<Change<E>>();
/// Adds [item] only if [condition] resolves to true.
void addIf(condition, E item) {
if (condition is Condition) condition = condition();
if (condition is bool && condition) add(item);
}
/// Adds all [items] only if [condition] resolves to true.
void addAllIf(condition, Iterable<E> items) {
if (condition is Condition) condition = condition();
if (condition is bool && condition) addAll(items);
}
operator []=(int index, E value) {
super[index] = value;
subject.add(Change<E>.set(item: value, pos: index));
}
void _add(E item) => super.add(item);
void add(E item) {
super.add(item);
subject.add(Change<E>.insert(item: item, pos: length - 1));
}
/// Adds only if [item] is not null.
void addNonNull(E item) {
if (item != null) add(item);
}
void insert(int index, E item) {
super.insert(index, item);
subject.add(Change<E>.insert(item: item, pos: index));
}
bool remove(Object item) {
int pos = indexOf(item);
bool hasRemoved = super.remove(item);
if (hasRemoved) {
subject.add(Change<E>.remove(item: item, pos: pos));
}
return hasRemoved;
}
void clear() {
super.clear();
subject.add(Change<E>.clear());
}
close() {
_subscriptions.forEach((observable, subscription) {
subscription.cancel();
});
_subscriptions.clear();
subject.close();
_changeCtl.close();
}
/// Replaces all existing items of this list with [item]
void assign(E item) {
clear();
add(item);
}
/// Replaces all existing items of this list with [items]
void assignAll(Iterable<E> items) {
clear();
addAll(items);
}
/// A stream of record of changes to this list
Stream<Change<E>> get onChange {
final now = DateTime.now();
_changeCtl.addStream(_onChange.skipWhile((m) => m.time.isBefore(now)));
return _changeCtl.stream.asBroadcastStream();
}
Stream<Change<E>> _onChange;
@override
StreamController<Change<E>> subject = StreamController<Change<E>>();
addListener(Stream<Change<E>> rxGetx) {
if (_subscriptions.containsKey(rxGetx)) {
return;
}
_subscriptions[rxGetx] = rxGetx.listen((data) {
subject.add(data);
});
}
@override
var value;
@override
Stream<E> get stream => onChange.map((c) => c.item);
@override
void bind(RxInterface<E> reactive) {
value = reactive.value;
reactive.stream.listen((v) => value = v);
}
void bindStream(Stream<E> stream) => stream.listen((v) => value = v);
@override
void bindOrSet(/* T | Stream<T> | Rx<T> */ other) {
if (other is RxInterface<E>) {
bind(other);
} else if (other is Stream<E>) {
bindStream(other.cast<E>());
} else {
value = other;
}
}
@override
StreamSubscription<E> listen(ValueCallback<E> callback) =>
stream.listen(callback);
@override
void setCast(dynamic /* T */ val) => value = val;
}
typedef bool Condition();
typedef E ChildrenListComposer<S, E>(S value);
/// An observable list that is bound to another list [binding]
class BoundList<S, E> extends ListX<E> {
final ListX<S> binding;
final ChildrenListComposer<S, E> composer;
BoundList(this.binding, this.composer) {
for (S v in binding) _add(composer(v));
binding.onChange.listen((Change<S> n) {
if (n.op == ListChangeOp.add) {
insert(n.pos, composer(n.item));
} else if (n.op == ListChangeOp.remove) {
removeAt(n.pos);
} else if (n.op == ListChangeOp.clear) {
clear();
}
});
}
}
class BoolX<bool> extends _StoredValue<bool> {
BoolX([bool initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
class DoubleX<double> extends _StoredValue<double> {
DoubleX([double initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
class NumX<num> extends _StoredValue<num> {
NumX([num initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
class Rx<T> extends _StoredValue<T> {
Rx([T initial]) {
_value = initial;
_onChange = subject.stream.asBroadcastStream();
}
}
extension StringExtension on String {
StringX<String> get obs {
if (this != null)
return StringX(this);
else
return StringX(null);
}
}
extension IntExtension on int {
IntX<int> get obs {
if (this != null)
return IntX(this);
else
return IntX(null);
}
}
extension DoubleExtension on double {
DoubleX<double> get obs {
if (this != null)
return DoubleX(this);
else
return DoubleX(null);
}
}
extension MapExtension on Map {
MapX<Map> get obs {
if (this != null)
return MapX(this);
else
return MapX(null);
}
}
extension ListExtension on List {
ListX get obs {
if (this != null)
return ListX()..assignAll(this);
else
return ListX(null);
}
}
extension BoolExtension on bool {
BoolX<bool> get obs {
if (this != null)
return BoolX(this);
else
return BoolX(null);
}
}
extension ObjectExtension on Object {
Rx<Object> get obs {
if (this != null)
return Rx(this);
else
return Rx(null);
}
}
... ...
import 'dart:async';
import 'package:get/src/rx/rx_callbacks.dart';
import 'package:get/src/rx/rx_model.dart';
abstract class RxInterface<T> {
RxInterface([T initial]);
/// Get current value
T get value;
/// Set value
set value(T val);
/// Cast [val] to [T] before setting
void setCast(dynamic /* T */ val);
/// Stream of record of [Change]s of value
Stream<Change<T>> get onChange;
/// add listener to stream
addListener(Stream<Change<T>> rxGetx);
/// close stream
close() {
subject?.close();
}
StreamController<Change<T>> subject;
/// Stream of changes of value
Stream<T> get stream;
/// Convert value on string
// String get string;
/// Binds if [other] is [Stream] or [RxInterface] of type [T]. Sets if [other] is
/// instance of [T]
void bindOrSet(/* T | Stream<T> | Reactive<T> */ other);
/// Binds [other] to this
void bind(RxInterface<T> other);
/// Binds the [stream] to this
void bindStream(Stream<T> stream);
/// Calls [callback] with current value, when the value changes.
StreamSubscription<T> listen(ValueCallback<T> callback);
/// Maps the changes into a [Stream] of [S]
// Stream<S> map<S>(S mapper(T data));
}
class RxController implements DisposableInterface {
void onInit() async {}
void close() async {}
}
abstract class DisposableInterface {
void close() async {}
void onInit() async {}
}
... ...
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:get/src/get_main.dart';
import 'rx_impl.dart';
import 'rx_interface.dart';
class ListViewX<T extends RxController> extends StatefulWidget {
final Widget Function(T, int) builder;
final bool global;
final ListX Function(T) list;
final bool autoRemove;
final void Function(State state) initState, dispose, didChangeDependencies;
final T init;
final int itemCount;
ListViewX({
this.builder,
this.global = true,
this.autoRemove = true,
this.initState,
@required this.list,
this.itemCount,
this.dispose,
this.didChangeDependencies,
this.init,
});
_ListViewXState<T> createState() => _ListViewXState<T>();
}
class _ListViewXState<T extends RxController> extends State<ListViewX<T>> {
RxInterface _observer;
StreamSubscription _listenSubscription;
T controller;
_ListViewXState() {
_observer = ListX();
}
@override
void initState() {
if (widget.global) {
if (Get.isRegistred<T>()) {
controller = Get.find<T>();
} else {
controller = widget.init;
Get.put<T>(controller);
}
} else {
controller = widget.init;
}
if (widget.initState != null) widget.initState(this);
try {
controller?.onInit();
} catch (e) {
if (Get.isLogEnable) print("Failure on call onInit");
}
_listenSubscription = widget.list.call(controller).listen((data) {
setState(() {});
});
super.initState();
}
@override
void dispose() {
controller?.close();
_listenSubscription?.cancel();
_observer?.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
_observer.close();
final observer = Get.obs;
Get.obs = this._observer;
final result = ListView.builder(
itemCount: widget.itemCount ?? widget.list.call(controller).length,
itemBuilder: (context, index) {
return widget.builder(controller, index);
});
Get.obs = observer;
return result;
}
}
... ...
class Change<T> {
/// Value before change
final T $old;
/// Value after change
final T $new;
final T item;
final ListChangeOp op;
final int pos;
final DateTime time;
final int batch;
Change(
{this.$new,
this.$old,
this.batch,
this.item,
this.op,
this.pos,
DateTime time})
: time = time ?? DateTime.now();
String toString() => 'Change(new: ${$new}, old: ${$old})';
Change.insert(
{this.$new, this.$old, this.batch, this.item, this.pos, DateTime time})
: op = ListChangeOp.add,
time = time ?? new DateTime.now();
Change.set(
{this.$new, this.$old, this.batch, this.item, this.pos, DateTime time})
: op = ListChangeOp.set,
time = time ?? new DateTime.now();
Change.remove(
{this.$new, this.$old, this.batch, this.item, this.pos, DateTime time})
: op = ListChangeOp.remove,
time = time ?? new DateTime.now();
Change.clear({this.$new, this.$old, this.batch, DateTime time})
: op = ListChangeOp.clear,
pos = null,
item = null,
time = time ?? new DateTime.now();
}
typedef bool Condition();
typedef E ChildrenListComposer<S, E>(S value);
/// Change operation
enum ListChangeOp { add, remove, clear, set }
... ...
import 'dart:math' as math;
class DelegatingList<E> extends DelegatingIterable<E> implements List<E> {
const DelegatingList(List<E> base) : super(base);
List<E> get _listBase => _base;
E operator [](int index) => _listBase[index];
void operator []=(int index, E value) {
_listBase[index] = value;
}
List<E> operator +(List<E> other) => _listBase + other;
void add(E value) {
_listBase.add(value);
}
void addAll(Iterable<E> iterable) {
_listBase.addAll(iterable);
}
Map<int, E> asMap() => _listBase.asMap();
List<T> cast<T>() => _listBase.cast<T>();
void clear() {
_listBase.clear();
}
void fillRange(int start, int end, [E fillValue]) {
_listBase.fillRange(start, end, fillValue);
}
set first(E value) {
if (this.isEmpty) throw RangeError.index(0, this);
this[0] = value;
}
Iterable<E> getRange(int start, int end) => _listBase.getRange(start, end);
int indexOf(E element, [int start = 0]) => _listBase.indexOf(element, start);
int indexWhere(bool test(E element), [int start = 0]) =>
_listBase.indexWhere(test, start);
void insert(int index, E element) {
_listBase.insert(index, element);
}
insertAll(int index, Iterable<E> iterable) {
_listBase.insertAll(index, iterable);
}
set last(E value) {
if (this.isEmpty) throw RangeError.index(0, this);
this[this.length - 1] = value;
}
int lastIndexOf(E element, [int start]) =>
_listBase.lastIndexOf(element, start);
int lastIndexWhere(bool test(E element), [int start]) =>
_listBase.lastIndexWhere(test, start);
set length(int newLength) {
_listBase.length = newLength;
}
bool remove(Object value) => _listBase.remove(value);
E removeAt(int index) => _listBase.removeAt(index);
E removeLast() => _listBase.removeLast();
void removeRange(int start, int end) {
_listBase.removeRange(start, end);
}
void removeWhere(bool test(E element)) {
_listBase.removeWhere(test);
}
void replaceRange(int start, int end, Iterable<E> iterable) {
_listBase.replaceRange(start, end, iterable);
}
void retainWhere(bool test(E element)) {
_listBase.retainWhere(test);
}
@deprecated
List<T> retype<T>() => cast<T>();
Iterable<E> get reversed => _listBase.reversed;
void setAll(int index, Iterable<E> iterable) {
_listBase.setAll(index, iterable);
}
void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) {
_listBase.setRange(start, end, iterable, skipCount);
}
void shuffle([math.Random random]) {
_listBase.shuffle(random);
}
void sort([int compare(E a, E b)]) {
_listBase.sort(compare);
}
List<E> sublist(int start, [int end]) => _listBase.sublist(start, end);
}
class DelegatingIterable<E> extends _DelegatingIterableBase<E> {
final Iterable<E> _base;
const DelegatingIterable(Iterable<E> base) : _base = base;
}
abstract class _DelegatingIterableBase<E> implements Iterable<E> {
Iterable<E> get _base;
const _DelegatingIterableBase();
bool any(bool test(E element)) => _base.any(test);
Iterable<T> cast<T>() => _base.cast<T>();
bool contains(Object element) => _base.contains(element);
E elementAt(int index) => _base.elementAt(index);
bool every(bool test(E element)) => _base.every(test);
Iterable<T> expand<T>(Iterable<T> f(E element)) => _base.expand(f);
E get first => _base.first;
E firstWhere(bool test(E element), {E orElse()}) =>
_base.firstWhere(test, orElse: orElse);
T fold<T>(T initialValue, T combine(T previousValue, E element)) =>
_base.fold(initialValue, combine);
Iterable<E> followedBy(Iterable<E> other) => _base.followedBy(other);
void forEach(void f(E element)) => _base.forEach(f);
bool get isEmpty => _base.isEmpty;
bool get isNotEmpty => _base.isNotEmpty;
Iterator<E> get iterator => _base.iterator;
String join([String separator = ""]) => _base.join(separator);
E get last => _base.last;
E lastWhere(bool test(E element), {E orElse()}) =>
_base.lastWhere(test, orElse: orElse);
int get length => _base.length;
Iterable<T> map<T>(T f(E element)) => _base.map(f);
E reduce(E combine(E value, E element)) => _base.reduce(combine);
@deprecated
Iterable<T> retype<T>() => cast<T>();
E get single => _base.single;
E singleWhere(bool test(E element), {E orElse()}) {
return _base.singleWhere(test, orElse: orElse);
}
Iterable<E> skip(int n) => _base.skip(n);
Iterable<E> skipWhile(bool test(E value)) => _base.skipWhile(test);
Iterable<E> take(int n) => _base.take(n);
Iterable<E> takeWhile(bool test(E value)) => _base.takeWhile(test);
List<E> toList({bool growable = true}) => _base.toList(growable: growable);
Set<E> toSet() => _base.toSet();
Iterable<E> where(bool test(E element)) => _base.where(test);
Iterable<T> whereType<T>() => _base.whereType<T>();
String toString() => _base.toString();
}
... ...
... ... @@ -32,6 +32,8 @@ class GetController extends State {
}
}
void close() {}
@override
Widget build(_) => throw ("build method can't be called");
}
... ... @@ -86,14 +88,24 @@ class _GetBuilderState<T extends GetController> extends State<GetBuilder<T>> {
}
} else {
controller = widget.init;
if (controller._allStates[controller] == null) {
controller._allStates[controller] = [];
}
controller._allStates[controller]
.add(RealState(state: this, id: widget.id));
}
if (widget.initState != null) widget.initState(this);
try {
controller?.initState();
} catch (e) {
if (Get.isLogEnable) print("Controller is not attach");
}
}
@override
void dispose() {
void dispose() async {
super.dispose();
if (widget.init != null) {
var b = controller;
if (b._allStates[controller].hashCode == this.hashCode) {
... ... @@ -109,6 +121,7 @@ class _GetBuilderState<T extends GetController> extends State<GetBuilder<T>> {
if (widget.init != null) {
if (widget.autoRemove && Get.isRegistred<T>()) {
controller.close();
Get.delete<T>();
}
} else {
... ... @@ -116,8 +129,6 @@ class _GetBuilderState<T extends GetController> extends State<GetBuilder<T>> {
controller._allStates[controller]
.remove(RealState(state: this, id: widget.id));
}
super.dispose();
}
@override
... ...
name: get
description: Open screens/snackbars/dialogs/bottomSheets without context, manage states and inject dependencies easily with Get.
version: 2.2.6
version: 2.5.0
homepage: https://github.com/jonataslaw/get
environment:
sdk: ">=2.1.0 <3.0.0"
sdk: ">=2.6.0 <3.0.0"
dependencies:
flutter:
... ...