Last active
October 31, 2021 18:22
-
-
Save loushou/2b3c4e46a7931b40fc15a15069a03cec to your computer and use it in GitHub Desktop.
Flutter - Programmatically trigger button without directly tapping it #flutter #statemanagement #provider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
The goal of this is to show you how to abstract the action of tapping a button, | |
such that it can be triggered from some other code. In this case we trigger one | |
button's action from tapping another button... but the principle should carry | |
over if you are triggering it from somewhere else in the code as well, possibly | |
not related to a user button tap (maybe after a certain amount of time, or when | |
another state updates elsewhere in the code). | |
*/ | |
// this package provides the state management utilities we need for this magic to happen | |
import 'package:provider/provider.dart'; | |
// base flutter material import | |
import 'package:flutter/material.dart'; | |
// our other files in this example | |
import 'my_button.dart'; | |
import 'my_secret_button.dart'; | |
void main() => runApp(Home()); | |
class Home extends StatefulWidget { | |
@override | |
HomeState createState() => HomeState(); | |
} | |
class HomeState extends State<Home> { | |
// the holds the current state of the action button. | |
// true == do something like show the menu | |
// false == do something else like close the menu | |
ValueNotifier<bool> buttonTrigger; | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
title: 'Programmatic Trigger Example', | |
// ChangeNotifierProvider will provide that state handler to child widgets | |
home: ChangeNotifierProvider<ValueNotifier<bool>>( | |
builder: (BuildContext context) => buttonTrigger, | |
// everything below here will have access to the state | |
child: Container( | |
color: Colors.white, | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
crossAxisAlignment: CrossAxisAlignment.center, | |
children: <Widget>[ | |
// the button that actually should trigger the action menu | |
Padding( | |
padding: const EdgeInsets.all(16), | |
child: MyButton(), | |
), | |
// the other button that will trigger that first button's action menu | |
Padding( | |
padding: const EdgeInsets.all(16), | |
child: MySecretButton(), | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
no work 2021