Created
July 13, 2024 13:40
-
-
Save Mastersam07/c81dd22c0dc5021288015aa6ae61541e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import 'package:flutter/material.dart'; | |
GlobalKey<_CounterWidgetState> counterKey = GlobalKey<_CounterWidgetState>(); | |
void main() { | |
runApp(const MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
debugShowCheckedModeBanner: false, | |
home: Scaffold( | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
counterKey.currentState?.increment(); | |
}, | |
child: Icon(Icons.add), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
CounterWidget(key: counterKey), | |
ElevatedButton( | |
onPressed: () { | |
counterKey.currentState?.reset(); | |
}, | |
child: Text('Reset Counter'), | |
), | |
], | |
), | |
), | |
), | |
); | |
} | |
} | |
class CounterWidget extends StatefulWidget { | |
CounterWidget({Key? key}) : super(key: key); | |
@override | |
_CounterWidgetState createState() => _CounterWidgetState(); | |
} | |
class _CounterWidgetState extends State<CounterWidget> { | |
int _count = 0; | |
void increment() { | |
setState(() { | |
_count++; | |
}); | |
} | |
void reset() { | |
setState(() { | |
_count = 0; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Text('Count: $_count'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment