Flutter Change height of an OutlineButton inside an AppBar? - button

Just wondering how I would change the height of an OutlineButton? I suppose this would likely apply to other button types as well.
return Scaffold(
appBar: AppBar(
title: Text('Test'),
actions: <Widget> [
SizedBox(
width: 100.0,
height: 8.0,
child: OutlineButton(
borderSide: BorderSide(width: 4.0)
child: Text('Hi'),
onPressed: (){},
),
),
],
),
body: Container(),
);
I am finding the button just about 8px too high for my case, and want to squish it a bit.

SizedBox should do the work. Wrap your button by a SizedBox.
From the document:
If given a child, this widget forces its child to have a specific width and/or height (assuming values are permitted by this widget's parent). If either the width or height is null, this widget will size itself to match the child's size in that dimension.
If not given a child, this widget will size itself to the given width and height, treating nulls as zero.
This will work for RaisedButton also
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My Layout',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("SizedBox Demo"),
),
body: new Center(
child: new SizedBox(
width: 200.0,
height: 80.0,
child: new OutlineButton(
borderSide: BorderSide(width: 4.0),
child: Text('I am a button'),
onPressed: (() {})),
),
),
);
}
}
UPDATED (2018/05/26):
If you want to reduce the height of OutlineButton inside AppBar, use Padding
return Scaffold(
appBar: AppBar(
title: Text('Test'),
actions: <Widget> [
Padding(
child: OutlineButton(
borderSide: BorderSide(width: 4.0)
child: Text('Hi'),
onPressed: (){},
padding: EdgeInsets.all(10.0),
),
),
],
),
body: Container(),
);

Flutter 2.5
OutlineButton is deprecated. Instead, use the Material button.
Put the Material Button inside Padding.
The padding property of Padding will control the height and width of the button.
AppBar(
title: Text("Stack Overflow"),
actions: [
Padding(
padding: EdgeInsets.all(8.0),
child: MaterialButton(
color: Colors.yellow,
onPressed: () {
},
child: Text('SUBMIT'),
),
)
],
)

Thanks #phuc-tran, I've made a small fix:
return Scaffold(
appBar: AppBar(
title: Text('Test'),
actions: <Widget> [
Padding(
padding: EdgeInsets.all(10.0),
child: OutlineButton(
borderSide: BorderSide(color: Colors.blue),
child: Text('Hi'),
onPressed: (){},
),
),
],
),
body: Container(),
);

Related

How to display one particular data from Realtime Database?

In a firebase animated list, how do you put in a conditional statement, or anything else, so that only one set of data in Realtime Database will be displayed? I currently can display all of them in a ListTile but I only want to display a destination whose name is 'Spain' and its description instead of all the database that contains Spain, Italy, USA etc.
class _TestDestinationsState extends State<TestDestinations> {
final destdatabaseref = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations');
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF4D71AC),
elevation: 0,
centerTitle: true,
title: Text('Eh',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.white)),
),
body: SafeArea(
child: FirebaseAnimatedList(
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 15),
Padding(
padding: const EdgeInsets.all(8),
child: ListTile(
title: Text(snapshot.value['name'],
style: TextStyle(fontSize: 20)),
subtitle: Text(snapshot.value['description'])),
),
],
),
);
},
query: destdatabaseref,
)),
);
}
}
If we need to only display specific data from FirebaseDatabase we can use the following logic:
Visibility(
visible: snapshot.value['name'] == 'Spain',
child: ...
),
The complete snippet can be found below:
class _TestDestinationsState extends State<TestDestinations> {
final destdatabaseref = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations');
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF4D71AC),
elevation: 0,
centerTitle: true,
title: Text('Eh',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.white)),
),
body: SafeArea(
child: FirebaseAnimatedList(
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
return Visibility(
visible: snapshot.value['name'] == 'Spain',
child: SingleChildScrollView(
child: Column(
children: [
SizedBox(height: 15),
Padding(
padding: const EdgeInsets.all(8),
child: ListTile(
title: Text(snapshot.value['name'],
style: TextStyle(fontSize: 20)),
subtitle: Text(snapshot.value['description'])),
),
],
),
),
);
},
query: destdatabaseref,
)),
);
}
}
However a much better solution, would be to retrieve only specific data based on the filter, which can be done by filtering our query to FirebaseDatabase as follows:
final destdatabaseref = FirebaseDatabase.instance
.reference()
.child('Database')
.child('Destinations')
.orderByChild('name')
.equalTo('Spain');

Implementing comment section for each post in flutter with cloud firestore

I'm creating instagram app clone in flutter with firebase at backend. It's a beginner level project so the coding and structure is basic.
I am stuck at adding comment section under each post. I'm using streambuilder to display data and trying to create a function in which with every image is on the feed screen would have a comment box which is connected to the current-image document in cloud-firestore.
Below is my code and images of database:
class FeedScreen extends StatefulWidget {
const FeedScreen({Key? key}) : super(key: key);
#override
_FeedScreenState createState() => _FeedScreenState();
}
class _FeedScreenState extends State<FeedScreen> {
User? user = FirebaseAuth.instance.currentUser;
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
bottomNavigationBar: BottomNavigation(),
appBar: AppBar(
backgroundColor: Colors.black,
automaticallyImplyLeading: false,
title: Text(
"Platform",
style: TextStyle(
color: Colors.white,
fontSize: 32.96,
fontWeight: FontWeight.w500,
fontFamily: 'Yaldevi',
),
),
),
body: StreamBuilder<QuerySnapshot>(
stream: FirebaseFirestore.instance.collection('users').snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot){
if(snapshot.hasData){
final List<DocumentSnapshot> documents = snapshot.data!.docs;
return ListView(
children: documents.map((doc) => SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ListTile(
leading: doc['profileImage'] == null ?
CircleAvatar(
radius: 16.6,
backgroundColor: Colors.white24,
) :
CircleAvatar(
radius: 16.6,
backgroundImage: NetworkImage(
doc['profileImage']
)
),
title: Text(
doc['displayName'],
style: TextStyle(
color: Colors.white,
fontSize: 16.5,
)
),
subtitle: doc['title'] !=null ?
Text(
doc['title'],
style: TextStyle(
color: Colors.white,
fontSize: 12.5,
),
) :
Text(
"Some Title",
style: TextStyle(
color: Colors.white,
)
),
),
if(doc['photoURL'] != null) ... [
Container(
height: 400,
width: 400,
child: Image(
image: NetworkImage(
doc['photoURL'],
),
fit: BoxFit.contain,
)
),
IconButton(
icon: Icon(
Icons.mode_comment_outlined,
color: Colors.white,
),
onPressed: () {
Navigator.push(context,
MaterialPageRoute(
builder: (context) =>
CommentSection(),
));
},
)
] else if(doc['photoURL'] == null) ...[
Container(
height: 400,
width: 400,
child: Image(
image: AssetImage(
"assets/images/placeholder.png"
),
fit: BoxFit.contain,
)
)
],
ListTile(
leading: Padding(
padding: EdgeInsets.only(bottom: 13.5 ),
child: Text( "# " +
doc['displayName'],
style: TextStyle(
color: Colors.white,
),
),
),
subtitle: Padding(
padding: EdgeInsets.only(bottom: 13.5),
child: doc['decsription'] != null ?
Text( ":" +
doc['decsription'],
style: TextStyle(
color: Colors.white,
)
) :
Text(
"Some Descritiption",
style: TextStyle(
color: Colors.white,
)
)
)
),
]
),
)).toList(),
);
} else {
return CircularProgressIndicator();
}
}
)
);
}
}
and here`s the comment screen code
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
class CommentSection extends StatefulWidget {
// const CommentSection({Key? key}) : super(key: key);
#override
_CommentSectionState createState() => _CommentSectionState();
}
class _CommentSectionState extends State<CommentSection> {
var username = ' ';
List photoURL = [];
User? user = FirebaseAuth.instance.currentUser;
CollectionReference userRef = FirebaseFirestore.instance.collection('users');
final _formKey = GlobalKey<FormState>();
late String comments = ' ';
sendComment() async {
final isValid = _formKey.currentState!.validate();
final name = user!.displayName;
var res = await userRef.where('userid', isEqualTo: user!.uid).get();
_formKey.currentState!.save();
var doc = userRef.doc('photoURL');
doc.set({
'comment' : comments,
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.only(top: 50),
child: TextFormField(
style: TextStyle(
color: Colors.white,
),
decoration: InputDecoration(
labelText: "Leave a Comment..",
labelStyle: TextStyle(
color: Colors.white,
)
),
onSaved: (value) {
comments = value!;
}
),
)
],
)
),
ElevatedButton.icon(
onPressed: sendComment,
icon: Icon(Icons.send,
color: Colors.white,
),
label: Text(
"Send"
))
],
)
),
);
}
}
That's a really broad use-case, and honestly a bit too broad to answer on Stack Overflow. I recommend focusing on a more concrete, specific problem.
For example, you mention in your comment:
I tried creating a separate collection for comment but the comment would be fetched for every image in database and I'm trying to save and retrieve the comment data for particular image
To allow reading only comments on a specific image, you'll need to associate each comment in the database with an image. The two most common approaches for this are:
Create a document for each image in a top-level collection, and then create a subcollection under that document for the comments on that specific image.
Create a single top-level comments collection, and store the ID of the image in each comment document.

How can I resolve "A RenderFlex overflowed by 77 pixels on the bottom."

I have this error with that code code :
import 'package:flutter/material.dart';
import 'package:yummy/main.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(
backgroundColor: Colors.white,
leading: IconButton(
icon: Image.asset("doodles/theuser.png"),
onPressed: (){},
),
centerTitle: true,
title: Image.asset("doodles/halfyummylog.png"),
actions: <Widget>[
IconButton(onPressed: (){}, icon: Image.asset(("doodles/favrec.png")))
],
),
body: Container(
width: MediaQuery.of(context).size.width,
height: 100,
color: Color(0xFFFFDEE2),
child: Column(
children: <Widget>[
Image.asset("doodles/DinnerPlace.png"),
SizedBox(
height: 30,
), Container(
decoration: BoxDecoration(color : Colors.white, borderRadius: BorderRadius.circular(14)),
child: TextField(
decoration: InputDecoration(
border: InputBorder.none,
prefixIcon: Icon(Icons.search,color: Colors.grey,size : 33),
hintText: "Search",
hintStyle: TextStyle(
fontFamily: "SFProDisplay",
color : Colors.grey,
fontSize: 20.0
),
),
)),
],
),
),
);
}
}
The error pop at the bottom of the image "doodles/DinnerPlace.png" after the appbar and I don't know why.
If somoene can help me for resolve this I will be really greatful.
As your container of the body is 100, you have to bound the image within this height.But the height of Image is not specified, so it take the space more than body's container's 100.So either bound the image with container with height like this -
Container(
height: 70,
child: Image.asset("doodles/DinnerPlace.png"),
)
or increase the size of body's Container from 100 to 200.
The problem was because of the second container I just add an Expanded widget for the container and it's working properly now.

Flutter problem size icon in tabbar in appbar?

I have a little problem I can't find the solution.
I created a TABBAR in an APPBAR, but I cannot resize it so that my icon of my tabbar is visible.
My tabbar its ok, but size of icon and tab not good...
I tried several ways but none worked ...
My problem: My probleme
My code:
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>
with SingleTickerProviderStateMixin {
TabController _tabcontroller;
#override
void initState() {
super.initState();
_tabcontroller = new TabController(length: 3, vsync: this);
_tabcontroller.addListener(() {
setState(() {});
});
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
automaticallyImplyLeading: false,
elevation: 1,
title: new TabBar(
indicatorColor: Colors.transparent,
controller: _tabcontroller,
tabs: [
new SafeArea(
child: new Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(20.0)),
child: Center(
child: new Icon(
Icons.icecream,
color: _tabcontroller.index == 0
? Theme.of(context).primaryColor
: Colors.grey,
size: ScreenUtil().setSp(80.0),
),
),
),
),
new SafeArea(
child: new Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(20.0)),
child: Center(
child: new Icon(
Tinder_clone.iconfinder_338_tinder_logo_4375488__1_,
color: _tabcontroller.index == 1
? Theme.of(context).primaryColor
: Colors.grey,
size: ScreenUtil().setSp(80.0),
),
),
),
),
new SafeArea(
child: new Container(
padding: EdgeInsets.all(ScreenUtil().setWidth(20.0)),
child: Center(
child: new Icon(
Tinder_clone.iconfinder_message_01_186393,
color: _tabcontroller.index == 2
? Theme.of(context).primaryColor
: Colors.grey,
size: ScreenUtil().setSp(80.0),
),
),
),
),
]),
),
Thanks for your help,
When placing TabBar within the AppBar, you should use the bottom property.
// ... other lines
return new Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
automaticallyImplyLeading: false,
elevation: 1,
bottom: new TabBar(
indicatorColor: Colors.transparent,
controller: _tabcontroller,
// ... other lines

How to have a Flutter button be as wide as possible up to a maximum width?

In the following layout, I'd like the button to be able to grow to be as wide as possible on the screen, up to a maximum width. I've tried the following, which doesn't work (the button is always as wide as possible):
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(),
TextFormField(),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 200),
child: RaisedButton(child: Text("button"), onPressed: () {}),
),
],
),
),
),
),
);
}
}
To expand on the layout I'm looking for: the button must be the same width as the smaller of the following two quantities: 1) the width of the screen, 2) a given fixed maximum width.
Example scenarios:
A) the screen is 1000 pixels wide, and the given fixed maximum width is 600 pixels, then the button will be 600 pixels wide.
B) the screen is 400 pixels wide, and the given fixed maximum width is 600 pixels, then the button will be 400 pixels wide.
The solution is pretty simple, simply wrap your ConstrainedBox in Align and instead of using maxWidth use minWidth.
Align(
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: 200),
child: RaisedButton(child: Text("button"), onPressed: () {}),
),
)
Output:
If screen width > 200, button takes up 200 width
If screen width < 200, button takes up screen width
You can remove crossAxisAlignment: CrossAxisAlignment.stretch, because TextFormField is stretching anyway. This code will make the button width to be of a max width size, but no bigger than screen width:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) => MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
children: [
TextFormField(),
TextFormField(),
Container(
width: 200,
child: RaisedButton(
onPressed: () {},
child: Text('button'),
),
),
Container(
width: 200,
child: RaisedButton(
onPressed: () {},
child: Text(
'Button with long text asf sadf sdf as df s df as '
'dfas dfsd f asfauhiusg isdugfisudgfi asudgk usgkdu'
'ksdfhk sudfhk sudhfk',
),
),
),
],
),
),
),
),
);
}
You can put the RaisedButton in a Row:
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(),
TextFormField(),
ConstrainedBox(
constraints: BoxConstraints(maxWidth: 250),
child: Row(
children: <Widget>[
Expanded(
child: RaisedButton(child: Text('test')),
),
],
),
),
],
),
),
),
),
);
}
}
The Row will create a horizontal row, and the RaisedButton widget will only take as much room as its own size.
first wrap with container and add width to infinity to be responsive:
Container(
width: double.infinity,
child: ElevatedButton(
child: Text("button"),
onPressed: (){}
),
),
you can add padding too..
known that RaisedButton is deprecated and migrated to ElevatedButton..

Resources