How to tap existing flutter widget onTap / onPressed with code?

54 views Asked by At

I want to make an app with a gamepad, I succeeded in making a tap function but there is no tap effect like pressing a manual widget,

How do I make the widget button have an effect like a manual tap?

this is the code I made:

// ignore_for_file: unnecessary_brace_in_string_interps

import 'package:flutter/material.dart';
import 'package:gamepads/gamepads.dart';
 


class _MyHomePageState extends State<MyHomePage> {
  int counter = 0;
  GlobalKey floatingKey = GlobalKey();
  

  @override
  void initState() {
    super.initState();
    task();
  }

  Future<void> task() async {
    Gamepads.events.listen(gamePadE);
    
  }

  void gamePadE(GamepadEvent gamepadEvent) {
    
      try {
        FloatingActionButton floatingActionButton = (floatingKey.currentWidget as FloatingActionButton);
        floatingActionButton.onPressed!();

        setState(() {
          counter += 1;
        }); 
      } catch (e) {}
  }

 

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // ---
      // more code 
      // ---
      floatingActionButton: FloatingActionButton(
        key: floatingKey,
        onPressed: () {
          print("ON PRESSED");
        },
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

How do I make the widget button have an effect like a manual tap?

enter image description here

1

There are 1 answers

1
Autocrab On

You can move callback to function and call it:

void onFloatingActionButtonTap() {
  print("ON PRESSED"); 
}

Define it in FAB constructor:

floatingActionButton: FloatingActionButton(
        key: floatingKey,
        onPressed: onFloatingActionButtonTap,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      )

Use it in gamepad events:

 void gamePadE(GamepadEvent gamepadEvent) {
    
      try {
        onFloatingButtonTap();

        setState(() {
          counter += 1;
        }); 
      } catch (e) {}
  }