gpt4 book ai didi

Flutter : Exception on using Navigator. of(context) 用于 RaisedButton 的 onPressed 事件

转载 作者:IT王子 更新时间:2023-10-29 07:15:21 30 4
gpt4 key购买 nike

我遇到了这个异常

Exception has occurred. NoSuchMethodError (NoSuchMethodError: The method 'ancestorStateOfType' was called on null. Receiver: null Tried calling: ancestorStateOfType(Instance of 'TypeMatcher'))

关于使用我为 onPressed 函数传递的自定义方法 (navigateToLogin),对于 RaisedButton,但是,当我直接在 onPressed = (){ ...Navigation code..} 上编写相同的导航时,它工作正常。是因为它没有得到上下文吗?

import 'package:credit/src/pages/credit/home.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/gestures.dart';
import 'dart:convert';

class LandingPage extends StatelessWidget {
BuildContext context;

@override
Widget build(BuildContext context) {
//return HomePage(); // Un coment this method for Homepage
String loginTxt = "Login";

// Set login value on click of Login button
setLoginValue() async {
SharedPreferences loginCheck = await SharedPreferences.getInstance();
await loginCheck.setString("userstatus", "loggedin");
print("Set login value");
print(loginCheck.getString("userstatus"));
}

return WillPopScope(
onWillPop: () {
SystemNavigator.pop();
return Future.value(false);
},
child: SafeArea(
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(35),
child: AppBar(
backgroundColor: Colors.lightBlueAccent,
title: Text("Select Language"),
automaticallyImplyLeading: false,
primary: false,
),
),
bottomNavigationBar: BottomAppBar(
child: RaisedButton(
onPressed: navigateToLogin(),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: new Text("Continue",
style: TextStyle(fontSize: 20)),
),
Container(
child: new Icon(Icons.navigate_next),
)
],
),
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
color: Colors.lightBlueAccent,
splashColor: Colors.orangeAccent,
),
),
body: Column(
children: <Widget>[],
)))));
}

navigateToLogin() {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
}

最佳答案

是的,如果你想让它工作,你必须将 context 作为参数传递:

navigateToLogin(BuildContext context) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}

当你调用它时:

onPressed: () => navigateToLogin(context);

关于Flutter : Exception on using Navigator. of(context) 用于 RaisedButton 的 onPressed 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57547108/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com