FloatingActionButton Example

FloatingActionButton Example #

This is an example to demostrate how you can navigate to another page in Flutter when clicking on a FloatingActionButton.

First, create a new StatefulWidget called HomePage that will display the FloatingActionButton:

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: const Center(
        child: Text('This is the home page'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => const SecondPage()),
          );
        },
        child: const Icon(Icons.navigate_next),
      ),
    );
  }
}

In the build method of this widget, you can see that we have defined a FloatingActionButton with an onPressed callback. Inside this callback, we are using the Navigator.push method to navigate to another page. In this case, we are using the MaterialPageRoute class to define the new page we want to navigate to.

Next, create a new StatelessWidget called SecondPage that will display the second page:

import 'package:flutter/material.dart';

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Second Page'),
      ),
      body: const Center(
        child: Text('This is the second page'),
      ),
    );
  }
}

In this widget, we are defining the layout for the second page. We’ve added a Scaffold with an AppBar and a Center widget that displays some text.

Finally, to display the HomePage widget, you can add it to your MaterialApp widget in your main.dart file:

import 'package:flutter/material.dart';

import 'home_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

That’s it! Now, when you run your app, you should see a FloatingActionButton on the HomePage. When you click on it, you should be navigated to the SecondPage.