flutter - RaisedButton onTap 在新版本上返回 null
问题描述
在我的颤振应用程序中,我的 BottomNavigationBar 的第一页上有一个 RaisedButton 小部件。此页面包含一个按钮,该按钮应将用户带到应用程序的第四页和最后一页,该页面也恰好是 BottomNavigationBar 上的第四页(我知道这很愚蠢,但客户要求就是这样)。这是我的 RaisedButton:
Padding(
padding: const EdgeInsets.only(top: 20),
child: SizedBox(
width: MediaQuery.of(context).size.width * 0.6,
height: MediaQuery.of(context).size.width * 0.15,
child: RaisedButton(
textColor: Colors.white,
color: Constants.secondaryYellow,
child: new AlignText(
alignmentDirection: Alignment.center,
fontSize: 22,
fontWeight: FontWeight.normal,
text: 'Go to Settings',
textColour: Constants.primaryWhite,
),
onPressed: () {
navigationBar.onTap(3);
},
splashColor: Constants.secondaryLightBlue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0))),
),
)
BottomNavigationBar 键在构建函数上方的有状态小部件中实例化,如下所示
final BottomNavigationBar navigationBar = navBarGlobalKey.currentWidget;
如果我导航到不同的屏幕,返回主页然后按下按钮,按钮会按预期工作。但是,如果按钮是我在应用程序中进行的第一次按下,则 onTap 函数会在控制台中返回以下错误
在 null 上调用了 getter 'onTap'。接收者:null 尝试调用:onTap
这是我的底部导航栏:
BottomNavigationBar(
key: navBarGlobalKey,
onTap: onTapped,
currentIndex: currentIndex,
fixedColor: Constants.secondaryLightBlue,
backgroundColor: Colors.white,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: new Icon(Icons.dashboard),
title: new Text('Page 1'),
activeIcon: new Icon(
Icons.dashboard,
color: Constants.secondaryLightBlue,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.apps),
title: new Text('Page 2'),
activeIcon: new Icon(
Icons.apps,
color: Constants.secondaryLightBlue,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.people),
title: new Text('Page 3'),
activeIcon: new Icon(
Icons.people,
color: Constants.secondaryLightBlue,
)),
BottomNavigationBarItem(
icon: new Icon(Icons.question_answer),
title: new Text('Page 4'),
activeIcon: new Icon(
Icons.question_answer,
color: Constants.secondaryLightBlue,
)),
],
)
onTap 中调用的变量 navigationBar 是 main.dart 中的全局变量,并作为 BottomNavigationBar 的键附加
GlobalKey navBarGlobalKey = GlobalKey(debugLabel: 'bottomAppBar');
void main() {
runApp(
MaterialApp(
theme: ThemeData(primaryColor: Color.fromRGBO(35, 40, 55, 1)),
home: SampleApp(),
),
);
}
解决方案
推荐阅读
- function - javascript对象初始化器的方法定义中'function'关键字的真正作用是什么
- reactjs - 大日历反应我们可以在月份的不同日期有多种颜色吗?
- c# - 我将 c# windows 应用程序与 Access 数据库 (accdb) 连接,但该应用程序在其他计算机上不起作用
- c++ - QString从列表中解析项目
- angular - Angular 6通过服务将组件之间的数据共享到模板组件中
- excel - 保存AS文件,不打开
- php - 路由在 laravel 7 上不起作用,除了默认的一个
- spring - 春季无法提交 LocalTime 列表
- gitlab - 为什么我最近在 Gitlab 中的提交与分支历史不一致?
- ios - 如果宽度小于 116,搜索栏看起来很奇怪