milad-akarie / auto_route_library Goto Github PK
View Code? Open in Web Editor NEWFlutter route generator
License: MIT License
Flutter route generator
License: MIT License
Hi,
we have an issue if we are using stream as a parameter of a route. We got this error:
Compiler message: lib/routes/router.gr.dart:12:8: Error: Not found: 'dart:async/stream.dart' import 'dart:async/stream.dart';
Is there a possibility to use streams as parameters?
Thanks,
Werner
Exception:
E/flutter (19356): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'pushReplacementNamed' was called on null.
E/flutter (19356): Receiver: null
E/flutter (19356): Tried calling: pushReplacementNamed<Object, Object>("/second-screen-route")
E/flutter (19356): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (19356): #1 MyHomePage.build.<anonymous closure> (package:flutterapp/main.dart:29:12)
E/flutter (19356): #2 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter (19356): #3 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (19356): #4 _FutureListener.handleValue (dart:async/future_impl.dart:140:18)
E/flutter (19356): #5 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:682:45)
E/flutter (19356): #6 Future._propagateToListeners (dart:async/future_impl.dart:711:32)
E/flutter (19356): #7 Future._complete (dart:async/future_impl.dart:516:7)
E/flutter (19356): #8 new Future.delayed.<anonymous closure> (dart:async/future.dart:313:16)
E/flutter (19356): #9 _rootRun (dart:async/zone.dart:1122:38)
E/flutter (19356): #10 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (19356): #11 _CustomZone.runGuarded (dart:async/zone.dart:925:7)
E/flutter (19356): #12 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:965:23)
E/flutter (19356): #13 _rootRun (dart:async/zone.dart:1126:13)
E/flutter (19356): #14 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter (19356): #15 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:949:23)
E/flutter (19356): #16 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:23:15)
E/flutter (19356): #17 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:398:19)
E/flutter (19356): #18 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:429:5)
E/flutter (19356): #19 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
Minimal repro:
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutterapp/router.gr.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
builder: ExtendedNavigator<Router>(router: Router()),
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
Future.delayed(Duration(seconds: 1)).then((value) {
ExtendedNavigator.rootNavigator
.pushReplacementNamed(Routes.secondScreenRoute);
});
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('First page'),
],
),
),
);
}
}
class MySecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Second page'),
],
),
),
);
}
}
import 'package:auto_route/auto_route_annotations.dart';
import 'package:flutterapp/main.dart';
@MaterialAutoRouter()
class $Router {
@initial
MyHomePage myHomePage; // your desired route name
MySecondPage secondScreenRoute;
}
Pubspec.yaml:
dependencies:
flutter:
sdk: flutter
# Simple routing
auto_route: ^0.4.2
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
# Auto Route library for zero boilerplate navigation
auto_route_generator: ^0.4.0
build_runner:
Flutter doctor:
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.15.17, on Mac OS X 10.15.3 19D76, locale en-AE)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Xcode - develop for iOS and macOS (Xcode 11.4)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.6)
[✓] Connected device (3 available)
Thanks a lot for you work on this magical library by the way!
Hi,
When I try to use
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// Tell MaterialApp to use our ExtendedNavigator instead of
// the native one by assigning it to it's builder
// instead of return the nativeNavigator we're returning our ExtendedNavigator
builder: ExtendedNavigator<Router>(router: Router()),
);
}
}
I'm getting errors:
The argument type 'ExtendedNavigator' can't be assigned to the parameter type 'Widget Function(BuildContext, Widget)'.dart(argument_type_not_assignable) The type 'ExtendedNavigator' is declared with 0 type parameters, but 1 type arguments were given. Try adjusting the number of type arguments.dart(new_with_invalid_type_parameters)
on the other hand this is working fine:
return MaterialApp(
title: 'Covid Checker',
debugShowCheckedModeBanner: false,
initialRoute: Router.formPageView,
onGenerateRoute: Router.onGenerateRoute,
navigatorKey: Router.navigator.key,
theme: covidTheme(),
);
What am I doing wrong?
And the other question is how to add a nested navigator? Should it also be passed at the top level of the widget tree (MaterialApp)?
Hi! I'm using the linting rules specified by Flutter themselves in their repository and every time I go to debug my app, I have to click "Debug Anyways" because the generated router file throws an error. I ignored the file in my analysis_options.yaml
file but the Dart linter currently has a bug where when you open ignored files, the errors and/or warnings stay. The error I'm getting is when you define a route (MaterialPageRoute
, PageRoute
, CupertinoPageRoute
), it doesn't have a type argument such as MaterialPageRoute<dynamic>
.
There's other things like not defining type annotations for the route strings (couldn't you just make them all of type String
?) and the variable args
not being used at the top of onGenerateRoute()
but it doesn't bother me as much as the red errors. It would be great if you could just define the PageRoute
s type arguments to dynamic
.
I'm new to auto_route
and was looking for about 5 minutes for generated Arguments
class with no success. After that I found that:
if you define more then one parameter in your screen constructor autoRoute will automatically generate a class that holds your screen arguments and keep them typed
Even though a single argument Widget is pretty simple it still makes sense to use Arguments
class instead of passing argument as is.
Please remove this limitation and generate Arguments
class for routes with single param
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel dev, v1.15.3, on Microsoft Windows [Version 10.0.17763.437], locale zh-TW)
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[√] IntelliJ IDEA Community Edition (version 2019.3)
@MaterialAutoRouter()
class $ScreenRouter {
@initial
FeatureScreen2 featureScreen;
}
class FeatureScreen2 extends StatefulWidget {
@override
_FeatureScreen2State createState() => _FeatureScreen2State();
}
class _FeatureScreen2State extends State<FeatureScreen2> {
...
@override
Widget build(BuildContext context) {
MyLogger.info(msg: 'bar build', tag: tag);
return Scaffold(
key: _scaffoldKey,
bottomNavigationBar: _navBar,
body: Container(),
);
}
...
}
[+5192 ms] Compiler message:
[ ] ../../flutter/.pub-cache/hosted/pub.dartlang.org/auto_route-0.3.0/lib/src/extended_navigator.dart:79:56: Error: This expression has type 'void' and can't be used.
[ ] bool pop<T extends Object>([T result]) => _navigator.pop<T>(result);
[ ] ^
[+2399 ms] 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:compileFlutterBuildDebug'.
[ ] > 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 8s
This error happened after upgrading to v0.3.0
There's no compile error on the last version (v0.2.2)
Does the API has any version requirement?
I'm compiling my application for the web and I get the following error:
Target dart2js failed: Exception: /C:/flutter/.pub-cache/hosted/pub.dartlang.org/auto_route-0.4.0/lib/src/extended_navigator.dart:89:24:
Error: The getter 'isInitialRoute' isn't defined for the class 'RouteSettings'.
- 'RouteSettings' is from 'package:flutter/src/widgets/navigator.dart' ('/C:/flutter/packages/flutter/lib/src/widgets/navigator.dart').
if (route.settings.isInitialRoute &&
^^^^^^^^^^^^^^
Error: Compilation failed.
I've rebuild the router.gr.dart
file and still the issue persists.
I was using version 0.2.2
of this package, with the following setup
final Map<TabItem, WidgetBuilder> widgetBuilders;
final Map<TabItem, GlobalKey<NavigatorState>> navigatorKeys;
// in build method:
return CupertinoTabView(
navigatorKey: navigatorKeys[item],
builder: (context) => widgetBuilders[item](context),
onGenerateRoute: CupertinoTabViewRouter.onGenerateRoute,
);
// where
@CupertinoAutoRouter()
class $CupertinoTabViewRouter {
@CupertinoRoute(fullscreenDialog: false)
JobEntriesPage jobEntriesPage;
}
However, in recent versions, the generatedCupertinoTabViewRouter.onGenerateRoute
is no longer a static method.
So, how should I use the new API?
I've seen that the documentation shows some example code with MaterialApps(builder: ExtendedNavigator<Router>(router: Router()))
.
But this doesn't work in my case as I have multiple CupertinoTabView
s, each with its own widgetBuilder
.
If the solution is indeed to use ExtendedNavigator
, how can I adapt it to work with multiple tabs?
In my HomeScreen
's initState
I'm checking for Router.navigator.canNavigate(Router.secureScreen)
. If true it'll redirect there, if false it'll redirect to the login page.
Is there any way this (redirecting to login if canNavigate
is false) can be configured and done automatically for every page with a guard?
Hi there,
First, thanks for the awesome package!
I'm trying to use a nested navigator and I keep getting the following error:
Directives must appear before any declarations
When looking at router.gr.dart
, I'm seeing that imports are being duplicated for each declared router.
Here's my router.dart
file:
import 'package:animations/animations.dart';
import 'package:auto_route/auto_route.dart';
import 'package:auto_route/auto_route_annotations.dart';
import 'package:flutter/material.dart';
import 'package:scout_app/locator.dart';
import 'package:scout_app/router.gr.dart';
import 'package:scout_app/screens/secure/customer_edit_screen.dart';
import 'package:scout_app/screens/secure/customer_new_screen.dart';
import 'package:scout_app/screens/secure/customer_profile_screen.dart';
import 'package:scout_app/screens/secure/index_screen.dart';
import 'package:scout_app/screens/forgot_password_screen.dart';
import 'package:scout_app/screens/login_screen.dart';
import 'package:scout_app/screens/secure/staff_edit_screen.dart';
import 'package:scout_app/screens/secure/staff_new_screen.dart';
import 'package:scout_app/screens/secure/staff_profile_screen.dart';
import 'package:scout_app/services/session_service.dart';
@MaterialAutoRouter()
class $Router {
@CustomRoute(transitionsBuilder: fadeThroughTransition)
LoginScreen loginScreen;
@MaterialRoute(fullscreenDialog: true)
ForgotPasswordScreen forgotPasswordScreen;
@GuardedBy([AuthGuard])
@CustomRoute(initial: true, transitionsBuilder: fadeThroughTransition)
SecureScreen secureScreen;
}
@MaterialAutoRouter()
class $CustomerRouter {
@initial
CustomerProfileScreen customerProfileScreen;
CustomerNewScreen customerNewScreen;
@CustomRoute(transitionsBuilder: sharedAxisTransition)
CustomerEditScreen customerEditScreen;
}
@MaterialAutoRouter()
class $StaffRouter {
@initial
StaffNewScreen staffNewScreen;
StaffProfileScreen staffProfileScreen;
@CustomRoute(transitionsBuilder: sharedAxisTransition)
StaffEditScreen staffEditScreen;
}
And here's the output in router.gr.dart
:
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// AutoRouteGenerator
// **************************************************************************
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:auto_route/auto_route.dart';
import 'package:scout_app/screens/login_screen.dart';
import 'package:scout_app/router.dart';
import 'package:scout_app/screens/forgot_password_screen.dart';
import 'package:scout_app/screens/secure/index_screen.dart';
abstract class Routes{
static const loginScreen = '/login-screen';
static const forgotPasswordScreen = '/forgot-password-screen';
static const secureScreen = '/';
}
class Router extends RouterBase {
@override
Map<String, List<Type>> get guardedRoutes => {
Routes.secureScreen:[AuthGuard],};
//This will probably be removed in future versions
//you should call ExtendedNavigator.ofRouter<Router>() directly
static ExtendedNavigatorState get navigator =>
ExtendedNavigator.ofRouter<Router>();
@override
Route<dynamic> onGenerateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case Routes.loginScreen:
return PageRouteBuilder<dynamic>(pageBuilder: (ctx, animation, secondaryAnimation) => LoginScreen(), settings: settings,transitionsBuilder: fadeThroughTransition,);
case Routes.forgotPasswordScreen:
return MaterialPageRoute<dynamic>(builder: (_) => ForgotPasswordScreen(), settings: settings,fullscreenDialog:true,);
case Routes.secureScreen:
return PageRouteBuilder<dynamic>(pageBuilder: (ctx, animation, secondaryAnimation) => SecureScreen(), settings: settings,transitionsBuilder: fadeThroughTransition,);
default: return unknownRoutePage(settings.name);
}
}
}
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:auto_route/auto_route.dart';
import 'package:scout_app/screens/secure/customer_profile_screen.dart';
import 'package:scout_app/screens/secure/customer_new_screen.dart';
import 'package:scout_app/screens/secure/customer_edit_screen.dart';
import 'package:scout_app/router.dart';
import 'package:scout_app/models/customer.dart';
abstract class Routes{
static const customerProfileScreen = '/';
static const customerNewScreen = '/customer-new-screen';
static const customerEditScreen = '/customer-edit-screen';
}
class CustomerRouter extends RouterBase {
//This will probably be removed in future versions
//you should call ExtendedNavigator.ofRouter<Router>() directly
static ExtendedNavigatorState get navigator =>
ExtendedNavigator.ofRouter<CustomerRouter>();
@override
Route<dynamic> onGenerateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case Routes.customerProfileScreen:
if(hasInvalidArgs<String>(args
)){return misTypedArgsRoute<String>(args);}
final typedArgs = args as String
;return MaterialPageRoute<dynamic>(builder: (_) => CustomerProfileScreen(typedArgs), settings: settings,);
case Routes.customerNewScreen:
return MaterialPageRoute<dynamic>(builder: (_) => CustomerNewScreen(), settings: settings,);
case Routes.customerEditScreen:
if(hasInvalidArgs<Customer>(args
)){return misTypedArgsRoute<Customer>(args);}
final typedArgs = args as Customer
;return PageRouteBuilder<dynamic>(pageBuilder: (ctx, animation, secondaryAnimation) => CustomerEditScreen(typedArgs), settings: settings,transitionsBuilder: sharedAxisTransition,);
default: return unknownRoutePage(settings.name);
}
}
}
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:auto_route/auto_route.dart';
import 'package:scout_app/screens/secure/staff_new_screen.dart';
import 'package:scout_app/screens/secure/staff_profile_screen.dart';
import 'package:scout_app/screens/secure/staff_edit_screen.dart';
import 'package:scout_app/router.dart';
import 'package:scout_app/models/staff.dart';
abstract class Routes{
static const staffNewScreen = '/';
static const staffProfileScreen = '/staff-profile-screen';
static const staffEditScreen = '/staff-edit-screen';
}
class StaffRouter extends RouterBase {
//This will probably be removed in future versions
//you should call ExtendedNavigator.ofRouter<Router>() directly
static ExtendedNavigatorState get navigator =>
ExtendedNavigator.ofRouter<StaffRouter>();
@override
Route<dynamic> onGenerateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case Routes.staffNewScreen:
return MaterialPageRoute<dynamic>(builder: (_) => StaffNewScreen(), settings: settings,);
case Routes.staffProfileScreen:
if(hasInvalidArgs<String>(args
)){return misTypedArgsRoute<String>(args);}
final typedArgs = args as String
;return MaterialPageRoute<dynamic>(builder: (_) => StaffProfileScreen(typedArgs), settings: settings,);
case Routes.staffEditScreen:
if(hasInvalidArgs<Staff>(args
)){return misTypedArgsRoute<Staff>(args);}
final typedArgs = args as Staff
;return PageRouteBuilder<dynamic>(pageBuilder: (ctx, animation, secondaryAnimation) => StaffEditScreen(typedArgs), settings: settings,transitionsBuilder: sharedAxisTransition,);
default: return unknownRoutePage(settings.name);
}
}
}
I'm using version 0.4.3
.
Thanks in advance!
Hi thanks for your amazing work and lib. it is possible to have default value on routes?
My use case is, I have a wrapper class that I use for all my routes, this class has pageType
parameter, on each route definition, I want to pass the default value for this parameter. Thanks
You got my star on a very nice package there 👍.
Since I move from my handmade routing to auto_route, I encounter a bug or at least something to specify in the documentation.
If you have you personal route argument before the class, the generator will not match the class but rather the first class. So if you put the class argument first, it will generate a bad file.
class WidgetsListViewArguments {
final String title;
WidgetsListViewArguments({this.dataFuture, this.title});
}
class MainClass extends StatelessWidget {
const MainClass({Key key, this.title})
: super(key: key);
final String title;
@override
Widget build(BuildContext context) {
...
}
Should at least mention to either suppress them or put them after the class.
Hope this is clear.
Regards.
I want to use the home parameter of MaterialApp because my Initial route has parameter.
Or how to set this API in a such architecture : https://github.com/bizz84/starter_architecture_flutter_firebase
flutter packages pub run build_runner build
No .dart_tool/package_config.json file found, please run "pub get" first. Starting with Dart 2.7 this file configures the resolution of package import URIs. Running "pub get" will generate this file.
pub get
Resolving dependencies...
Because every version of auto_route_generator from path depends on auto_route from hosted and
example depends on auto_route from path, auto_route_generator from path is forbidden.
So, because example depends on auto_route_generator from path, version solving failed.
Hi there!
Very cool packages, can save a lot of time!
I have one question: Is it already possible or planned to integrate Nested Navigation with your Package?
So that we have a NestedRouter Class or so.
Best regards
Andy
Thanks for this awesome package.
Is there is anyway to customize route name instead of default variable name?
How to write middleware to check login status for each route
Hi,
There is a problem when using callback to generated route. for example if we have a class like this
class MyPage extends StatelessWidget {
const MyPage({
Key key,
@required this.id,
@required this.name,
@required this.callback,
}) : super(key: key);
final int id;
final String name;
final void Function(int id) callback;
}
the builder can not generate proper class for arguments, it failed immediately. and shows error
// Error: NoSuchMethodError: The getter 'source' was called on null.
// Receiver: null
// Tried calling: source
but using a typedef for the callback function fix the problem
typedef CustomCallback = void Function(int id);
Thanks for this awesome package to simplify routing.
In my use case, trying to provide a bloc to my route page seem impossible since the route file is auto regenerated on build_runner watch thus clearing my changes made to the route.gr.dart file. My suggestion would be to annotate a specific route with @noAutoGenerate or something related to disable the route from re-generating.
thanks.
Hi Milad, first of all thanks for an awesome Plugin.
I'm having an issue with my generated routes causing some sort of flutter error. My flutter program is never fully compiled (i.e Android Studio doesn't show the hot reload button). The UI actually works and you can navigate around.
Occurring for Android API 28 and 29.
I have no idea if this is an issue with the emulator, Flutter, Android Studio or the plugin generated code.
I generated my code based on Reso's tutorial:
https://resocoder.com/2020/01/10/flutter-zero-boilerplate-router-with-auto-route-flutter-navigation-tutorial/
But i get stuck with the following message:
D/FlutterView( 6866): Attaching to a FlutterEngine: io.flutter.embedding.engine.FlutterEngine@e184f11
D/FlutterActivityAndFragmentDelegate( 6866): Executing Dart entrypoint: main, and sending initial route: /
This is taking longer than expected...
Code:
Main.dart
import 'package:fhir_test/bloc/bloc.dart';
import 'package:fhir_test/route/router.gr.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider<PatientBloc>(
create: (BuildContext context) => PatientBloc(),
),
],
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
initialRoute: Router.homePage,
onGenerateRoute: Router.onGenerateRoute,
navigatorKey: Router.navigatorKey,
),
);
}
}
Router
import 'package:auto_route/auto_route_annotations.dart';
import 'package:fhir_test/ui/homePage.dart';
import 'package:fhir_test/ui/patientSearchPage.dart';
@autoRouter
class $Router {
@initial
HomePage homePage;
PatientSearchPage patientSearchPage;
}
Routes
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:auto_route/router_utils.dart';
import 'package:fhir_test/ui/homePage.dart';
import 'package:fhir_test/ui/patientSearchPage.dart';
class Router {
static const homePage = '/';
static const patientSearchPage = '/patientSearchPage';
static GlobalKey<NavigatorState> get navigatorKey =>
getNavigatorKey<Router>();
static NavigatorState get navigator => navigatorKey.currentState;
static Route<dynamic> onGenerateRoute(RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case Router.homePage:
return MaterialPageRoute(
builder: (_) => HomePage(),
settings: settings,
);
case Router.patientSearchPage:
if (hasInvalidArgs<PatientSearchPageArguments>(args)) {
return misTypedArgsRoute<PatientSearchPageArguments>(args);
}
final typedArgs =
args as PatientSearchPageArguments ?? PatientSearchPageArguments();
return MaterialPageRoute(
builder: (_) =>
PatientSearchPage(key: typedArgs.key, title: typedArgs.title),
settings: settings,
);
default:
return unknownRoutePage(settings.name);
}
}
}
//**************************************************************************
// Arguments holder classes
//***************************************************************************
//PatientSearchPage arguments holder class
class PatientSearchPageArguments {
final Key key;
final String title;
PatientSearchPageArguments({this.key, this.title});
}
Flutter Doctor:
[√] Flutter (Channel dev, v1.14.1, on Microsoft Windows [Version 10.0.17134.1130], locale en-AU)
• Flutter version 1.14.1 at C:\flutter
• Framework revision c88320458e (32 hours ago), 2020-01-15 11:38:02 -0500
• Engine revision bc41ab5139
• Dart version 2.8.0 (build 2.8.0-dev.1.0 fe666ce592)[√] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
• Android SDK at C:/Users/pullend/AppData/Local/Android/Sdk
• Android NDK location not configured (optional; useful for native profiling support)
• Platform android-29, build-tools 29.0.2
• ANDROID_HOME = C:/Users/pullend/AppData/Local/Android/Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)
• All Android licenses accepted.[√] Chrome - develop for the web
• Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe[√] Android Studio (version 3.5)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 42.1.1
• Dart plugin version 191.8593
• Java version OpenJDK Runtime Environment (build 1.8.0_202-release-1483-b03)[√] VS Code (version 1.41.1)
• VS Code at C:\Users\pullend\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.7.1[!] Proxy Configuration
• HTTP_PROXY is set
! NO_PROXY is not set[√] Connected device (3 available)
• AOSP on IA Emulator • emulator-5554 • android-x86 • Android 9 (API 28) (emulator)
• Chrome • chrome • web-javascript • Google Chrome 79.0.3945.117
• Web Server • web-server • web-javascript • Flutter Tools! Doctor found issues in 1 category.
Hi @Milad-Akarie on the newer version I can't push anymore MaterialPageRoute
for dynamic routes.
I'm using it extensively with nested navigators. Why you introduced this breaking change? thanks.
Route generator fails to generate a routeGenerator.dart class. Instead, the routeGenerator.gr.dart holds the following comment:
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// AutoRouteGenerator
// **************************************************************************
// Error: NoSuchMethodError: The getter 'isInSystemLibrary' was called on null.
// Receiver: null
// Tried calling: isInSystemLibrary
my $RouteGenerator class looks like this:
@AutoRouter(generateRouteList: true)
class $RouteGenerator {
@initial
LoadScreen loadScreen;
@CustomRoute(transitionsBuilder: TransitionsBuilders.fadeIn, durationInMilliseconds: 0, )
Application application;
SelectedCatagoryPage catagory;
SelectedRewardPage reward;
BusinessPage business;
@CustomRoute(transitionsBuilder: TransitionsBuilders.fadeIn, durationInMilliseconds: 0)
LoginPage login;
@CustomRoute(transitionsBuilder: TransitionsBuilders.fadeIn, durationInMilliseconds: 0)
OnBoard onBoard;
}
There are no broken imports, and no errors in my $RouteGenerator class.
I am getting a build error (below), while trying to add a new route.
[SEVERE] auto_route_generator:autoRouteGenerator on lib/routes/router.dart:
Error running AutoRouteGenerator
NoSuchMethodError: The getter 'isInSystemLibrary' was called on null.
Receiver: null
Tried calling: isInSystemLibrary
@autoRouter
class $Router {
@initial
LoginPage loginPage;
DashboardPage dashboardPage;
DashboardDetailPage dashboardDetailPage;
}
class DashboardDetailPage extends StatelessWidget {
// final dynamic itemPayload;
final String selectedType;
const DashboardDetailPage({Key key, this.selectedType}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(child: Text("HELL"));
}
}
if I comment DashboardDetailPage, then everything works fine. I want to add a dynamic route argument in this class/page.
Hello,
After upgrading library version from 0.2.2 to the newest one (0.4.1) I encountered an issue with Android system back button. Whenever I press it, even if I am not on initial route, application is being closed. If I call pop() method on my router, then it works in expected way. When I swipe back on iPhone, it also works.
I tried to go around it and add WillPopScope widget to my main page, but onWillPop was never called.
My MaterialApp:
MaterialApp(
title: translate(Keys.Common_App_Name),
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.supportedLocales,
locale: localizationDelegate.currentLocale,
theme: Themes.mainTheme(context),
builder: ExtendedNavigator<Router>(router: Router()),
)
fullscreenDialog
is only available in @MaterialRoute
and @CupertinoRoute
but should also be supported by a custom route with PageRouteBuilder
.
I have this widget and I'm using ValueChanged
from flutter
class AddressScreen extends StatefulWidget {
final ValueChanged<UserAddress> onAddressSelected;
final bool showCloseAsCross;
const AddressScreen(
{Key key, this.showCloseAsCross = false, this.onAddressSelected})
: super(key: key);
@override
AddressScreenState createState() => AddressScreenState();
}
and this is the generated argument
//**************************************************************************
// Arguments holder classes
//***************************************************************************
//AddressScreen arguments holder class
class AddressScreenArguments{
final Key key;
final bool showCloseAsCross;
final null onAddressSelected;
AddressScreenArguments({
this.key,this.showCloseAsCross = false,this.onAddressSelected});
}
I'm using auto_router
version 0.3.0
Hi,
I have trouble using this package with navKey. Do you have an example by any chance ?
I have declared :
static final navKey = new GlobalKey<ExtendedNavigatorState<Router>>();
but when I access navKey.currentState
is always null.
Regards,
Hey Milad,
after enjoying your injectable package, it would be really nice to also use the generated auto_route class with DI (i.e. for mocking, etc.). What about generating a non-static class? If anybody really, really wants the static variant, there is always a possibility of a singleton.
Cheers, Sascha
Hey,
since introduction of these argument classes, it is really hard to just call different routes by name receiving the same type of arguments. Is there any reason for this change to the previous version? It is still only a runtime check.
Cheers, Sascha
[This is more of a question than an issue]
Like a lot of apps, I've got a situation where a user can use a lot of the app without being logged in, but it gets to a point where they need to be logged in to continue to the next screen.
Imagine the user is on screen /a
and tries to navigate to screen /b
. If they're already logged in, pushing to /b
should go straight there, otherwise, they get taken via /login
which, after successful authentication, then sends them on to b
.
I guess it is sort of like the concept of the route guard, but with a bit more logic that allows a passthrough transition.
Any thoughts on whether there's some existing behaviour in auto_route that might help achieve this? Or any other pointers/suggestions? Thanks.
Hello Milad!
The same problem that happened in injectable mentioned in the issue no. 12 also happens in auto_route with route arguments.
final Option<Note> editedNoteOption;
const NoteFormPage({
Key key,
@required this.editedNoteOption,
}) : super(key: key);
generates the following erroneous import
import 'package:dartz/src/option.dart';
Maybe this can be renamed, it seems to be a convention for generated files.
Currently one has to manually add router.dart
to .gitignore where as router.g.dart
would often be ignored by default.
In my case I have to also change build files in CI because router.dart
doesn't match the pattern.
Maybe even allow changing the file name and path by adding an @AutoRouter()
annotation or something like this.
/// /lib/foo/bar_router.dart
import 'package:auto_route/auto_route_annotation.dart';
part 'bar_router.g.dart';
@AutoRouter()
class BarRouter with _BarRouter {
}
Your library generates classes encapsulating arguments for a page which is great. My question is how could I access a stack so that when I do pop
I can get what arguments have been passed to a previous page. In my case, all pages are of the same type and the only difference is something like a view model which one of argument injected into them.
Hello. I'm checking description:
ExtendedNavigator.of(context).pushSecondScreen(args...);
//or
ExtendedNavigator.ofRouter<Router>().pushSecondScreen(args...)
ExtendedNavigator.ofRouter<Router>()
works as expected - I can call pushSecondScreen
method. ExtendedNavigator.of(context)
doesn't have any page-specific methods. Is the description correct?
Is it possible to add observers? For example HeroController()
?
I have a drawer and I'm navigating to the pages by index. It would be great if in the generated class there was a list of all the routes so that I can just say for example Router.routes[index]
. I know that I could just maintain a list of all the routes myself but it would be cumbersome to maintain it over time and if I, say, add new routes and forget to add it to said list, my code would break. It would also avoid me having to create a function to get a route from the index. The list should be in the order that they are defined in the class.
Hi,
Pressing system back button inside nested navigator cause navigate to main navigator instead of returning ot prevoius page in nested navigator.
Main Navigator -> Main Page -> Nested Navigator -> Page A -> Page B
Pressing back button on Page B should return to Page A
My @required
annotations from my page parameters get lost inside the generated arguments classes.
I think it would be great if they get generated as well, maybe even some automatically generated asserts for @required
parameters.
it could be nice to use const and final variables in the generated files when it is possible
transitionDuration: const Duration(milliseconds: n),
instead of:
transitionDuration: Duration(milliseconds: n),
When I annotate a field with @CustomRoute
:
@CustomRoute(
transitionsBuilder: TransitionsBuilders.zoomIn,
durationInMilliseconds: 200,
)
ThirdPage thirdPage;
I would expect this in the generated file:
...
return PageRouteBuilder(
transitionsBuilder: TransitionsBuilders.zoomIn,
transitionDuration: Duration(milliseconds: 200),
pageBuilder: (ctx, animation, secondaryAnimation) =>
ThirdPage(userName: typedArgs.userName, points: typedArgs.points),
settings: settings,
);
...
Instead, transitionsBuilder
and transitionDuration
aren't passed in as arguments to the PageRouteBuilder
.
Hi,
Sorry for bothering you again ;) Up to this point I worked on the simulator and didn't care that the transition animation looked bad. Today I started to use real devices iPhone 5s, iPhone X and iPhone Xs Max. It looks bad on all of them. Instead of being smooth, it is very jerky. In addition to it when displaying the system alert it freezes the transition in the middle (a picture attached). I haven't touched anything related to transitions so it has to be a default push one. Any ideas how I can fix it? BTW before using the Router,
I had the Pave View and it was working very smoothly. Cheers,
mat
I just had a conflict with a route named settings
. This conflicts in the generated router class with RouteSettings settings
.
This can simply be fixed by always prepending the router class to all constant expressions:
case settings: // conflict
// to
case AppRouter.settings:
Hi there, thanks for this awesome package ❤️
Is it possible to customize the page when an unknown route is pushed? Or maybe provide the unknown page ourselves? The current unknown page is kinda scary IMHO haha.
Hello!
Even a simple widget like this:
import 'package:auto_route/auto_route_annotation.dart';
import 'package:flutter/material.dart';
@AutoRoute()
class PolicySelectorPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}
Causes a build error:
[SEVERE] auto_route_generator:autoRouteGenerator on lib/features/policies/ui/pages/policy_selector_page.dart:
Error running AutoRouteGenerator
RangeError: Value not in range: -1
I am running Flutter 1.9.1+hotfix.6 and package versions 0.111 for auto_route, 0.1.2 for auto_route_generator.
[INFO] Starting Build
[INFO] Updating asset graph...
[INFO] Updating asset graph completed, took 1ms
[INFO] Running build...
[INFO] Running build completed, took 7ms
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 14ms
[INFO] Succeeded after 23ms with 0 outputs (0 actions)
and it stops here . I got noting file names like Route.dart.
There is nothing special about the initial route compared to other routes.
It should be possible to make this a material/cupertino/custom route so that a back navigation will use the correct animation.
Currently it always is a MaterialPageRoute
and it is required. In order to circumvent this, I always create a dummy route with @InitialRoute()
but don't use it.
Hello
How to pass arguments to the initial route?
BR,
Hi,
With respect to your latest changes to auto_route, I am looking for a way to render a widget that can be accessible across the app. Earlier I used to something like this:
MaterialApp(
builder: (BuildContext context, Widget widget) {
setErrorBuilder();
return Column(
children: <Widget>[
Expanded(
child: widget,
),
AlertsScreen(),
],
);
},
title: 'App name',
onGenerateRoute: Router.onGenerateRoute,
initialRoute: Router.splashScreen,
navigatorKey: Router.navigator.key,
),
But now since the builder is used for Navigation I am unable to mount AlertsScreen
widget into the app. Is there a way to mount a common widget which can be accessible across the app?
Is it possible to get the right context for such common widgets as the below code used to throw the error:
code:
//AlertsScreen.dart
Flushbar(
title: 'title',
message: 'body',
duration: const Duration(seconds: 5),
).show(context);
error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Navigator operation requested with a context that does not include a Navigator. The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
Thanks
Just updated to new v0.3.0 and can't build Flutter app anymore.
Compiler message:
../../../flutter/.pub-cache/hosted/pub.dartlang.org/auto_route-0.3.0/lib/src/extended_navigator.dart:79:56: Error: This expression has type 'void' and can't be used.
bool pop<T extends Object>([T result]) => _navigator.pop<T>(result);
My Flutter version:
[✓] Flutter (Channel dev, v1.15.3, on Mac OS X 10.14.6 18G103, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 11.3.1)
[✓] Android Studio (version 3.5)
[✓] VS Code (version 1.42.1)
[✓] Connected device (1 available)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.