Global Key
In Flutter, you can use a GlobalKey
to access a child widget’s functions from multiple parents. To achieve this, you can create a GlobalKey
in the child widget and pass it to both parents.
Here’s an example of how you can use GlobalKey
with two different parents and a single child:
- Create the child widget and define a
GlobalKey
inside it:
1class ChildWidget extends StatefulWidget {
2 const ChildWidget({Key? key}) : super(key: key);
3
4 @override
5 _ChildWidgetState createState() => _ChildWidgetState();
6}
7
8class _ChildWidgetState extends State<ChildWidget> {
9 GlobalKey<_ChildWidgetState> childKey = GlobalKey<_ChildWidgetState>();
10
11 void childFunction() {
12 // Function logic here
13 }
14
15 @override
16 Widget build(BuildContext context) {
17 return Container(
18 // Child widget UI
19 );
20 }
21}
- Pass the
childKey
to both parent widgets and store a reference to it:
1class ParentWidget extends StatelessWidget {
2 final GlobalKey<_ChildWidgetState> childKey;
3
4 const ParentWidget({Key? key, required this.childKey}) : super(key: key);
5
6 @override
7 Widget build(BuildContext context) {
8 return SomeWidget(
9 child: ChildWidget(key: childKey),
10 );
11 }
12}
13
14class AnotherParentWidget extends StatelessWidget {
15 final GlobalKey<_ChildWidgetState> childKey;
16
17 const AnotherParentWidget({Key? key, required this.childKey}) : super(key: key);
18
19 @override
20 Widget build(BuildContext context) {
21 return SomeOtherWidget(
22 child: ChildWidget(key: childKey),
23 );
24 }
25}
- Now, both parent widgets have access to the child’s functions through the childKey:
1// Accessing child's function from the parent widget
2childKey.currentState?.childFunction();
By using the same GlobalKey
in both parents, you can access the child widget’s functions from either parent as needed.
Convert String Date
1import 'package:intl/intl.dart';
2
3void main() {
4 final dateString = "2023-05-16";
5 final inputFormat = DateFormat("yyyy-MM-dd");
6 final outputFormat = DateFormat("MMMM dd, yyyy");
7
8 final date = inputFormat.parse(dateString);
9 final formattedDate = outputFormat.format(date);
10
11 print(formattedDate); // Output: May 16, 2023
12}
Icon
https://www.geeksforgeeks.org/flutter-changing-app-icon/
Rewarded Ad
https://chat.openai.com/share/fb53019f-b0a4-4a01-b686-353a5b863453
Toast
Missing