Skip to content

Instantly share code, notes, and snippets.

@Mastersam07
Created July 13, 2024 13:40
Show Gist options
  • Save Mastersam07/c81dd22c0dc5021288015aa6ae61541e to your computer and use it in GitHub Desktop.
Save Mastersam07/c81dd22c0dc5021288015aa6ae61541e to your computer and use it in GitHub Desktop.
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