【发布时间】:2019-06-19 16:34:52
【问题描述】:
我想在另一个小部件中使用 Button 来点击 TitledBottomNavigationBar 项目。
我只使用导航栏中的键它仍然说我正在使用它仍然说 Multiple widgets used the same GlobalKey.
import 'package:flutter/material.dart';
import 'package:titled_navigation_bar/titled_navigation_bar.dart';
class TesterPage extends StatefulWidget {
@override
_TesterPageState createState() => _TesterPageState();
}
class _TesterPageState extends State<TesterPage> {
final GlobalKey _navigationBarKey = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: TitledBottomNavigationBar(
key: _navigationBarKey,
onTap: (int index) {
print(index.toString());
},
items: [
TitledNavigationBarItem(title: 'Home', icon: Icons.home),
TitledNavigationBarItem(title: 'Help', icon: Icons.help),
TitledNavigationBarItem(title: 'Account', icon: Icons.person),
],
),
body: Center(
child: RaisedButton(
child: Text("Test"),
onPressed: () {
final TitledBottomNavigationBar navigationBar = _navigationBarKey.currentWidget;
navigationBar.onTap(1);
},
),
),
);
}
}
它抛出错误:
I/flutter ( 3573): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 3573): The following assertion was thrown building
I/flutter ( 3573): TitledBottomNavigationBar-[GlobalKey#03b8b](dependencies: [_InheritedTheme,
I/flutter ( 3573): _LocalizationsScope-[GlobalKey#4d232], MediaQuery], state: _TitledBottomNavigationBarState#4cc2f):
I/flutter ( 3573): Multiple widgets used the same GlobalKey.
I/flutter ( 3573): The key [GlobalKey#03b8b] was used by multiple widgets. The parents of those widgets were:
I/flutter ( 3573): - MediaQuery(MediaQueryData(size: Size(411.4, 868.6), devicePixelRatio: 3.5, textScaleFactor: 0.9,
I/flutter ( 3573): platformBrightness: Brightness.dark, padding: EdgeInsets.zero, viewInsets: EdgeInsets.zero,
I/flutter ( 3573): alwaysUse24HourFormat: false, accessibleNavigation: falsedisableAnimations: falseinvertColors:
I/flutter ( 3573): falseboldText: false))
I/flutter ( 3573): - TitledBottomNavigationBar-[GlobalKey#03b8b](dependencies: [_InheritedTheme,
I/flutter ( 3573): _LocalizationsScope-[GlobalKey#4d232], MediaQuery], state: _TitledBottomNavigationBarState#4cc2f)
I/flutter ( 3573): A GlobalKey can only be specified on one widget at a time in the widget tree.
【问题讨论】:
-
我认为这是
TitledBottomNavigationBar的问题。我浏览了它的代码,看起来它重用了提供的密钥。我看到you've already filed an issue about it。你可以改用ValueKey吗? -
@jamesdlin 因为
.currentWidget属性,我使用了GlobalKey。我认为ValueKey/LocalKey不适合这里。 -
为什么不能使用带有唯一字符串的
ValueKey? -
@jamesdlin 通过使用
ValueKey可以访问TitledBottomNavigationBar的onTap()方法吗? -
我不明白为什么这行不通。
标签: flutter dart flutter-navigation