Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is onUnknownRoute in flutter

I'm new to flutter, In MaterailApp Widget have an attribute called onUnknownRoute. What is the main use of onUnknownRoute?

Thanks for your help!

like image 674
Magesh Pandian Avatar asked Jan 26 '23 06:01

Magesh Pandian


1 Answers

You can copy paste run full code below
In flutter web, when user manually key a undefine route, it can produce like 404 effect

enter image description here

full code

import 'package:flutter/material.dart';

void main() {
  runApp( MaterialApp(    
    initialRoute: "/screen1",
    routes: <String, WidgetBuilder>{
      '/screen1': (BuildContext context) =>  Screen1(),
      '/screen2': (BuildContext context) =>  Screen2(),
      '/screen3': (BuildContext context) =>  Screen3(),
      '/screen4': (BuildContext context) =>  Screen4()
    },
    onUnknownRoute: (RouteSettings settings) {
      return MaterialPageRoute<void>(
        settings: settings,
        builder: (BuildContext context) =>
            Scaffold(body: Center(child: Text('Not Found'))),
      );
    },
  )
  );
}

class Screen1 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class Screen2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class Screen3 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

class Screen4 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
like image 120
chunhunghan Avatar answered Feb 07 '23 22:02

chunhunghan