‘0 <= currentIndex && currentIndex < items.length': is not true in Flutter App.

huangapple go评论104阅读模式
英文:

line 207 pos 15: '0 <= currentIndex && currentIndex < items.length': is not true in Flutter App

问题

我遇到了一个问题。我想要创建一个Flutter应用程序,在这个应用程序中,所有页面都会像Android的Fragment一样显示在主体部分。

我已经创建了一个列表,

int _currentIndex = 0;

List<Widget> pages = [
    const HomeMain(),
    const AdPage(),
    const ImageCleanPage(),
    const HomeMain(),
  ];

我在这里列出了4个页面。
我还创建了一个抽屉和底部导航栏。
我试图从底部导航栏访问0和1页面,从抽屉中访问0、2和3页面,就像Fragment一样。

我尝试了这段代码,

        drawer: SafeArea(
          child: Drawer(
            child: Container(
              color: Colors.white,
              child: ListView(
                children:  [
                  DrawerHeader(
                    decoration: const BoxDecoration(
                        color: Colors.indigoAccent
                    ),
                    child: Column(
                      children: [
                        Container(
                          width: 70,
                          height: 70,
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(50),
                              border: Border.all(
                                  color: Colors.white,
                                  width: 2.0),
                              image: const DecorationImage(
                                image: AssetImage('assets/images/logo_image.png'),
                              )
                          ),
                        ),
                        const SizedBox(height: 15,),
                        const Text("Image Cleaner",
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold, fontSize: 15,
                          ),),
                        const SizedBox(height: 2,),
                        const Text("support.imageclean@gmail.com",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            decorationThickness: 15,
                          ),)
                      ],
                    ),
                  ),
                  ListBody(
                    children: [
                      ListTile(
                        leading: const Icon(Icons.home),
                        title: const Text('Home'),
                        onTap: () {
                          setState(() {
                            _currentIndex = 0;
                            Navigator.of(context).pop();
                            // 在点击主页时执行一些操作。
                          });
                        },
                      ),
                      ListTile(
                        leading: const Icon(Icons.settings),
                        title: const Text('Settings'),
                        onTap: () {
                          setState(() {
                            _currentIndex = 2;
                            Navigator.of(context).pop();
                            // 在点击设置时执行一些操作。
                          });
                        },
                      ),
                      ListTile(
                        leading: const Icon(Icons.help),
                        title: const Text('Help'),
                        onTap: () {
                          setState(() {
                            _currentIndex = 3;
                            Navigator.of(context).pop();
                            // 在点击帮助时执行一些操作。
                          });
                        },
                      ),
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
        bottomNavigationBar: BottomNavigationBar(
          onTap: NavClick,
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Home',
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.ad_units),
              label: 'Free Coin',
            ),
          ],
          currentIndex: _currentIndex,
          selectedItemColor: Colors.amber[800],
        ),
        backgroundColor: Colors.white,
        body:   SafeArea(
          child:  pages[_currentIndex],
        )
    );
  }
  void NavClick(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

当我从抽屉中点击索引2时,我得到了这个错误,

Failed assertion: line 207 pos 15: '0 <= currentIndex && currentIndex < items.length': is not true.
英文:

I am facing a problem. I want to make a Flutter app where all pages will show in the body like Android Fragment.

I have created a list,

int _currentIndex = 0;
List&lt;Widget&gt; pages = [
const HomeMain(),
const AdPage(),
const ImageCleanPage(),
const HomeMain(),
];

I have listed here 4 pages.
I also created a Drawer and bottom navigation bar.
I am trying to access 0 and 1 pages from the bottom nav bar, And 0,2,3 from the drawer, like fragments.

I have tried this code,

        drawer: SafeArea(
child: Drawer(
child: Container(
color: Colors.white,
child: ListView(
children:  [
DrawerHeader(
decoration: const BoxDecoration(
color: Colors.indigoAccent
),
child: Column(
children: [
Container(
width: 70,
height: 70,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
border: Border.all(
color: Colors.white,
width: 2.0),
image: const DecorationImage(
image: AssetImage(&#39;assets/images/logo_image.png&#39;),
)
),
),
const SizedBox(height: 15,),
const Text(&quot;Image Cleaner&quot;,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold, fontSize: 15,
),),
const SizedBox(height: 2,),
const Text(&quot;support.imageclean@gmail.com&quot;,
style: TextStyle(
color: Colors.white,
fontSize: 12,
decorationThickness: 15,
),)
],
),
),
ListBody(
children: [
ListTile(
leading: const Icon(Icons.home),
title: const Text(&#39;Home&#39;),
onTap: () {
setState(() {
_currentIndex = 0;
Navigator.of(context).pop();
// Do something when the home page is tapped.
});
},
),
ListTile(
leading: const Icon(Icons.settings),
title: const Text(&#39;Settings&#39;),
onTap: () {
setState(() {
_currentIndex = 2;
Navigator.of(context).pop();
// Do something when the home page is tapped.
});
},
),
ListTile(
leading: const Icon(Icons.help),
title: const Text(&#39;Help&#39;),
onTap: () {
setState(() {
_currentIndex = 3;
Navigator.of(context).pop();
// Do something when the home page is tapped.
});
},
),
],
)
],
),
),
),
),
bottomNavigationBar: BottomNavigationBar(
onTap: NavClick,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: &#39;Home&#39;,
),
BottomNavigationBarItem(
icon: Icon(Icons.ad_units),
label: &#39;Free Coin&#39;,
),
],
currentIndex: _currentIndex,
selectedItemColor: Colors.amber[800],
),
backgroundColor: Colors.white,
body:   SafeArea(
child:  pages[_currentIndex],
)
);
}
void NavClick(int index) {
setState(() {
_currentIndex = index;
});
}

I am getting this error when I clicked index 2 from the drawer,

Failed assertion: line 207 pos 15: &#39;0 &lt;= currentIndex &amp;&amp; currentIndex &lt; items.length&#39;: is not true.
</details>
# 答案1
**得分**: 0
遇到的错误表明当前索引值 `_currentIndex` 超出了 `BottomNavigationBar` 中项目的范围。在您的情况下,`BottomNavigationBar` 中有两个项目,但在选择抽屉中的 "Settings" 时,您将 `_currentIndex` 设置为 2。这会导致断言失败,因为有效的索引范围应该在 0 和 1 之间(包括边界)。
要解决此问题,您需要调整抽屉内的 `ListTile` 小部件的 `onTap` 回调中的索引值。以下是您应该进行的更改:
对于 "Home" 选项,请将 `_currentIndex` 设置为 0。
对于 "Settings" 选项,请将 `_currentIndex` 设置为 1。
对于 "Help" 选项,请将 `_currentIndex` 设置为 2。
通过进行这些调整,您将确保 `_currentIndex` 值保持在 `BottomNavigationBar` 的有效范围内。这将解决您遇到的错误,并使您的应用程序能够正常运行。
<details>
<summary>英文:</summary>
The error you encountered indicates that the current index value `_currentIndex` is exceeding the range of items in the `BottomNavigationBar`. In your case, you have two items in the `BottomNavigationBar`, but you&#39;re setting `_currentIndex` to 2 when selecting &quot;Settings&quot; in the Drawer. This causes an assertion failure because the valid index range should be between 0 and 1 (inclusive) for your current configuration.
To resolve this issue, you need to adjust the index values in the `onTap` callbacks of the `ListTile` widgets inside the Drawer. Here are the changes you should make:
For the &quot;Home&quot; option, set `_currentIndex` to 0.
For the &quot;Settings&quot; option, set `_currentIndex` to 1.
For the &quot;Help&quot; option, set `_currentIndex` to 2.
By making these adjustments, you&#39;ll ensure that the `_currentIndex` value stays within the valid range for the `BottomNavigationBar`. This will resolve the error you encountered and allow your app to function correctly.
</details>
# 答案2
**得分**: 0
`BottomNavigationBar`始终需要在`items`数量范围内具有`currentIndex`。所以在你的代码中,你有以下部分:

bottomNavigationBar: BottomNavigationBar(
onTap: NavClick,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: 'Home',
),
BottomNavigationBarItem(
icon: Icon(Icons.ad_units),
label: 'Free Coin',
),
],
currentIndex: _currentIndex,
selectedItemColor: Colors.amber[800],
),


你在这里有2个`items`。这意味着`currentIndex`必须是0或1。但是在你的代码中,通过抽屉(drawer)使`currentIndex`变为2会超出范围。请注意,你也不能将其设置为"未选定"或其他状态。因此,即使你想要索引2,你也需要在底部栏中选择0或1。为了消除错误,你可能想要将以下行

currentIndex: _currentIndex,


更改为

currentIndex: (_currentIndex == 0 || _currentIndex == 1) ? _currentIndex : 0,


以便在超出范围时将其回退到0。
<details>
<summary>英文:</summary>
The `BottomNavigationBar` always needs to have a `currentIndex` within the range of the number of `items`. So in your code you have
bottomNavigationBar: BottomNavigationBar(
onTap: NavClick,
items: const [
BottomNavigationBarItem(
icon: Icon(Icons.home),
label: &#39;Home&#39;,
),
BottomNavigationBarItem(
icon: Icon(Icons.ad_units),
label: &#39;Free Coin&#39;,
),
],
currentIndex: _currentIndex,
selectedItemColor: Colors.amber[800],
),
You have 2 `items` there. Which means that `currentIndex` MUST be 0 or 1. But your code makes it go outside that when making `currentIndex` 2 through the drawer. Note you also can&#39;t have it &quot;deselected&quot; or something. So even when you want index 2 you will need to have 0 or 1 selected in your bottom bar. To get rid of the error you maybe want to change the line
currentIndex: _currentIndex,
to
currentIndex: (_currentIndex == 0 || _currentIndex == 1) ? _currentIndex : 0,
to make it fall back to 0 when it&#39;s out of range
</details>

huangapple
  • 本文由 发表于 2023年6月5日 12:35:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定