skip to Main Content

So I face an error when using webview_flutter and I am not sure how to fix it:

In my Page.dart I have the below onTap actions:

Navigator.pushNamed(context, WebView.routeName,
   arguments:
      MyPageArguments("Page Title1", "https://example1.com"));
    
Navigator.pushNamed(context, WebView.routeName,
   arguments:
      MyPageArguments("Page Title2", "https://example2.com"));

class MyPageArguments {
  final String title;
  final String url;
  MyPageArguments(this.title, this.url);
}

Then in my WebView.dart I do the following:

class WebView extends StatefulWidget {
  static const routeName = '/myRoute';
  final String title;
  final String url;

  const WebView({
    super.key,
    required this.title,
    required this.url,
  });

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

class _WebViewState extends State<WebView> {
     //Remaining code
}

And in my main.dart I try to define the route:

  '/myRoute': (context) => WebView(),

But I get the following error:

The named parameter 'title' is required, but there's no corresponding argument. (Documentation)

Try adding the required argument.

So I should do something like the example below, however I am not sure how to pass the dynamic title and url parameters to main.dart:

'/myRoute': (context) => WebView(title: "Page Title1", url: "https://example1.com"),

2

Answers


  1. While you are already using route arguments, you can remove WebView ‘s constructor parameters or make them option(with nullable dataType).

    Your WebView state class will access the route arguments.

    class WebView extends StatefulWidget {
      static const routeName = '/myRoute';
      const WebView({super.key});
      @override
      _WebViewState createState() => _WebViewState();
    }
    
    class _WebViewState extends State<WebView> {
      @override
      Widget build(BuildContext context) {
        final routeArguments = ModalRoute.of(context)?.settings.arguments as MyPageArguments?;
    
        final url = routeArguments?.url;
        final title = routeArguments?.title;
        return SizedBox();
      }
    }
    

    You can check my another answer with more example code.

    Login or Signup to reply.
  2. You can use onGenerateRoute in MaterialApp

    Route<dynamic> onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case WebView.routeName:
        return MaterialPageRoute(
            settings: settings, builder: (_) => const WebView(
              args: settings.arguments as MyPageArguments
            ))
            }}
    

    in WebView you should declare MyPageArguments

    final MyPageArguments args;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search