'Call method on a different page using FloatingActionButton in Flutter
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
Solution 1:[1]
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,
),
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dharman |
| Solution 2 | Iliya Mirzaei |
