Skip to content

Instantly share code, notes, and snippets.

@bettdouglas
Created March 18, 2020 12:23
Show Gist options
  • Save bettdouglas/1d3943caa87d2aec562d4029c1c1f770 to your computer and use it in GitHub Desktop.
Save bettdouglas/1d3943caa87d2aec562d4029c1c1f770 to your computer and use it in GitHub Desktop.
How to reuse a method used in another Widget
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: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
static void printMessage(BuildContext context,String message) {
print(message + " from $context");
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Static Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Press FAB to show snack bar',
),
RaisedButton(
child: Text('Go to OtherWidget'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context)=>AnotherWidget())
);
}
)
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => printMessage(context,'Hello'),
tooltip: 'Show Snack Bar',
child: Icon(Icons.add),
),
);
}
}
class AnotherWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('App Bar'),
),
body: Center(
child: RaisedButton(
onPressed: () {
MyHomePage.printMessage(context,'Another Hello');
},
child: Text('PRESS ME')
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment