Git Product home page Git Product logo

jonataslaw / getx Goto Github PK

View Code? Open in Web Editor NEW
9.8K 134.0 1.6K 33.29 MB

Open screens/snackbars/dialogs/bottomSheets without context, manage states and inject dependencies easily with Get.

License: MIT License

Dart 93.97% Kotlin 0.02% Swift 0.14% Objective-C 0.08% HTML 0.45% CMake 2.06% C++ 2.95% C 0.17% Java 0.06% Shell 0.10%
getx dependency-injection flutter state-management routes internationalization framework mobile web dart

getx's Introduction

pub package popularity likes pub points building style: effective dart Discord Shield Get on Slack Telegram Awesome Flutter Buy Me A Coffee

Languages:

English Vietnamese Indonesian Urdu Chinese Portuguese Spanish Russian Polish Korean French Japanese Hindi Bangla

About Get

  • GetX is an extra-light and powerful solution for Flutter. It combines high-performance state management, intelligent dependency injection, and route management quickly and practically.

  • GetX has 3 basic principles. This means that these are the priority for all resources in the library: PRODUCTIVITY, PERFORMANCE AND ORGANIZATION.

    • PERFORMANCE: GetX is focused on performance and minimum consumption of resources. GetX does not use Streams or ChangeNotifier.

    • PRODUCTIVITY: GetX uses an easy and pleasant syntax. No matter what you want to do, there is always an easier way with GetX. It will save hours of development and will provide the maximum performance your application can deliver.

      Generally, the developer should be concerned with removing controllers from memory. With GetX this is not necessary because resources are removed from memory when they are not used by default. If you want to keep it in memory, you must explicitly declare "permanent: true" in your dependency. That way, in addition to saving time, you are less at risk of having unnecessary dependencies on memory. Dependency loading is also lazy by default.

    • ORGANIZATION: GetX allows the total decoupling of the View, presentation logic, business logic, dependency injection, and navigation. You do not need context to navigate between routes, so you are not dependent on the widget tree (visualization) for this. You don't need context to access your controllers/blocs through an inheritedWidget, so you completely decouple your presentation logic and business logic from your visualization layer. You do not need to inject your Controllers/Models/Blocs classes into your widget tree through MultiProviders. For this, GetX uses its own dependency injection feature, decoupling the DI from its view completely.

      With GetX you know where to find each feature of your application, having clean code by default. In addition to making maintenance easy, this makes the sharing of modules something that until then in Flutter was unthinkable, something totally possible. BLoC was a starting point for organizing code in Flutter, it separates business logic from visualization. GetX is a natural evolution of this, not only separating the business logic but the presentation logic. Bonus injection of dependencies and routes are also decoupled, and the data layer is out of it all. You know where everything is, and all of this in an easier way than building a hello world. GetX is the easiest, practical, and scalable way to build high-performance applications with the Flutter SDK. It has a large ecosystem around it that works perfectly together, it's easy for beginners, and it's accurate for experts. It is secure, stable, up-to-date, and offers a huge range of APIs built-in that are not present in the default Flutter SDK.

  • GetX is not bloated. It has a multitude of features that allow you to start programming without worrying about anything, but each of these features are in separate containers and are only started after use. If you only use State Management, only State Management will be compiled. If you only use routes, nothing from the state management will be compiled.

  • GetX has a huge ecosystem, a large community, a large number of collaborators, and will be maintained as long as the Flutter exists. GetX too is capable of running with the same code on Android, iOS, Web, Mac, Linux, Windows, and on your server. It is possible to fully reuse your code made on the frontend on your backend with Get Server.

In addition, the entire development process can be completely automated, both on the server and on the front end with Get CLI.

In addition, to further increase your productivity, we have the extension to VSCode and the extension to Android Studio/Intellij

Installing

Add Get to your pubspec.yaml file:

dependencies:
  get:

Import get in files that it will be used:

import 'package:get/get.dart';

Counter App with GetX

The "counter" project created by default on new project on Flutter has over 100 lines (with comments). To show the power of Get, I will demonstrate how to make a "counter" changing the state with each click, switching between pages and sharing the state between screens, all in an organized way, separating the business logic from the view, in ONLY 26 LINES CODE INCLUDING COMMENTS.

  • Step 1: Add "Get" before your MaterialApp, turning it into GetMaterialApp
void main() => runApp(GetMaterialApp(home: Home()));
  • Note: this does not modify the MaterialApp of the Flutter, GetMaterialApp is not a modified MaterialApp, it is just a pre-configured Widget, which has the default MaterialApp as a child. You can configure this manually, but it is definitely not necessary. GetMaterialApp will create routes, inject them, inject translations, inject everything you need for route navigation. If you use Get only for state management or dependency management, it is not necessary to use GetMaterialApp. GetMaterialApp is necessary for routes, snackbars, internationalization, bottomSheets, dialogs, and high-level apis related to routes and absence of context.

  • Note²: This step is only necessary if you gonna use route management (Get.to(), Get.back() and so on). If you not gonna use it then it is not necessary to do step 1

  • Step 2: Create your business logic class and place all variables, methods and controllers inside it. You can make any variable observable using a simple ".obs".

class Controller extends GetxController{
  var count = 0.obs;
  increment() => count++;
}
  • Step 3: Create your View, use StatelessWidget and save some RAM, with Get you may no longer need to use StatefulWidget.
class Home extends StatelessWidget {

  @override
  Widget build(context) {

    // Instantiate your class using Get.put() to make it available for all "child" routes there.
    final Controller c = Get.put(Controller());

    return Scaffold(
      // Use Obx(()=> to update Text() whenever count is changed.
      appBar: AppBar(title: Obx(() => Text("Clicks: ${c.count}"))),

      // Replace the 8 lines Navigator.push by a simple Get.to(). You don't need context
      body: Center(child: ElevatedButton(
              child: Text("Go to Other"), onPressed: () => Get.to(Other()))),
      floatingActionButton:
          FloatingActionButton(child: Icon(Icons.add), onPressed: c.increment));
  }
}

class Other extends StatelessWidget {
  // You can ask Get to find a Controller that is being used by another page and redirect you to it.
  final Controller c = Get.find();

  @override
  Widget build(context){
     // Access the updated count variable
     return Scaffold(body: Center(child: Text("${c.count}")));
  }
}

Result:

This is a simple project but it already makes clear how powerful Get is. As your project grows, this difference will become more significant.

Get was designed to work with teams, but it makes the job of an individual developer simple.

Improve your deadlines, deliver everything on time without losing performance. Get is not for everyone, but if you identified with that phrase, Get is for you!

The Three pillars

State management

Get has two different state managers: the simple state manager (we'll call it GetBuilder) and the reactive state manager (GetX/Obx)

Reactive State Manager

Reactive programming can alienate many people because it is said to be complicated. GetX turns reactive programming into something quite simple:

  • You won't need to create StreamControllers.
  • You won't need to create a StreamBuilder for each variable
  • You will not need to create a class for each state.
  • You will not need to create a get for an initial value.
  • You will not need to use code generators

Reactive programming with Get is as easy as using setState.

Let's imagine that you have a name variable and want that every time you change it, all widgets that use it are automatically changed.

This is your count variable:

var name = 'Jonatas Borges';

To make it observable, you just need to add ".obs" to the end of it:

var name = 'Jonatas Borges'.obs;

And in the UI, when you want to show that value and update the screen whenever the values changes, simply do this:

Obx(() => Text("${controller.name}"));

That's all. It's that simple.

More details about state management

See an more in-depth explanation of state management here. There you will see more examples and also the difference between the simple state manager and the reactive state manager

You will get a good idea of GetX power.

Route management

If you are going to use routes/snackbars/dialogs/bottomsheets without context, GetX is excellent for you too, just see it:

Add "Get" before your MaterialApp, turning it into GetMaterialApp

GetMaterialApp( // Before: MaterialApp(
  home: MyHome(),
)

Navigate to a new screen:

Get.to(NextScreen());

Navigate to new screen with name. See more details on named routes here

Get.toNamed('/details');

To close snackbars, dialogs, bottomsheets, or anything you would normally close with Navigator.pop(context);

Get.back();

To go to the next screen and no option to go back to the previous screen (for use in SplashScreens, login screens, etc.)

Get.off(NextScreen());

To go to the next screen and cancel all previous routes (useful in shopping carts, polls, and tests)

Get.offAll(NextScreen());

Noticed that you didn't have to use context to do any of these things? That's one of the biggest advantages of using Get route management. With this, you can execute all these methods from within your controller class, without worries.

More details about route management

Get works with named routes and also offers lower-level control over your routes! There is in-depth documentation here

Dependency management

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:

Controller controller = Get.put(Controller()); // Rather Controller controller = Controller();
  • Note: If you are using Get's State Manager, pay more attention to the bindings API, which will make it easier to connect your view to your controller.

Instead of instantiating your class within the class you are using, you are instantiating it within the Get instance, which will make it available throughout your App. So you can use your controller (or class Bloc) normally

Tip: Get dependency management is decoupled from other parts of the package, so if for example, your app is already using a state manager (any one, it doesn't matter), you don't need to rewrite it all, you can use this dependency injection with no problems at all

controller.fetchApi();

Imagine that you have navigated through numerous routes, and you need data that was left behind in your controller, you would need a state manager combined with the Provider or Get_it, correct? Not with Get. You just need to ask Get to "find" for your controller, you don't need any additional dependencies:

Controller controller = Get.find();
//Yes, it looks like Magic, Get will find your controller, and will deliver it to you. You can have 1 million controllers instantiated, Get will always give you the right controller.

And then you will be able to recover your controller data that was obtained back there:

Text(controller.textFromApi);

More details about dependency management

See a more in-depth explanation of dependency management here

Utils

Internationalization

Translations

Translations are kept as a simple key-value dictionary map. To add custom translations, create a class and extend Translations.

import 'package:get/get.dart';

class Messages extends Translations {
  @override
  Map<String, Map<String, String>> get keys => {
        'en_US': {
          'hello': 'Hello World',
        },
        'de_DE': {
          'hello': 'Hallo Welt',
        }
      };
}

Using translations

Just append .tr to the specified key and it will be translated, using the current value of Get.locale and Get.fallbackLocale.

Text('title'.tr);

Using translation with singular and plural

var products = [];
Text('singularKey'.trPlural('pluralKey', products.length, Args));

Using translation with parameters

import 'package:get/get.dart';


Map<String, Map<String, String>> get keys => {
    'en_US': {
        'logged_in': 'logged in as @name with email @email',
    },
    'es_ES': {
       'logged_in': 'iniciado sesión como @name con e-mail @email',
    }
};

Text('logged_in'.trParams({
  'name': 'Jhon',
  'email': '[email protected]'
  }));

Locales

Pass parameters to GetMaterialApp to define the locale and translations.

return GetMaterialApp(
    translations: Messages(), // your translations
    locale: Locale('en', 'US'), // translations will be displayed in that locale
    fallbackLocale: Locale('en', 'UK'), // specify the fallback locale in case an invalid locale is selected.
);

Change locale

Call Get.updateLocale(locale) to update the locale. Translations then automatically use the new locale.

var locale = Locale('en', 'US');
Get.updateLocale(locale);

System locale

To read the system locale, you could use Get.deviceLocale.

return GetMaterialApp(
    locale: Get.deviceLocale,
);

Change Theme

Please do not use any higher level widget than GetMaterialApp in order to update it. This can trigger duplicate keys. A lot of people are used to the prehistoric approach of creating a "ThemeProvider" widget just to change the theme of your app, and this is definitely NOT necessary with GetX™.

You can create your custom theme and simply add it within Get.changeTheme without any boilerplate for that:

Get.changeTheme(ThemeData.light());

If you want to create something like a button that changes the Theme in onTap, you can combine two GetX™ APIs for that:

  • The api that checks if the dark Theme is being used.
  • And the Theme Change API, you can just put this within an onPressed:
Get.changeTheme(Get.isDarkMode? ThemeData.light(): ThemeData.dark());

When .darkmode is activated, it will switch to the light theme, and when the light theme becomes active, it will change to dark theme.

GetConnect

GetConnect is an easy way to communicate from your back to your front with http or websockets

Default configuration

You can simply extend GetConnect and use the GET/POST/PUT/DELETE/SOCKET methods to communicate with your Rest API or websockets.

class UserProvider extends GetConnect {
  // Get request
  Future<Response> getUser(int id) => get('http://youapi/users/$id');
  // Post request
  Future<Response> postUser(Map data) => post('http://youapi/users', body: data);
  // Post request with File
  Future<Response<CasesModel>> postCases(List<int> image) {
    final form = FormData({
      'file': MultipartFile(image, filename: 'avatar.png'),
      'otherFile': MultipartFile(image, filename: 'cover.png'),
    });
    return post('http://youapi/users/upload', form);
  }

  GetSocket userMessages() {
    return socket('https://yourapi/users/socket');
  }
}

Custom configuration

GetConnect is highly customizable You can define base Url, as answer modifiers, as Requests modifiers, define an authenticator, and even the number of attempts in which it will try to authenticate itself, in addition to giving the possibility to define a standard decoder that will transform all your requests into your Models without any additional configuration.

class HomeProvider extends GetConnect {
  @override
  void onInit() {
    // All request will pass to jsonEncode so CasesModel.fromJson()
    httpClient.defaultDecoder = CasesModel.fromJson;
    httpClient.baseUrl = 'https://api.covid19api.com';
    // baseUrl = 'https://api.covid19api.com'; // It define baseUrl to
    // Http and websockets if used with no [httpClient] instance

    // It's will attach 'apikey' property on header from all requests
    httpClient.addRequestModifier((request) {
      request.headers['apikey'] = '12345678';
      return request;
    });

    // Even if the server sends data from the country "Brazil",
    // it will never be displayed to users, because you remove
    // that data from the response, even before the response is delivered
    httpClient.addResponseModifier<CasesModel>((request, response) {
      CasesModel model = response.body;
      if (model.countries.contains('Brazil')) {
        model.countries.remove('Brazilll');
      }
    });

    httpClient.addAuthenticator((request) async {
      final response = await get("http://yourapi/token");
      final token = response.body['token'];
      // Set the header
      request.headers['Authorization'] = "$token";
      return request;
    });

    //Autenticator will be called 3 times if HttpStatus is
    //HttpStatus.unauthorized
    httpClient.maxAuthRetries = 3;
  }

  @override
  Future<Response<CasesModel>> getCases(String path) => get(path);
}

GetPage Middleware

The GetPage has now new property that takes a list of GetMiddleWare and run them in the specific order.

Note: When GetPage has a Middlewares, all the children of this page will have the same middlewares automatically.

Priority

The Order of the Middlewares to run can be set by the priority in the GetMiddleware.

final middlewares = [
  GetMiddleware(priority: 2),
  GetMiddleware(priority: 5),
  GetMiddleware(priority: 4),
  GetMiddleware(priority: -8),
];

those middlewares will be run in this order -8 => 2 => 4 => 5

Redirect

This function will be called when the page of the called route is being searched for. It takes RouteSettings as a result to redirect to. Or give it null and there will be no redirecting.

RouteSettings redirect(String route) {
  final authService = Get.find<AuthService>();
  return authService.authed.value ? null : RouteSettings(name: '/login')
}

onPageCalled

This function will be called when this Page is called before anything created you can use it to change something about the page or give it new page

GetPage onPageCalled(GetPage page) {
  final authService = Get.find<AuthService>();
  return page.copyWith(title: 'Welcome ${authService.UserName}');
}

OnBindingsStart

This function will be called right before the Bindings are initialize. Here you can change Bindings for this page.

List<Bindings> onBindingsStart(List<Bindings> bindings) {
  final authService = Get.find<AuthService>();
  if (authService.isAdmin) {
    bindings.add(AdminBinding());
  }
  return bindings;
}

OnPageBuildStart

This function will be called right after the Bindings are initialize. Here you can do something after that you created the bindings and before creating the page widget.

GetPageBuilder onPageBuildStart(GetPageBuilder page) {
  print('bindings are ready');
  return page;
}

OnPageBuilt

This function will be called right after the GetPage.page function is called and will give you the result of the function. and take the widget that will be showed.

OnPageDispose

This function will be called right after disposing all the related objects (Controllers, views, ...) of the page.

Other Advanced APIs

// give the current args from currentScreen
Get.arguments

// give name of previous route
Get.previousRoute

// give the raw route to access for example, rawRoute.isFirst()
Get.rawRoute

// give access to Routing API from GetObserver
Get.routing

// check if snackbar is open
Get.isSnackbarOpen

// check if dialog is open
Get.isDialogOpen

// check if bottomsheet is open
Get.isBottomSheetOpen

// remove one route.
Get.removeRoute()

// back repeatedly until the predicate returns true.
Get.until()

// go to next route and remove all the previous routes until the predicate returns true.
Get.offUntil()

// go to next named route and remove all the previous routes until the predicate returns true.
Get.offNamedUntil()

//Check in what platform the app is running
GetPlatform.isAndroid
GetPlatform.isIOS
GetPlatform.isMacOS
GetPlatform.isWindows
GetPlatform.isLinux
GetPlatform.isFuchsia

//Check the device type
GetPlatform.isMobile
GetPlatform.isDesktop
//All platforms are supported independently in web!
//You can tell if you are running inside a browser
//on Windows, iOS, OSX, Android, etc.
GetPlatform.isWeb


// Equivalent to : MediaQuery.of(context).size.height,
// but immutable.
Get.height
Get.width

// Gives the current context of the Navigator.
Get.context

// Gives the context of the snackbar/dialog/bottomsheet in the foreground, anywhere in your code.
Get.contextOverlay

// Note: the following methods are extensions on context. Since you
// have access to context in any place of your UI, you can use it anywhere in the UI code

// If you need a changeable height/width (like Desktop or browser windows that can be scaled) you will need to use context.
context.width
context.height

// Gives you the power to define half the screen, a third of it and so on.
// Useful for responsive applications.
// param dividedBy (double) optional - default: 1
// param reducedBy (double) optional - default: 0
context.heightTransformer()
context.widthTransformer()

/// Similar to MediaQuery.sizeOf(context);
context.mediaQuerySize()

/// Similar to MediaQuery.paddingOf(context);
context.mediaQueryPadding()

/// Similar to MediaQuery.viewPaddingOf(context);
context.mediaQueryViewPadding()

/// Similar to MediaQuery.viewInsetsOf(context);
context.mediaQueryViewInsets()

/// Similar to MediaQuery.orientationOf(context);
context.orientation()

/// Check if device is on landscape mode
context.isLandscape()

/// Check if device is on portrait mode
context.isPortrait()

/// Similar to MediaQuery.devicePixelRatioOf(context);
context.devicePixelRatio()

/// Similar to MediaQuery.textScaleFactorOf(context);
context.textScaleFactor()

/// Get the shortestSide from screen
context.mediaQueryShortestSide()

/// True if width be larger than 800
context.showNavbar()

/// True if the shortestSide is smaller than 600p
context.isPhone()

/// True if the shortestSide is largest than 600p
context.isSmallTablet()

/// True if the shortestSide is largest than 720p
context.isLargeTablet()

/// True if the current device is Tablet
context.isTablet()

/// Returns a value<T> according to the screen size
/// can give value for:
/// watch: if the shortestSide is smaller than 300
/// mobile: if the shortestSide is smaller than 600
/// tablet: if the shortestSide is smaller than 1200
/// desktop: if width is largest than 1200
context.responsiveValue<T>()

Optional Global Settings and Manual configurations

GetMaterialApp configures everything for you, but if you want to configure Get manually.

MaterialApp(
  navigatorKey: Get.key,
  navigatorObservers: [GetObserver()],
);

You will also be able to use your own Middleware within GetObserver, this will not influence anything.

MaterialApp(
  navigatorKey: Get.key,
  navigatorObservers: [
    GetObserver(MiddleWare.observer) // Here
  ],
);

You can create Global Settings for Get. Just add Get.config to your code before pushing any route. Or do it directly in your GetMaterialApp

GetMaterialApp(
  enableLog: true,
  defaultTransition: Transition.fade,
  opaqueRoute: Get.isOpaqueRouteDefault,
  popGesture: Get.isPopGestureEnable,
  transitionDuration: Get.defaultDurationTransition,
  defaultGlobalState: Get.defaultGlobalState,
);

Get.config(
  enableLog = true,
  defaultPopGesture = true,
  defaultTransition = Transitions.cupertino
)

You can optionally redirect all the logging messages from Get. If you want to use your own, favourite logging package, and want to capture the logs there:

GetMaterialApp(
  enableLog: true,
  logWriterCallback: localLogWriter,
);

void localLogWriter(String text, {bool isError = false}) {
  // pass the message to your favourite logging package here
  // please note that even if enableLog: false log messages will be pushed in this callback
  // you get check the flag if you want through GetConfig.isLogEnable
}

Local State Widgets

These Widgets allows you to manage a single value, and keep the state ephemeral and locally. We have flavours for Reactive and Simple. For instance, you might use them to toggle obscureText in a TextField, maybe create a custom Expandable Panel, or maybe modify the current index in BottomNavigationBar while changing the content of the body in a Scaffold.

ValueBuilder

A simplification of StatefulWidget that works with a .setState callback that takes the updated value.

ValueBuilder<bool>(
  initialValue: false,
  builder: (value, updateFn) => Switch(
    value: value,
    onChanged: updateFn, // same signature! you could use ( newValue ) => updateFn( newValue )
  ),
  // if you need to call something outside the builder method.
  onUpdate: (value) => print("Value updated: $value"),
  onDispose: () => print("Widget unmounted"),
),

ObxValue

Similar to ValueBuilder, but this is the Reactive version, you pass a Rx instance (remember the magical .obs?) and updates automatically... isn't it awesome?

ObxValue((data) => Switch(
        value: data.value,
        onChanged: data, // Rx has a _callable_ function! You could use (flag) => data.value = flag,
    ),
    false.obs,
),

Useful tips

.observables (also known as Rx Types) have a wide variety of internal methods and operators.

Is very common to believe that a property with .obs IS the actual value... but make no mistake! We avoid the Type declaration of the variable, because Dart's compiler is smart enough, and the code looks cleaner, but:

var message = 'Hello world'.obs;
print( 'Message "$message" has Type ${message.runtimeType}');

Even if message prints the actual String value, the Type is RxString!

So, you can't do message.substring( 0, 4 ). You have to access the real value inside the observable: The most "used way" is .value, but, did you know that you can also use...

final name = 'GetX'.obs;
// only "updates" the stream, if the value is different from the current one.
name.value = 'Hey';

// All Rx properties are "callable" and returns the new value.
// but this approach does not accepts `null`, the UI will not rebuild.
name('Hello');

// is like a getter, prints 'Hello'.
name() ;

/// numbers:

final count = 0.obs;

// You can use all non mutable operations from num primitives!
count + 1;

// Watch out! this is only valid if `count` is not final, but var
count += 1;

// You can also compare against values:
count > 2;

/// booleans:

final flag = false.obs;

// switches the value between true/false
flag.toggle();


/// all types:

// Sets the `value` to null.
flag.nil();

// All toString(), toJson() operations are passed down to the `value`
print( count ); // calls `toString()` inside  for RxInt

final abc = [0,1,2].obs;
// Converts the value to a json Array, prints RxList
// Json is supported by all Rx types!
print('json: ${jsonEncode(abc)}, type: ${abc.runtimeType}');

// RxMap, RxList and RxSet are special Rx types, that extends their native types.
// but you can work with a List as a regular list, although is reactive!
abc.add(12); // pushes 12 to the list, and UPDATES the stream.
abc[3]; // like Lists, reads the index 3.


// equality works with the Rx and the value, but hashCode is always taken from the value
final number = 12.obs;
print( number == 12 ); // prints > true

/// Custom Rx Models:

// toJson(), toString() are deferred to the child, so you can implement override on them, and print() the observable directly.

class User {
    String name, last;
    int age;
    User({this.name, this.last, this.age});

    @override
    String toString() => '$name $last, $age years old';
}

final user = User(name: 'John', last: 'Doe', age: 33).obs;

// `user` is "reactive", but the properties inside ARE NOT!
// So, if we change some variable inside of it...
user.value.name = 'Roi';
// The widget will not rebuild!,
// `Rx` don't have any clue when you change something inside user.
// So, for custom classes, we need to manually "notify" the change.
user.refresh();

// or we can use the `update()` method!
user.update((value){
  value.name='Roi';
});

print( user );

StateMixin

Another way to handle your UI state is use the StateMixin<T> . To implement it, use the with to add the StateMixin<T> to your controller which allows a T model.

class Controller extends GetController with StateMixin<User>{}

The change() method change the State whenever we want. Just pass the data and the status in this way:

change(data, status: RxStatus.success());

RxStatus allow these status:

RxStatus.loading();
RxStatus.success();
RxStatus.empty();
RxStatus.error('message');

To represent it in the UI, use:

class OtherClass extends GetView<Controller> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(

      body: controller.obx(
        (state)=>Text(state.name),
        
        // here you can put your custom loading indicator, but
        // by default would be Center(child:CircularProgressIndicator())
        onLoading: CustomLoadingIndicator(),
        onEmpty: Text('No data found'),

        // here also you can set your own error widget, but by
        // default will be an Center(child:Text(error))
        onError: (error)=>Text(error),
      ),
    );
}

GetView

I love this Widget, is so simple, yet, so useful!

Is a const Stateless Widget that has a getter controller for a registered Controller, that's all.

 class AwesomeController extends GetController {
   final String title = 'My Awesome View';
 }

  // ALWAYS remember to pass the `Type` you used to register your controller!
 class AwesomeView extends GetView<AwesomeController> {
   @override
   Widget build(BuildContext context) {
     return Container(
       padding: EdgeInsets.all(20),
       child: Text(controller.title), // just call `controller.something`
     );
   }
 }

GetResponsiveView

Extend this widget to build responsive view. this widget contains the screen property that have all information about the screen size and type.

How to use it

You have two options to build it.

  • with builder method you return the widget to build.
  • with methods desktop, tablet,phone, watch. the specific method will be built when the screen type matches the method when the screen is [ScreenType.Tablet] the tablet method will be exuded and so on. Note: If you use this method please set the property alwaysUseBuilder to false

With settings property you can set the width limit for the screen types.

example Code to this screen code

GetWidget

Most people have no idea about this Widget, or totally confuse the usage of it. The use case is very rare, but very specific: It caches a Controller. Because of the cache, can't be a const Stateless.

So, when do you need to "cache" a Controller?

If you use, another "not so common" feature of GetX: Get.create().

Get.create(()=>Controller()) will generate a new Controller each time you call Get.find<Controller>(),

That's where GetWidget shines... as you can use it, for example, to keep a list of Todo items. So, if the widget gets "rebuilt", it will keep the same controller instance.

GetxService

This class is like a GetxController, it shares the same lifecycle ( onInit(), onReady(), onClose()). But has no "logic" inside of it. It just notifies GetX Dependency Injection system, that this subclass can not be removed from memory.

So is super useful to keep your "Services" always reachable and active with Get.find(). Like: ApiService, StorageService, CacheService.

Future<void> main() async {
  await initServices(); /// AWAIT SERVICES INITIALIZATION.
  runApp(SomeApp());
}

/// Is a smart move to make your Services intiialize before you run the Flutter app.
/// as you can control the execution flow (maybe you need to load some Theme configuration,
/// apiKey, language defined by the User... so load SettingService before running ApiService.
/// so GetMaterialApp() doesnt have to rebuild, and takes the values directly.
void initServices() async {
  print('starting services ...');
  /// Here is where you put get_storage, hive, shared_pref initialization.
  /// or moor connection, or whatever that's async.
  await Get.putAsync(() => DbService().init());
  await Get.putAsync(SettingsService()).init();
  print('All services started...');
}

class DbService extends GetxService {
  Future<DbService> init() async {
    print('$runtimeType delays 2 sec');
    await 2.delay();
    print('$runtimeType ready!');
    return this;
  }
}

class SettingsService extends GetxService {
  void init() async {
    print('$runtimeType delays 1 sec');
    await 1.delay();
    print('$runtimeType ready!');
  }
}

The only way to actually delete a GetxService, is with Get.reset() which is like a "Hot Reboot" of your app. So remember, if you need absolute persistence of a class instance during the lifetime of your app, use GetxService.

Tests

You can test your controllers like any other class, including their lifecycles:

class Controller extends GetxController {
  @override
  void onInit() {
    super.onInit();
    //Change value to name2
    name.value = 'name2';
  }

  @override
  void onClose() {
    name.value = '';
    super.onClose();
  }

  final name = 'name1'.obs;

  void changeName() => name.value = 'name3';
}

void main() {
  test('''
Test the state of the reactive variable "name" across all of its lifecycles''',
      () {
    /// You can test the controller without the lifecycle,
    /// but it's not recommended unless you're not using
    ///  GetX dependency injection
    final controller = Controller();
    expect(controller.name.value, 'name1');

    /// If you are using it, you can test everything,
    /// including the state of the application after each lifecycle.
    Get.put(controller); // onInit was called
    expect(controller.name.value, 'name2');

    /// Test your functions
    controller.changeName();
    expect(controller.name.value, 'name3');

    /// onClose was called
    Get.delete<Controller>();

    expect(controller.name.value, '');
  });
}

Tips

Mockito or mocktail

If you need to mock your GetxController/GetxService, you should extend GetxController, and mixin it with Mock, that way

class NotificationServiceMock extends GetxService with Mock implements NotificationService {}
Using Get.reset()

If you are testing widgets, or test groups, use Get.reset at the end of your test or in tearDown to reset all settings from your previous test.

Get.testMode

if you are using your navigation in your controllers, use Get.testMode = true at the beginning of your main.

Breaking changes from 2.0

1- Rx types:

Before After
StringX RxString
IntX RxInt
MapX RxMap
ListX RxList
NumX RxNum
DoubleX RxDouble

RxController and GetBuilder now have merged, you no longer need to memorize which controller you want to use, just use GetxController, it will work for simple state management and for reactive as well.

2- NamedRoutes Before:

GetMaterialApp(
  namedRoutes: {
    '/': GetRoute(page: Home()),
  }
)

Now:

GetMaterialApp(
  getPages: [
    GetPage(name: '/', page: () => Home()),
  ]
)

Why this change? Often, it may be necessary to decide which page will be displayed from a parameter, or a login token, the previous approach was inflexible, as it did not allow this. Inserting the page into a function has significantly reduced the RAM consumption, since the routes will not be allocated in memory since the app was started, and it also allowed to do this type of approach:

GetStorage box = GetStorage();

GetMaterialApp(
  getPages: [
    GetPage(name: '/', page:(){
      return box.hasData('token') ? Home() : Login();
    })
  ]
)

Why Getx?

1- Many times after a Flutter update, many of your packages will break. Sometimes compilation errors happen, errors often appear that there are still no answers about, and the developer needs to know where the error came from, track the error, only then try to open an issue in the corresponding repository, and see its problem solved. Get centralizes the main resources for development (State, dependency and route management), allowing you to add a single package to your pubspec, and start working. After a Flutter update, the only thing you need to do is update the Get dependency, and get to work. Get also resolves compatibility issues. How many times a version of a package is not compatible with the version of another, because one uses a dependency in one version, and the other in another version? This is also not a concern using Get, as everything is in the same package and is fully compatible.

2- Flutter is easy, Flutter is incredible, but Flutter still has some boilerplate that may be unwanted for most developers, such as Navigator.of(context).push (context, builder [...]. Get simplifies development. Instead of writing 8 lines of code to just call a route, you can just do it: Get.to(Home()) and you're done, you'll go to the next page. Dynamic web urls are a really painful thing to do with Flutter currently, and that with GetX is stupidly simple. Managing states in Flutter, and managing dependencies is also something that generates a lot of discussion, as there are hundreds of patterns in the pub. But there is nothing as easy as adding a ".obs" at the end of your variable, and place your widget inside an Obx, and that's it, all updates to that variable will be automatically updated on the screen.

3- Ease without worrying about performance. Flutter's performance is already amazing, but imagine that you use a state manager, and a locator to distribute your blocs/stores/controllers/ etc. classes. You will have to manually call the exclusion of that dependency when you don't need it. But have you ever thought of simply using your controller, and when it was no longer being used by anyone, it would simply be deleted from memory? That's what GetX does. With SmartManagement, everything that is not being used is deleted from memory, and you shouldn't have to worry about anything but programming. You will be assured that you are consuming the minimum necessary resources, without even having created a logic for this.

4- Actual decoupling. You may have heard the concept "separate the view from the business logic". This is not a peculiarity of BLoC, MVC, MVVM, and any other standard on the market has this concept. However, this concept can often be mitigated in Flutter due to the use of context. If you need context to find an InheritedWidget, you need it in the view, or pass the context by parameter. I particularly find this solution very ugly, and to work in teams we will always have a dependence on View's business logic. Getx is unorthodox with the standard approach, and while it does not completely ban the use of StatefulWidgets, InitState, etc., it always has a similar approach that can be cleaner. Controllers have life cycles, and when you need to make an APIREST request for example, you don't depend on anything in the view. You can use onInit to initiate the http call, and when the data arrives, the variables will be populated. As GetX is fully reactive (really, and works under streams), once the items are filled, all widgets that use that variable will be automatically updated in the view. This allows people with UI expertise to work only with widgets, and not have to send anything to business logic other than user events (like clicking a button), while people working with business logic will be free to create and test the business logic separately.

This library will always be updated and implementing new features. Feel free to offer PRs and contribute to them.

Community

Community channels

GetX has a highly active and helpful community. If you have questions, or would like any assistance regarding the use of this framework, please join our community channels, your question will be answered more quickly, and it will be the most suitable place. This repository is exclusive for opening issues, and requesting resources, but feel free to be part of GetX Community.

Slack Discord Telegram
Get on Slack Discord Shield Telegram

How to contribute

Want to contribute to the project? We will be proud to highlight you as one of our collaborators. Here are some points where you can contribute and make Get (and Flutter) even better.

  • Helping to translate the readme into other languages.
  • Adding documentation to the readme (a lot of Get's functions haven't been documented yet).
  • Write articles or make videos teaching how to use Get (they will be inserted in the Readme and in the future in our Wiki).
  • Offering PRs for code/tests.
  • Including new functions.

Any contribution is welcome!

Articles and videos

getx's People

Contributors

ahmednfwela avatar allcontributors[bot] avatar aratheunseen avatar cpdncristiano avatar edugemini avatar enghitalo avatar grohden avatar hp1909 avatar jonataslaw avatar justkawal avatar jwelmac avatar kamazoun avatar khangahs avatar kranfix avatar nipodemos avatar nivisi avatar paulosilva159 avatar rafaruiz avatar renatfakhrutdinov avatar roipeker avatar rws08 avatar sametcilingir avatar schabanbo avatar stefandevo avatar sumitsharansatsangi avatar unacorbatanegra avatar usamasarwar avatar vbuberen avatar wheeos avatar williamcunhacardoso avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

getx's Issues

Unhandled Exception: type 'Transition' is not a subtype of type 'bool'

When i use this version in master channel show this error and not show next page.

pubspec.yml:

get: ^1.14.0-dev

Screen:

Screenshot

Code:
Get.to(FirstLoginScreen(),transition: Transition.fade,duration: Duration(milliseconds: 100));


Flutter doctor:

[√] Flutter (Channel master, v1.18.1-pre.3, on Microsoft Windows [Version 10.0.17134.1365], locale en-US)
    • Flutter version 1.18.1-pre.3 at D:\java\flutter\flutter
    • Framework revision e3e189219b (19 hours ago), 2020-04-06 14:31:38 -0700
    • Engine revision df257e59c2
    • Dart version 2.8.0 (build 2.8.0-dev.20.0 1210d27678)


[√] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at E:\Android\sdk
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = E:\Android\sdk
    • Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)
    • All Android licenses accepted.

[√] Android Studio (version 3.2)
    • Android Studio at C:\Program Files\Android\Android Studio
    • Flutter plugin version 31.3.1
    • Dart plugin version 181.5656
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1136-b06)

[√] IntelliJ IDEA Community Edition (version 2018.2)
    • IntelliJ at C:\Program Files\JetBrains\IntelliJ IDEA Community Edition 2018.2.4
    • Flutter plugin version 34.0.1
    • Dart plugin version 182.5215

[√] VS Code, 64-bit edition (version 1.28.2)
    • VS Code at C:\Program Files\Microsoft VS Code
    • Flutter extension version 2.21.1

[√] Connected device (1 available)
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 7.0 (API 24) (emulator)

• No issues found!


Error:

ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type 'Transition' is not a subtype of type 'bool'
E/flutter (25785): #0      Get.to (package:get/src/get_main.dart:59:32)
E/flutter (25785): #1      _SplashScreenState.goToNextPage.<anonymous closure> (package:amack_v4_backend/ui/screens/splash_screen.dart:57:9)
E/flutter (25785): #2      _rootRun (dart:async/zone.dart:1180:38)
E/flutter (25785): #3      _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (25785): #4      _CustomZone.runGuarded (dart:async/zone.dart:979:7)
E/flutter (25785): #5      _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1019:23)
E/flutter (25785): #6      _rootRun (dart:async/zone.dart:1184:13)
E/flutter (25785): #7      _CustomZone.run (dart:async/zone.dart:1077:19)
E/flutter (25785): #8      _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1003:23)
E/flutter (25785): #9      Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter (25785): #10     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (25785): #11     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (25785): #12     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (25785): 

Transition.material?

The default transition seems to be fade.

  • Are there plans to support the default material transition?
  • Or does it have a different transition name?

No support for nested Navigators?

Just curious how you see this working in apps where I have multiple views containing tab bars, or a desktop style app that has sidemenu that pushes views to the content area in the right, but still wants to show fullscreen dialogs over the entire app.

Seems like this would be more flexible if it had the ability to have the root navigator, but also a context based lookup.

NestedNavigator(key: Get.getKey(context))

Get.to(SomeNestedPage(), context)

Throwing error on Flutter build

Get was working perfectly for both Android and iOS but now my app will no compile. Getting the following error when debugging or flutter build...

I have tested with dev and master flutter branches.

UPDATE:
still have this issue after:
flutter clean
flutter pub cache repair
Tested with get: ^1.7.3 and get: ^1.7.4
Removed get and app compiles.
The issue started randomly. Not aware of any updates that could have triggered this.

Compiler message:
../../AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/get-1.7.4/lib/src/snack_route.dart:279:8: 
Error: The method 'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.
  void install(OverlayEntry insertionPoint) {
       ^
/C:/dev/flutter/packages/flutter/lib/src/widgets/routes.dart:40:8: Context: This is the overridden method ('install').
  void install() {
       ^
../../AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/get-1.7.4/lib/src/snack_route.dart:289:18: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
    super.install(insertionPoint);
                 ^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.                                                           

FAILURE: Build failed with an exception.

* Where:
Script 'C:\dev\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 817

* What went wrong:
Execution failed for task ':app:compileFlutterBuildRelease'.
> Process 'command 'C:\dev\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 18s
Running Gradle task 'assembleRelease'...                                
Running Gradle task 'assembleRelease'... Done                      19.5s
Gradle task assembleRelease failed with exit code 1

Cupertino Routes

The built-in cupertino routes match the feel of native ios transitions, including the ability to navigate back with a gesture. Have you gotten these to work with Get? I found this in the documentation:

and if you need custom transitions, use PageRouteBuilder by adding the parameter 'opaque = false' to maintain compatibility with the library.

but this didn't work for me. I was hoping I could use CupertinoPageRoute.buildPageTransitions, but got a NPE:

This is my code:

final getRoute = GetRoute(
      settings: settings,
      page: Builder(builder: builder),
      opaque: false,
    );
    return PageRouteBuilder(
      settings: settings,
      pageBuilder: (context, animation, secondary) {
        return builder(context);
      },
      fullscreenDialog: fullscreenDialog,
      opaque: true,
      transitionsBuilder:
          (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
        return CupertinoPageRoute.buildPageTransitions(getRoute, context, animation, secondaryAnimation, child);
      },
    );

This is the error I got:

final getRoute = GetRoute(
      settings: settings,
      page: Builder(builder: builder),
      opaque: false,
    );
    return PageRouteBuilder(
      settings: settings,
      pageBuilder: (context, animation, secondary) {
        return builder(context);
      },
      fullscreenDialog: fullscreenDialog,
      opaque: false,
      transitionsBuilder:
          (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
        return CupertinoPageRoute.buildPageTransitions(getRoute, context, animation, secondaryAnimation, child);
      },
    );

Flutter 1.13.6

Is there a way to check which one is the current route?

I have a navigation bar when I call Get.toNamed(routeName) whenever I tap on a button.

But I'd like to prevent that call when the currentRoute is the same as routeName.

Couldn't find a way to get the current route name except from within the middleware. Would be nice to get an accesor to the current route from Get directly, like Get.currentRoute or something

[Question] Support for web?

This looks promising to me! Just wondering how this works with web navigation? The /#/ in all web URL's currently is frustrating to deal with. Also does this pair nicely with animated routes?

I'm going to check these things out shortly as well :)

Transition bug?

When I call Get.to(..., transition.fade)

I see the off transition on the previous page rightToLeft with fade (but it will be fade OUT ONLY)

Any way to create a Transition.Nothing? (and/or transitionIn/transitionOut?)

I need to handle the in and out animations too.

Thanks

Undefined name 'Transition'

Screen Shot 2020-03-04 at 16 08 42

Hi @jonataslaw. Great library!
There's this one thing. Could you help me with how to set the transition type, because the IDE (vscode) cannot find the class Transition?

dependencies:
get: ^1.11.0

Thank you!

Context: This is the overridden method ('install').

after adding get, i get this message, from macos build


Compiler message:

../../../../../.pub-cache/hosted/pub.dartlang.org/get-1.17.3/lib/src/snackbar/snack_route.dart:279:8: Error: The method 'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.

  void install(OverlayEntry insertionPoint) {

       ^

../../../../../development/flutter/packages/flutter/lib/src/widgets/routes.dart:41:8: Context: This is the overridden method ('install').

  void install() {

       ^
Running pod install...                                              1.5s
../../../../../.pub-cache/hosted/pub.dartlang.org/get-1.17.3/lib/src/routes/default_route.dart:242:9: Error: No named parameter with the name 'animation'.
        animation: animation,
        ^^^^^^^^^
../../../../../development/flutter/packages/flutter/lib/src/cupertino/route.dart:435:3: Context: Found this candidate, but the arguments don't match.
  CupertinoFullscreenDialogTransition({
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
../../../../../.pub-cache/hosted/pub.dartlang.org/get-1.17.3/lib/src/snackbar/snack_route.dart:289:18: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
    super.install(insertionPoint);
                 ^
Building macOS application...
[INFO:persistent_cache.cc(338)] PersistentCache::UpdateAssetPath: /Users/softmarshmallow/Documents/Apps/inked/inked-flutter/inked/build/macos/Build/Products/Debug/inked.app/Contents/Frameworks/App.framework/Resources/flutter_assets
flutter: started application..

Custom transitions/animations

First I want to thank you for the effort to bring us this amazing library, it's really time saving!

I want to know if is it possible to add custom transitions/animations both to Get.to and Get.dialog. I saw some parameters in getroute.dart but I couldn't find a way to do it.

If it's not present, is it possible to add this feature? I think that this is the only thing that is preventing me to use it for all my navigations and dialogs as I have custom transitions almost everywhere.

[HELP] Example of event listening inside the screen widget

Sorry to be bugging so much... can you tell I'm new to flutter?

I was able to implement the middleware to observer every time a screen gets pushed or popped. But I don't understand how to use that to actually perform something on the screen itself. For instance, I want to refresh data from an API every time a screen is either pushed or popped.

I have this in my Middleware

class MiddleWare {
  static observer(Routing routing) {
    print(routing.current);
  }
}

And I do get the name of the screen when I expect it to appear. But how do I call the method on that screen?

Thank you!

Issue with cupertino route

Flutter version v 1.15.22

Get lib version 1.16.1-dev

Hi!

Running Xcode build...

Compiler message:
../../../.pub-cache/hosted/pub.dartlang.org/get-1.16.1-dev/lib/src/routes/default_route.dart:240:9: Error: No named parameter with the name 'primaryRouteAnimation'.
        primaryRouteAnimation: animation,
        ^^^^^^^^^^^^^^^^^^^^^
../../flutter/packages/flutter/lib/src/cupertino/route.dart:425:3: Context: Found this candidate, but the arguments don't match.
  CupertinoFullscreenDialogTransition({
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Xcode build done.                                           40.1s
Failed to build iOS app
Error output from Xcode build:
↳
    ** BUILD FAILED **


Xcode's output:
↳
    In file included from /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:2:
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:328:19: warning: empty paragraph passed to '@param' command [-Wdocumentation]
     @param sharedStyle
     ~~~~~~~~~~~~~~~~~^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:343:25: warning: empty paragraph passed to '@param' command [-Wdocumentation]
     @param allowTapToDismiss
     ~~~~~~~~~~~~~~~~~~~~~~~^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:343:9: warning: parameter 'allowTapToDismiss' not found in the function declaration [-Wdocumentation]
     @param allowTapToDismiss
            ^~~~~~~~~~~~~~~~~
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:343:9: note: did you mean 'tapToDismissEnabled'?
     @param allowTapToDismiss
            ^~~~~~~~~~~~~~~~~
            tapToDismissEnabled
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:362:20: warning: empty paragraph passed to '@param' command [-Wdocumentation]
     @param queueEnabled
     ~~~~~~~~~~~~~~~~~~^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:19:23: warning: unused variable 'viewController' [-Wunused-variable]
        UIViewController *viewController =
                          ^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:70:21: warning: unused variable 'topPadding' [-Wunused-variable]
                CGFloat topPadding = window.safeAreaInsets.top;
                        ^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:71:21: warning: unused variable 'bottomPadding' [-Wunused-variable]
                CGFloat bottomPadding = window.safeAreaInsets.bottom;
                        ^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:48:19: warning: unused variable 'size' [-Wunused-variable]
            NSNumber *size = call.arguments[@"size"];
                      ^
    8 warnings generated.

    Compiler message:
    ../../../.pub-cache/hosted/pub.dartlang.org/get-1.16.1-dev/lib/src/routes/default_route.dart:240:9: Error: No named parameter with the name 'primaryRouteAnimation'.
            primaryRouteAnimation: animation,
            ^^^^^^^^^^^^^^^^^^^^^
    ../../flutter/packages/flutter/lib/src/cupertino/route.dart:425:3: Context: Found this candidate, but the arguments don't match.
      CupertinoFullscreenDialogTransition({
      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
    build failed.
    Command PhaseScriptExecution failed with a nonzero exit code
    note: Using new build system
    note: Planning build
    note: Constructing build description

Could not build the precompiled application for the device.

[✓] Flutter (Channel unknown, v1.15.22, on Mac OS X 10.14.5 18F132, locale en-RU)
    • Flutter version 1.15.22
    • Framework revision 1606d87834 (5 weeks ago), 2020-03-16 00:36:01 -0400
    • Engine revision 6801b4dae7
    • Dart version 2.8.0 (build 2.8.0-dev.14.0 7079c49b05)

 
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
 
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-29, build-tools 29.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 11.3.1, Build version 11C504
    • CocoaPods version 1.9.1

[✓] Android Studio (version 3.6)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 45.0.1
    • Dart plugin version 192.7761
    • Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b4-5784211)

but on get lib 1.15.2

i have that issue

Compiler message:
../../../.pub-cache/hosted/pub.dartlang.org/get-1.15.2/lib/src/snackbar/snack_route.dart:279:8: Error: The method 'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.
  void install(OverlayEntry insertionPoint) {
       ^
../../flutter/packages/flutter/lib/src/widgets/routes.dart:40:8: Context: This is the overridden method ('install').
  void install() {
       ^
Automatically signing iOS for device deployment using specified development team in Xcode project: LYX986LPZU
Running Xcode build...
../../../.pub-cache/hosted/pub.dartlang.org/get-1.15.2/lib/src/snackbar/snack_route.dart:289:18: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
    super.install(insertionPoint);
                 ^
Xcode build done.                                           40.4s
Failed to build iOS app
Error output from Xcode build:
↳
    2020-04-17 17:51:55.405 xcodebuild[47675:355165]  DTDeviceKit: deviceType from 608b39e0b917088594c74ed7c89a7d3dca9cc4dc was NULL
    2020-04-17 17:51:55.573 xcodebuild[47675:355167]  DTDeviceKit: deviceType from 608b39e0b917088594c74ed7c89a7d3dca9cc4dc was NULL
    ** BUILD FAILED **


Xcode's output:
↳
    In file included from /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:2:
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:328:19: warning: empty paragraph passed to '@param' command [-Wdocumentation]
     @param sharedStyle
     ~~~~~~~~~~~~~~~~~^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:343:25: warning: empty paragraph passed to '@param' command [-Wdocumentation]
     @param allowTapToDismiss
     ~~~~~~~~~~~~~~~~~~~~~~~^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:343:9: warning: parameter 'allowTapToDismiss' not found in the function declaration [-Wdocumentation]
     @param allowTapToDismiss
            ^~~~~~~~~~~~~~~~~
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:343:9: note: did you mean 'tapToDismissEnabled'?
     @param allowTapToDismiss
            ^~~~~~~~~~~~~~~~~
            tapToDismissEnabled
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/UIView+Toast.h:362:20: warning: empty paragraph passed to '@param' command [-Wdocumentation]
     @param queueEnabled
     ~~~~~~~~~~~~~~~~~~^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:19:23: warning: unused variable 'viewController' [-Wunused-variable]
        UIViewController *viewController =
                          ^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:70:21: warning: unused variable 'topPadding' [-Wunused-variable]
                CGFloat topPadding = window.safeAreaInsets.top;
                        ^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:71:21: warning: unused variable 'bottomPadding' [-Wunused-variable]
                CGFloat bottomPadding = window.safeAreaInsets.bottom;
                        ^
    /Users/devel/.pub-cache/hosted/pub.dartlang.org/fluttertoast-4.0.1/ios/Classes/FluttertoastPlugin.m:48:19: warning: unused variable 'size' [-Wunused-variable]
            NSNumber *size = call.arguments[@"size"];
                      ^
    8 warnings generated.

    Compiler message:
    ../../../.pub-cache/hosted/pub.dartlang.org/get-1.15.2/lib/src/snackbar/snack_route.dart:279:8: Error: The method 'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.
      void install(OverlayEntry insertionPoint) {
           ^
    ../../flutter/packages/flutter/lib/src/widgets/routes.dart:40:8: Context: This is the overridden method ('install').
      void install() {
           ^
    ../../../.pub-cache/hosted/pub.dartlang.org/get-1.15.2/lib/src/snackbar/snack_route.dart:289:18: Error: Too many positional arguments: 0 allowed, but 1 found.
    Try removing the extra positional arguments.
        super.install(insertionPoint);
                     ^
    Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
    build failed.
    Command PhaseScriptExecution failed with a nonzero exit code
    note: Using new build system
    note: Planning build
    note: Constructing build description


What problem it can be?

Very big thanks for any answering!

Prevent dialog from appearing on top of another dialog

I'm currently displaying a dialog when my API throws an error.

The problem I'm running into is that I'm making mulitple calls at the same time, and sometimes I get multiple errors, so I end up with getting multiple dialogs open at the same time.

Is there a way to prevent this? Or is there a way to figure out if there is currently a dialog open? So I can check for that before displaying the dialog.

Bottom sheet

Is it shows bottom sheet without context?
If not can you add??

Keyboard or focusNode

Is there any way to use nextFocus without a context? Because when my TextField in a widget that is opened via Get my keyboard is going to be crazy from this line:

onSubmitted: (_) => FocusScope.of(context).nextFocus(), // move focus to next
),

Are there plans to support cupertino?

Is your feature request related to a problem? Please describe.
Currently this package only supports material apps. I see ThemeData and MaterialLocalizations being used.

Describe the solution you'd like
Check the platform before using things like ThemeData.

Describe alternatives you've considered
The solution will probably find all the occurrences of material dependencies and add a platform check there.

how to pass params?

i need help to pass params for another page.

Get.toNamed('/view_folder', {title:'page name'} )

bottomSheet is always rebuild

I have a

Get.bottomSheet(
isScrollControlled: true,
builder: (_) => MySheetWidget(title));

MySheetWidget is a statefulwidget

When i move the sheet top/bottom the build method always triggering

Flutter Test

First at all very good job, it is a nice plugin. This is not really an issue but I am trying to test a logic service, and this calls to "Get.offNamed", but I could not find a way to mock it or get around it in order to pass my test. Sorry if this is not the best way to ask about this and thank you.

Erro ao acessar Get.arguments

Antes de tudo, parabéns pela Lib!
Precisei recentemente abrir um snackbar, mas tive dificuldade excessiva pra realizar uma "tarefa tão simples", e acabei vindo experimentar o Get, que se mostrou bem prático nesse e em todos os outros quesitos de navegação, mas agora estou tendo dificuldades com a passagem de parâmetros com rotas nomeadas em um projeto de estudo.

Acredito que o codigo que fiz esteja conforme foi exemplificado na documentação.

Describe the bug
Tento navegar com Get.toNamed passando um argumento, na tela de destino, ao acessar Get.arguments uma Exceção é lançada.

Erro:

The getter 'args' was called on null.
Receiver: null
Tried calling: args

To Reproduce
Steps to reproduce the behavior:

  1. Clique em um dos items listados na GridView.

Expected behavior
Acessar o valor enviado via arguments no widget/tela de destino.

Flutter Version:
environment:
sdk: ">=2.1.0 <3.0.0"
Flutter 1.12.13+hotfix.9

Get Version:
get: ^1.17.3

Describe on which device you found the bug:
ex: AVD com SDK 21 - Android 5.1.1.

Minimal reproduce code
`import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() => runApp(MyApp());

class Routes {
static const PRODUCT_DETAIL = '/product-detail';
}

class Router {
static Route generateRoute(RouteSettings settings) {
switch (settings.name) {
case '/':
return GetRoute(
settings: settings,
page: ProductsOverviewScreen(),
);
case Routes.PRODUCT_DETAIL:
return GetRoute(
settings: settings,
page: ProductDetailsScreen(),
);
default:
return GetRoute(
settings: settings,
page: Scaffold(
body: Center(child: Text('No route defined for ${settings.name}')),
),
);
}
}
}

class MyApp extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: Get.key,
title: 'Minha Loja',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.deepOrange,
),
initialRoute: '/',
onGenerateRoute: Router.generateRoute,
);
}
}

class ProductsOverviewScreen extends StatelessWidget {
final List items = ['item 1', 'item 2'];

@OverRide
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'Minha loja',
),
),
body: Padding(
padding: const EdgeInsets.all(10.0),
child: GridView.builder(
itemCount: items.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 3 / 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (context, i) {
return InkWell(
onTap: () {
Get.toNamed(Routes.PRODUCT_DETAIL, arguments: items[i]);
},
child: Text(
items[i],
),
);
}),
),
);
}
}

class ProductDetailsScreen extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
print('antes');
print(Get.arguments);
print('depois');

return Scaffold(
  appBar: AppBar(
    title: Text(Get.arguments),
  ),
);

}
}
`

Rebuild last page

Hi,
first of all thank you very much for your great work on this package.
I'm using your package to improve the performance of my app by getting rid of the unnecessary build calls after several page switches.
Unfortunately, this also has the consequence that the page to which you switch when the back button is pressed is not reloaded.

E.g. if we got the following path: A --> B --> C. If the user goes back from C to B, B is not reloaded.
Is it possible to add a parameter in the configuration of Get() so that only the last page is reloaded if the user presses the back button?

Using Get.until while avoiding closing a Snackbar

So I have a use case which I'm having a hard time implementing correctly.

In my app, in order to create a user, I need to go through 2 screens. So after you are done, I want to get back to the first screen while also showing a Snackbar.

So currently I have this:

    Get.snackbar(
      'Patient ${patient.fullName}',
      'Successfully added',
      backgroundColor: CustomColors.statusGoodColor(),
      colorText: Colors.white,
    );
    Get.until(Routes.PatientsPatient, (Route route) {
      setState(() {
        isCreatingPatient = false;
      });
      return route.settings.name == Routes.PatientsPatient;
    });
  }

That is crashing my app with this exception RangeError (index): Invalid value: Valid value range is empty: -1

It probably has something to do with the fact that Get.back also closes the snackbar. But I can't figure out how to leave the snackbar while going to the first screen in the first place.

I tried opening the snackbar after the Get.until, but the same crash occurs.

Any help?

Thanks!

[PROPOSAL] middleware capabilities

I think it would be great if we could pass some kind of middleware to be executed on every page transition for example. The motivation is to be able to for examplo log to the console which route you are going to.

Duration of transition for Get.to()

Can I globally change time of fade transition? In GetRoute is parameter duration, but I don't know how used it without changes in library code. Is it possible?

Get.back() doesn't work from an async function

I have a page that will perform a HTTP Post when a button is pressed. That button will call an async function to perform the actual HTTP Post which could take a second or two. When I get a success or failure back I'm attempting to navigate back to the previous page, but it doesn't do anything.

No error was reported, it just fails silently.

I found a work around, just call the Get.back() function inside the button event:
onPressed: () {saveClicked(); Get.back();},

Flutter Version:
Flutter 1.12.13+hotfix.9 • channel stable • https://github.com/flutter/flutter.git
Framework • revision f139b11009 (3 weeks ago) • 2020-03-30 13:57:30 -0700
Engine • revision af51afceb8
Tools • Dart 2.7.2

Get Version:
get: ^1.17.2

Describe on which device you found the bug:
Samsung Galaxy S8

Get Snackbar causes an exception in scheduler library

Describe the bug
A clear and concise description of what the bug is.
Hi, many thanks for your work !

Unfortunately, while trying to use your Snackbar after an API Call, it raises an exception
image
I am simply calling it like the documentation said:
Capture d’écran 2020-04-21 à 11 26 03
I've tried to add a blank ThemeData in my MaterialApp Widget but with no success.
Have I done something wrong here ?

Flutter Version:
Enter the version of the Flutter you are using
Flutter 1.12.13+hotfix.9

Get Version:
Enter the version of the Get you are using
get: ^1.17.0

Describe on which device you found the bug:
Nexus 5X

[Feature request] Get dialougue with return

@jonataslaw
Can I do this same like this using any widget of get.defaultdialogue, get.snackbar or getBar

               bool shouldUpdate = await showDialog(
                  context: this.context,
                  child:new AlertDialog(
                    content: new FlatButton(
                      child: new Text("update home"),
                      onPressed: () => Navigator.pop(context, true),
                    ),
                  ),
                );
                setState(() {
                  shouldUpdate ? this._homeData = "updated" : null;
                });

Error in build after Flutter update on 4.2.2020

After I ran flutter update, Im unable to build my app.

Compiler message:
../../AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/get-1.7.4/lib/src/snack_route.dart:279:8: Error: The method 'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.
void install(OverlayEntry insertionPoint) {
^
/C:/Flutter/SDK/flutter/packages/flutter/lib/src/widgets/routes.dart:40:8: Context: This is the overridden method ('install').
void install() {
^
../../AppData/Roaming/Pub/Cache/hosted/pub.dartlang.org/get-1.7.4/lib/src/snack_route.dart:289:18: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
super.install(insertionPoint);
^
Target kernel_snapshot failed: Exception: Errors during snapshot creation: null
build failed.

FAILURE: Build failed with an exception.

  • Where:
    Script 'C:\Flutter\SDK\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 803

  • What went wrong:
    Execution failed for task ':app:compileFlutterBuildDebug'.

Process 'command 'C:\Flutter\SDK\flutter\bin\flutter.bat'' finished with non-zero exit value 1

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 19s
Finished with error: Gradle task assembleDebug failed with exit code 1

[Question] Parallel routes auto redirect

Hi, I'm quite new to flutter world and I've been trying something to implement automatic route redirect based on current authentication state. I haven't found material about that and most of them is to have manual implementation that in a authenticated route keep listening if was unauthenticated, and then navigate back.

Then I got more or less the result that I was looking applying something that I used in RN and Native projects, but I wonder if there is any suggested way to do so.

                          -> HomePage -> SettingsPage
App -> AuthenticationPage  
                          -> LoginPage -> RegisterPage

When user login on LoginPage, it would navigate automatically to HomePage
When user logout on SettingsPage, it would navigate automatically to LoginPage

class AuthenticationPage extends StatefulWidget {
  const AuthenticationPage({Key key}) : super(key: key);

  @override
  _AuthenticationPageState createState() => _AuthenticationPageState();
}

class _AuthenticationPageState extends ModularState<AuthenticationPage, AuthenticationController> {
  @override
  void initState() {
    super.initState();
    // addPostFrameCallback is documented to be triggered only once, then listener is discarded
    WidgetsBinding.instance.addPostFrameCallback((_) => autorun((_) => _onRegisterNavigation()));
  }

  void _onRegisterNavigation() {
    final AuthenticationState authenticationState = controller.authenticationState;
    if (authenticationState is AuthenticatedAuthenticationState) {
      Get.offNamedUntil("/home", ModalRoute.withName(Modular.initialRoute)).then((_) => _onHandleRouteReturn());
    } else if (authenticationState is UnauthenticatedAuthenticationState) {
      Get.offNamedUntil("/login", ModalRoute.withName(Modular.initialRoute)).then((_) => _onHandleRouteReturn());
    } else {
      throw UnimplementedError("Not supported $authenticationState");
    }
  }

  void _onHandleRouteReturn() {
    if (!Get.key.currentState.canPop()) {
      SystemNavigator.pop();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 0,
      height: 0,
      color: Theme.of(context).backgroundColor,
    );
  }
}

on master channel even on ^1.12.0-dev version when add this package to pubspec.yaml i got below error but stable channel works well

Compiler message:
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/get-1.11.1/lib/src/snack_route.dart:279:8: Error: The method
'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.
void install(OverlayEntry insertionPoint) {
^
/C:/flutter/packages/flutter/lib/src/widgets/routes.dart:41:8: Context: This is the overridden method ('install').
void install() {
^
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/get-1.11.1/lib/src/snack_route.dart:289:18: Error: Too many positionalarguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
super.install(insertionPoint);
^
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/get-1.11.1/lib/src/getroute_cupertino.dart:232:9: Error: No named
parameter with the name 'animation'.
animation: animation,
^^^^^^^^^
/C:/flutter/packages/flutter/lib/src/cupertino/route.dart:435:3: Context: Found this candidate, but the arguments
don't match.
CupertinoFullscreenDialogTransition({
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem was found with the configuration of task ':app:compileFlutterBuildDebug'.

Cannot write to file 'C:\flutter' specified for property 'outputFiles' as it is a directory.

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 3s
Running Gradle task 'assembleDebug'...
Running Gradle task 'assembleDebug'... Done 4.5s
Exception: Gradle task assembleDebug failed with exit code 1

Scaffold's drawer opening is not added to navigation stack

I don't know if this is intended, but opening a Scaffold's drawer doesn't add to the navigation stack, while Flutter default navigation does.

Navigator.pop(context) // closes the drawer in Flutter navigation
Get.back() // ignores the drawer in Get navigation

[Proposal] Optional debugging messages

It looks like you are currently printing debug messages (at least on the RouteObserver).
Can you make it an optional setting to be able to turn it off?

Thanks!

Snackbar doesn't show up until touch screen

I want to show snackbar on firebase notification arrived.
I have this:

    Get.snackbar(
      "Notif",
      data['data']['notification_title'],
      shouldIconPulse: true,
      barBlur: 20,
      isDismissible: true,
      duration: Duration(seconds: 3),
      backgroundColor: ColorPalette.primary,
      snackPosition: SnackPosition.BOTTOM,
      margin: EdgeInsets.only(bottom: 10.0, left: 15.0, right: 15.0),
      colorText: Colors.white,
    );

but snackbar show up only user touch or scroll screen.

Get.bottomSheet show/hide keyboard triggers rebuild

I have a Get.bottomSheet(builder: (_) {

And some textfield in it

When the keyboard is show/hide on this fields then the widget is rebuild... How can I fix this?
I don't want to rebuild the widget in that case.

Thanks

GetRoute Duration doesn't seem to work

I'm trying to use custom transitions on named routes:

class Router {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case Routes.PriorityHome:
        return GetRoute(
          settings: settings,
          page: PriorityHomeScreen(),
          duration: Duration(milliseconds: 0),
        );
      case Routes.PriorityPatient:
        return GetRoute(
          settings: settings,
          page: PriorityPatientScreen(),
          duration: Duration(milliseconds: 0),
        );
      default:
        return GetRoute(
          settings: settings,
          transition: Transition.fade,
          page: Scaffold(
            body: Center(
              child: Text('No route defined for ${settings.name}'),
            ),
          ),
        );
    }
  }
}

My expectation is for no animation to occur (since milliseconds is 0), but it is still happening.
Changing the value to other values (higher than the default 400 for example) doesn't change anything either

Compile error

using get: ^1.11.6

As soon as I include import 'package:get/get.dart'; on my main.dart file

I get this error during compile:

Compiler message:
../../../.pub-cache/hosted/pub.dartlang.org/get-1.11.6/lib/src/snackbar/snack_route.dart:279:8: Error: The method 'SnackRoute.install' has more required arguments than those of overridden method 'OverlayRoute.install'.
  void install(OverlayEntry insertionPoint) {
       ^
../../../flutter/packages/flutter/lib/src/widgets/routes.dart:40:8: Context: This is the overridden method ('install').
  void install() {
       ^
../../../.pub-cache/hosted/pub.dartlang.org/get-1.11.6/lib/src/snackbar/snack_route.dart:289:18: Error: Too many positional arguments: 0 allowed, but 1 found.
Try removing the extra positional arguments.
    super.install(insertionPoint);
                 ^

This is my main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:rpm/models/state.dart';
import 'package:provider/provider.dart';
import 'routes.dart';

void main() => runApp(ChangeNotifierProvider(
      create: (context) => StateModel(),
      child: MyApp(),
    ));

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: '/',
      routes: routes,
    );
  }
}

Get.back() with Get or Get.snackbar

First I want to thank you for this amazing lib!

I want to know if there is a way to not dismiss the "GetBar" when we do a "Get.back()" or the user press the back button.

I'm struggling with this because I have a Firebase Messaging Service running on the background, e some times the user can receive a notification on the screen with a Snackbar. And i really want to use your implementation, my life would be much easier. But when the user presses the back button or i use "Get.back", the "GetBar" is dismissed.

Is there a way to prevent this behavior?

Will you implement showSearch?

I'm currently using your package to completely separate my UI from all the logic and I want to use the search delegate, but it needs the context to be called. Are you planning to implement this feature?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.