In this example, I have shared ed how to call method from another class in Flutter? Here is an example of what you could use passing around the Business object. It would be even better if you use other patterns like BLOC, ScopedModel, Streams, etc. But for the sake of simplicity I think this should be enough.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | import "package:flutter/material.dart"; void main() { runApp(MyApp(new Logic())); } class Logic { void doSomething() { print("doing something"); } } class MyApp extends StatelessWidget { final Logic logic; MyApp(this.logic); @override Widget build(BuildContext context) { return new MaterialApp( home: new HomePage(widget.logic), ); } } class HomePage extends StatelessWidget { final Logic logic; HomePage(this.logic); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FlatButton( onPressed: () { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => AnotherPage(logic), ))}, child: Text("Go to AnotherPage"), ), ), ); } } class AnotherPage extends StatelessWidget { final Logic logic; AnotherPage(this.logic); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FlatButton( onPressed: logic.doSomething, child: Text("Press me"), ), ), ); } } |
If you still want to call a function in the other Page and you are sure the page is mounted (you have done a push instead of a pushReplacement) you could do the following. (handle with care)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class HomePage extends StatelessWidget { HomePage(); void onCalledFromOutside() { print("Call from outside"); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FlatButton( onPressed: () { Navigator.of(context).push( MaterialPageRoute( builder: (context) => AnotherPage(onCalledFromOutside), ))}, child: Text("Go to AnotherPage"), ), ), ); } } class AnotherPage extends StatelessWidget { final Function callback AnotherPage(this.callback); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: FlatButton( onPressed: callback, child: Text("Press me"), ), ), ); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.