我有4个类SignUp,Auth,PageOne和InWidget(继承的窗口小部件)。在类signUpState中,我有一个可以使用控制器控制的滑动器。
注册
class SignUp extends StatefulWidget {
static const String id = 'history_page';
@override
SignUpState createState() => SignUpState();
goto(bool x) => createState().goto(x);
}
SignUpState
class SignUpState extends State<SignUp> {
SwiperController _swOneCtrl;
@override
void initState() {
_swOneCtrl = new SwiperController();
super.initState();
}
goto(bool anim){
_swOneCtrl.next(animation: anim);
print("goto fired");
}
}
Auth
class Auth extends StatelessWidget {
SignUp s = SignUp();
verifyPhoneNumber() {
s.goto(true);
}
}
PageOne
class PageOneState extends State<PageOne> {
@override
Widget build(BuildContext context) {
final MyInheritedWidgetState state = MyInheritedWidget.of(context);
return RaisedButton(
color: Colors.blueGrey,
disabledColor: Colors.grey[100],
textColor: Colors.white,
elevation: 0,
onPressed: !phonebtn
? null
: () {
final MyInheritedWidgetState state =
MyInheritedWidget.of(context);
state.verifyPhoneNumber();
},
child: Text("CONTINUER"),
),
);
}
}
事情是我想从auth调用verifyPhoneNumber(),它将使用inwidget作为中介从pageone调用goto()方法,但我遇到此错误:
Unhandled Exception: NoSuchMethodError: The method 'next' was called on null.
你知道为什么吗?
[initState()
是在有状态窗口小部件插入到窗口小部件树中时被调用一次的方法。
[通常,如果我们需要进行某种初始化工作(例如注册侦听器,因为与build()不同,此方法被调用一次。),所以我们重写此方法。
我认为您在SignUPState类中声明了Swipe控制器。
class SignUpState extends State<SignUp> {
SwiperController _swOneCtrl;
@override
void initState() {
_swOneCtrl = new SwiperController();
super.initState();
}
goto(bool anim){
_swOneCtrl.next(animation: anim);
print("goto fired");
}
}
但是您已经在initState()
中对其进行了初始化。问题是因为您没有在小部件树中插入SignUp小部件,所以您的滑动控制器未初始化且为空。因此,当您调用下一个方法为null时,它会显示错误。
作为解决方案,首先将您的注册小部件插入小部件树中。
如果我的解决方案对您有所帮助。请给我评分。
在声明时尝试初始化。
class SignUpState extends State<SignUp> {
SwiperController _swOneCtrl = new SwiperController();
@override
void initState() {
super.initState();
}
goto(bool anim){
_swOneCtrl.next(animation: anim);
print("goto fired");
}
}
如果有效,请回复我。