Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add one BottomNavigationBarItem only

I have a BottomNavigationBar which I need to add only one centralized button inside, but I am getting this error:

'package:flutter/src/material/bottom_navigation_bar.dart': Failed assertion: line 191 pos 15: 'items.length >= 2': is not true.

which is logical as the flutter's source code has this condition:

//..
assert(items.length >= 2),

So, here's my code, is there a workaround for this using BottomNavigationBar to keep the code clean?

BottomNavigationBar(

   items: <BottomNavigationBarItem>[
      buildBottomNavigationBarItem(
         iconData: Icons.close,
      ),

// AN ERROR AFTER COMMENTING THIS:

//    buildBottomNavigationBarItem(
//       iconData: Icons.open,
//    ),
   ],
),


BottomNavigationBarItem buildBottomNavigationBarItem(
      {IconData iconData, String title = ''}
    ) {
    return BottomNavigationBarItem(
      icon: Icon(
        iconData,
        color: Theme.of(context).accentColor,
        size: 0.04 * _deviceHeight,
      ),
      title: Text(
        title,
      ),
    );
}

thanks

like image 755
Jehad Nasser Avatar asked Jan 26 '23 20:01

Jehad Nasser


1 Answers

You can't use BottomNavigationBar but instead of it you can create your own widget and pass it into the bottomNavigationBar parameter.

Demo

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        body: SafeArea(
          child: Text('Hi'),
        ),
        bottomNavigationBar: Container(
          height: 60,
          color: Colors.black12,
          child: InkWell(
            onTap: () => print('tap on close'),
            child: Padding(
              padding: EdgeInsets.only(top: 8.0),
              child: Column(
                children: <Widget>[
                  Icon(
                    Icons.close,
                    color: Theme.of(context).accentColor,
                  ),
                  Text('close'),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

If the new, custom bottom navigation bar overlaps with the phone's OS GUI, you can wrap the InkWell with a SafeArea widget.

like image 61
Kherel Avatar answered Jan 28 '23 11:01

Kherel