【问题标题】:Problem with Navigation (Error: RangeError (index): Index out of range: index should be less than 3: 3)导航问题(错误:RangeError(索引):索引超出范围:索引应小于3:3)
【发布时间】:2021-11-07 16:18:24
【问题描述】:

我正在尝试为我的颤振应用程序创建自定义导航,该应用程序和导航工作正常,直到有 3 个屏幕/页面。添加第 4 个屏幕后,我得到一个范围错误,错误堆栈如下:

 ======== Exception caught by gesture ===============================================================
The following IndexError was thrown while handling a gesture:
RangeError (index): Index out of range: index should be less than 3: 3

When the exception was thrown, this was the stack: 
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 236:49  throw_
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/js_array.dart 581:7             _get]
packages/test_proj/page_navigator.dart 17:35                                                                               <fn>
packages/flutter/src/material/bottom_navigation_bar.dart 987:25                                                            <fn>
packages/flutter/src/material/ink_well.dart 989:21                                                                         [_handleTap]
...
Handler: "onTap"
Recognizer: TapGestureRecognizer#86634
  debugOwner: GestureDetector
  state: ready
  won arena
  finalPosition: Offset(908.8, 678.4)
  finalLocalPosition: Offset(131.8, 5.4)
  button: 1
  sent tap down
====================================================================================================

添加第四页后,我的第三页上的屏幕输出也将停止。这是代码:

    class App extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => AppState();
}

class AppState extends State<App> {
  String _currentPage = "Page1";
  List<String> pageKeys = ["Page1", "Page2", "Page3, Page4"];
  Map<String, GlobalKey<NavigatorState>> _navigatorKeys = {
    "Page1": GlobalKey<NavigatorState>(),
    "Page2": GlobalKey<NavigatorState>(),
    "Page3": GlobalKey<NavigatorState>(),
    "Page4": GlobalKey<NavigatorState>(),
  };
  int _selectedIndex = 0;


  void _selectTab(String tabItem, int index) {
    if(tabItem == _currentPage ){
      _navigatorKeys[tabItem]!.currentState!.popUntil((route) => route.isFirst);
    } else {
      setState(() {
        _currentPage = pageKeys[index];
        _selectedIndex = index;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        final isFirstRouteInCurrentTab =
        !await _navigatorKeys[_currentPage]!.currentState!.maybePop();
        if (isFirstRouteInCurrentTab) {
          if (_currentPage != "Page1") {
            _selectTab("Page1", 1);

            return false;
          }
        }
        // let system handle back button if we're on the first route
        return isFirstRouteInCurrentTab;
      },
      child: Scaffold(
        body: Stack(
            children:<Widget>[
              _buildOffstageNavigator("Page1"),
              _buildOffstageNavigator("Page2"),
              _buildOffstageNavigator("Page3"),
              _buildOffstageNavigator("Page4"),
            ]
        ),
        bottomNavigationBar: BottomNavigationBar(
          selectedItemColor: Colors.blueAccent,
          onTap: (int index) { _selectTab(pageKeys[index], index); },
          currentIndex: _selectedIndex,
          items: [
            BottomNavigationBarItem(
              icon: new Icon(Icons.looks_one),
              label: 'Page1'
            ),
            BottomNavigationBarItem(
              icon: new Icon(Icons.looks_two),
              label: 'Page2'
            ),
            BottomNavigationBarItem(
              icon: new Icon(Icons.looks_3),
              label: 'Page3'
            ),
            BottomNavigationBarItem(
              icon: new Icon(Icons.looks_4),
              label: 'Page4'
            ),
          ],
          type: BottomNavigationBarType.fixed,
        ),
      ),
      );

  }



  Widget _buildOffstageNavigator(String tabItem) {
    return Offstage(
      offstage: _currentPage != tabItem,
      child: TabNavigator(
        navigatorKey: _navigatorKeys[tabItem]!,
        tabItem: tabItem,
      ),
    );
  }
}

和....

class TabNavigatorRoutes {
  static const String root = '/';
  static const String detail = '/detail';
}

class TabNavigator extends StatelessWidget {
  TabNavigator({required this.navigatorKey, required this.tabItem});
  final GlobalKey<NavigatorState> navigatorKey;
  final String tabItem;

  @override
  Widget build(BuildContext context) {

    Widget child = Text("plz work");
    if(tabItem == "Page1")
      child = Page1();
    else if(tabItem == "Page2")
      child = Page2();
    else if(tabItem == "Page3")
      child = Page3();
    else if(tabItem == "Page4")
      child = Page4();

    return Navigator(
      key: navigatorKey,
      onGenerateRoute: (routeSettings) {
        return MaterialPageRoute(
            builder: (context) => child
        );
      },
    );
  }
}

至于页面上的实际内容,它只是一个文本小部件。如果可能,请帮助我。谢谢。

【问题讨论】:

  • 您可能会遇到一个错误,` _selectTab("Page1", 1);` ,这里 Page1 不应该有索引 1,而是索引 0,依此类推,直到第 4 页索引为 3。

标签: flutter flutter-layout flutter-dependencies flutter-test


【解决方案1】:

最后两个索引似乎连接到一个字符串。这就是为什么最大索引是 3 而不是预期的 4 - 指向抛出的错误:"RangeError (index): Index out of range: index should be less than 3: 3"

List<String> pageKeys = ["Page1", "Page2", "Page3, Page4"];

这应该是

List<String> pageKeys = ['Page1', 'Page2', 'Page3', 'Page4'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2020-07-16
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    相关资源
    最近更新 更多