currentIndex to have onPressed function - flutter

I am making a flutter app and i am working on the bottom navigation bar and i want to know if i can make the buttons to redirect the user to a new page UI from the app.I used this 'package:bubble_bottom_bar/bubble_bottom_bar.dart' and i don't know how to cal currentIndex = 1 ,2,3,4 to redirect to a new page when the user pressed the icon. I tried to add to my BubbleBottomBarItem a onPressed action but it doesn't work.
This is the code that i am using
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tariffo/favoriteProviders.dart';
import 'package:tariffo/messages_list.dart';
import 'package:bubble_bottom_bar/bubble_bottom_bar.dart';
import 'HomePage.dart';
class BarDetail extends StatefulWidget {
#override
_BarDetailState createState() => _BarDetailState();
}
class _BarDetailState extends State<BarDetail> {
int currentIndex;
#override
void initState() {
super.initState();
currentIndex = 0;
}
changePage(int index) {
setState(() {
currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(top: MediaQuery.of(context).size.height * 0.8),
child: BubbleBottomBar(
opacity: 0.2,
backgroundColor: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
currentIndex: currentIndex,
hasInk: true,
inkColor: Colors.black12,
hasNotch: true,
fabLocation: BubbleBottomBarFabLocation.end,
onTap: changePage,
items: <BubbleBottomBarItem>[
BubbleBottomBarItem(
backgroundColor: Colors.red,
icon: Icon(Icons.dashboard, color: Colors.black),
activeIcon: Icon(Icons.dashboard, color: Colors.red),
title: Text("Home")),
BubbleBottomBarItem(
backgroundColor: Colors.red,
icon: Icon(Icons.favorite_border, color: Colors.black),
activeIcon: Icon(Icons.dashboard, color: Colors.red),
title: Text("Saved")),
BubbleBottomBarItem(
backgroundColor: Colors.red,
icon: Icon(Icons.search, color: Colors.black),
activeIcon: Icon(Icons.dashboard, color: Colors.red),
title: Text("Search")),
BubbleBottomBarItem(
backgroundColor: Colors.red,
icon: Icon(Icons.send, color: Colors.black),
activeIcon: Icon(Icons.dashboard, color: Colors.red),
title: Text("Messages")),
],
),
);
}
}
and this are the pages that i want the buttons to open : FavoriteProviders(),MessageList()

Another way to go about it is by using PageView, create a PageController and assign it to the property of PageView called controller.
The controller - PageController _controller = PageController();
The PageView itself
PageView(
controller: _controller;
children: <Widget>[
FavoriteProviders(),
MessageList()
]
)
So FavoriteProviders() is now index 0, and MessageList() is now index 1
You can use one of these in the onTap to navigate to that page
_controller.jumpToPage(index) or
controller.animateToPage(index, duration: Duration(milliseconds: 500), curve: Curves.easeIn)
Pass in whatever you want for the duration and curve.

You should have something like this:
A list of pages:
final List<Widget> _pages = [
FavoriteProviders(),
MessageList()
];
A Scaffold where the body: _pages[currentIndex],
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: _bubbleBottomNavBar(),
body: _pages[currentIndex],
)
}
where _bubbleBottomNavBar() is your bottom bar.
OR
Replace on onTap function with:
BubbleBottomBar(
opacity: 0.2,
backgroundColor: Colors.white,
borderRadius: BorderRadius.vertical(top: Radius.circular(16.0)),
currentIndex: currentIndex,
hasInk: true,
inkColor: Colors.black12,
hasNotch: true,
fabLocation: BubbleBottomBarFabLocation.end,
onTap: (index) {
if(index == 1)
Navigator.push(
context,
MaterialPageRoute(builder: (context) => FavoriteProviders()),
);
if (index == 2)
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MessageList()),
);
},
items: <BubbleBottomBarItem>[
[...]
]
)

Related

Display BottomNavbar throughout the whole application instagram like

I have a homepage that includes an AppBar a bottomnavbar and a body to which I pass a list of widgets (pages) I want the navbar to navigate to when I click on its icons. I want to be able to display my bottomnavbar even in pages that are not included in the list .
Example when I click on a list tile it takes me to another details page , my navbar disappears I want the whole home page (appbar, bottomnavbar,...) to be static throughout the whole app without having to call each component on its own in my pages just like instagram style.
Here's my home page
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
var pages = [
MyQrqc(),
NoDataUI(),
];
int index = 0;
var _appPageController = PageController();
return SafeArea(
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: PreferredSize(
preferredSize: Size.fromHeight(70.0), child: CustomAppBar()),
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/images/bg.png"),
fit: BoxFit.cover,
),
),
child: PageView(
children: pages,
onPageChanged: (index) {
setState(() {
index = index;
});
},
controller: _appPageController,
),
),
bottomNavigationBar: ClipRRect(
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(17.0),
topRight: Radius.circular(17.0),
),
child: BottomAppBar(
clipBehavior: Clip.antiAlias, //bottom navigation bar on scaffold
color: Colors.transparent,
shape: CircularNotchedRectangle(), //shape of notch
notchMargin:
5, //notche margin between floating button and bottom appbar
child: Mainmenu(currentIndex: index, appPageController: _appPageController,),
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
backgroundColor: kPrimaryLightColor,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyQrqc()),
);
},
child: const Icon(Icons.add),
),
),
);
}
}
and this is my main menu page :
import 'package:deepnrise/Screens/qrqc/mes_qrqc_view.dart';
import 'package:deepnrise/constants/colors.dart';
import 'package:deepnrise/services/auth_services.dart';
import 'package:deepnrise/utils/size_config.dart';
import 'package:flutter/material.dart';
import 'package:deepnrise/services/settings/settings_service.dart';
import 'package:flutter_svg/flutter_svg.dart';
class Mainmenu extends StatefulWidget {
int currentIndex = 0;
var appPageController = PageController();
Mainmenu({Key? key, required this.currentIndex,required this.appPageController}) : super(key: key);
#override
CustomNavBar createState() => CustomNavBar();
}
class CustomNavBar extends State<Mainmenu> {
#override
Widget build(BuildContext context) {
setBottomBarIndex(index) {
setState(() {
widget.currentIndex = index;
});
widget.appPageController.animateToPage(index,
duration: Duration(milliseconds: 500), curve: Curves.ease);
}
SizeConfig.init(context);
return Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [kPrimaryColor, kPrimaryLightColor],
begin: Alignment.topLeft,
end: Alignment.topRight,
stops: [0.1, 0.8],
tileMode: TileMode.clamp,
),
),
child: Wrap(
//children inside bottom appbar
alignment: WrapAlignment.spaceAround,
children: <Widget>[
const SizedBox(
width: 30,
),
IconButton(
icon: Image.asset("assets/icons/menuIcon2.png"),
onPressed: () {
setBottomBarIndex(0);
},
),
const SizedBox(
width: 20,
),
IconButton(
icon: Image.asset("assets/icons/menuIcon1.png"),
onPressed: () {
setBottomBarIndex(1);
},
),
const SizedBox(
width: 50,
),
IconButton(
icon: const Icon(
Icons.person,
color: Colors.white,
),
onPressed: () {
setBottomBarIndex(2);
},
),
const SizedBox(
width: 20,
),
IconButton(
icon: Image.asset("assets/icons/menuIcon3.png"),
onPressed: () {
setBottomBarIndex(3);
},
),
const SizedBox(
width: 20,
),
],
),
);
}
}
Here, First you need to create one file for BottomNavigationBar,
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _selectedIndex = 0;
//For changing the screen
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
//This is a screens list which you want to navigate through BottomNavigationBar
final List<Widget> _children = [
const HomeScreen(),
const ProfileScreen()
];
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
iconSize: 32.0,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white54,
currentIndex: _selectedIndex,
backgroundColor: Colors.black,
type: BottomNavigationBarType.fixed,
items: const [
BottomNavigationBarItem(
label: "Home",
icon: Icon(Icons.list),
),
BottomNavigationBarItem(
label: "Profile",
icon: Icon(Icons.person),
),
],
onTap: _onItemTapped,
),
);
}
}
Then, You can create another screens like HomeScreen, ProfileScreen etc.
So, By using this code HomePage to be static throughout the whole app without having to call each component in any screen.
To show the bottom navbar on all screens, one way is to use PageView with the bottom navbar. Another way is to use persistent_bottom_nav_bar

Getting Error while Home widget (MyHomepage) loading

I am getting The following error while Run my app default page (Homepage) .
════════ Exception caught by widgets library ═══════════
The following ArgumentError was thrown building MyHomePage(dirty, dependencies: [MediaQuery, _EffectiveTickerMode], state: _MyHomePageState#7da5f(ticker inactive)):
Invalid argument(s)
**The Tracker showing the following reasons:**
The relevant error-causing widget was:
MyHomePage file:///F:/Orangebd/app/GoogleDriveClone-Flutter/lib/Screen/Home.dart:37:15
When the exception was thrown, this was the stack:
#0 _StringBase.+ (dart:core-patch/string_patch.dart:272:57)
#1 _MyHomePageState.build (package:googledriveclone_flutter/Screen/Home.dart:133:45)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4716:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4599:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4772:11)
...
══════════════════════════════════════════
During that error, the screen appears something like that
Here is my Home page code
import 'package:fab_circular_menu/fab_circular_menu.dart';
//import 'package:file_picker/file_picker.dart';
import 'package:floating_action_bubble/floating_action_bubble.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:googledriveclone_flutter/Screen/Files.dart';
import 'package:googledriveclone_flutter/Screen/HomeScreen.dart';
import 'package:googledriveclone_flutter/Screen/LoginPage.dart';
import 'package:googledriveclone_flutter/Screen/Profile.dart';
import 'package:googledriveclone_flutter/Widget/constants.dart';
import 'package:prompt_dialog/prompt_dialog.dart';
import 'package:sk_alert_dialog/sk_alert_dialog.dart';
import 'package:storage_capacity/storage_capacity.dart';
import 'IssudFile.dart';
void main() {
runApp(HomePage());
}
class HomePage extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
try {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Digilocker',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Digilocker'),
);
}
catch(e){
print('Loading expception of page'+e.toString());
}
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
Widget _widgetBody = HomeScreen();
int _currrentIndex = 0;
Animation<double> _animation;
AnimationController _animationController;
TextEditingController _foldername = TextEditingController();
String _fileName;
var scaffoldKey = GlobalKey<ScaffoldState>();
bool isFolder;
double _diskSpace = 0;
var _freespace ;
var _freespacemb;
var _occupiedSpace ;
var _totalSpace;
#override
void initState() {
// TODO: implement initState
// _controller.addListener(() => _extension = _controller.text);
_getStorgeInfo();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 300),
);
final curvedAnimation = CurvedAnimation(curve: Curves.easeInOut, parent: _animationController);
_animation = Tween<double>(begin: 0, end: 1).animate(curvedAnimation);
// initDiskSpace();
super.initState();
}
#override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _onItemTapped(int index) async{
setState(() {
if(index == 0){
_currrentIndex = index;
_widgetBody = HomeScreen();
}
else if(index == 1){
_currrentIndex = index;
_widgetBody = MyIssuedDocScreen();
}
else if(index == 2){
_currrentIndex = index;
_widgetBody = Center(child: Text('Shared documents'),);
}
else if(index == 3){
_currrentIndex = index;
_widgetBody = MyDriveScreen();
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
endDrawerEnableOpenDragGesture: false, // This way it will not open
// endDrawer: Drawer(),
drawer: new Drawer(
elevation: 10,
child: new ListView(
padding: EdgeInsets.all(0),
children: <Widget>[
DrawerHeader(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Image.asset('assets/digi_locker.png', width: MediaQuery.of(context).size.width*0.30,),
SizedBox(height: 10,),
Text('Available space: '+_freespace+'\t (MB)'),
]
),
decoration: BoxDecoration(
color: kPrimaryLightColor,
),
),
ListTile(
leading: Icon(Icons.person),
title: Text('My profile'),
onTap: () {
// Get.back();
Get.to(profilePage());
},
),
Divider(),
ListTile(
leading: Icon(Icons.create_new_folder),
title: Text('Create folder'),
onTap: () {
// Get.back();
_showMyDialog();
},
),
ListTile(
leading: Icon(Icons.cloud_upload_rounded),
title: Text('File upload'),
onTap: () {
// Get.back();
},
),
ListTile(
leading: Icon(Icons.six_ft_apart_outlined),
title: Text('Issued documents'),
onTap: () {
// Get.back();
},
),
Divider(),
ListTile(
leading: Icon(Icons.translate_rounded),
title: Text('Change lagnuage'),
onTap: () {
// Get.back();
//Get.offAll(LoginPage());
//Do some stuff here
//Closing programmatically - very less practical use
scaffoldKey.currentState.openEndDrawer();
},
),
ListTile(
leading: Icon(Icons.logout),
title: Text('Logout'),
onTap: () {
// Get.back();
Get.offAll(LoginPage());
//Do some stuff here
//Closing programmatically - very less practical use
scaffoldKey.currentState.openEndDrawer();
},
)
],
),
),
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
brightness: Theme.of(context).brightness,
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children:
[
Expanded(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(35)),
color: Colors.grey.shade50,
),
child: TextFormField(
decoration: InputDecoration(
hintText: "Search in locker",
border: InputBorder.none,
icon: Container(
margin: EdgeInsets.only(left: 10),
child: Icon(Icons.search, color: kPrimaryColor,)
),
),
),
),
),
]
),
iconTheme: IconThemeData(color: kPrimaryColor),
actions: <Widget>[
IconButton(
onPressed: (){
print("Sync started");
showSnackMessage(context,"Sync Started please wait...", scaffoldKey,'');
},
icon: Icon(
Icons.sync,
color:kPrimaryColor,
),
),
IconButton(
icon: Container(
height: 50,
width: 50,
margin: EdgeInsets.all(5),
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.white,
child: CircleAvatar(
radius: 14.0,
backgroundColor: Colors.grey[200],
backgroundImage: NetworkImage("https://qph.fs.quoracdn.net/main-qimg-11ef692748351829b4629683eff21100.webp"),
),
),
),
onPressed: () {
// do something
},
)
],
),
body: SafeArea(
child: Container(
padding: EdgeInsets.all(15.0),
child: _widgetBody
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
//Init Floating Action Bubble
floatingActionButton: FloatingActionBubble(
// Menu items
items: <Bubble>[
// Floating action menu item
Bubble(
title:"Upload",
iconColor :kPrimaryColor,
bubbleColor : Colors.white.withOpacity(0.9),
titleStyle:TextStyle(fontSize: 16 , color: kPrimaryColor),
icon:Icons.cloud_upload,
onPress: () {
// OpenFilePicker();
_animationController.reverse();
_openFileType(context);
},
),
// Floating action menu item
Bubble(
title:"Folder",
icon:Icons.create_new_folder,
iconColor :kPrimaryColor,
bubbleColor : Colors.white.withOpacity(0.9),
titleStyle:TextStyle(fontSize: 16 , color: kPrimaryColor),
onPress: () {
_animationController.reverse();
print('creating folder');
_showMyDialog();
},
),
//Floating action menu item
],
// animation controller
animation: _animation,
// On pressed change animation state
onPress: _animationController.isCompleted
? _animationController.reverse
: _animationController.forward,
// Floating Action button Icon color
iconColor: kPrimaryColor,
// Flaoting Action button Icon
icon: AnimatedIcons.menu_close,
),
bottomNavigationBar: BottomNavigationBar(
currentIndex: _currrentIndex,
type: BottomNavigationBarType.fixed,
showSelectedLabels: true,
showUnselectedLabels: true,
selectedItemColor: kPrimaryColor,
onTap: _onItemTapped,
items: [
BottomNavigationBarItem(
icon: _currrentIndex==0?Icon(Icons.home,size: 25,):Icon(Icons.home_outlined,size: 25),
title: Text("Home")
),
BottomNavigationBarItem(
icon: _currrentIndex==1?Icon(Icons.file_download_done,size: 25,):Icon(Icons.file_download_done_outlined,size: 25),
title: Text("Issued")
),
BottomNavigationBarItem(
icon: _currrentIndex==2?Icon(Icons.supervised_user_circle,size: 25,):Icon(Icons.supervised_user_circle,size: 25),
title: Text("Shared")
),
BottomNavigationBarItem(
icon: _currrentIndex==3?Icon(Icons.folder,size: 25,):Icon(Icons.folder_open,size: 25),
title: Text("My locker")
),
],
), );
}
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: Colors.white,
elevation: 13,
title: Text('Create folder'),
content: TextField(
onChanged: (value) { },
controller: _foldername,
decoration: InputDecoration(hintText: "your folder/directory name",
suffixIcon: IconButton(
onPressed: () => _foldername.clear(),
icon: Icon(Icons.clear),
),
),
),
actions: <Widget>[
TextButton(
child: Text('Cancel', style: TextStyle(color: Colors.red),),
onPressed: () {
//Navigator.pop(_);
Navigator.of(context).pop();
// _animationController.reverse();
},
),
TextButton(
child: Text('Create', style: TextStyle(color: kPrimaryColor),),
onPressed: () {
createFolder(context, scaffoldKey, _foldername.text.toString()) ;
Get.back();
//Navigator.of(context).pop();
// _animationController.reverse();
},
),
],
);
},
);
}
void _openFileType(BuildContext context) {
SKAlertDialog.show(
context: context,
type: SKAlertType.radiobutton,
radioButtonAry: {'Certificate': 1, 'Signature': 2, 'NID': 3, 'Passport': 4, 'Driving licence': 5},
title: 'Choose File category',
onCancelBtnTap: (value) {
print('Cancel Button Tapped');
Navigator.of(context).pop(false);
},
onRadioButtonSelection: (value) {
print('onRadioButtonSelection $value');
},
);
}
/* Future<void> initDiskSpace() async {
double diskSpace = 0;
diskSpace = await DiskSpace.getFreeDiskSpace;
if (!mounted) return;
setState(() {
_diskSpace = diskSpace;
});
}
*/
Future<void> _getStorgeInfo() async{
_freespace = await StorageCapacity.getFreeSpace;
//_freespacemb = await StorageCapacity.toMegaBytes(double.parse(_freespace.toString()));
_occupiedSpace = await StorageCapacity.getOccupiedSpace;
_totalSpace = await StorageCapacity.getTotalSpace;
}
}
NOTE: if I Hot Reload this page, it's working okay again
Please help.
the problem is, you are getting your data in the initState method, but your widget's build is being completed before initializing the data to _freespace, and that's why the error is appearing.
as a solution, I suggest removing _getStorgeInfo() call from initState, and implementing the following structure:
#override
Widget build(BuildContext context) {
return Scaffold(
key: scaffoldKey,
endDrawerEnableOpenDragGesture: false, // This way it will not open
// endDrawer: Drawer(),
drawer: new Drawer(
...
),
appBar: AppBar(
...
),
body: SafeArea(
child: Container(
padding: EdgeInsets.all(15.0),
child: FutureBuilder(
future: _getStorgeInfo(),
builder: (context, snapshot) {
if(snapshot.connectionState!=ConnectionState.Done) return CircularProgressIndicator();
return _widgetBody;
},
),
),
));
}

Flutter: SnackBar inside Dismissible widget is not working properly

My Home Screen is a Scaffold with a list of Dismissible widgets at its body. The child of each Dismissible is a custom widget I created, named Box. I have a FloatingActionButton that takes me to a new screen where I can add more Boxes to the list. (Each Box receive a String as an argument, that is used as its title).
I want the method onDismissed to show a SnackBar with the text "(Title of the box) excluded". However, this is not working as expected. The problem is that it always displays the title of the last box included, and not the title of the one I just dismissed. For example, if I add a Box named "Box 1", and then a Box named "Box 2", and then I dismiss the "Box 1", the snackbar will say "Box 2 excluded".
What am I doing wrong?
Here is the relevant code:
import 'package:flutter/material.dart';
import 'box.dart';
import 'addCounter.dart';
class Home extends StatefulWidget {
#override
HomeState createState() => HomeState();
}
class HomeState extends State<Home> {
List<String> lista;
void incrementLista(String novoItem) {
print('$lista');
setState(() {
lista.add(novoItem);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counters'),
backgroundColor: Colors.black,
),
body: ListView.builder(
itemCount: lista.length,
itemBuilder: (context, index) {
return Dismissible(
background: Container(color: Colors.grey[800], child: Icon(Icons.delete, color: Colors.grey[100])),
key: Key(lista[index]),
onDismissed: (direction) {
setState(() {
lista.removeAt(index);
});
Scaffold.of(context).showSnackBar(
SnackBar(content: Text(lista[index] + ' excluded.')));
},
child: Box(lista[index]));
},
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.grey[1000],
onPressed: () {
//Navega para tela de adicionar tarefa
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => AddCounter(f: incrementLista)));
},
child: Icon(Icons.add, color: Colors.white)),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
bottomNavigationBar: BottomNavigationBar(
//backgroundColor: Colors.grey[50],
unselectedItemColor: Colors.grey[700],
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.list),
title: Text('List'),
),
BottomNavigationBarItem(
icon: Icon(Icons.insert_chart),
title: Text('Chart'),
),
],
// currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
//onTap: _onItemTapped,
),
);
}
}
And here is the code of the addCounter.dart:
import 'package:flutter/material.dart';
class AddCounter extends StatefulWidget {
final Function f;
AddCounter({#required this.f});
#override
_AddCounterState createState() => _AddCounterState();
}
class _AddCounterState extends State<AddCounter> {
final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add a counter'),
backgroundColor: Colors.blue,
),
body: Column(children: [
Padding(
padding: EdgeInsets.all(15),
child: TextField(
controller: myController,
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: Colors.blue, width: 2)),
hintText: 'Type a name for the counter'),
),
),
RaisedButton(
color: Colors.green,
onPressed: () {
widget.f(myController.text);
Navigator.pop(context);
},
child: Text(
'Save',
style: TextStyle(color: Colors.white),
),
)
]));
}
}
I think the problem is that you first remove the item of the list. When you show the SnackBar the item is already removed so you can't access it in the list. So I would suggest to first show the Snackbar and then remove the item.
Like this: (In your itemBuilder)
return Dismissible(
background: Container(color: Colors.grey[800], child: Icon(Icons.delete,
color: Colors.grey[100])),
key: Key(lista[index]),
onDismissed: (direction) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text(lista[index] + ' excluded.')));
setState(() {
lista.removeAt(index);
});
},
child: Box(lista[index]));
},

Navigating with curved navigation bar flutter

I am using curved bottom navigation bar and I want everytime to have an option selected as default just for the look(e.g Home button) although I want the user to have the ability to tap it.But when I select as default the user hasn't. What can I do?
class MainClass extends StatelessWidget{
#override
Widget build(BuildContext context) {
return Scaffold(
body: MyRV(),
bottomNavigationBar:CurvedNavigationBar(
height: 50,
index: 1,
color: Colors.orange,
buttonBackgroundColor: Colors.white,
backgroundColor: Colors.blueAccent,
items: <Widget>[
Icon(Icons.arrow_back, size: 20,color: Colors.blueAccent,),
Icon(Icons.home, size: 20,color: Colors.blueAccent,),
Icon(Icons.contact_mail, size: 20,color: Colors.blueAccent,),
],
animationDuration:Duration(
milliseconds: 1000
),
animationCurve: Curves.linearToEaseOut,
onTap: (index) {
if (index==1)
Navigator.of(context).push(MaterialPageRoute(builder: (BuildContext context){return
b_afandou();})
);
},
),
);
}
}
You have already implement that. Here index: 1 means you have set default button as the button corresponding to index 1.
Check this for more details.
Corrected way to implement curved navigation bar
I noticed that the question is still getting viewed, so I would like to tell you that it was just a bug I guess. Cause I didn't do anything and it started working just fine.
The issue is you are navigation to different route instead of view. Use
body:[yourWidget1,yourWidget2,yourWidget3][_currentIndex]
class MainClass extends StatefulWidget {
#override
State<MainClass> createState() => _MainClassState();
}
class _MainClassState extends State<MainClass> {
int _currentIndex = 1;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: [///this will hold your three page
Text("First View "),
Text("second/middle View "),
Text("Thired View "),
][_currentIndex],
),
bottomNavigationBar: CurvedNavigationBar(
height: 50,
index: _currentIndex,
color: Colors.orange,
buttonBackgroundColor: Colors.white,
backgroundColor: Colors.blueAccent,
items: <Widget>[
Icon(
Icons.arrow_back,
size: 20,
color: Colors.blueAccent,
),
Icon(
Icons.home,
size: 20,
color: Colors.blueAccent,
),
Icon(
Icons.contact_mail,
size: 20,
color: Colors.blueAccent,
),
],
animationDuration: Duration(milliseconds: 1000),
animationCurve: Curves.linearToEaseOut,
onTap: (index) {
setState(() {
_currentIndex = index;
});
},
),
);
}
}
More about curved_navigation_bar

How can I have the BottomNavigationBar respond to navigation to a new page via AlertDialog?

I have a navigation_bar.dart file that handles changing to new pages within my app. Within it, I am using the bottomNavigationBar to build out four different pages based on what tab is currently selected like so:
class NavigationBar extends StatefulWidget {
#override
_NavigationBarState createState() => _NavigationBarState();
}
class _NavigationBarState extends State<NavigationBar> {
int _selectedIndex = 0;
final List<Widget> _pageOptions = <Widget>[
Page1(),
Page2(),
Page3(),
Page4(),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
String userID =
Provider.of<FirebaseUser>(context, listen: false) != null ? Provider.of<FirebaseUser>(context).uid : 'null';
return MultiProvider(
providers: [StreamProvider<MyUser>.value(value: DatabaseService().streamUser(userID))],
child: Scaffold(
body: IndexedStack(
children: _pageOptions,
index: _selectedIndex,
),
bottomNavigationBar: Theme(
data: Theme.of(context).copyWith(
canvasColor: Color(0xff271037).withOpacity(0.90),
splashColor: Colors.transparent,
),
child: BottomNavigationBar(
currentIndex: _selectedIndex,
onTap: _onItemTapped,
unselectedItemColor: Colors.white,
selectedItemColor: Color(0xff3ADEA7),
type: BottomNavigationBarType.fixed,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Container(),
title: Icon(FontAwesomeIcons.fire, color: Colors.white),
),
BottomNavigationBarItem(
icon: Container(),
title: Icon(Icons.fastfood, color: Colors.white),
),
BottomNavigationBarItem(
icon: Container(),
title: Icon(Icons.directions_bike, color: Colors.white),
),
BottomNavigationBarItem(
icon: Container(),
title: Icon(Icons.person, color: Colors.white),
)
],
),
),
),
);
}
}
Now, in a different file which is Page3.dart, on that page there is an alert dialog that pops up and when clicked, I want it to navigate to Page4().
Future<void> _showMissingDataDialog(String data) async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text('You have not set your $data yet.'),
actions: <Widget>[
FlatButton(
splashColor: Colors.transparent,
highlightColor: Colors.grey[200],
textColor: Colors.black,
child: const Text('Cancel'),
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
splashColor: Colors.transparent,
highlightColor: Colors.grey[200],
textColor: Colors.black,
child: Text('Set $data', style: TextStyle(fontWeight: FontWeight.bold)),
onPressed: () {
Navigator.of(context).pop();
// TODO: Redirect to page4() here as if it was tapped on the BottomNavigationBar
})
],
);
},
);
}
How can I have it so that clicking the "Set $data" button would route to Page4()? I want to make it so that the bottomNavigationBar reacts to this as if you tapped on the actual fourth BottomNavigationBarItem item.
Give your Nav Bar a Global Key. I declared this outside of all widgets on my main Dart file.
GlobalKey navBarGlobalKey = GlobalKey(debugLabel: 'bottomAppBar');
bottomNavigationBar: BottomNavigationBar(
key: navBarGlobalKey,
onTap: _onItemTapped,
currentIndex: _selectedIndex,
type: BottomNavigationBarType.fixed,
items: [ ... ]
Then use the global key to call the onTap Method in the onPressed method of your button. You will have to import the other dart file into this page before the global key is available.
final BottomNavigationBar navigationBar = navBarGlobalKey.currentWidget;
initialIndex = 0;
navigationBar.onTap(3); //Starts at index 0, so passing in 3 should do the trick.