How to Pass Parameters to Flutter Web App

How to Pass Parameters to Flutter Web App ??

when we build a mobile application we need to pass data using the get or post method. so in today’s article, we will go through how to pass Parameters to Flutter Web App.

How to Pass Parameters to Flutter Web App??

You can get everything (paths, parameters, etc) from onGenerateRoute. Your Home will be / and everything from there can be grabbed and used to redirect users.

My approach to solving this is the following. Your base App() should be like:

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Website Title',
      onGenerateRoute: (settings) => NavigatorRoute.route(settings.name),
    );
  }
}

and the class NavigatorRoute will be:

class NavigatorRoute extends StatefulWidget {
  final String path;

  static Route<dynamic> route(String path) {
    return SimpleRoute(
      name: '', // this one is always empty as you didn't route yet
      title: 'Website Title',
      builder: (_) => NavigatorRoute(path: path),
      animated: false
    );
  }

  const NavigatorRoute({Key key, this.path}) : super(key: key);

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

class _NavigatorRouteState extends State<NavigatorRoute> {

  @override
  void initState() {
    super.initState();
    Future.microtask(() {
      if (widget.path == '/') {
        Navigator.of(context).pushAndRemoveUntil(HomeScreen.route(false), (_) => false);
        return;
      } else if (widget.path == '/user') {
        Navigator.of(context).pushAndRemoveUntil(UserScreen.route(false), (_) => false);
        return;
      } else if (widget.path.contains('/user/')) {
        Navigator.of(context).pushAndRemoveUntil(UserScreen.routeCode(widget.path.split('/')[2]), (_) => false);
        return;
      } else if (widget.path == '/about') {
        Navigator.of(context).pushAndRemoveUntil(AboutScreen.route(), (_) => false);
        return;
      } else {
        Navigator.of(context).pushAndRemoveUntil(HomeScreen.route(), (_) => false);
        return;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SizedBox();
  }
}

So the code for the SimpleRoute is:

class SimpleRoute extends PageRoute {
  SimpleRoute({@required String name, @required this.title, @required this.builder, @required this.animated})
      : super(settings: RouteSettings(name: name));

  final String title;
  final WidgetBuilder builder;

  final bool animated;

  @override
  Color get barrierColor => null;

  @override
  String get barrierLabel => null;

  @override
  bool get maintainState => true;

  @override
  Duration get transitionDuration => Duration(milliseconds: 200);

  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
    return animated
        ? FadeTransition(
            opacity: animation,
            child: Title(
              title: this.title,
              color: Theme.of(context).primaryColor,
              child: builder(context),
            ),
          )
        : Title(
            title: this.title,
            color: Theme.of(context).primaryColor,
            child: builder(context),
          );
  }
}

So, finally… if you want to easily open one of your screens, you can do:

class HomeScreen extends StatefulWidget {
  static Route<dynamic> route(bool animated) {
      return SimpleRoute(name: '/', title: 'Home', builder: (_) => HomeScreen(), animated: animated);
  }

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

class _HomeScreenState extends State<HomeScreen> {
...
}

The routeCode could be:

static Route<dynamic> routeCode(String id) {
     return SimpleRoute(name: '/user/$id', title: 'User', builder: (_) => UserScreen(id: id), animated: false);
}

So the main benefit of doing this is avoiding the stack of pages generated by accessing the last screen.

It works efficiently and cleanly you only need to add one routing file and do all the routing in one file rather than editing every page you want to route to, here’s how you would implement it:

main.dart will have a code snippet like the below:

void main() {
  FluroRouter.setupRouter();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Website Title',
      onGenerateRoute: FluroRouter.router.generator
    );
  }
}

fluro_router.dart will have a code snippet like the below:

class FluroRouter {
  static Router router = Router();
  //Define  your routers here
  static void setupRouter() {
    router.define('/', handler: _homeHandler);
    router.define('/login', handler: _loginHandler);
    router.define('/online-enquiry/:userId', handler: _userHandler);
  }
  //Add your handlers here
  static Handler _homeHandler = Handler(handlerFunc: (context, Map<String, dynamic> params) => Home());
  static Handler _loginHandler = Handler(handlerFunc: (context, Map<String, dynamic> params) => Login());
  static Handler _userHandler = Handler(handlerFunc: (context, Map<String, dynamic> params) => UserProfile(userID: params['userId'].first));
}

Conclusion:

So in this article, we have been through how to pass parameters to flutter web app.

Keep Learning !!! Keep Fluttering !!!

Do let us know in the comments if you are still confused in flutter!!

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *

Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Build Your Agile Team

Hire Skilled Developer From Us

"*" indicates required fields

✓ Valid number ✕ Invalid number

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number