Black-Screen with the FlatButton in the AppBar - android

My App contains basically 2 parts -> Appbar (with 1 Button) and BottomNavigationBar (with some buttons that works properly). The problem came when I pressed the Appbar button (goes to a black screen instead of show the "manual_page.dart")
this is the content of the 2 files (the home_page.dart and manual_page.dart):
home_page.dart
import 'package:flutter/material.dart';
import 'package:opening_a_pdf/manual_page.dart';
import 'package:opening_a_pdf/first_page.dart';
import 'package:opening_a_pdf/second_page.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _selectedPage = 0;
List<Widget> pageList = List<Widget>();
#override
void initState() {
pageList.add(FirstPage());
pageList.add(SecondPage());
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xFFFAFAFA),
appBar: AppBar(
backgroundColor: Colors.black,
title: const Text('Aplicación en Desarrollo'),
actions: <Widget>[
FlatButton(
textColor: Colors.white,
child: Text(
'MANUAL',
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
),
),
onPressed: (){
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Voice()),
);
}
)
],
),
body: IndexedStack(
index: _selectedPage,
children: pageList,
),
bottomNavigationBar: BottomNavigationBar(
// type: BottomNavigationBarType.fixed,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.compare_arrows),
title: Text('Conectividad'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.blur_on),
title: Text('Captura Datos'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.graphic_eq),
title: Text('Voz'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.list),
title: Text('Comandos'),
),
BottomNavigationBarItem(
backgroundColor: Colors.black,
icon: Icon(Icons.settings),
title: Text('Ajustes'),
),
],
currentIndex: _selectedPage,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
void _onItemTapped(int index) {
setState(() {
_selectedPage = index;
});
}
}
manual_page.dart
import 'package:flutter/material.dart';
// ignore: camel_case_types
class Voice extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Sección de Órdenes por Voz"),
),
body: Stack(
fit: StackFit.expand,
children: <Widget>[
Positioned(
bottom: 0,
width: MediaQuery.of(context).size.width,
child: Center(
child: MaterialButton(
onPressed: () {},
color: Colors.red,
),
),
)
],
),
);
}
}

Try to initial the height of container in the second screen before Stack

There are no errors in the code. Works correctly. Maybe the fault is in the main () or in the emulator.
Code in main:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

I executed your code and found no problem with it:
But you can put empty Container() as the child of MaterialButton().
Corrected code:
MaterialButton(
onPressed: () {},
color: Colors.red,
child:Container(),
),

Related

How can I use same navigation route I used for bottomnavigationbar in drawer widget in flutter?

I already have a bottom navigation bar which navigates to different pages.
then I add a drawer which I want it to change the widget in the body only, but the issue is that I made the drawer in another page and I called it, so it is not responding or I'm not calling it perfectly as I should.
Below is the navigation for the bottomnavigationbar, I have imported all necessary files
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int currentTab = 0;
final tabs = [
IndexPage(),
Save(),
Invest(),
Wallet(),
Cards(),
];
#override
Widget build(BuildContext context) {
return MaterialApp(
color: Colors.grey[900],
debugShowCheckedModeBanner: false,
title: 'Flochristos App',
theme: ThemeData(),
home: Scaffold(
backgroundColor: Colors.black,
resizeToAvoidBottomPadding: false,
resizeToAvoidBottomInset: false,
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.grey[900],
title: Text(
'PettySave',
style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.brightness_7_outlined),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.keyboard_arrow_down_sharp),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.account_circle_rounded),
onPressed: () {},
),
],
//shadowColor: Colors.grey,
),
body: tabs[currentTab], //this is where I want to change the pages
floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
bottomNavigationBar: BottomNavigationBar(
onTap: (int index) {
setState(() {
currentTab = index;
});
},
currentIndex: currentTab,
backgroundColor: Colors.grey[900],
unselectedIconTheme: IconThemeData(color: Colors.grey),
selectedItemColor: Colors.green,
unselectedItemColor: Colors.grey,
type: BottomNavigationBarType.fixed,
items: [
BottomNavigationBarItem(
icon: Icon(Icons.home_filled),
// ignore: deprecated_member_use
title: Text(
"Home",
),
),
BottomNavigationBarItem(
icon: FaIcon(FontAwesomeIcons.pagelines),
// ignore: deprecated_member_use
title: Text(
"Save",
),
),
BottomNavigationBarItem(
icon: Icon(Icons.trending_up),
// ignore: deprecated_member_use
title: Text(
"Invest",
),
),
BottomNavigationBarItem(
icon: Icon(Icons.account_balance_wallet_outlined),
// ignore: deprecated_member_use
title: Text(
"Wallet",
),
),
BottomNavigationBarItem(
icon: Icon(Icons.credit_card),
// ignore: deprecated_member_use
title: Text(
"Cards",
),
),
],
),
),
);
}
}
}
that's the main.dart code
body: tabs[currentTab], //this is where I want to change the pages
then I created another page for drawer which I called all appropriate pages
from one of the list style in the slidedrawer.dart , I'm trying to set currentTab to any index I want.... but it's not working.
ListTile(
contentPadding: EdgeInsets.fromLTRB(30, 0, 0, 0),
leading: Icon(
Icons.trending_up,
color: Colors.grey[500],
),
title: Text(
'Investments',
style: TextStyle(
color: Colors.grey[300],
fontWeight: FontWeight.bold,
),
),
onTap: () {
setState(() {
currentTab = 1;
});
},
),
I want the index to turn to Save()
List<Widget> tabs = [
IndexPage(),
Save(),
Invest(),
Wallet(),
Cards(),
];
There are many ways to add a drawer to an app, but the most common one is to use the drawer property thats within the Scaffold() Widget.
e.x.
Scaffold(
appBar: AppBar(
...
),
drawer: Drawer() // This is where you call the new Widget(class) that you made the drawer in
body: tabs[currentTab],
);
This is how I understood your question, correct me if I misunderstood it.
This is an example how I used a navigation tab bar in one of my projects.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/auth.dart';
import '../../../widgets/auth/admin/main_drawer.dart';
import '../../auth/profile_screen.dart';
import '../../home_screen.dart';
import './../projects_screen.dart';
class AdminTabBarScreen extends StatefulWidget {
static const routeName = 'auth-tab-bar-view';
#override
_AdminTabBarScreenState createState() => _AdminTabBarScreenState();
}
class _AdminTabBarScreenState extends State<AdminTabBarScreen>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
_tabController = TabController(length: 3, vsync: this);
super.initState();
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
final auth = Provider.of<Auth>(context);
return Scaffold(
// appBar: AppBar(
// title: Text('SHTEGU'),
// ),
extendBody: true,
drawer: MainDrawer(), // this is where I called my drawer
body: Container(
// color: Colors.blueAccent,
child: TabBarView(
children: <Widget>[
HomeScreen(),
ProjectsScreen(),
ProfileScreen(),
// LoginScreen(),
],
controller: _tabController,
),
),
bottomNavigationBar: Container(
padding: EdgeInsets.all(16.0),
child: ClipRRect(
borderRadius: BorderRadius.all(
Radius.circular(50.0),
),
child: Container(
color: Colors.black26,
child: TabBar(
labelColor: Color(0xFFC41A3B),
unselectedLabelColor: Colors.white,
labelStyle: TextStyle(fontSize: 13.0),
indicator: UnderlineTabIndicator(
borderSide: BorderSide(color: Colors.black54, width: 0.0),
insets: EdgeInsets.fromLTRB(50.0, 0.0, 50.0, 40.0),
),
//For Indicator Show and Customization
indicatorColor: Colors.black54,
tabs: <Widget>[
Tab(
text: 'Home',
),
Tab(
text: 'Projects',
),
Tab(
text: 'Profile',
),
// Tab(
// text: 'Login',
// ),
],
controller: _tabController,
),
),
),
),
);
}
}
Here is how I called the class above to check if admin
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../screens/auth/admin/admin_tab_bar_screen.dart';
import '../../screens/auth/user_tab_bar_screen.dart';
import '../../providers/auth.dart';
class AuthTabBarScreen extends StatelessWidget {
static const routeName = 'auth-tab-bar-view';
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: Provider.of<Auth>(context, listen: false).isAdmin(),
builder: (context, snapshot) => snapshot.hasData
? snapshot.data
? AdminTabBarScreen()
: UserTabBarScreen()
: CircularProgressIndicator(), // while you're waiting for the data, show some kind of loading indicator
);
}
}
And here is my drawer:
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../screens/auth/admin/register_user_screen.dart';
import '../../../screens/auth/auth_tab_bar_screen.dart';
import '../../../screens/tab_bar_screen.dart';
import '../../../providers/auth.dart';
class MainDrawer extends StatelessWidget {
Widget buildListTile(
String title, IconData icon, Function tapHandler, BuildContext ctx) {
return ListTile(
tileColor: Color(0xffF2F7FB),
selectedTileColor: Theme.of(ctx).accentColor,
leading: Icon(
icon,
size: 26,
color: Theme.of(ctx).primaryColor,
),
title: Text(
title,
style: TextStyle(
fontFamily: 'RobotoCondensed',
fontSize: 16,
fontWeight: FontWeight.bold,
color: Theme.of(ctx).primaryColor,
),
),
onTap: tapHandler,
);
}
#override
Widget build(BuildContext context) {
final authData = Provider.of<Auth>(context, listen: false);
return Drawer(
child: SafeArea(
child: SingleChildScrollView(
child: Column(
children: <Widget>[
buildListTile(
'Home',
Icons.home_rounded,
() {
Navigator.of(context)
.pushReplacementNamed(AuthTabBarScreen.routeName);
},
context,
),
buildListTile(
'Add user',
Icons.person_add_alt_1_rounded,
() {
// Navigator.of(context).pop();
Navigator.of(context)
.pushReplacementNamed(RegisterUserScreen.routeName);
},
context,
),
buildListTile(
'Sign Out',
Icons.exit_to_app_rounded,
() {
authData.signOut();
},
context,
),
],
),
),
),
);
}
}
Hope this is at least of help to you :D

Flutter : Staying inside wrapper when navigating with AppBar

I have a bottom navigation bar, that lets me navigate between pages, while keeping the Bottom Navigation bar in place (Using Persistent Bottom Navigation bar package)
I also want to have a extra navigation button, that sends me to another page not listed on the Bottom Navigation bar, but all the different ways I have tried, it pushes me to another page, that is not inside the wrapper.
How could I navigate to another page from AppBar (Page is not listed on the bottom navigation bar) without losing the Navigation bar?
Attatching wrapper code
class Wrapper extends StatefulWidget {
final BuildContext menuScreenContext;
Wrapper({Key key, this.menuScreenContext}) : super(key: key);
#override
_WrapperState createState() => _WrapperState();
}
class _WrapperState extends State<Wrapper> {
final AuthService _auth = AuthService();
PersistentTabController _controller;
bool _hideNavBar;
#override
void initState() {
super.initState();
_controller = PersistentTabController(initialIndex: 0);
_hideNavBar = false;
}
List<Widget> _buildScreens() {
return [
HomePage(
hideStatus:_hideNavBar,
),
Page1(),
Page2(),
Page3(),
Page4(
hideStatus:_hideNavBar,
),
];
}
List<PersistentBottomNavBarItem> _navBarsItems() {
return [
PersistentBottomNavBarItem(
icon: Icon(Icons.home),
title: "Home",
activeColor: Colors.blue,
inactiveColor: Colors.grey,
),
PersistentBottomNavBarItem(
icon: Icon(Icons.search),
title: ("Search"),
activeColor: Colors.teal,
inactiveColor: Colors.grey,
),
PersistentBottomNavBarItem(
icon: Icon(Icons.add),
title: ("Add"),
activeColor: Colors.deepOrange,
inactiveColor: Colors.grey,
),
PersistentBottomNavBarItem(
icon: Icon(Icons.settings),
title: ("Settings"),
activeColor: Colors.indigo,
inactiveColor: Colors.grey,
),
PersistentBottomNavBarItem(
icon: Icon(Icons.settings),
title: ("Settings"),
activeColor: Colors.indigo,
inactiveColor: Colors.grey,
),
];
}
#override
Widget build(BuildContext context)
{
final user = Provider.of<NUser>(context);
if(user==null){
return Authenticate();}
else {
return Scaffold
(
drawer: Drawer(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>
[
TextButton
(child:Text('hey'), onPressed: ()
{
pushNewScreenWithRouteSettings(
context,
settings: RouteSettings(name:'/home'),
screen: HomePage());
}
),
ElevatedButton.icon(
onPressed: () async {await _auth.signOut();},
icon: Icon(Icons.person),
label: Text('Logout'),
),
],
),
),
),
appBar: AppBar(
actions: [
IconButton(iconSize: 150,icon: Image.asset("assets/BUTTON.png", color: Colors.black,height: 1000,width: 1000,), onPressed: ()
{
Navigator.push(context, MaterialPageRoute(builder: (context) => Profile()));
}),
ButtonTheme(
minWidth: 100.0,
height: 100.0,
child: TextButton(
onPressed: () {},
child: Text(" 4444 "),
),
),
],
),
body: PersistentTabView.custom
(
context,
controller: _controller,
screens: _buildScreens(),
confineInSafeArea: true,
itemCount: 5,
handleAndroidBackButtonPress: true,
resizeToAvoidBottomInset: false,
stateManagement: true,
hideNavigationBar: _hideNavBar,
screenTransitionAnimation: ScreenTransitionAnimation(
animateTabTransition: true,
curve: Curves.ease,
duration: Duration(milliseconds: 200),
),
customWidget: CustomNavBarWidget
(
items: _navBarsItems(),
onItemSelected: (index) {
setState(() {
_controller.index = index; // THIS IS CRITICAL!! Don't miss it!
});
},
selectedIndex: _controller.index,
),
),
);
}
}
}
class Profile extends StatefulWidget {
Profile({Key key}): super(key: key);
#override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:Text('sample'),
),
);
}
}
I tried creating a class for the page in wrapper, but no luck. Other pages are individual files. I am trying to navigate with the AppBar Button

How to open this type of alert dialog in flutter

I wanted to show dialog in my application. How can i achieve this using flutter
You can use a PopupMenuButton (https://api.flutter.dev/flutter/material/PopupMenuButton-class.html) to achieve this in flutter.
See example code below:
PopupMenuButton<int>(
itemBuilder: (context) => [
const PopupMenuItem(
value: 1,
child: Center(
child: Icon(
Icons.download_outlined,
size: 30.0,
),
),
),
const PopupMenuItem(
value: 2,
child: Center(
child: Icon(
Icons.link,
size: 30.0,
),
),
),
const PopupMenuItem(
value: 2,
child: Center(
child: Icon(
Icons.share,
size: 30.0,
),
),
),
],
icon: const Icon(
Icons.more_horiz,
size: 40.0,
),
offset: const Offset(150, -150),
);
The above example popups a list of Icons when the PopupMenuButton is pressed.
You can adapt this to your use-case above.
Finally I found a Solution thanks enfinity. Here how i solve the problem.
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
/// An arbitrary widget that lives in a popup menu
class PopupMenuWidget<T> extends PopupMenuEntry<T> {
const PopupMenuWidget({ Key key, this.height, this.child }) : super(key: key);
#override
final Widget child;
#override
final double height;
#override
bool get enabled => false;
#override
_PopupMenuWidgetState createState() => new _PopupMenuWidgetState();
}
class _PopupMenuWidgetState extends State<PopupMenuWidget> {
#override
Widget build(BuildContext context) => widget.child;
}
class MyHomePage extends StatelessWidget {
MyHomePage({Key key}) : super(key: key);
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
actions: <Widget>[
new PopupMenuButton<String>(
onSelected: (String value) {
print("You selected $value");
},
itemBuilder: (BuildContext context) {
return [
new PopupMenuWidget(
height: 40.0,
child: new Row(
children: [
IconButton(
icon: Icon(
Icons.remove,
color: Colors.green,
),
onPressed: () {
print("Remove");
}),
Text("1"),
IconButton(
icon: Icon(
Icons.add,
color: Colors.green,
),
onPressed: () {
print("Add");
}),
],
),
),
];
}
),
],
),
);
}
}

How to pass data/Images from one page to another in Bottom Navigation Bar

I wanted to send Data/images from one page to another. In the Homepage when I tap on the add Icon button image should be passed to the Cart page and if the icon is tapped again image is removed from the Cart page. But, the cart page should be accessed from bottom navigation bar.
but it is showing an error called 1 positional argument(s) expected, but 0 found.
Try adding the missing arguments.. when it calls the cart page.
HomePage.dart file
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
home: NavBar(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Dish> _dishes = List<Dish>();
List<Dish> _cartList = List<Dish>();
#override
void initState() {
super.initState();
_populateDishes();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 16.0, top: 8.0),
child: GestureDetector(
child: Stack(
alignment: Alignment.topCenter,
children: <Widget>[
Icon(
Icons.shopping_cart,
size: 36.0,
),
if (_cartList.length > 0)
Padding(
padding: const EdgeInsets.only(left: 2.0),
child: CircleAvatar(
radius: 8.0,
backgroundColor: Colors.red,
foregroundColor: Colors.white,
child: Text(
_cartList.length.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12.0,
),
),
),
),
],
),
onTap: () {
if (_cartList.isNotEmpty)
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Cart(_cartList),
),
);
},
),
)
],
),
body: _buildGridView(),
);
}
ListView _buildListView() {
return ListView.builder(
itemCount: _dishes.length,
itemBuilder: (context, index) {
var item = _dishes[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
vertical: 2.0,
),
child: Card(
elevation: 4.0,
child: ListTile(
leading: Icon(
item.icon,
color: item.color,
),
title: Text(item.name),
trailing: GestureDetector(
child: (!_cartList.contains(item))
? Icon(
Icons.add_circle,
color: Colors.green,
)
: Icon(
Icons.remove_circle,
color: Colors.red,
),
onTap: () {
setState(() {
if (!_cartList.contains(item))
_cartList.add(item);
else
_cartList.remove(item);
});
},
),
),
),
);
},
);
}
GridView _buildGridView() {
return GridView.builder(
padding: const EdgeInsets.all(4.0),
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemCount: _dishes.length,
itemBuilder: (context, index) {
var item = _dishes[index];
return Card(
elevation: 4.0,
child: Stack(
fit: StackFit.loose,
alignment: Alignment.center,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
item.icon,
color: (_cartList.contains(item))
? Colors.grey
: item.color,
size: 100.0,
),
Text(
item.name,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.subhead,
)
],
),
Padding(
padding: const EdgeInsets.only(
right: 8.0,
bottom: 8.0,
),
child: Align(
alignment: Alignment.bottomRight,
child: GestureDetector(
child: (!_cartList.contains(item))
? Icon(
Icons.add_circle,
color: Colors.green,
)
: Icon(
Icons.remove_circle,
color: Colors.red,
),
onTap: () {
setState(() {
if (!_cartList.contains(item))
_cartList.add(item);
else
_cartList.remove(item);
});
},
),
),
),
],
));
});
}
void _populateDishes() {
var list = <Dish>[
Dish(
name: 'Chicken Zinger',
icon: Icons.fastfood,
color: Colors.amber,
),
Dish(
name: 'Chicken Zinger without chicken',
icon: Icons.print,
color: Colors.deepOrange,
),
Dish(
name: 'Rice',
icon: Icons.child_care,
color: Colors.brown,
),
Dish(
name: 'Beef burger without beef',
icon: Icons.whatshot,
color: Colors.green,
),
Dish(
name: 'Laptop without OS',
icon: Icons.laptop,
color: Colors.purple,
),
Dish(
name: 'Mac wihout macOS',
icon: Icons.laptop_mac,
color: Colors.blueGrey,
),
];
setState(() {
_dishes = list;
});
}
}
Cart.dart file
import 'package:flutter/material.dart';
import 'dish_object.dart';
class Cart extends StatefulWidget {
final List<Dish> _cart;
Cart(this._cart);
#override
_CartState createState() => _CartState(this._cart);
}
class _CartState extends State<Cart> {
_CartState(this._cart);
List<Dish> _cart;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cart'),
),
body: ListView.builder(
itemCount: _cart.length,
itemBuilder: (context, index) {
var item = _cart[index];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
child: Card(
elevation: 4.0,
child: ListTile(
leading: Icon(
item.icon,
color: item.color,
),
title: Text(item.name),
trailing: GestureDetector(
child: Icon(
Icons.remove_circle,
color: Colors.red,
),
onTap: () {
setState(() {
_cart.remove(item);
});
},
),
),
),
);
},
),
);
}
}
NavBar.dart file
import 'package:flutter/material.dart';
import 'package:sharewallpaper/cart.dart';
import 'package:sharewallpaper/main.dart';
class NavBar extends StatefulWidget {
#override
_NavBarState createState() => _NavBarState();
}
class _NavBarState extends State<NavBar> {
int _currentIndex = 0;
final List<Widget> _children = [
MyHomePage(),
Cart(), ** This line is throwing an error **
];
void onTappedBar(int index) {
setState(() {
_currentIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: _children[_currentIndex],
bottomNavigationBar: BottomNavigationBar(
onTap: onTappedBar,
currentIndex: _currentIndex,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(
icon: Icon(Icons.bookmark), title: Text('BookMark')),
],
),
);
}
}
Yep, it will throw an error because the constructor of the Cart class is expecting one parameter to be passed in. You could use a named constructor instead like this:
class Cart extends StatefulWidget {
final List<Dish> _cart;
Cart(this._cart);
That way, you can call it like so:
Cart(cart: _cartList),
But if you actually need the cart list, I would recommend that you write a provider to keep track of the cart data across screens.

Is it possible to get a bottomNavBar without icons / with text only

I want to get a bottom navigation bar, but the Tabs should be text-only. The problem is, that icon is a required property of BottomNavigationBarItem().
Edit: I got it working using a tab bar as bottom nav bar, but #Fernando Rocha 's solution seems to work less tricky and works better. To sum it up, simply add "size: 0" to each icon (you will still need an icon).
I used size 0 at icon size and it worked
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
#override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static const List<Widget> _widgetOptions = <Widget>[
Text(
'Index 0: Home',
style: optionStyle,
),
Text(
'Index 1: Business',
style: optionStyle,
),
Text(
'Index 2: School',
style: optionStyle,
),
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('BottomNavigationBar Sample'),
),
body: Center(
child: _widgetOptions.elementAt(_selectedIndex),
),
bottomNavigationBar: BottomNavigationBar(
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home, size: 0),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.business, size: 0),
title: Text('Business'),
),
BottomNavigationBarItem(
icon: Icon(Icons.school, size: 0),
title: Text('School'),
),
],
currentIndex: _selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
),
);
}
}
You can do
BottomNavigationBarItem(
icon: Icon(null),
title: Text('Just Text'),
)
to achieve this.
With this approach there will still be an empty space where the Icon is "supposed" to go. With #Fernando Rocha 's approach it looks like the text is centered.
I used tabs instead :
static const List<Tab> _tabs = [
Tab(text: "A"),
Tab(text: "AA"),
Tab(text: "AAA")
];
return WillPopScope(
child: DefaultTabController(
length: _tabs.length,
child: Scaffold(
bottomNavigationBar: Container(
// color: Color(0xFF3F5AA6),
margin: const EdgeInsets.only(bottom: 11),
child: TabBar(
// labelColor: Colors.white,
// unselectedLabelColor: Colors.white60,
// indicatorSize: TabBarIndicatorSize.tab,
indicatorPadding: const EdgeInsets.symmetric(vertical: 7, horizontal: 23),
indicatorColor: Colors.white,
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
},
tabs: _tabs,
),
),
body: Center(
child: _pages[_selectedIndex]
),
),
),
onWillPop: () async {
return Navigator.canPop(context);
}
);

Categories

Resources