我是编程和 Flutter 的新手。
在我的应用程序中,我构建了一个带有 int 变量的页面导航器。更改整数值后,我希望应用程序将用户路由到特定的指定页面。但是,我在按下时收到“匿名关闭”错误。
如果有人可以解释为什么我会收到此错误并发布此代码的更正版本,将不胜感激?
以下是调试器中的完整错误片段。
Reloaded 1 of 529 libraries in 885ms.
flutter: Page #1 Clicked
════════ Exception caught by gesture ═══════════════════════════════════════════
The following NoSuchMethodError was thrown while handling a gesture:
The method 'call' was called on null.
Receiver: null
Tried calling: call()
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _MyHomePageState.build.<anonymous closure>
package:navigator_test/main.dart:45
#2 _InkResponseState._handleTap
package:flutter/…/material/ink_well.dart:993
#3 _InkResponseState.build.<anonymous closure>
package:flutter/…/material/ink_well.dart:1111
#4 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:183
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#5df0c
debugOwner: GestureDetector
state: possible
won arena
finalPosition: Offset(208.7, 509.7)
finalLocalPosition: Offset(76.7, 19.7)
button: 1
sent tap down
════════════════════════════════════════════════════════════════════════════════
下面是导航器的示意图
import 'package:flutter/material.dart';
import 'package:navigator_test/main.dart';
import 'package:navigator_test/page1.dart';
class Navigator extends StatefulWidget {
@override
_NavigatorState createState() => _NavigatorState();
}
class _NavigatorState extends State<Navigator> {
int nav = 0;
void page1() {
setState(() {
nav = 1;
});
}
@override
Widget build(BuildContext context) {
if (nav < 1) {
return MyHomePage(page1: page1);
} else if (nav < 2) {
return Page1();
} else {
return null;
}
}
}
我正在主页上导入功能。
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
final Function page1;
MyHomePage({this.page1});
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Navigation Test'),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20),
FlatButton.icon(
onPressed: () {
print('Page #1 Clicked');
widget.page1();
},
icon: Icon(Icons.add_shopping_cart),
label: Text('Goto Page #1'),
)
],
),
),
// This trailing comma makes auto-formatting nicer for build methods.
);
}
}