Home > Back-end >  Call a function inside Flutter Widget
Call a function inside Flutter Widget

Time:08-08

I am pretty new to OOP and Flutter. I created the following widget and want to call the widget function when creating it inside another stateless Widget.

My plan is to create the widget as a child and then use the defined variable widgetState to check if it is true and if it is, it should call the void printSample() function. The conditional check shout be triggered by onTap of the widget (InkWell).

Widget with the Function:

class WhiteCard extends StatelessWidget {
  final widgetState = true;
  final VoidCallback onTap;
  final Color switchColor = Colors.red;

  void printSample() {
    print("Sample text");
  }
  
  const WhiteCard({
    Key? key,
    required this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Container(
        width: 320,
        height: 200,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(18),
          color: Colors.white,
        ),
        child: Center(
          child: ScreenController.isLargeScreen(context)
              ? Text("large")
              : ScreenController.isMediumScreen(context)
                  ? Text("medium")
                  : Text("small"),
        ),
      ),
    );
  }
}

Widget that calls the WhiteCard()

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

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        color: Colors.orangeAccent,
        child: Center(
          child: WhiteCard(
            onTap: () {
              CALL THE FUNCTION FROM WIDGET);
            },
          ),
        ),
      ),
    );
  }
}

CodePudding user response:

Well if I understood your question correctly then your onTap should be something like this:

onTap: () {
  if (widgetState) {
     printSample();
  }

Good luck, Feel free to respond if you have queries

CodePudding user response:

You can also define a function to leave the definition of object cleaner:

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

  onTapFunction() {
    // write he whatever you need to do when taping widget
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Container(
        color: Colors.orangeAccent,
        child: Center(
          child: WhiteCard(
            onTap: onTapFunction,
          ),
        ),
      ),
    );
  }
}

So if you need to call the onTapFunction from elsewhere, you can.

  • Related