我收到此异常
发生异常。 NoSuchMethodError(NoSuchMethodError:方法'ancestorStateOfType'在null上调用。 接收者:null 尝试调用:ancestorStateOfType('TypeMatcher'的实例))
使用针对RaisedButton的onPressed函数传递的自定义方法(navigateToLogin),但是,当我直接在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();
}));
}
}
答案 0 :(得分:1)
是的,如果您希望它能正常工作,则必须传递context
作为参数:
navigateToLogin(BuildContext context) {
Navigator.of(context)
.push(MaterialPageRoute<Null>(builder: (BuildContext context) {
return HomePage();
}));
}
当您调用它时:
onPressed: () => navigateToLogin(context);