Home > database >  How to define the body of a method in Flutter
How to define the body of a method in Flutter

Time:12-03

I am actaully embarrassed to ask this question as I don't remember how it is done. I am trying to define a method that I can change its body whenever I need. It will be used for a floating action button that will have a certain function in each page of a PageView(). I didn't find anything about it, so can someone remind me of what and how this is done?

CodePudding user response:

If you want to define a method that can be changed or customized in different pages of a PageView in Flutter, you can use a closure or a lambda expression to create a function that can be passed to the floating action button.

Here is an example of how you can define a floating action button with a lambda expression that can be customized in different pages of a PageView:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: PageView(
        children: [
          MyHomePage(),
          MySecondPage(),
          MyThirdPage(),
        ],
      ),
    );
  }
}

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => print('Button pressed on Home Page'),
      ),
    );
  }
}

class MySecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => print('Button pressed on Second Page'),
      ),
    );
  }
}

class MyThirdPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        onPressed: () => print('Button pressed on Third Page'),
      ),
    );
  }
}

In this example, the onPressed property of the floating action button is set to a lambda expression that defines the action to be performed when the button is pressed. This lambda expression is different for each page of the PageView, so the button will have a different function on each page.

  • Related