class App extends StatelessWidget{ build(context){ return MaterialApp( Title: 'Iniciar Sesion',home: LoginBlocProvIDer(child: WelcomeScreen()),); } }@H_404_7@然后WelcomeScreen有一个导航到LoginScreen的按钮 @H_404_7@
class WelcomeScreen extends StatelessWidget { @overrIDe Widget build(BuildContext context){ return Scaffold( body: Center(child: Mybutton) ); }}class Mybutton extends StatelessWidget { @overrIDe Widget build(BuildContext context) { return Raisedbutton( shape: Stadiumborder(),child: Text('Ingresar',style: TextStyle(color: colors.black)),elevation: 5.0,onpressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (BuildContext context) =>LoginScreen() )); } ); }}@H_404_7@最后在LoginScreen中我想访问inheritedWidget @H_404_7@
class LoginScreen extends StatefulWidget { @overrIDe _LoginScreenState createState() => _LoginScreenState();}class _LoginScreenState extends State<LoginScreen> { LoginBloc bloc; @overrIDe voID dIDChangeDependencIEs() { bloc = LoginBlocProvIDer.of(context); super.dIDChangeDependencIEs(); } @overrIDe Widget build(BuildContext context){ return Scaffold( body: Stack( fit: StackFit.expand,children: <Widget>[ positioned( top: 0.0,child: Image.asset('assets/images/img.jpg',fit: BoxFit.none,),_buildLogin(),],); }}@H_404_7@编辑:这是LoginBlocProvIDer @H_404_7@
class LoginBlocProvIDer extends inheritedWidget { final bloc; LoginBlocProvIDer({Key key,Widget child}) : bloc = LoginBloc(),super(key:key,child:child); @overrIDe bool updateShouldNotify(inheritedWidget oldWidget) => true; static LoginBloc of(BuildContext context) { return (context.inheritFromWidgetOfExactType(LoginBlocProvIDer) as LoginBlocProvIDer).bloc; }}@H_404_7@但是,当我运行inheritedWidget的.of方法时,我得到了这个错误 @H_404_7@
I/Flutter (27725): The following NoSuchMethodError was thrown building Builder:I/Flutter (27725): The getter 'bloc' was called on null.I/Flutter (27725): Receiver: nullI/Flutter (27725): TrIEd calling: bloc@H_404_7@我的印象是,这一切都与Navigator.push构建器方法中的上下文有关.
因为如果我使用不带Navigator.push的LoginScreen小部件,我可以完美地使用inheritedWidget @H_404_7@发生错误是因为传递给LoginBlocProvIDer.of()方法的上下文未找到实例. @H_404_7@有什么想法吗?解决方法 在您提供的代码中,LoginScreen不是LoginBlocProvIDer的后代,这就是它无法找到祖先小部件的原因.您的代码在LoginBlocProvIDer中包装WelcomeScreen路由,但不包括整个导航器.解决方案是将您的MaterialApp包装在LoginBlocProvIDer中,然后您可以在应用程序的任何位置访问它. @H_404_7@ @H_404_7@
class App extends StatelessWidget { @overrIDe Widget build(context) { return LoginBlocProvIDer( child: MaterialApp( Title: 'Iniciar Sesion',home: WelcomeScreen(),); }}总结
以上是内存溢出为你收集整理的dart – InheritedWidget – 在navigator.push之后调用getter全部内容,希望文章能够帮你解决dart – InheritedWidget – 在navigator.push之后调用getter所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)