Home > Enterprise >  Call method on a different page using FloatingActionButton in Flutter
Call method on a different page using FloatingActionButton in Flutter

Time:03-16

I'm trying to call a method(defined in a different page), using the Floating Action Button from another page.

FloatingActionButton

floatingActionButton: FloatingActionButton(
      onPressed: () {},
      child: Icon(
        Icons.add,
        color: Colors.white70,
      ),
      splashColor: Colors.blueGrey,
      backgroundColor: Colors.blueAccent,
    ),

Method which I need to call is inside

void _showForm(int? id) async {}

_showForm returns showModalBottomSheet

CodePudding user response:

Set up the method in a separate .dart file or outside any other class. Remember to include the BuildContext in the arguments:

import 'package:flutter/material.dart';

showForm(int id, BuildContext ctx) {
  return showModalBottomSheet(
    context: ctx,
    builder: (ctx) => BottomSheet(
      onClosing: () {},
      builder: (ctx) => Container(
        height: 200,
        child: Center(
          child: Text('Hello, there!'),
        ),
      ),
    ),
  );
}

Now, import the .dart file where your floating action button is and call the method in the onPressed callback:

 floatingActionButton: FloatingActionButton(
    onPressed: () {
      showForm(1, context);
    },
    child: Icon(
      Icons.add,
      color: Colors.white70,
    ),
    splashColor: Colors.blueGrey,
    backgroundColor: Colors.blueAccent,
  ),

CodePudding user response:

Just pass the function to your FAB (Floating Action Button) Page. You can see an example here: Pass method as parameter to a widget

  • And by the way, voidCallBack is just a nice word instead of "void" type.
  • Related