Flutter - FlatButton Fill available horizontal space - flutter

I'm trying to have a UI in such a way that the number of buttons in a row changes depending on available information. More specifically, there will always be one FlatButton that links to an external page, but if a download link is also provided, then there will be a second FlatButton in the row.
On the website that currently exists, we have this working for one button versus two buttons, but I can't get the one button to horizontally expand to fill the available space.
At the moment, I add the FlatButtons to a List<Widget> variable that I pass as the children for a row. I have tried using Flex -> Expanded, SizedBox.expand, CrossAxisAlignment.stretch and every solution I have found on this site so far to get it to expand, but every solution I have tried have all resulted in forced infinite width or unbounded width or non-zero flex but incoming width constraints are unbounded.
Here's my code in the build method as it currently stands:
List<Widget> fullTextDownloadBtns = new List();
if (this.fullArticleUrl != null && this.fullArticleUrl.isNotEmpty) {
fullTextDownloadBtns.add(
FlatButton(
color: Color(0x66629c44),
onPressed: _openFullArticle,
child: Text(
"Full Article",
style: TextStyle(color: Color(0xff629c44)),
),
)
);
}
if (this.downloadUrl != null && this.downloadUrl.isNotEmpty) {
fullTextDownloadBtns.add(
FlatButton(
color: Color(0x664d69b1),
onPressed: _download,
child: Text(
"Download",
style: TextStyle(color: Color(0xff4d69b1)),
),
)
);
}
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff0096b0)
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ...related image, title
Container(
padding: EdgeInsets.all(15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: fullTextDownloadBtns,
),
), // Read full article & download PDF
// ... Authors, excerpt/description, like/share buttons, comments
],
)
),
);

Wrapping your buttons with Expanded is the way to go here (I tried it with your code) :
Row(
children: [
Expanded(
child: FlatButton(onPressed: (){},
child: Text("1")),
),
Expanded(
child: FlatButton(onPressed: (){},
child: Text("2")),
)
],
),
By the way, since the SDK 2.2.2 (in your pubspec.yaml), you can use conditions within the children list :
children: [
if(true == true)
FlatButton(
onPressed: (){},
child: Text("1")),
],

I just wanted to add that you can adjust the width of the buttons border by using the 'width' property inside 'side: BorderSide(color: Colors.black54, width: 2.2)'.
Row(
children: <Widget>[
Expanded(
child: FlatButton(
onPressed: () {},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0),
side: BorderSide(color: Colors.black54, width: 2.2),
),
color: Colors.white,
child: (Text('BUTTON NAME')),
),
),
],
),
Couldn't find how to change the border outline width for a long while on here. So thought I might add it here. Maybe help some other noobie like me in the future.

You can use a Row widget and use two Expanded widget which their child are FlatButton.implement the condition fot them seperately sth like:
Row(
children:[
trueCondition ? Expanded(
child: FlatButton()
) : SizedBox()
]
)

Related

Adding multiple rows or column in body

Hi trying to figure out why my hamburger is getting misaligned when i add another Expanded() code within the body.
I tried to follow this url to develop a hamburger menu and responsive for all platforms at once.
Flutter Blog
Below is the code that i tried where i added Expanded() below the Row()
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
#override
Widget build(BuildContext context) {
final width = MediaQuery.of(context).size.width;
return Scaffold(
key: _scaffoldKey,
drawer: AppDrawer(),
body: Row(
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: IconButton(
icon: Icon(Icons.menu, size: 30),
onPressed: () {
_scaffoldKey.currentState.openDrawer();
}),
),
],
),
Expanded(
child: Container(
width: width,
child: Column(
children: [
Expanded(
child: Lottie.network(
'https://assets2.lottiefiles.com/datafiles/6WfDdm3ooQTEs1L/data.json'),
),
Expanded(
child: Column(
children: [
Flexible(
child: Text(
"Multivariate Testing",
style: GoogleFonts.montserrat(
fontSize: 50,
),
),
),
SizedBox(
height: 10,
),
Flexible(
child: Text(
'Run experiments to make key flows more effective.',
style: GoogleFonts.montserrat(
fontSize: 25,
),
),
),
SizedBox(
height: 35,
),
// ignore: deprecated_member_use
TextButton(
onPressed: () {},
child: Text(
'Create Experiment',
style: GoogleFonts.montserrat(
fontSize: 20,
),
),
)
],
),
),
],
),
),
)
],
),
);
}
}
and the output that i am seeing from mobile view. Appreciate any help. Sorry for too big screenshot!
This is because of the default functionality of Row.
So change your first child for your top level Row to this,
Scaffold(
key: _scaffoldKey,
drawer: AppDrawer(),
body: Row(
children: [
Align(
alignment: Alignment.topCenter,
child: Padding(
padding: const EdgeInsets.all(16),
child: IconButton(
icon: Icon(Icons.menu, size: 30),
onPressed: () {
_scaffoldKey.currentState.openDrawer();
})),
),
Expanded( ...... rest of your code
Here, we are using the Align widget with alignment: Alignment.topCenter.
Align widget takes the entire available space in the parent and then depending on the alignment property, aligns it't child inside it.
So, saying Alignment.topCenter will place it at the top vertically and middle horizontally.
Using an AppBar will unnecessarily complicate your situation since now, the AppBar is going to take up space a the top, but in your case, you want your Lottie view to be visible at the top, so it will overlap.
Because Expanded fills up the whole space and that's why your hamburger is getting misaligned.
Why don't you try using appbar for the hamburger?

Flutter - draggable text when oveflow in Row

I'm making a simple task app, which gets tasks from server api and then I am able to change their state from mobile.
I have a list of task items. Each item is made from Column, which has two rows (one is empty for now).
My question is - it is possible to make the text dragable, so i can drag the overflown text (to left) and see the rest of it (and then back to right)? I have found some solutions which used animations to move the text all the time. I just wanna control it with my finger.
Here is my simplified code:
return Container(
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(TaskDetailScreen.routeName,
arguments: task.id);
},
child: Text(
task.id + ' - ' + task.name,
overflow: TextOverflow.fade,
maxLines: 1,
softWrap: false,
style: TextStyle(fontSize: 18),
),
),
),
ButtonTheme(
buttonColor: Color(0xff24a0ed),
minWidth: 100,
child: RaisedButton(
child: Text(
'DokonĨit',
),
onPressed: () {
task.toggleActiveStatus(context);
},
),
)
],
),
Row(
children: <Widget>[],
),
],
),
padding: EdgeInsets.all(15),
color: Color(0xffcfcfcf),
);
You could try a number of solutions for this including a GestureDetector to change the Row into a Wrap widget when it finds a pan down occurring.

How to center AlertDialog FlatButton in Flutter

How can I style the FlatButton to be aligned on center without having to create a custom AlertDialog?
AlertDialog(
title: Text(
'Alert Dialog'.toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 28.0),
),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Scrollable AlertDialog' * 100),
],
),
),
actions: <Widget>[
FlatButton(
child: Text(
'Accept'.toUpperCase(),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
This is how it looks like
I tried removing 'actions' and adding the FlatButton inside a row in 'content', but the scroll stopped working and the content overflowed.
content: Column(
children: <Widget>[
SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Scrollable AlertDialog.' * 50),
],
),
),
Row(
children: <Widget>[
FlatButton(
child: Text(
'Accept'.toUpperCase(),
style: TextStyle(
color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold,
fontSize: 16.0
),
),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
],
),
Google's material design guidelines don't want you to place that in center, which is why Flutter team used ButtonBar for actions and you have no control over ButtonBar's alignment inside actions property, so if you really want to center your single button, there are 2 simple workarounds:
Make changes in source code, in dialog.dart's AlertDialog's build method, you'll see a ButtonBar, widget, add alignment to it.
ButtonBar(
alignment: MainAxisAlignment.center, // add this line
// ...
)
You can use dummy widgets like SizedBox and provide some width to it.
actions: [
SizedBox(width: space),
FlatButton(
onPressed: () {},
child: Text('Button'),
),
SizedBox(width: space),
]
Screenshot:
Try to play around with actionsPadding which is one of the property of AlertDialog.
final horizontalPadding=50;
horizontal padding is the one that is transparent to the left and right of the dialog.
actionsPadding: EdgeInsets.only(right: MediaQuery.of(context).size.width/2-horizontalPadding*2),
Also, go through How to style AlertDialog Actions in Flutter . You can change and play around within the library as mentioned here. But, this may not work for your colleagues who are sharing the git repo. They will have to update their libraries as well in their local machines.
actions: <Widget>[
Align(
alignment: Alignment.center,
child: ElevatedButton(
onPressed: () {
//your logic
Navigator.pop(context);
},
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text('Close'),
),
),
),
],
Just use actionsAlignment property in AlertDialog Widget.
AlertDialog(
actions: ...,
actionsAlignment: MainAxisAlignment.spaceBetween
)

Is there a way to align a widget to the far right of a row in Flutter?

I have a row in Flutter with two widgets. I'm trying to keep the first widget centered in the middle of the screen and the second widget forced to the far right of the screen.
I've tried using Spacer(). This results in the app returning a blank screen.
I've also tried using Expanded. This sends the second widget off the screen completely.
Trying mainAxisAlignment: MainAxisAlignment.spaceBetween did not seem to have any effect.
#override
Widget build(BuildContext context) {
return new Container(
height: MediaQuery.of(context).size.height,
child: SingleChildScrollView(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
new Container(
child: new GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(new FocusNode());
},
child: Column(
children: <Widget>[
SizedBox(height: 40.0),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Column(
children: <Widget>[
new Container(
child: Row(
mainAxisAlignment:MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(),
Container(
child: Text(
'Profile',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Lato',
color: Colors.white,
fontSize: 50.0,
fontWeight: FontWeight.w700,
),
),
),
Container(
child: IconButton(
icon: Icon(
Icons.settings,
color: Colors.white,
size: 30.0,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => OnBoarding()),
);
}),
),
]),
),
),
],
),
],
),
You can use a Row with an Expanded child that contains a Stack. Centre your text with Center and position the icon with Positioned, like so:
[...]
child: Column(
children: <Widget>[
SizedBox(height: 40.0),
Row(
children: <Widget>[
Expanded(
child: Stack(
children: [
Center(
child: Text(...),
),
),
Positioned(
right: 8,
child: IconButton(...),
[...]
Simply just add Spacer() between your main text and the Icon you want to the far right.
For example:
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {},
),
Text(
'Random test text',
style: TextStyle(color: Colors.white),
),
Spacer(),
IconButton(
icon: Icon(Icons.more_vert_rounded),
color: Colors.white,
onPressed: () {},
),
],
)
I hope this helps you. And I hope the format of the code is readable. Still getting a hang of stackoverflow comments
I did this and worked in my project
child:Row(
**crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end,**
children: [
Icon(MaterialCommunityIcons.comment_outline),
Text("0"),
Icon(Icons.favorite_border),
Text("0"),
],
),
I needed align Icons and Text at right in Row widget
Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end
children: [ // put your widget list and be happy ]
)
)
enter image description here
Use a row with this following structure:
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(),
Container(
child: Text(
'Profile',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: 'Lato',
color: Colors.white,
fontSize: 50.0,
fontWeight: FontWeight.w700,
),
),
),
Container(
child: IconButton(
icon: Icon(
Icons.settings,
color: Colors.white,
size: 30.0,
),
),
),
]
),
what will happen is that the spaceBetween property will divide available space equally between the widgets in the row, so I put an empty Container, and this will force the Text widget to be in the middle of the row and the IconButton in the far end as you desire.
I noticed in your code snippet that you have a Column with a single Row which again contains a single Column , you should eliminate this redundancy to optimize your code and make it easier to debug:
Have you tried setting the mainAxisAlignment of the row to mainAxisAlignment.center?
Imo the easiest way to do this is to create a row with 2 children: The first child is an Expanded Row with all your "main" widgets. The second child is your widget which must be aligned to the end.
Row(
children: [
Expanded(
child: Row(
children: [...mainWidgets...],
),
),
...endWidget...
],
),
Note that Expanded is space-greedy. If you use e.g. MainAxisAlignment.center for your Expanded Row, then your children are drawn across the whole avialable width. If this is not to your liking, Id suggest to wrap the Expanded-Row (not Expanded) inside a Container with "constraints: BoxConstraints(maxWidth: 500)". Obviously Expanded shouldnt be Constrained.
Achieve using Expanded & Align like below inside Row:
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
...some other widgets,
Expanded(
//Expanded will help you to cover remaining space of Row
flex: 1,
child: Align(
//Align with alignment.centerRight property will move the child to righteous inside Expanded
alignment: Alignment.centerRight,
child: const Icon(Icons.arrow_back),
),
),
],
),
Note, the Expanded has to be just inside the Row children: <Widget>[],
othewise suppose you've put the GestureDetector inside Row children: <Widget>[], and inside GestureDetector you have put your Expanded, then it won't
work.
Hope this would help many one.

how to center FloatingActionButton inside the persistentFooterButtons

Can someone explain to me how can i center the FloatingActionButton inside the persistentFooterButtons. im missing something here.
List _footer() {
return <Widget>[
new ButtonBar(
children: <Widget>[
new Container(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new FloatingActionButton(
backgroundColor: Colors.redAccent,
onPressed: () => {},
),
],
),
)
],
)
];}
===
#override Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Question"),
),
body: _body(),
persistentFooterButtons: _footer(),
); }
I looked at the code of Scaffold, below is how persistentFooterButtons created:
new Container(
decoration: new BoxDecoration(
border: new Border(
top: Divider.createBorderSide(context, width: 1.0),
),
),
child: new SafeArea(
child: new ButtonTheme.bar(
child: new SafeArea(
top: false,
child: new ButtonBar(
children: widget.persistentFooterButtons
),
),
),
),
)
You can see here, your buttons are wrapped by a ButtonBar. Now let's look at the ButtonBar code below, the DEFAULT alignment is MainAxisAlignment.end. I guess this follows the Material guidelines.
const ButtonBar({
Key key,
this.alignment: MainAxisAlignment.end,
this.mainAxisSize: MainAxisSize.max,
this.children: const <Widget>[],
}) : super(key: key);
The Flutter framework is being updated, but till today (2018 June 08th), you can not put the buttons to the center using persistentFooterButtons.
Solution: I suggest you follow my answer here to put your buttons at the center-bottom of the screen.
I found an easy solution is to wrap the FloatingActionButton in a sized box that is the same width as the screen.
persistentFooterButtons: <Widget>[
SizedBox(
width: MediaQuery.of(context).size.width,
child: FloatingActionButton(
onPressed: () {
print('Close pressed');
},
child: Text('Close'),
)
)
],
I have the same problem. I achieved the desired result with this:
persistentFooterButtons: [
Container(
width: MediaQuery.of(context).copyWith().size.width,
child: Row(
children: [
Expanded(
child: FlatButton(
child: Text('Your centered button'),
onPressed: (){},
),
)
],
),
)
]
I've used a flatbutton just as example but it works as well with floatinActionButtons.
Hope it helps
Found yet another solution. MaterialTheme (theme_data.dart) has buttonBarTheme attribute. You can modify it like following:
var myTheme = ThemeData(
buttonBarTheme: ButtonBarThemeData(
alignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
),
)
And specify it in your MaterialApp widget:
MaterialApp(theme: myTheme)
For anyone trying something similar, but instead of a FloatingActionButton, a set of, let's say two ElevatedButtons, you can center them like this:
...
persistentFooterButtons: [
Center(
child: Column(
children: [
ElevatedButton(), //Button 1
SizedBox(),
ElevatedButton(), //Button 2
],
),
),
],
...
In hope that anyone might find it useful in the future.
floatingActionButton can be aligned or positioned by making use of floatingActionButtonLocation property, however it is not useful for button placed inside persistentFooterButtons.
The persistentFooterButtons are wrapped inside ButtonBar and we don't have any way to override the ButtonBar default alignment of MainAxisAlignment.end for persistentFooterButtons.
Flutter team could have provided persistentFooterButtonsAlignment property but without it, one can achieve similar layout using following bottomNavigationBar hack, if it is not already being used for something else.
bottomNavigationBar: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Divider(
height: 0,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: FlatButton(
child: Text('Button'),
color: Theme.of(context).primaryColor,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
textColor: Theme.of(context).colorScheme.background,
onPressed: () {},
),
),
],
),