URLs in Flutter with Example

In Flutter, you can navigate between screens using URLs. To do this, you need to use the Flutter Navigator class and define a named route for each screen in your app.

Here is an example of how to use URLs in Flutter

Define your named routes in your main.dart file

import 'package:flutter/material.dart';
import 'package:flutter_blog/screens/home_screen.dart';
import 'package:flutter_blog/screens/post_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Blog',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/post': (context) => PostScreen(),
      },
    );
  }
}ā€‹

In this example, we have defined two routes: '/' for the home screen and '/post' for the post screen.

In your home screen widget, add a button that will navigate to the post screen

import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Read Post'),
          onPressed: () {
            Navigator.pushNamed(context, '/post');
          },
        ),
      ),
    );
  }
}ā€‹

In this example, we are using the Navigator class to navigate to the post screen when the button is pressed.

In your post screen widget, add a back button that will navigate back to the home screen

import 'package:flutter/material.dart';
class PostScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Go back'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}ā€‹

In this example, we are using the Navigator class to navigate back to the home screen when the button is pressed.

Finally, run your app and test the navigation between screens using the URLs:

flutter run

This is just a basic example of how to use URLs in Flutter. You can customize the routes and the navigation to fit your app's specific needs.