Skip to content

Instantly share code, notes, and snippets.

@pmatatias
Created June 20, 2023 17:03
Show Gist options
  • Select an option

  • Save pmatatias/3dea9e4d0394a433165dae44e16dc0fd to your computer and use it in GitHub Desktop.

Select an option

Save pmatatias/3dea9e4d0394a433165dae44e16dc0fd to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: ParentWidget(),
);
}
}
class ParentWidget extends StatefulWidget {
const ParentWidget({super.key});
@override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
String parentTxt = "Initial Text";
int count = 0;
void updateParentTxt(String param) {
count++;
parentTxt = '$param $count times';
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(parentTxt)),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
/// another child widget
Child(methodFromParent: updateParentTxt),
],
), // pass the method as argument
),
);
}
}
class Child extends StatelessWidget {
const Child({super.key, this.methodFromParent});
final Function(String val)? methodFromParent;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
methodFromParent?.call("Btn pressed from child: ");
},
child: const Text("Update parent"),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment