How to get the status bar height when SystemUiMode is defined to hide the status bar? - flutter

I'm overlaying my SystemUiMode, the code is below:
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
I need this SystemUiMode.
Well i have widgets within a SingleChildScrollView (a form let's say). When the keyboard shows up and my content inside the ScrollView is big enough to fill all the available space it hits the top margin of the screen. I wanted a design where my SingleChildScroview had a top padding of the same size of the status bar.
I tried:
To use SafeArea: but it doesn't work, in a first moment my widget fill the entire available space ignoring the status bar height, then it flickers between the expected layout and then goes to filled again. Below is the code:
class Test extends StatelessWidget {
const Test({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
return SafeArea(
child: Scaffold(
backgroundColor: Colors.green,
body: Center(
child: SingleChildScrollView(
child: Center(
child: Container(
width: size.width * .8,
height: size.height * .9,
color: Colors.red,
child: Center(child: TextField()),
),
),
),
),
),
);
}
}
I tried to listen to the changes of the MediaQuery and store the value of the height, but when the keyboard shows up for the first time (sometimes in a second too) it fills the entire space available.
static double topPadding = 0;
setTopPadding(double newPad) {
if (newPad > topPadding) topPadding = newPad;
}
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
setTopPadding(MediaQuery.of(context).viewPadding.top);
return Scaffold(
backgroundColor: Colors.green,
body: Center(
child: Padding(
padding: EdgeInsets.only(top: topPadding),
child: SingleChildScrollView(
child: Center(
child: Container(
width: size.width * .8,
height: size.height * .9,
color: Colors.red,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text("A"),
TextField(),
Text("B"),
TextField(),
],
)),
),
),
),
),
);
}
What's the way to get the static height of the status bar?

you can the give Colors.transparent to statusBarColor of the systemOverlayStyle
that makes the statusBar disappear
better to use CustomScrollView Widget instead of SingleChildScrollView...
CustomScrollView(
physics: const BouncingScrollPhysics(), slivers: [
SliverAppBar(
systemOverlayStyle:
const SystemUiOverlayStyle(statusBarColor: Colors.transparent ),
flexibleSpace: FlexibleSpaceBar(
centerTitle: true,
title: 'hello',
background: NetworkImage(imageUrl: networkImage),
),
),
SliverList(
delegate: SliverChildListDelegate(
[
Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(30),
topLeft: Radius.circular(30))),
padding: const EdgeInsets.symmetric(horizontal: 14.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: getScreenHeight(10)),
Text(
name,
maxLines: 1,
style: Theme.of(context).textTheme.subtitle1,
textAlign: TextAlign.start,
),]
),)
]);
),
),
},

Related

Center the trailing icon of expansion tile in Flutter

I would like to horizontally center the trailing icon of my expansionTile,
Here is my expansionTile with the trailing on the bottom right :
I already tried to encapsulate the Icon in a Align and a Container but doesn't work, I also tried Padding but it's not stable if you change the size of the screen.
Code with Align :
trailing : Align(
alignment: Alignment.center,
child: Icon(
BeoticIcons.clock,
color: BeoColors.lightGreyBlue
)
),
With Container :
trailing: Container(
alignment: Alignment.center,
child: Icon(
BeoticIcons.clock,
color: BeoColors.lightGreyBlue
)
),
Thanks for your help.
This will work for you. Use LayoutBuilder to get parent widget width, and set relative padding using constraints. For example, use constraints.maxWidth * 0.5, to center across width. Your padding will be stable if you change the size of the screen:)
trailing: LayoutBuilder(builder: (ctx, constraints) {
return Padding(
padding: EdgeInsets.only(
right: constraints.maxWidth * 0.5,
),
child: Icon(
Icons.menu,
),
);
}),
you can use column and align your icon like this way hope this code will help you, thank you
import 'package:flutter/material.dart';
class Hello extends StatelessWidget {
const Hello({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
height: 140,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Colors.deepPurple[200],
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Center(child: Text("Hello")),
Text("Hello"),
SizedBox(height: 50,),
Align(
alignment: Alignment.center,
child: Icon(Icons.lock_clock))
],
),
),
),
),
),
);
}
}
Ok, I found how to do it.
Simply put the icon in the title attribute of the ExpansionTile :
return ExpansionTile(
title: Icon(
BeoticIcons.simply_down,
color: BeoColors.lightGreyBlue,
),

Flutter: Make Buttons stretch

I having an issue with a Flutter Widget tree I am building:
I Want the Buttons on the Bottom to be bigger and fill all the available space from the text above to the bottom of the screen.
Here my current Code:
class Body extends StatelessWidget {
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return SafeArea(
child: Column(
children: [
UpperDetailsContainer(),
TitleAndPrice(),
//The Row below contains the Two Buttons
Expanded(
child: Row(
children: [
Container(
width: size.width / 2,
child: TextButton(
child: Text("Buy Now"),
style: TextButton.styleFrom(
backgroundColor: kPrimaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(50)
)
)
),
),
),
Container(
width: size.width / 2,
child: TextButton(
child: Text("Description"),
style: TextButton.styleFrom(
backgroundColor: kPrimaryColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(50)
)
)
),
),
),
],
),
)
],
),
);
}
}
I have already tried:
Making the upper widgets smaller
Adding Mainaxisaligment.spacebetween to the surrounding column
Adding Crossaxisaligment.stretch to the Row that contains the buttons
Removing SafeArea bottom / SafeArea as a whole
Setting the height for the buttons manually as an absolute value, but I don't really wanna do this for obvious reasons
What else can i do? And where does that grey bottom Stripe come from?
add crossAxisAlignment: CrossAxisAlignment.stretch to the row, so that it fills all available vertical space
note: you need the Expanded widget so that the constraint your row gets, isn't infinite
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
height: size.height * 0.7,
child: Container(
color: Colors.amber,
),
),
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_buildBuyNowButton(size),
_buildDescriptionButton(size),
],
),
)
],
),
);
}
Runnable example: https://www.dartpad.dev/4f568d8e0a334d23e7211207081356b4?null_safety=true

How to limit draggable scrollable sheet to take height according to its child height in flutter?

I am using draggableScrollableSheet. I am giving these parameters
DraggableScrollableSheet(initialChildSize: 0.4,maxChildSize: 1,minChildSize: 0.4,builder: (BuildContext context, ScrollController scrollController) {
return SingleChildScrollView(controller: scrollController,
child: Theme(
data: Theme.of(context).copyWith(canvasColor: Colors.transparent),
child: Opacity(
opacity: 1,
child: IntrinsicHeight(
child: Column(mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(height: 10,),
Container(
margin: EdgeInsets.only(right: 300),
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Colors.blue,
width: 3,
style: BorderStyle.solid),
),
),
),
Card(
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
S
.of(context)
.we_have_found_you_a_driver,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 10,
),
Text(S
.of(context)
.driver_is_heading_towards +
' ${widget.order.foodOrders.first.food.restaurant.name}')
],
),
),
],
),
elevation: 5,
),
SizedBox(height: 10,),
Card(
elevation: 5,
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
CircleAvatar(
radius: 50.0,
backgroundColor: Colors.white,
child:
Image.asset(
'assets/img/image_not_available.jpg'),
),
Expanded(
child: Column(mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
child: Text('Test',
textAlign: TextAlign.start,
style: new TextStyle(
color: Colors.black,
fontSize: 16.0,
)),
),
Icon(Icons.star, color: Colors.yellow.shade700,)
],
),
SizedBox(height: 30,),
Row(mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Expanded(
child: Container(
child: Text('Mobile number',
textAlign: TextAlign.start,
style: new TextStyle(
color: Colors.black,
fontSize: 16.0,
)),
),
),
Icon(Icons.phone,),
SizedBox(width: 10,),
Icon(Icons.message),
],
),
],
),
)
]),
),
SizedBox(height: 10,),
Card(
child: Align( alignment: Alignment(-1,1),
child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
S
.of(context)
.you_ordered_from + ' ${widget.order.foodOrders.first.food.restaurant.name}',
style: TextStyle(
color: Colors.grey,
),
),
SizedBox(
height: 5,
),
Column(children: List.generate(widget.order.foodOrders.length,(index) {
return Text(
'${widget.order.foodOrders[index].food.name}'
);
},),),
Row(
children: <Widget>[
Column(crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('See details', style: TextStyle(fontWeight: FontWeight.bold,color: Colors.blue),),
],
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
SizedBox(height: 40,),
Row(
children: <Widget>[
Icon(Icons.monetization_on),
Text(widget.order.foodOrders
.first.price
.toString()),
],
),
],
),
),
],
),
),
elevation: 5,
),
],
),
),
),
),
)
and I also used a single child scroll view and column so that I can show my cards in that column of draggableScrollableSheet. But I want draggableScrollableSheet to take height dynamically instead of defining size. Like now I want to show only 2 to 3 cards and that is taking full screen. But I want it to take the minimum height of the screen. How can we achieve this?
I was struggling with this for a while, and then discovered that the correct way to achieve this is to use ClampingScrollPhysics as the physics parameter of the scroll view.
https://api.flutter.dev/flutter/widgets/ClampingScrollPhysics-class.html
I'm a week into Flutter but I found a solution to this. It might be substandard so correct me if I'm wrong.
So what I've done is create a variable called bsRatio for the bottom sheet. This is will be the height of the child view/widget (or bottom sheet content) divide by the height of the parent/screen. This ratio should be set to the maxChildSize and probably even the initialChildSize of your DraggableScrollableSheet.
So in your parent widget or Widget State class add something like this.
class ParentWidget extends StatefulWidget {
ParentWidget({Key? key}) : super(key: key);
#override
State<ParentWidget> createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
var bsRatio = 0.4; // Set an initial ratio
#override
Widget build(BuildContext context) {
// The line below is used to get status bar height. Might not be required if you are not using the SafeArea
final statusBarHeight = MediaQuery.of(context).viewPadding.top;
// If you are not using SafeArea Widget you can skip subtracting status bar height from the Window height
final windowHeight = MediaQuery.of(context).size.height - statusBarHeight;
// This below is a callback function that will be passed to the child Widget of the DraggableScrollableSheet ->
childHeightSetter(childHeight) {
// setState rebuilds the UI with the new `bsRatio` value
setState(() {
// The new bottom sheet max height ratio is the height of the Child View/Widget divide by the screen height
bsRatio = childHeight / windowHeight;
});
}
return Scaffold(
backgroundColor: Colors.black12,
body: SafeArea(
child: Stack(
children: [
const SomeBackgroundView(),
DraggableScrollableSheet(
initialChildSize: bsRatio, // here you set the newly calculated ratio as the initial height of the Bottom Sheet
minChildSize: 0.2,
maxChildSize: bsRatio, // here you set the newly calculated ratio as the initial height of the Bottom Sheet
snap: true,
builder: (_, controller) {
return LayoutBuilder(builder: (_, box) {
// Added a container here to add some curved borders and decent looking shadows via the decoration property
return Container(
child: SingleChildScrollView(
controller: controller,
// The child view/widget `MyBottomSheet` below is the actual bottom sheet view/widget
child: MyBottomSheet(childHeightSetter: childHeightSetter),
),
decoration: const BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.grey,
blurRadius: 5.0,
spreadRadius: 2.0
)
],
borderRadius: BorderRadius.all(Radius.circular(20.0))
),
);
});
},
),
],
),
),
);
}
}
And this would be your child view/widget (also your BottomSheet view/widget)
class MyBottomSheet extends StatefulWidget {
// This below is the local callback variable. The `?` is because it may not be set if not required
final ValueSetter<double>? childHeightSetter;
const MyBottomSheet({Key? key, this.childHeightSetter}) : super(key: key);
#override
_MyBottomSheetState createState() => _MyBottomSheetState();
}
class _LoginBottomSheetState extends State<LoginBottomSheet> {
// bsKey is the key used to reference the Child widget we are trying to calculate the height of. Check the `Card` container below
GlobalKey bsKey = GlobalKey();
// this method will me used to get the height of the child content and passed to the callback function so it can be triggered and the ratio can be calculated and set in the parent widget
_getSizes() {
final RenderBox? renderBoxRed =
bsKey.currentContext?.findRenderObject() as RenderBox?;
final cardHeight = renderBoxRed?.size.height;
if (cardHeight != null)
super.widget.childHeightSetter?.call(cardHeight);
}
// This is the function to be called after the Child has been drawn
_afterLayout(_) {
_getSizes();
}
#override
void initState() {
super.initState();
// On initialising state pass the _afterLayout method as a callback to trigger after the child Widget is drawn
WidgetsBinding.instance?.addPostFrameCallback(_afterLayout);
}
#override
Widget build(BuildContext context) {
return Card(
key: bsKey, // This is the key mentioned above used to calculate it's height
color: Colors.white,
shadowColor: Colors.black,
elevation: 40.0,
margin: EdgeInsets.zero,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.0), topRight: Radius.circular(20.0))),
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
// Random children for bottom sheet content
const SizedBox(height: 10.0),
Center(
child: Container(
child: const SizedBox(width: 40.0, height: 5.0),
decoration: BoxDecoration(
color: Colors.grey[400],
borderRadius: BorderRadius.circular(5.0)
),
),
),
const SizedBox(height: 10.0),
const AnotherBottomSheetContentView()
],
),
);
}
}
the initialChildSize is the height of your ScrollView before its actually scrolled, so that means you can actually decide what it would look like.
here is an example![the draggable scrollsheet here has initialChildSize: 0.1,maxChildSize: 1,minChildSize: 0.1,
]1

Flutter TabBar and TabBarView inside body of the application

I was trying to build a UI for my application like this. But views of tabs are not visible. I've used tabs in many flutter applications but the UI has to exactly like below
Appbar with image as background
Half portion of user image in appbar section and rest below it
A tabbar below these.
.
.
.
My code here
class _MyHomePageState extends State<MyHomePage> with
TickerProviderStateMixin{
double screenSize;
double screenRatio;
AppBar appBar;
List<Tab> tabList = List();
TabController _tabController;
#override
void initState() {
tabList.add(new Tab(text:'Overview',));
tabList.add(new Tab(text:'Workouts',));
_tabController = new TabController(vsync: this, length:
tabList.length);
super.initState();
}
#override
void dispose() {
_tabController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
screenSize = MediaQuery.of(context).size.width;
appBar = AppBar(
backgroundColor: Colors.transparent,
elevation: 0.0,
);
return Container(
color: Colors.white,
child: Stack(
children: <Widget>[
new Container(
height: 300,
width: screenSize,
decoration:new BoxDecoration(
image: new DecorationImage(
image: new AssetImage("images/app_image.jpg"),
fit: BoxFit.cover,
),
),
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: appBar,
body:
Stack(
children: <Widget>[
new Positioned(
child: Column(
children: <Widget>[
Center(
child: Container(
child: CircleAvatar(
backgroundImage:
NetworkImage('http://res.cloudinary.com/'),
backgroundColor: Colors.green,
radius: 20,
),
),
),
SingleChildScrollView(
child: Container(
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text('* * * * *',textAlign: TextAlign.center,style: TextStyle(fontSize: 18.0,color: Colors.pink),),
new Text('CAPTAIN',textAlign: TextAlign.center,style: TextStyle(fontSize: 18.0)),
],
crossAxisAlignment: CrossAxisAlignment.center,
),
),
),
],
),
width: screenSize,
top: 170,
),
new Positioned(
width: screenSize,
top: 310,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: new Column(
children: <Widget>[
new Container(
decoration: new BoxDecoration(color: Theme.of(context).primaryColor),
child: new TabBar(
controller: _tabController,
indicatorColor: Colors.pink,
indicatorSize: TabBarIndicatorSize.tab,
tabs: tabList
),
),
new Container(
height: 20.0,
child: new TabBarView(
controller: _tabController,
children: tabList.map((Tab tab){
_getPage(tab);
}).toList(),
),
)
],
),
),
)
],
),
),
],
),
);
}
Widget _getPage(Tab tab){
switch(tab.text){
case 'Overview': return OverView();
case 'Orders': return Workouts();
}
}
}
tabList.map((Tab tab){
_getPage(tab);
}).toList()
The piece above is from your provided code, you called _getPage(tab) in the map without a return statement. Simply make a slight change to this
tabList.map((Tab tab){
return _getPage(tab);
}).toList()
Or
tabList.map((Tab tab) => _getPage(tab)).toList()
children: tabList.map((Tab tab){
_getPage(tab);
}).toList(),
Some how this above your logic will getting null children for TabBarView, So views of tabs are not visible, need to check for it.
OtherWise you can assign children of TabBarView manualy
children: <Widget>[
OverView(),
Workouts(),
],

How to remove Padding from DrawerHeader

Here's my DrawerHeader :
class MyDrawerHeader extends StatefulWidget {
#override
_MyDrawerHeaderState createState() => _MyDrawerHeaderState();
}
class _MyDrawerHeaderState extends State<MyDrawerHeader> {
#override
Widget build(BuildContext context) {
return DrawerHeader(
padding: EdgeInsets.all(0),
margin: EdgeInsets.all(0),
child: Center(child: Text('Header', style: Theme.of(context).textTheme.headline))
);
}
}
As you can see I made the Padding and Margin from the DrawerHeader be 0, but this is how my Header is being shown:
It's just too big and I can't make it smaller. I have no idea why its being rendered this way, I looked into DrawerHeader source code and I can't see anything in there overriding my Padding or Margin.
Just to be sure the problem is in DrawerHeader, this is what Happens when I substitute it for a Container:
It works as it should!
Am I missing something, or is this a bug in Flutter?
drawer: Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: [
DrawerHeader(
padding: EdgeInsets.all(0.0),
child: Container(
color: Theme.of(context).primaryColor,
),
),
ListTile(
title: Text("Home"),
)
],
),
),
There is always padding on DrawerHeader. If you look in sources:
#override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
assert(debugCheckHasMediaQuery(context));
final ThemeData theme = Theme.of(context);
final double statusBarHeight = MediaQuery.of(context).padding.top;
return Container(
height: statusBarHeight + _kDrawerHeaderHeight,
margin: margin,
decoration: BoxDecoration(
border: Border(
bottom: Divider.createBorderSide(context),
),
),
child: AnimatedContainer(
padding: padding.add(EdgeInsets.only(top: statusBarHeight)),
decoration: decoration,
duration: duration,
curve: curve,
child: child == null ? null : DefaultTextStyle(
style: theme.textTheme.body2,
child: MediaQuery.removePadding(
context: context,
removeTop: true,
child: child,
),
),
),
);
}
You can customize this code:
height: statusBarHeight + _kDrawerHeaderHeight - here is total height of header
padding: padding.add(EdgeInsets.only(top: statusBarHeight)) - here is padding of child element in DrawerHeader
Try replacing your drawer by the code below
drawer: Drawer(
child: DrawerHeader(
child: ListView(
children: <Widget>[
Container(
alignment: Alignment.topLeft,
child: Text('Header', style: Theme.of(context).textTheme.headline),
),
],
),
),
),