您必须谨慎对待尝试做的事情,因为您可能正在访问未装载的页面/小部件。想象你做一个
pushReplacement(newMaterialPageroute(...))。前一页在树中不再可用,因此您无法访问它或它的任何方法。
除非您在树中有明确的父子关系,否则应将逻辑抽象为外部或业务逻辑类。因此,您可以确定正在调用类的活动实例。
这是您可以使用的围绕Business对象传递的示例。如果使用其他模式(例如BLOC,ScopedModel,Streams等)会更好。但是为了简单起见,我认为这应该足够了。
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"), ), ), ); }}如果您仍然想在另一个Page中调用一个函数,并且确定该页面已装入(您已经完成了
push而不是的操作
pushReplacement),则可以执行以下操作。(小心轻放)
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"), ), ), ); }}


