Remove Padding or Margin from Drawer Header in Flutter App - navigation-drawer

How do I remove the padding or margin from my Drawer Header in this example below.
I've set margin and padding to EdgeInsets.zero for both but this is not doing the job.
Menu Screen Example Image
Here is the code that produced this menu. Everything works. I simply can't remove the padding from the header specifically. The blue field should reach all the way to the edges on the top and sides.
import "package:flutter/material.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: 'My Menu App',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
drawer: AppDrawer(mainMenu),
appBar: AppBar(
title: Text("My Menu App"),
),
);
}
}
class AppDrawer extends StatelessWidget {
List menuChoices;
AppDrawer(this.menuChoices);
#override
Widget build(BuildContext context) {
return Drawer(
child: ListView.builder(
padding: EdgeInsets.zero,
itemCount: menuChoices.length,
itemBuilder: (BuildContext cntxt, int index) {
return _constructItem(menuChoices[index]);
},
),
);
}
Widget _constructHeader(Choices choice) {
return DrawerHeader(
margin: EdgeInsets.zero,
padding: EdgeInsets.zero,
child: Container(
child: Stack(
children: <Widget>[
Positioned(
bottom: 12.0,
left: 16.0,
child: Text(
choice.title,
style: TextStyle(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w500),
),
),
],
),
),
decoration: BoxDecoration(
color: Colors.blue,
),
);
}
Widget _constructItem(Choices choice) {
switch (choice.itemType) {
case "Header":
return DrawerHeader(child: _constructHeader(choice));
break;
case "Item":
return ListTile(
leading: Icon(choice.icon),
title: Opacity(
opacity: choice.enabled ? 1 : 0.5,
child: Text(choice.title),
),
onTap: choice.action,
enabled: choice.enabled);
break;
case "Divider":
return Divider(
thickness: 2.0,
);
break;
}
}
}
class Choices {
const Choices(
{#required this.title,
#required this.itemType,
this.icon,
this.enabled = true,
this.action});
final String itemType;
final String title;
final IconData icon;
final bool enabled;
final Function action;
}
// These are the menu choices
const List<Choices> mainMenu = const <Choices>[
const Choices(
itemType: "Header",
title: "My Header Text",
icon: Icons.face,
),
const Choices(
itemType: "Item",
title: 'My Profile',
icon: Icons.person,
enabled: true,
action: null,
),
const Choices(
itemType: "Divider",
),
const Choices(
itemType: "Item",
title: 'About',
icon: Icons.info,
enabled: true,
action: null,
),
const Choices(
itemType: "Divider",
),
const Choices(
itemType: "Item",
title: 'Help',
icon: Icons.help_outline,
enabled: true,
action: null,
),
];

Widget _constructItem(Choices choice) {
switch (choice.itemType) {
case "Header":
return DrawerHeader(padding: EdgeInsets.zero ,child: _constructHeader(choice));
break;
case "Item":
return ListTile(
leading: Icon(choice.icon),
title: Opacity(
opacity: choice.enabled ? 1 : 0.5,
child: Text(choice.title),
),
onTap: choice.action,
enabled: choice.enabled);
break;
case "Divider":
return Divider(
thickness: 2.0,
);
break;
}
}

DrawerHeader has been called both in the switch statement and in the _constructHeaderMethod. Simply calling the _constructHeaderMethod is all that is needed. Essentially I had a DrawerHeader as a child of a DrawerHeader which was unnecessary.
Changing the _constructItem method as below solves the problem.
Widget _constructItem(Choices choice) {
switch (choice.itemType) {
case "Header":
return _constructHeader(choice);
break;
case "Item":
return ListTile(
leading: Icon(choice.icon),
title: Opacity(
opacity: choice.enabled ? 1 : 0.5,
child: Text(choice.title),
),
onTap: choice.action,
enabled: choice.enabled);
break;
case "Divider":
return Divider(
thickness: 2.0,
);
break;
}
}
}

Related

Why isn't the image changing using the Provider Package?

I'm working with the Provider Package on Flutter but can't work out why it's not changing the background image when I call mymodel.image. It should access the MyModal class and change the existing image: Image.asset('images/background_image.jpeg', fit: BoxFit.fill) with the one in the SmallImage screen.
mymodel.image = Image.asset('images/hello_image.png', fit: BoxFit.fill);
Which replaces the background image on the HomePage.
HomePage Screen
import 'package:flutter/material.dart';
import 'package:flutter_app_background/small_images.dart';
import 'package:flutter/cupertino.dart';
import 'package:provider/provider.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MyModel>(
create: (context) => MyModel(),
child: MaterialApp(
title: 'Title',
home: HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
extendBodyBehindAppBar: true,
appBar: AppBar(
title: Text('Background Image', style: TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
iconTheme: IconThemeData(color: Colors.white),
actions: <Widget>[
IconButton(
icon: Icon(Icons.settings, color: Colors.black,),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SmallImages()),
);
},
),
],
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Stack(
children: <Widget>
[
Positioned.fill(
child: GestureDetector(
child: Consumer<MyModel>(
builder: (context, myModel, child) {
return myModel.image = Image.asset('images/background_image.jpeg', fit: BoxFit.fill);
},
),
),
),
],
),
);
}
}
class MyModel extends ChangeNotifier {
Image _image;
set image(Image value) {
_image = value;
notifyListeners();
}
Image get image => _image;
}
SmallImage Screen
import 'package:flutter/material.dart';
import 'package:flutter_app_background/main.dart';
import 'package:provider/provider.dart';
class SmallImages extends StatefulWidget {
static int tappedGestureDetector = 1;
#override
_SmallImagesState createState() => _SmallImagesState();
}
class _SmallImagesState extends State<SmallImages> {
List<bool> isSelected;
void initState() {
isSelected = [true, false, false, false, false, false, false, false, false];
super.initState();
}
#override
Widget build(BuildContext context) {
final mymodel = Provider.of<MyModel>(context,listen:false); //default for listen is `true`
return Scaffold(
appBar: AppBar(
title: Text('Small Image', style: TextStyle(
color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold),
),
iconTheme: IconThemeData(color: Colors.white),
actions: <Widget>[
IconButton(
icon: Icon(Icons.arrow_left, color: Colors.black,),
onPressed: () {
Navigator.pop(
context,
MaterialPageRoute(builder: (context) => HomePage()),
);
},
),
],
backgroundColor: Colors.transparent,
elevation: 0.0,
),
body: Material(
child: GestureDetector(
child: MaterialApp(
builder: (context, snapshot) {
return GridView.count(
crossAxisCount: 1,
childAspectRatio: 1.0,
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 0.0,
crossAxisSpacing: 0.0,
children: [
GridView(
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3,
childAspectRatio: MediaQuery
.of(context)
.size
.width /
(MediaQuery
.of(context)
.size
.height / 2),
),
children: [
GestureDetector(
onTap: () {
// return myValue;
setState(() {
SmallImages.tappedGestureDetector = 1;
});
return mymodel.image = Image.asset('images/hello_image.png', fit: BoxFit.fill);
print('hi');
},
child: Container(
height: 100,
width: 107,
decoration: BoxDecoration(border: SmallImages
.tappedGestureDetector == 1
? Border.all(
color: Color(0xff2244C7), width: 1.0)
: Border
.all(color: Colors.transparent,),),
child: Image.asset(
'images/nightsky_image.png',
),
),
),
Consumer<MyModel>(
builder: (context, myModel, child) {
return GestureDetector(
onTap: () {
setState(() {
SmallImages.tappedGestureDetector = 2;
}); // <-- replaced 'tapped' and 'other'
},
child: Container(
height: 100,
width: 107,
decoration: BoxDecoration(border: SmallImages
.tappedGestureDetector == 2
? Border.all(
color: Color(0xff2244C7), width: 1.0)
: Border
.all(color: Colors.transparent,),),
child: Image.asset(
'images/own_image.png',
),
),
);
},
),
Consumer<MyModel>(
builder: (context, myModel, child) {
return GestureDetector(
onTap: () {
setState(() {
SmallImages.tappedGestureDetector = 3;
}); // <-- replaced 'tapped' and 'other'
},
child: Container(
height: 100,
width: 107,
decoration: BoxDecoration(border: SmallImages
.tappedGestureDetector == 3
? Border.all(
color: Color(0xff2244C7), width: 1.0)
: Border
.all(color: Colors.transparent,),),
child: Image.asset(
'images/iceland_image.png',
),
),
);
},
),
].toList(),
),
],
);
}),
),
),
);
}
}
You have to call notifyListeners in your model when the image has changed otherwise the changenotifierprovider will not know that it needs to rebuild.
One way of doing the would be to wrap the image field with a getter and setter and call notifyListeners in the setter after updating the underlying field.
var Image _image;
set image(Image value) {
_image = value;
notifyListeners();
}
Image get image => _image;

Flutter dropdown, select is disabled on validation error

Validation is working well but incase of validation error, option to select on option is disabled.
DropdownButtonFormField(
isExpanded: true,
hint: Text('Gender'),
value: _selectedGender,
onChanged: (newValue) {
setState(() {
_selectedGender = newValue;
});
},
items: _gender.map((gender) {
return DropdownMenuItem(
child: new Text(gender),
value: gender,
);
}).toList(),
validator: (value) {
if (value == null)
return "Please select your gender";
return null;
},
),
Above code is in a page view,
my variables
List<String> _gender = ['Male', 'Female'];
String _selectedGender;
My entire Form code : just reduced to one field its very long
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final List<GlobalKey<FormState>> _page = [
GlobalKey<FormState>(),
GlobalKey<FormState>(),
GlobalKey<FormState>(),
];
final _key = GlobalKey<ScaffoldState>();
List<String> _gender = ['Male', 'Female'];
String _selectedGender;
void changePage() {
if (currentPageValue < 3) {
if (_page[currentPageValue].currentState.validate()) {
setState(() {
currentPageValue += 1;
});
}
}
}
#override
Widget build(BuildContext context) {
var deviceSize = MediaQuery.of(context).size;
var deviceWidth = deviceSize.width;
return Scaffold(
key: _key,
backgroundColor: _backgroundColor,
appBar: AppBar(
backgroundColor: _backgroundColor,
leading: IconButton(
icon: Icon(
currentPageValue == 0 ? Icons.close : Icons.keyboard_backspace,
size: 20.0,
color: _headerColor,
),
onPressed: currentPageValue == 0
? () => Navigator.pop(context)
: () => back()),
centerTitle: true,
elevation: 0.0,
),
body: Form(
key: _page[0],
child: Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: deviceWidth * 0.9,
height: dropDownHeight,
child: ButtonTheme(
child: DropdownButtonFormField(
isExpanded: true,
hint: Text('Gender'),
value: _selectedGender,
onChanged: (newValue) {
setState(() {
_selectedGender = newValue;
});
},
items: _gender.map((gender) {
return DropdownMenuItem(
child: new Text(gender),
value: gender,
);
}).toList(),
validator: (value) {
if (value == null) return "Please select your gender";
return null;
},
),
),
),
RaisedButton(
color: buttonColor,
shape: RoundedRectangleBorder(
borderRadius:
BorderRadius.circular(10.0),
),
child: Text(
'Next',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w400,
),
),
onPressed: () => changePage(),
),
],
),
),
),
);
Looking at your code, I strongly recommend you create 3 different Forms and validate them separately, so you don't have any problem regarding form state. To achieve this, you can just wrap the fields into their respective Form and be sure not to mix the forms nor have them one inside the other.
Below, an example based on your code and on what I have said:
class SignUp extends StatefulWidget {
#override
_SignUpState createState() => _SignUpState();
}
class _SignUpState extends State<SignUp> {
final _page1 = GlobalKey<FormState>();
final _page2 = GlobalKey<FormState>();
final _page3 = GlobalKey<FormState>();
final _key = GlobalKey<ScaffoldState>();
int currentPageValue;
List<String> _gender = ['Male', 'Female'];
String _selectedGender;
void changePage(GlobalKey<FormState> page) {
if (currentPageValue < 3) {
if (page.currentState.validate()) {
setState(() {
currentPageValue += 1;
});
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
key: _key,
body: ListView(
children: <Widget>[
Form(
key: _page1,
child: Column(
children: [
DropdownButtonFormField(
isExpanded: true,
hint: Text('Gender'),
value: _selectedGender,
onChanged: (newValue) {
setState(() {
_selectedGender = newValue;
});
},
items: _gender.map((gender) {
return DropdownMenuItem(
child: new Text(gender),
value: gender,
);
}).toList(),
validator: (value) {
if (value == null) return "Please select your gender";
return null;
},
),
RaisedButton(
child: Text('Next'),
onPressed: () => changePage(_page1),
),
],
),
),
Form(
key: _page2,
child: Column(
children: [
// SomeField(
//
// ),
// SomeOtherField(
//
// ),
RaisedButton(
child: Text('Next'),
onPressed: () => changePage(_page2),
),
],
),
),
],
),
);
}
}

Flutter Radio Buttons validation

I am implementing a custom radio button with validation and values are passed in those buttons. There is a run time error which i am not able to figure out. I am getting the following error
The following assertion was thrown during performLayout():
I/flutter (10799): An InputDecorator, which is typically created by a TextField, cannot have an unbounded width.
I/flutter (10799): This happens when the parent widget does not provide a finite width constraint. For example, if the
I/flutter (10799): InputDecorator is contained by a Row, then its width must be constrained. An Expanded widget or a
I/flutter (10799): SizedBox can be used to constrain the width of the InputDecorator or the TextField that contains it.
I/flutter (10799): 'package:flutter/src/material/input_decorator.dart':
I/flutter (10799): Failed assertion: line 945 pos 7: 'layoutConstraints.maxWidth < double.infinity'
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter FormBuilder Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
inputDecorationTheme: InputDecorationTheme(
labelStyle: TextStyle(color: Colors.purple),
),
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
#override
MyHomePageState createState() {
return MyHomePageState();
}
}
class MyHomePageState extends State<MyHomePage> {
var data;
bool autoValidate = true;
bool readOnly = false;
bool showSegmentedControl = true;
final GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();
final GlobalKey<FormFieldState> _specifyTextFieldKey =
GlobalKey<FormFieldState>();
ValueChanged _onChanged = (val) => print(val);
// var genderOptions = ['Male', 'Female', 'Other'];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FormBuilder Example"),
),
body: Padding(
padding: EdgeInsets.all(10),
child: SingleChildScrollView(
child: Row(
children: <Widget>[
FormBuilder(
// context,
key: _fbKey,
autovalidate: true,
//initialValue: {
// 'movie_rating': 5,
// },
readOnly: false,
child: Row(
children: <Widget>[
FormBuilderRadio(
decoration:
InputDecoration(labelText: 'My chosen language'),
attribute: "best_language",
leadingInput: true,
onChanged: _onChanged,
validators: [FormBuilderValidators.required()],
options:
["Delete", "Approve", "Revert"]
.map((lang) => FormBuilderFieldOption(
value: lang,
child: Text('$lang'),
))
.toList(growable: false),
),
],
),
),
Row(
children: <Widget>[
Expanded(
child: MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
"Submit",
style: TextStyle(color: Colors.white),
),
onPressed: () {
if (_fbKey.currentState.saveAndValidate()) {
print(_fbKey.currentState.value);
} else {
print(_fbKey.currentState.value);
print("validation failed");
}
},
),
),
SizedBox(
width: 20,
),
Expanded(
child: MaterialButton(
color: Theme.of(context).accentColor,
child: Text(
"Reset",
style: TextStyle(color: Colors.white),
),
onPressed: () {
_fbKey.currentState.reset();
},
),
),
],
),
],
),
),
),
);
}
}
void changeIndex() {
setState(() {
selectedIndex = 1;
print("Value passed is delete");
});
}
void changeIndex1() {
setState(() {
selectedIndex = 1;
print("Value passed is a");
});
}
void changeIndex2() {
setState(() {
selectedIndex = 1;
print("Value passed is r");
});
}
Widget customRadio1() => OutlineButton(
onPressed: () => changeIndex(),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
borderSide: BorderSide(
color: selectedIndex == 0 ? Colors.red : Colors.grey),
child: Text(lst[0], style: TextStyle(
color: selectedIndex == 0 ? Colors.red : Colors.grey),),
);
Widget customRadio2() => OutlineButton(
onPressed: () => changeIndex1(),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
borderSide: BorderSide(
color: selectedIndex == 1 ? Colors.green : Colors.grey),
child: Text(lst[1], style: TextStyle(
color: selectedIndex == 1 ? Colors.green : Colors.grey),),
);
Widget customRadio3() {
return OutlineButton(
onPressed: () => changeIndex2(),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
borderSide: BorderSide(
color: selectedIndex == 2 ? Colors.cyan : Colors.grey),
child: Text(lst[2], style: TextStyle(
color: selectedIndex == 2 ? Colors.cyan : Colors.grey),),
);
}
}
An InputDecorator cannot have an unbounded width as mentioned in the logs. The cause of this is that the InputDecorator is in a Scrollable Row and has an undefined width. To solve this issue, you can wrap the child widgets in the Row with a Container with a width configured.

how to custom Tab Bar ? Flutter

I would like to customize my TabBar.
Right now I have this TabBar (stock UI) :
and I would like to have this UI :
I already coded the personalized tab but I don't know how to implement it.
There is my current code about my HomePage :
class HomePage extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
super.initState();
_tabController =
TabController(length: 6, vsync: this); // initialise it here
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: _tabController,
isScrollable: true,
tabs: [
Tab(text: "NewPay1.1"),
Tab(text: "NewMall 1.0"),
Tab(text: "海报"),
Tab(text: "企业版"),
Tab(text: "个版"),
Tab(text: "poa"),
],
),
title: Text('tabBar'),
),
body: TabBarView(
controller: _tabController,
children: [
// these are your pages
TaskListPage(),
TestPage(),
],
),
bottomNavigationBar: BottomAppBar(
color: Colors.white,
shape: CircularNotchedRectangle(),
child: Row(
children: <Widget>[
IconButton(
onPressed: () => _tabController.animateTo(0),
icon: Icon(Icons.home),
),
SizedBox(),
IconButton(
onPressed: () => _tabController.animateTo(1),
icon: Icon(Icons.more))
],
mainAxisAlignment: MainAxisAlignment.spaceAround,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
return TestPage().createState();
},
child: Icon(Icons.add),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
),
);
}
}
then my CustomTab class :
class CustomTab extends StatefulWidget {
final Function(int) tabSelected;
final List<String> items;
const CustomTab({Key key, this.tabSelected, this.items}) : super(key: key);
#override
_CustomTabState createState() => _CustomTabState();
}
class _CustomTabState extends State<CustomTab> {
var categorySelected = 0;
#override
Widget build(BuildContext context) {
return _getListCategory();
}
Widget _getListCategory(){
ListView listCategory = new ListView.builder(
itemCount: widget.items.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index){
return _buildCategoryItem(index);
}
);
return new Container(
height: 50.0,
child: listCategory,
color: Colors.grey[200].withAlpha(200),
);
}
Widget _buildCategoryItem(index){
return new InkWell(
onTap: (){
setSelectedItem(index);
print("click");
},
child: new Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Container(
margin: new EdgeInsets.only(left: 10.0),
child: new Material(
elevation: 2.0,
color: categorySelected == index ? Colors.black : Colors.grey,
borderRadius: const BorderRadius.all(const Radius.circular(25.0)),
child: new Container(
padding: new EdgeInsets.only(left: 12.0,top: 7.0,bottom: 7.0,right: 12.0),
child: new Text(widget.items[index],
style: new TextStyle(
color: categorySelected == index ? Colors.white : Colors.black),
),
),
),
)
],
),
);
}
void setSelectedItem(index) {
if(index != categorySelected) {
widget.tabSelected(index);
setState(() {
categorySelected = index;
});
}
}
}
There is already a plugin for this styled tabbar.
https://pub.dartlang.org/packages/bubble_tab_indicator
I hope this is what you are looking for :)
Yours Glup3
Try this code it is very simple
first initialize this
var radius = Radius.circular(150);
Then
class _Class_Name extends State<ClassName> {
var radius = Radius.circular(150);
#override
Widget build(BuildContext context) {
length: 2,
child: Scaffold(
appBar: AppBar(
elevation: 0,
backgroundColor: Colors.white,
centerTitle: true,
leading: // if you need
),
title:
// if you need
// Scrollable rounded Tab bar
body: TabBar(
isScrollable: true,
labelColor: Colors.black,
tabs: <Widget>[
Tab(
text: "Tab 1",
),
Tab(
text: "Tab 2",
),
],
indicator: ShapeDecoration(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(radius)),
color: HexColor('#005866')),
),
Container(
height: 80,
child: TabBarView(
children: <Widget>[
Container(
child: Center(
child: Text("Hello"),
),
),
Container(
child: Center(
child: Text("Hi"),
),
),
),
],
),
),
);
}

Flutter: hide and display app bar in scrolling detected

I'm having trouble with app bar animation, I'm using SilverAppBar, in my app. So, the problem is when I'm in the middle of my list and I scroll up, the app bar does not appear, but it appears just when scrolling reaches the top of the items list. I already tested the snap parameter and give it true, but not the result I expect. I have ideas about creating a custom animation for this, but I'm not too experienced in Flutter, and also if there is a way to add parameters, or another widget that will work for my situation, it would be great.
The actual code of the demo I'm using:
Widget _search() => Container(
color: Colors.grey[400],
child: SafeArea(
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
enabled: false,
style: TextStyle(fontSize: 16, color: Colors.white),
decoration: InputDecoration(
prefix: SizedBox(width: 12),
hintText: "Search",
contentPadding:
EdgeInsets.symmetric(horizontal: 32.0, vertical: 14.0),
border: InputBorder.none,
),
),
),
)),
);
Container _buildBody() {
return Container(
child: new GridView.count(
crossAxisCount: 2,
children: List.generate(100, (index) {
return Center(
child: Text(
'Item $index',
style: Theme.of(context).textTheme.headline,
),
);
}),
));
}
#override
Widget build(BuildContext context) {
return new Scaffold(
resizeToAvoidBottomPadding: false,
body: new NestedScrollView(
headerSliverBuilder:
(BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
new SliverAppBar(
title: Text("Demo",
style: TextStyle(
color: Colors.white,
)),
pinned: false,
floating: true,
forceElevated: innerBoxIsScrolled,
),
];
},
body: new Column(children: <Widget>[
_search(),
new Expanded(child: _buildBody())
])));
}
The result I have now:
Image 1
The result I got after giving true to the snap parameter:
Image 2
Plenty of applications like WhatsApp, Facebook, LinkedIn ... have this animating app bar. To explain more what exactly I expect with this animating app bar, I added an example of Google Play Store, showing the wanted animation: Play Store example
I had a similar issue with CustomScrollView and SliverAppbar using refresh indicator i ended up creating my own custom appbar.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
class HomeView extends StatefulWidget {
#override
HomeState createState() => HomeState();
}
class HomeState extends State<HomeView> with SingleTickerProviderStateMixin {
bool _isAppbar = true;
ScrollController _scrollController = new ScrollController();
#override
void initState() {
super.initState();
_scrollController.addListener(() {
if (_scrollController.position.userScrollDirection ==
ScrollDirection.reverse) {
appBarStatus(false);
}
if (_scrollController.position.userScrollDirection ==
ScrollDirection.forward) {
appBarStatus(true);
}
});
}
void appBarStatus(bool status) {
setState(() {
_isAppbar = status;
});
}
#override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(kToolbarHeight),
child: AnimatedContainer(
height: _isAppbar ? 55.0 : 0.0,
duration: Duration(milliseconds: 200),
child: CustomAppBar(),
),
),
body: ListView.builder(
controller: _scrollController,
itemCount: 20,
itemBuilder: (BuildContext context, int index) {
return container();
},
),
),
);
}
}
Widget container() {
return Container(
height: 80.0,
color: Colors.pink,
margin: EdgeInsets.all(8.0),
width: 100,
child: Center(
child: Text(
'Container',
style: TextStyle(
fontSize: 18.0,
),
)),
);
}
class CustomAppBar extends StatefulWidget {
#override
AppBarView createState() => new AppBarView();
}
class AppBarView extends State<CustomAppBar> {
#override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.white,
leading: InkWell(
onTap: () => {},
child: new Padding(
padding: const EdgeInsets.all(8.0),
child: CircleAvatar(
backgroundColor: Colors.white,
child: ClipOval(
child: Image.network(
'https://images.squarespace-cdn.com/content/5aee389b3c3a531e6245ae76/1530965251082-9L40PL9QH6PATNQ93LUK/linkedinPortraits_DwayneBrown08.jpg?format=1000w&content-type=image%2Fjpeg'),
),
),
),
),
actions: <Widget>[
IconButton(
alignment: Alignment.centerLeft,
icon: Icon(
Icons.search,
color: Colors.black,
),
onPressed: () {},
),
],
title: Container(
alignment: Alignment.centerLeft,
child: Text("Custom Appbar", style: TextStyle(color: Colors.black),)
),
);
}
}
To get this functionality to work, you will need to use the CustomScrollView widget instead of NestedScrollView. Google Documentation
Here is a working example:
class MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: <Widget>[
const SliverAppBar(
pinned: false,
snap: false,
floating: true,
flexibleSpace: FlexibleSpaceBar(
title: Text('Demo'),
),
),
SliverGrid(
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200.0,
mainAxisSpacing: 10.0,
crossAxisSpacing: 10.0,
childAspectRatio: 4.0,
),
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Container(
alignment: Alignment.center,
color: Colors.teal[100 * (index % 9)],
child: Text('grid item $index'),
);
},
childCount: 50,
),
),
],
)
);
}
}
Example of this running here
I was able to make the floating Appbar with Tabbar similar to that of WhatsApp by using SliverAppbar with NestedScrollView. Do remember to add floatHeaderSlivers: true, in NestedScrollView. Link to sample code
import 'dart:math';
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,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: CustomSliverAppbar(),
);
}
}
class CustomSliverAppbar extends StatefulWidget {
#override
_CustomSliverAppbarState createState() => _CustomSliverAppbarState();
}
class _CustomSliverAppbarState extends State<CustomSliverAppbar>
with SingleTickerProviderStateMixin {
TabController _tabController;
#override
void initState() {
_tabController = TabController(
initialIndex: 0,
length: 2,
vsync: this,
);
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: NestedScrollView(
floatHeaderSlivers: true,
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
title: Text(
"WhatsApp type sliver appbar",
),
centerTitle: true,
pinned: true,
floating: true,
bottom: TabBar(
indicatorColor: Colors.black,
labelPadding: const EdgeInsets.only(
bottom: 16,
),
controller: _tabController,
tabs: [
Text("TAB A"),
Text("TAB B"),
]),
),
];
},
body: TabBarView(
controller: _tabController,
children: [
TabA(),
const Center(
child: Text('Display Tab 2',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
),
],
),
),
);
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
}
class TabA extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scrollbar(
child: ListView.separated(
separatorBuilder: (context, child) => Divider(
height: 1,
),
padding: EdgeInsets.all(0.0),
itemCount: 30,
itemBuilder: (context, i) {
return Container(
height: 100,
width: double.infinity,
color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
);
},
),
);
}
}

Resources