सार्वजनिक जानकारी से बना चयन मार्गदर्शन। केवल संदर्भ हेतु।
ff_annotation_route एक Flutter पैकेज है जो एनोटेशन के माध्यम से स्वचालित रूप से रूट मैप बनाकर रूट प्रबंधन को सरल बनाता है। डेवलपर्स अपने कोड में सरल एनोटेशन का उपयोग करके रूट को परिभाषित कर सकते हैं, और पैकेज संकलन समय पर आवश्यक नेविगेशन तर्क उत्पन्न करता है। इससे बॉइलरप्लेट कम होता है और नेविगेशन सेटअप में त्रुटियाँ कम होती हैं। यह macOS, Windows और Linux जैसे बहुत सारे प्लेटफॉर्म का समर्थन करता है, जिससे यह क्रॉस-प्लेटफॉर्म एप्लिकेशन के लिए आदर्श है। पैकेज Flutter के नेविगेशन सिस्टम के साथ बिना किसी दिक्कत के एकीकृत होता है और विकास गति और रखरखाव में सुधार करता है।
उपयोग
स्वचालित मार्ग उत्पादन
नेविगेशन सेटअप को सरल बनाना
बॉयलरप्लेट कोड कम करना
क्रॉस-प्लेटफॉर्म एप्प डेवलपमेंट
साफ रूट परिभाषाओं को बनाए रखना
मुख्य विशेषताएँ
संकलन समय मार्ग उत्पादन
अनुमान-आधारित रूट परिभाषा
न्यूनतम बॉयलरप्लेट
प्लेटफॉर्म-समर्थन
Flutter नेविगेशन के साथ एकीकरण
इनके लिए उपयुक्त
कुशल रूटिंग समाधान खोज रहे विकासकर्ता
कोड रखरखाव को प्राथमिकता देने वाली टीमें
त्वरित मार्ग संरचना की आवश्यकता वाले प्रोजेक्ट
कई डेस्कटॉप प्लेटफॉर्म के लिए फ्लटर ऐप्स
जटिल नेविगेशन संरचना वाले ऐप्स
विचार योग्य बातें
कोड जनरेशन के लिए build_runner की आवश्यकता है
स्थिर मार्ग परिभाषाओं तक सीमित
थोड़ा बिल्ड समय बढ़ा सकता है
गतिशील मार्ग लोडिंग के लिए उपयुक्त नहीं
अनुलेखन प्रसंस्करण पर निर्भर
मूल README
संबंधित सोर्स रिपॉज़िटरी के मूल README का स्नैपशॉट। नवीनतम सामग्री के लिए रिपॉज़िटरी देखें।
Analysis: Resolve constructor signatures, infer needed imports (when not in fast mode or when using @FFAutoImport), build argument helper factories & codes map.
Emission: Produce routes file(s) + optional constants, argument helper classes, and mapping switch statements consumed by different navigation strategies.
Fast Mode vs Non-Fast Mode
Mode
Speed
Import inference
Super parameters helper
Recommended when
Fast (default)
Very fast
Manual (@FFAutoImport / argumentImports)
Limited
Large codebase frequent regen
Non-Fast (--no-fast-mode)
Slower
Automatic (constructor param types)
Full
Initial setup / complex generics
Nested Router Example
Use multiple FFRouterDelegate + FFRouteInformationParser instances (e.g. inside a tab) with ChildBackButtonDispatcher to correctly manage system back events. See example1 nested router demo.
Interceptors & Lifecycle
Per‑route interceptors declared directly on @FFRoute(interceptors: [...]) and global interceptors registered via RouteInterceptorManager. Lifecycle mixin RouteLifecycleState adds onPageShow/onPageHide/onForeground/onBackground/onRouteShow/onRouteHide for both pages and dialogs (via ExtendedRouteObserver).
Deep Link & Query Parsing
On web (Navigator 2.0) queries like ...?list=[1,2]&testMode={"id":2,"isTest":true} are converted using customizable FFConvert.convert to strong types (List, custom model etc.).
Monorepo / Multi-Package
Use --git to scan packages under melos or multi‑package workspace; exclude with --exclude-packages. Generates cross‑package route maps while respecting package boundaries.
Performance Notes
Prefer fast mode for CI or iterative development; switch to non‑fast to ensure imports & super arguments helpers are correct before release.
Troubleshooting
Missing import for a constructor param: add @FFAutoImport() above the import or specify in argumentImports or disable fast mode.
Interceptor not firing: ensure you use provided push APIs (pushNamedWithInterceptor) or route wrapper is not replacing settings.
Lifecycle not triggered: add ExtendedRouteObserver to navigatorObservers and ensure widget extends RouteLifecycleState.
Query parsing type errors: customize FFConvert.convert to handle your model/collection shape.
For an in‑depth Chinese deep dive see: 技术文章-ff_annotation_route深度解析.md.
The tool will handle it. What you should take care is that provide import url by setting argumentImports if it has
class/enum argument.you can use @FFAutoImport() instead now.
or you can use --no-fast-mode for now, it will add parameters refer import automatically.
@FFAutoImport('hide TestMode2')
import'package:example1/src/model/test_model.dart';
@FFAutoImport()
import'package:example1/src/model/test_model1.dart'hideTestMode3;
import'package:ff_annotation_route_library/ff_annotation_route_library.dart';
@FFRoute(
name: 'flutterCandies://testPageE',
routeName: 'testPageE',
description: 'Show how to push new page with arguments(class)',
// argumentImports are still work for some cases which you can't use @FFAutoImport()// argumentImports: <String>[// 'import \'package:example1/src/model/test_model.dart\';',// 'import \'package:example1/src/model/test_model1.dart\';',// ],
exts: <String, dynamic>{
'group': 'Complex',
'order': 1,
},
)
classTestPageEextendsStatelessWidget{
constTestPageE({
this.testMode = constTestMode(
id: 2,
isTest: false,
),
this.testMode1,
});
factoryTestPageE.deafult() => TestPageE(
testMode: TestMode.deafult(),
);
factoryTestPageE.required({@requiredTestMode testMode}) => TestPageE(
testMode: testMode,
);
finalTestMode testMode;
finalTestMode1 testMode1;
}
FFRoute
Parameter
Description
Default
name
The name of the route (e.g., "/settings")
required
showStatusBar
Whether to show the status bar.
true
routeName
The route name to track page.
''
pageRouteType
The type of page route.(material, cupertino, transparent)
-
description
The description of the route.
''
exts
The extend arguments.
-
argumentImports
The imports of arguments. For example, class/enum argument should provide import url. you can use @FFAutoImport() instead now.
-
codes
to support something can't write in annotation, it will be hadnled as a code when generate route. see
-h, --[no-]help Help usage
-p, --path Flutter project root path
(defaults to ".")
-n, --name Routes constant class name.
(defaults to "Routes")
-o, --output The path of main project route file and helper file.It is relative to the lib directory
-g, --git scan git lib(you should specify package names and split multiple by ,)
--exclude-packages Exclude given packages from scanning
--routes-file-output The path of routes file. It is relative to the lib directory
--generated-file-prefix Replace packageName in generated route files, for example foo for foo_route(.g).dart and foo_routes(.g).dart
--const-ignore The regular to ignore some route consts
--[no-]package Is this a package
--[no-]super-arguments Whether generate page arguments helper class
-s, --[no-]save Whether save the arguments into the local
It will execute the local arguments if run "ff_route" without any arguments
--[no-]null-safety enable null-safety
(defaults to on)
--[no-]arguments-case-sensitive arguments is case sensitive or not
(defaults to on)
--[no-]fast-mode fast-mode: only analyze base on single dart file, it's fast.
no-fast mode: analyze base on whole packages and sdk, support super parameters and add parameters refer import automatically.
(defaults to on)
import'dart:convert';
import'package:example1/src/model/test_model.dart';
import'package:ff_annotation_route_library/ff_annotation_route_library.dart';
import'package:flutter/foundation.dart';
import'package:flutter/material.dart';
import'example1_route.dart';
import'example1_routes.dart';
voidmain() {
// tool will handle simple types(int,double,bool etc.), but not all of them.// for example, you can type in web browser// http://localhost:64916/#flutterCandies://testPageF?list=[4,5,6]&map={"ddd":123}&testMode={"id":2,"isTest":true}// the queryParameters will be converted base on your case.FFConvert.convert = <T>(dynamic value) {
if (value == null) {
returnnull;
}
print(T);
finaldynamic output = json.decode(value.toString());
if (<int>[] is T && output isList<dynamic>) {
return output.map<int>((dynamic e) => asT<int>(e)).toList() as T;
} elseif (<String, String>{} is T && output isMap<dynamic, dynamic>) {
return output.map<String, String>((dynamic key, dynamic value) =>
MapEntry<String, String>(key.toString(), value.toString())) as T;
} elseif (constTestMode() is T && output isMap<dynamic, dynamic>) {
returnTestMode.fromJson(output) as T;
}
return json.decode(value.toString()) as T;
};
runApp(MyApp());
}
classMyAppextendsStatelessWidget{
finalFFRouteInformationParser _ffRouteInformationParser =
FFRouteInformationParser();
finalFFRouterDelegate _ffRouterDelegate = FFRouterDelegate(
getRouteSettings: getRouteSettings,
pageWrapper: <T>(FFPage<T> ffPage) {
return ffPage.copyWith(
widget: ffPage.name == Routes.fluttercandiesMainpage ||
ffPage.name == Routes.fluttercandiesDemogrouppage.name
? ffPage.widget
: CommonWidget(
child: ffPage.widget,
routeName: ffPage.routeName,
),
);
},
);
// This widget is the root of your application.@overrideWidgetbuild(BuildContext context) {
returnMaterialApp.router(
title: 'ff_annotation_route demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
// initialRoute
routeInformationProvider: PlatformRouteInformationProvider(
initialRouteInformation: constRouteInformation(
location: Routes.fluttercandiesMainpage,
),
),
routeInformationParser: _ffRouteInformationParser,
routerDelegate: _ffRouterDelegate,
);
}
}
FFRouteInformationParser
It's working on Web when you type in browser or report to browser. A delegate that is used by the [Router] widget to parse a route information
into a configuration of type [RouteSettings].
Detect page lifecycle events easily by extending RouteLifecycleState:
class_PageAStateextendsRouteLifecycleState<PageA> {
@overridevoidonPageShow() {
print('PageA is now visible');
// Refresh data, resume animations, track analytics
}
@overridevoidonPageHide() {
print('PageA is now hidden');
// Pause animations, save state
}
@overridevoidonForeground() {
print('App returned to foreground');
// Refresh real-time data
}
@overridevoidonBackground() {
print('App went to background');
// Pause tasks, release resources
}
}
Don't forget to add ExtendedRouteObserver to your MaterialApp:
Here are the possible scenarios corresponding to RouteInterceptResult.complete, RouteInterceptResult.next, and RouteInterceptResult.abort:
/// Represents the possible actions a route interceptor can take/// after being invoked during the route interception process.enumRouteInterceptAction {
/// Stops the interception chain and cancels any further actions./// This indicates that the current interceptor has determined/// that no route should be pushed, and the navigation process should be aborted.
abort,
/// Moves to the next interceptor in the chain./// This indicates that the current interceptor does not want to handle/// the route and delegates the decision to subsequent interceptors.
next,
/// Completes the interception process and allows the route to be pushed./// This indicates that the current interceptor has handled the route/// and the navigation should proceed as expected.
complete,
}
Add interceptors Annotation
Add an interceptors annotation to the page for route interception.
[ExtendedRouteObserver] is a utility class that extends the functionality of
Flutter's built-in RouteObserver. It allows for more advanced route
management and tracking in the navigation stack. This class maintains
an internal list of active routes and provides several utility methods
for route inspection and manipulation.
Key features of [ExtendedRouteObserver]:
Tracks all active routes in the navigation stack.
Provides access to the top-most route via the topRoute getter.
Allows checking if a specific route exists in the stack with containsRoute().
Enables retrieval of a route by its name using getRouteByName().
Notifies subscribers when a route is added or removed via onRouteAdded and onRouteRemoved.
Supports custom actions when a route is added or removed via onRouteAdd() and onRouteRemove().
This class is useful in cases where global route tracking or advanced
navigation behavior is needed, such as:
Monitoring which routes are currently active.
Handling custom navigation logic based on the current route stack.
Implementing a navigation history feature or a breadcrumb-style navigator.
By leveraging this class, developers can gain better insight into and
control over their app's navigation state.
GlobalNavigator class is a utility class for managing global navigation actions.
It provides easy access to the Navigator and BuildContext from anywhere in the app.
context is a crucial part of Flutter, involving many key functionalities such as themes, routing, and dependency injection. Flutter’s design philosophy is based on the propagation of context through the widget tree, allowing context to access relevant information and functionalities, which helps maintain good component separation and maintainability.
While it is possible to directly access the Navigator or context via a global navigatorKey in certain situations, it is generally not recommended to use this approach regularly, especially when Flutter’s recommended patterns (such as accessing via context) work well.
This approach can introduce some potential issues:
Violates Flutter’s Design Philosophy: Flutter’s original design is based on localized navigation and state management through BuildContext. Bypassing context with a global approach may lead to state management confusion and make the code harder to maintain.
Potential Performance Issues: Accessing context globally may bypass Flutter’s optimization mechanisms, as Flutter relies on the context tree’s structure for efficient UI updates.
Poor Maintainability: Relying on global navigation can make the code more difficult to understand and maintain, especially as the app grows larger. It may become hard to track navigation flow and state.