1

我想在另一个小部件中使用 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.

4

1 回答 1

0

我尝试使用您提供的最小复制来复制该问题。由于 TitledBottomNavigationBar 不可用,我使用了 Flutter 随时可用的 BottomNavigationBar。

在您的代码中,TitledBottomNavigationBar 需要在小部件键上强制转换为指定的小部件。

final TitledBottomNavigationBar navigationBar = 
    _navigationBarKey.currentWidget! as TitledBottomNavigationBar;

然后要更新 TitledBottomNavigationBar 的当前索引,应该在 onTap(int) 内部调用 setState。

currentIndex: _currentPage,
onTap: (int index) {
  debugPrint('Current index: $index');
  if (index != _currentPage) {
    setState(() => _currentPage = index);
  }
},

这是完整的示例。

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey _navigationBarKey = GlobalKey();
  int _currentPage = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            BottomNavigationBar navigationBar =
                _navigationBarKey.currentWidget! as BottomNavigationBar;
            debugPrint('Key $navigationBar');
            navigationBar.onTap!(2);
            // navigationBar.onTap(1);
          },
          child: const Text('Tap me!'),
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        key: _navigationBarKey,
        currentIndex: _currentPage,
        onTap: (int index) {
          debugPrint('Current index: $index');
          if (index != _currentPage) {
            setState(() => _currentPage = index);
          }
        },
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(label: 'Home', icon: Icon(Icons.home)),
          BottomNavigationBarItem(label: 'Help', icon: Icon(Icons.help)),
          BottomNavigationBarItem(label: 'Account', icon: Icon(Icons.person)),
        ],
      ),
    );
  }
}

演示

于 2021-10-25T04:51:37.153 回答