How can I show/hide a floatingActionButton in one tab to another? - flutter

I was wondering how can I show/hide a FloatingActionButton in a TabBarView.
So for example in my first tab, I wanna a FloatingActionButton, but in the second tab I wanna hide it.
So in my case my code is:
class Notifications extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
floatingActionButton: FloatingActionButton(
backgroundColor: kPink,
child: Icon(Icons.add),
onPressed: () => print(Localizations.localeOf(context)),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.only(top: kBigSeparation),
child: DefaultTabController(
length: 2,
initialIndex: 0,
child: Padding(
padding: kPaddingTabBar,
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(kTinySeparation),
decoration: BoxDecoration(
color: kLightGrey,
borderRadius: BorderRadius.all(
Radius.circular(50),
),
),
child: TabBar(
tabs: <Tab>[
Tab(
text: AppLocalizations.of(context)
.translate('messages'),
),
Tab(
text: AppLocalizations.of(context)
.translate('notifications'),
)
],
unselectedLabelColor: Colors.black54,
labelColor: Colors.black,
unselectedLabelStyle: kBoldText,
labelStyle: kBoldText,
indicatorSize: TabBarIndicatorSize.tab,
indicator: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(50),
color: Colors.white,
),
),
),
const SizedBox(height: kMediumSeparation),
Expanded(
child: TabBarView(children: [
MessagesTab(),
NotificationsTab(),
]),
),
],
),
),
),
),
),
);
}
}

You can copy paste run full code below
Step 1 : You need to use TabController
Step 2 : Show/hide floatingActionButton based on tabIndex
code snippet
TabBar(
controller: _tabController,
tabs: <Tab>[
...
floatingActionButton: _tabController.index == 0
? FloatingActionButton(
backgroundColor: Colors.pink,
child: Icon(Icons.add),
onPressed: () => print(Localizations.localeOf(context)),
)
: Container(),
working demo
full code
import 'package:flutter/material.dart';
class Notifications extends StatefulWidget {
#override
_NotificationsState createState() => _NotificationsState();
}
class _NotificationsState extends State<Notifications>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this, initialIndex: 0);
_tabController.addListener(_switchTabIndex);
}
void _switchTabIndex() {
print(_tabController.index);
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
floatingActionButton: _tabController.index == 0
? FloatingActionButton(
backgroundColor: Colors.pink,
child: Icon(Icons.add),
onPressed: () => print(Localizations.localeOf(context)),
)
: Container(),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.only(top: 2.0),
child: Padding(
padding: EdgeInsets.all(1.0),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.all(
Radius.circular(50),
),
),
child: TabBar(
controller: _tabController,
tabs: <Tab>[
Tab(
text: 'messages',
),
Tab(
text: 'notifications',
)
],
unselectedLabelColor: Colors.black54,
labelColor: Colors.black,
//unselectedLabelStyle: kBoldText,
//labelStyle: kBoldText,
indicatorSize: TabBarIndicatorSize.tab,
indicator: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(50),
color: Colors.white,
),
),
),
const SizedBox(height: 10),
Expanded(
child: TabBarView(controller: _tabController, children: [
MessagesTab(),
NotificationsTab(),
]),
),
],
),
),
),
),
);
}
}
class MessagesTab extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("MessagesTab");
}
}
class NotificationsTab extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Text("NotificationsTab");
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Notifications(),
);
}
}
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 _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Related

I am getting two appBar in flutter app. I am trying to add Drawer widget and TabBar widget in flutter app

main.dart
import 'package:flutter/material.dart';
import 'package:stray_animal_emergencyrescue/signUpPage.dart';
import './commons/commonWidgets.dart';
import 'package:stray_animal_emergencyrescue/loggedIn.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
//title: 'Flutter login UI',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
//String showPasswordText = "Show Password";
bool obscurePasswordText = true;
#override
Widget build(BuildContext context) {
final passwordField = TextField(
obscureText: obscurePasswordText,
decoration: InputDecoration(
//contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
hintText: "Password",
//border: OutlineInputBorder(borderRadius: BorderRadius.circular(32.0)),
suffixIcon: IconButton(
icon: new Icon(Icons.remove_red_eye),
onPressed: () {
setState(() {
this.obscurePasswordText = !obscurePasswordText;
});
},
)),
);
final loginButon = Material(
//elevation: 5.0,
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => LogIn()),
);
},
child: Text('Login', textAlign: TextAlign.center),
),
);
final facebookContinueButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
},
child: Text('Facebook', textAlign: TextAlign.center),
),
);
final googleContinueButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
//print(MediaQuery.of(context).size.width);
},
child: Text('Google ', textAlign: TextAlign.center),
),
);
final signUpButton = Material(
//borderRadius: BorderRadius.circular(30.0),
color: Colors.blue,
child: MaterialButton(
//minWidth: MediaQuery.of(context).size.width,
//padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => FormScreen()),
);
//print(MediaQuery.of(context).size.width);
},
child: Text('Sign Up ', textAlign: TextAlign.center),
),
);
return Scaffold(
appBar: AppBar(
title: Text("Animal Emergency App"),
),
body: Center(
child: Container(
//color: Colors.white,
child: Padding(
padding: const EdgeInsets.all(36.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
//SizedBox(height: 45.0),
getTextFieldWidget(),
SizedBox(height: 15.0),
passwordField,
sizedBoxWidget,
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
facebookContinueButton,
SizedBox(width: 5),
googleContinueButton,
SizedBox(width: 5),
loginButon
],
),
/*loginButon,
signUpButton,*/
sizedBoxWidget,
const Divider(
color: Colors.black,
height: 20,
thickness: 1,
indent: 20,
endIndent: 0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
//crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
signUpButton
],
),
],
),
),
),
),
);
}
}
loggedIn.dart
import 'package:flutter/material.dart';
import './tabbarviews/emergencyresue/EmergencyHome.dart';
import './tabbarviews/animalcruelty/animalCrueltyHome.dart';
import './tabbarviews/bloodbank/bloodBankHome.dart';
class LogIn extends StatefulWidget {
#override
_LogInState createState() => _LogInState();
}
class _LogInState extends State<LogIn> {
int _selectedIndex = 0;
static const TextStyle optionStyle =
TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
static List<Widget> _widgetOptions = <Widget>[
EmergencyHome(),
AnimalCrueltyHome(),
BloodBankHome()
];
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('First app bar appearing'),
actions: <Widget>[
GestureDetector(
onTap: () {},
child: CircleAvatar(
//child: Text("SC"),
backgroundImage: AssetImage('assets/images/760279.jpg'),
//backgroundImage: ,
),
),
IconButton(
icon: Icon(Icons.more_vert),
color: Colors.white,
onPressed: () {},
),
],
),
drawer: Drawer(
child: ListView(
children: <Widget>[
new ListTile(title: Text("Primary")),
MyListTile(
"Home",
false,
"Your customized News Feed about people you follow, ongoing rescues, nearby activities, adoptions etc.",
3,
Icons.home,
true,
() {}),
MyListTile(
"News & Media Coverage",
false,
"News about incidents which need immediate action, changing Laws",
3,
Icons.home,
false,
() {}),
MyListTile(
"Report",
true,
"Report cases with evidences anonymously",
3,
Icons.announcement,
false,
() {}),
MyListTile(
"Blood Bank",
true,
"Details to donate blood ",
3,
Icons.medical_services,
false,
() {}),
],
),
),
body: _widgetOptions[_selectedIndex],
bottomNavigationBar: BottomNavigationBar(
currentIndex: _selectedIndex,
selectedItemColor: Colors.blue,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.pets),
label: 'Emergency Rescue',
),
BottomNavigationBarItem(
icon: Icon(Icons.add_alert),
label: 'Report Cruelty',
),
BottomNavigationBarItem(
icon: Icon(Icons.medical_services),
label: 'Blood Bank',
),
/*BottomNavigationBarItem(
icon: Icon(Icons.school),
label: 'Safe Hands',
backgroundColor: Colors.blue),*/
],
onTap: _onItemTapped,
),
);
}
}
//Safe Hands
class MyListTile extends StatelessWidget {
final String title;
final bool isThreeLine;
final String subtitle;
final int maxLines;
final IconData icon;
final bool selected;
final Function onTap;
MyListTile(this.title, this.isThreeLine, this.subtitle, this.maxLines,
this.icon, this.selected, this.onTap);
#override
Widget build(BuildContext context) {
return ListTile(
title: Text(title),
isThreeLine: isThreeLine,
subtitle:
Text(subtitle, maxLines: maxLines, style: TextStyle(fontSize: 12)),
leading: Icon(icon),
selected: selected,
onTap: onTap);
}
}
EmergencyHome.dart
import 'package:flutter/material.dart';
import './finishedAnimalEmergencies.dart';
import './reportAnimalEmergency.dart';
import './ongoingAnimalEmergencies.dart';
class EmergencyHome extends StatefulWidget {
#override
_EmergencyHomeState createState() => _EmergencyHomeState();
}
class _EmergencyHomeState extends State<EmergencyHome> {
#override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
title: Text("Second appBar appearing"),
bottom: TabBar(
tabs: [
Tab(
//icon: Icon(Icons.more_vert),
text: "Report",
),
Tab(
text: "Ongoing",
),
Tab(
text: "Finished",
)
],
),
),
body: TabBarView(
children: [
ReportAnimalEmergency(),
OngoingAnimalEmergencies(),
FinishedAnimalEmergencies(),
],
),
)
);
}
}
The issue I am facing is two appBar, I tried removing appBar from loggedIn.dart but Drawer hamburger icon is not showing, and I cannot remove appBar from emergencyHome.dart as I wont be able to add Tab bar. What is viable solution for this? Please help how to Structure by app and routes to easily manage navigation within app
Remove the appbar from EmergencyHome.dart
this will remove the second app title. But there will be that shadow from the first app bar so put elvation:0
so, this will look like one appbar now your drawer will also work.
you can use flexibleSpace in EmergencyHome.dart
DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
flexibleSpace: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
TabBar(
tabs: [
Tab(
//icon: Icon(Icons.more_vert),
text: "Report",
),
Tab(
text: "Ongoing",
),
Tab(
text: "Finished",
)
],
)
],
),
),
body: TabBarView(
children: [
ReportAnimalEmergency(),
OngoingAnimalEmergencies(),
FinishedAnimalEmergencies(),
],
),
)
);
You don't want to make two appbar to get the drawer property. Use DefaultTabController then inside that you can use scaffold.so, you can have drawer: Drawer() inside that you can also get a appbar with it with TabBar as it's bottom.
This is most suitable for you according to your use case.
i will put the full code below so you can copy it.
void main() {
runApp(const TabBarDemo());
}
class TabBarDemo extends StatelessWidget {
const TabBarDemo({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
home: DefaultTabController(
length: 3,
child: Scaffold(
drawer: Drawer(),
appBar: AppBar(
bottom: const TabBar(
tabs: [
Tab(
text: "report",
),
Tab(text: "ongoing"),
Tab(text: "completed"),
],
),
title: const Text('Tabs Demo'),
),
body: const TabBarView(
children: [
Icon(Icons.directions_car),
Icon(Icons.directions_transit),
Icon(Icons.directions_bike),
],
),
),
),
);
}
}
OUTPUT

Is there any way to put custom toolbar on the keypad?

I want to put a custom toolbar on the keypad like the image above. Is it possible in flutter? or should I write code on the iOS or Android side?
You can copy paste run full code below
Please see working demo below
You can use package https://pub.dev/packages/keyboard_overlay
Step 1: Use with HandleFocusNodesOverlayMixin
Step 2: Use FocusNodeOverlay for focusNode
Step 3: Use GetFocusNodeOverlay and set _focusNodeOverlay = GetFocusNodeOverlay(
Step 4: TextField use TextField(focusNode: _focusNodeOverlay,
code snippet
class _MyHomePageState extends State<MyHomePage>
with HandleFocusNodesOverlayMixin {
FocusNodeOverlay _focusNodeOverlay;
#override
void initState() {
_focusNodeOverlay = GetFocusNodeOverlay(
child: TopKeyboardUtil(
Container(
color: Colors.white,
height: 45,
width: MediaQueryData.fromWindow(ui.window).size.width,
child: Row(
children: [
GestureDetector(
child: Icon(Icons.save),
onTap: () => print("click"),
),
...
Spacer(),
Container(
width: 60,
child: Center(
child: DoneButtonIos(
backgroundColor: Colors.white,
textColor: Colors.green,
label: 'Post',
onSubmitted: () {
print("submit");
},
platforms: ['android', 'ios'],
),
),
),
],
),
),
),
);
working demo
full code
import 'package:flutter/material.dart';
import 'package:keyboard_overlay/keyboard_overlay.dart';
import 'dart:ui' as ui;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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 HandleFocusNodesOverlayMixin {
FocusNodeOverlay _focusNodeOverlay;
#override
void initState() {
_focusNodeOverlay = GetFocusNodeOverlay(
child: TopKeyboardUtil(
Container(
color: Colors.white,
height: 45,
width: MediaQueryData.fromWindow(ui.window).size.width,
child: Row(
children: [
GestureDetector(
child: Icon(Icons.save),
onTap: () => print("click"),
),
GestureDetector(
child: Icon(Icons.computer),
onTap: () => print("click"),
),
GestureDetector(
child: Icon(Icons.home),
onTap: () => print("click"),
),
Spacer(),
Container(
width: 60,
child: Center(
child: DoneButtonIos(
backgroundColor: Colors.white,
textColor: Colors.green,
label: 'Post',
onSubmitted: () {
print("submit");
},
platforms: ['android', 'ios'],
),
),
),
],
),
),
),
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
focusNode: _focusNodeOverlay,
style: TextStyle(color: Colors.grey),
decoration: InputDecoration(
labelText: 'Type Something',
labelStyle: TextStyle(color: Colors.black),
fillColor: Colors.orange,
hintStyle: TextStyle(
color: Colors.grey,
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.black, width: 1.0),
),
),
),
],
),
),
);
}
}
Yes there is a way around in the flutter to achieve this.
Create a widget of the toolbar you want to add.
Set it visible on input focus.
For reference I am sharing the code how I achieve that.
class InputDoneView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
color: Style.lightGrey,
child: Align(
alignment: Alignment.topRight,
child: Padding(
padding: const EdgeInsets.only(top: 1.0, bottom: 1.0),
child: CupertinoButton(
padding: EdgeInsets.only(right: 24.0, top: 2.0, bottom: 2.0),
onPressed: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: Text(
"Done",
style: TextStyle(color: Style.primaryColor,fontWeight: FontWeight.normal)
),
),
),
),
);
}
}
To call this in your main view when input field is focused in and out.
showOverlay(BuildContext context) {
if (overlayEntry != null) return;
OverlayState overlayState = Overlay.of(context);
overlayEntry = OverlayEntry(builder: (context) {
return Positioned(
bottom: MediaQuery.of(context).viewInsets.bottom, right: 0.0, left: 0.0, child: InputDoneView());
});
overlayState.insert(overlayEntry);
}
removeOverlay() {
if (overlayEntry != null) {
overlayEntry.remove();
overlayEntry = null;
}
}

Layout issue: TabBarView with TextField Keyboard overflow

I'm trying to implement a specific design and as thhe title says I have encountered an issue in building my layout.
When I'm taping inside my TextField the keyboard open itself and create an overflow.
Screenshots
Code
deals_edition_page.dart
import 'package:flutter/material.dart';
import 'package:myuca/ui/manager/deals/edition_informations_tab.dart';
class DealsEditionPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => _DealsEditionPageState();
}
class _DealsEditionPageState extends State<DealsEditionPage> {
MemoryImage _image;
Widget _buildAppbar() {
return AppBar(
elevation: 0,
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
title: Text(/* random String */),
actions: [
IconButton(
icon: Icon(Icons.check),
onPressed: () => Navigator.pop(context),
),
],
);
}
Widget _buildHeaderTabBar() {
return SliverAppBar(
automaticallyImplyLeading: false,
expandedHeight: 224,
floating: true,
elevation: 0,
flexibleSpace:
FlexibleSpaceBar(background: Image.memory(_image.bytes, fit: BoxFit.cover)),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppbar(),
body: DefaultTabController(
length: 2,
child: CustomScrollView(
slivers: <Widget>[
_buildHeaderTabBar(),
SliverToBoxAdapter(
child: TabBar(
indicatorWeight: 2,
tabs: [
Tab(text: 'Informations'),
Tab(text: 'Informations'),
],
),
),
SliverFillRemaining(
child: Column(
children: [
Expanded(
child: TabBarView(
children: [
EditionInformationsTab(),
Center(child: Text("Tab 2")),
],
),
),
],
),
),
],
),
),
);
}
}
edition_informations_tab.dart
import 'package:flutter/material.dart';
import 'package:myuca/extensions/extensions.dart' show WidgetModifier;
class EditionInformationsTab extends StatefulWidget {
#override
State<StatefulWidget> createState() => _EditionInformationsTabState();
}
class _EditionInformationsTabState extends State<EditionInformationsTab> {
final _list1 = <String>['Culture', 'Test'];
final _list2 = <String>['Etablissement', 'Test 1', 'Test 2'];
List<DropdownMenuItem<String>> _menuItemsGenerator(List<String> values) =>
values
.map<DropdownMenuItem<String>>((e) => DropdownMenuItem<String>(
value: e,
child: Text(e),
))
.toList();
#override
Widget build(BuildContext context) {
return Form(
child: Column(
children: [
DropdownButtonFormField<String>(
value: _list1.first,
decoration: InputDecoration(
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(4))),
items: _menuItemsGenerator(_list1),
onChanged: (_) {},
).padding(EdgeInsets.only(bottom: 24)),
DropdownButtonFormField(
value: _list2.first,
decoration: InputDecoration(
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(4))),
items: _menuItemsGenerator(_list2),
onChanged: (_) {},
).padding(EdgeInsets.only(bottom: 24)),
TextFormField(
maxLength: 30,
decoration: InputDecoration(
labelText: "Nom de l'offre",
border:
OutlineInputBorder(borderRadius: BorderRadius.circular(4))),
),
],
),
).padding(EdgeInsets.only(
top: 16, left: 16, right: 16));
}
}
Any idea on how I could avoid this overflow when the keyboard is displayed ?
You can copy paste run full code below
You can in _EditionInformationsTabState wrap with SingleChildScrollView
class _EditionInformationsTabState extends State<EditionInformationsTab> {
...
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
working demo
full code
import 'package:flutter/material.dart';
class DealsEditionPage extends StatefulWidget {
#override
State<StatefulWidget> createState() => _DealsEditionPageState();
}
class _DealsEditionPageState extends State<DealsEditionPage> {
MemoryImage _image;
Widget _buildAppbar() {
return AppBar(
elevation: 0,
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () => Navigator.pop(context),
),
title: Text("demo"),
actions: [
IconButton(
icon: Icon(Icons.check),
onPressed: () => Navigator.pop(context),
),
],
);
}
Widget _buildHeaderTabBar() {
return SliverAppBar(
automaticallyImplyLeading: false,
expandedHeight: 224,
floating: true,
elevation: 0,
flexibleSpace: FlexibleSpaceBar(
background: Image.network("https://picsum.photos/250?image=9",
fit: BoxFit.cover)),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppbar(),
body: DefaultTabController(
length: 2,
child: CustomScrollView(
slivers: <Widget>[
_buildHeaderTabBar(),
SliverToBoxAdapter(
child: TabBar(
indicatorWeight: 2,
tabs: [
Tab(text: 'Informations'),
Tab(text: 'Informations'),
],
),
),
SliverFillRemaining(
child: Column(
children: [
Expanded(
child: TabBarView(
children: [
EditionInformationsTab(),
Center(child: Text("Tab 2")),
],
),
),
],
),
),
],
),
),
);
}
}
class EditionInformationsTab extends StatefulWidget {
#override
State<StatefulWidget> createState() => _EditionInformationsTabState();
}
class _EditionInformationsTabState extends State<EditionInformationsTab> {
final _list1 = <String>['Culture', 'Test'];
final _list2 = <String>['Etablissement', 'Test 1', 'Test 2'];
List<DropdownMenuItem<String>> _menuItemsGenerator(List<String> values) =>
values
.map<DropdownMenuItem<String>>((e) => DropdownMenuItem<String>(
value: e,
child: Text(e),
))
.toList();
#override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(top: 16, left: 16, right: 16),
child: Form(
child: Column(
children: [
Padding(
padding: EdgeInsets.only(bottom: 24),
child: DropdownButtonFormField<String>(
value: _list1.first,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4))),
items: _menuItemsGenerator(_list1),
onChanged: (_) {},
),
),
Padding(
padding: EdgeInsets.only(bottom: 24),
child: DropdownButtonFormField(
value: _list2.first,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4))),
items: _menuItemsGenerator(_list2),
onChanged: (_) {},
),
),
TextFormField(
maxLength: 30,
decoration: InputDecoration(
labelText: "Nom de l'offre",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(4))),
),
],
),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: DealsEditionPage(),
);
}
}
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 _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

how to open side menu bar in flutter?

I am new to flutter and I have created a menu button to open a side menu but however, I need some help to make it happen.
Can anyone help me implemented or guide me in my code of how to make it work. please and thank you very much!
Here is my code:
Widget _icon(IconData icon, {Color color = LightColor.iconColor}) {
return Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(13)),
color: Theme.of(context).backgroundColor,
boxShadow: AppTheme.shadow),
child: Icon(
icon,
color: color,
),
);
}
Main:
class _MainPageState extends State<MainPage> {
bool isHomePageSelected = true;
Widget _appBar() {
return Container(
padding: AppTheme.padding,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RotatedBox(
quarterTurns: 4,
child: _icon(Icons.menu, color: Colors.black54),
),
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(13)),
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
boxShadow: <BoxShadow>[
BoxShadow(
color: Color(0xfff8f8f8),
blurRadius: 10,
spreadRadius: 10),
],
),
),
)
],
),
);
}
You can copy paste run full code below
You can use GlobalKey() and call _key.currentState.openDrawer();
code snippet
GlobalKey<ScaffoldState> _key = GlobalKey();
...
child: InkWell(
onTap: () {
_key.currentState.openDrawer();
},
working demo
full code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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 _counter = 0;
GlobalKey<ScaffoldState> _key = GlobalKey();
void _incrementCounter() {
setState(() {
_counter++;
});
}
Widget _icon(IconData icon, {Color color = Colors.blue}) {
return Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(13)),
color: Theme.of(context).backgroundColor,
//boxShadow: AppTheme.shadow
),
child: InkWell(
onTap: () {
_key.currentState.openDrawer();
},
child: Icon(
icon,
color: color,
),
),
);
}
bool isHomePageSelected = true;
Widget _appBar() {
return Container(
//padding: AppTheme.padding,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
RotatedBox(
quarterTurns: 4,
child: _icon(Icons.menu, color: Colors.black54),
),
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(13)),
child: Container(
decoration: BoxDecoration(
color: Theme.of(context).backgroundColor,
boxShadow: <BoxShadow>[
BoxShadow(
color: Color(0xfff8f8f8),
blurRadius: 10,
spreadRadius: 10),
],
),
),
)
],
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _key,
appBar: AppBar(leading: _appBar()),
drawer: Drawer(
// Add a ListView to the drawer. This ensures the user can scroll
// through the options in the drawer if there isn't enough vertical
// space to fit everything.
child: ListView(
// Important: Remove any padding from the ListView.
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Item 1'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
ListTile(
title: Text('Item 2'),
onTap: () {
// Update the state of the app
// ...
// Then close the drawer
Navigator.pop(context);
},
),
],
),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
Use this code:
Scaffold.of(context).openDrawer();
Reference: https://api.flutter.dev/flutter/material/ScaffoldState/openDrawer.html
The recommended way is to call Scaffold.of(context).openDrawer();
Sample Code:
drawer: const NavBar(), // Your nav bar here
appBar: AppBar(
title: "Home".appBarText(),
leading: Builder(builder: (context) {
return IconButton(
icon: const Icon(Icons.menu),
onPressed: () {
Scaffold.of(context).openDrawer();
},
);

Set elevation under AppBar and under TabBarView

I have two tab. I want elevation bottom of Appbar and elevation bottom of TabBarView. How can I do this?
Here is my Code,
class MyOrder extends StatefulWidget {
#override
_MyOrderState createState() => _MyOrderState();
}
class _MyOrderState extends State<MyOrder> with SingleTickerProviderStateMixin{
var strTitle = Translations.globalTranslations.myOrders;
TabController _tabController;
#override
void initState() {
_tabController = new TabController(length: 2, vsync: this);
super.initState();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
elevation: 1.0,
leading: new IconButton(
icon: Image.asset('images/keyboard_backspace.png', width: 24.0, height: 24.0,),
onPressed: () => Navigator.of(context).pop(),
),
title: Text(strTitle,textAlign: TextAlign.left , style: UIUtills().getTextStyle(
fontName: AppFontName.appFontSemiBold,
fontsize: 20,
color: AppColor.redColor),),
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: AppColor.redColor),
bottom: TabBar(
indicatorColor: AppColor.redColor,
labelColor: AppColor.blackColor,
labelStyle: UIUtills().getTextStyle(
fontName: AppFontName.appFontSemiBold,
fontsize: 16,
color: AppColor.blackColor),
tabs: [
new Tab(text:Translations.globalTranslations.pastOrder),
new Tab(text: Translations.globalTranslations.upComing)
],
controller: _tabController,
indicatorSize: TabBarIndicatorSize.tab),
),
body: TabBarView(
children: [
PastOrder(),
UpComingOrder(),
],
controller: _tabController,),
);
}
}
As per my code layout looks like,
https://i.stack.imgur.com/D9BND.png
I want to design my layout like this,
https://i.stack.imgur.com/tPv8A.png
Try this one
ScreenShot https://imgur.com/Fz95DEr
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 8.0, // top bar
leading: InkWell(
onTap: () {},
child: Icon(
Icons.keyboard_arrow_left,
color: Colors.red,
),
),
backgroundColor: Colors.white,
title: Text(
"My Order",
style: TextStyle(color: Colors.red),
),
),
body: Scaffold(
body: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
elevation: 8.0, // bottom bar
bottom: PreferredSize(
child: TabBar(
labelColor: Colors.black,
indicatorColor: Colors.red,
tabs: <Widget>[
Tab(
text: "Past Order",
),
Tab(
text: "Upcoming",
),
],
),
preferredSize: Size.fromHeight(0.0),
),
backgroundColor: Colors.white,
),
body: TabBarView(
children: <Widget>[
Container(
color: Colors.white,
child: Center(
child: Text("Past Order"),
),
),
Container(
color: Colors.white,
child: Center(
child: Text("Upcoming"),
),
),
],
),
),
),
),
);
}
}