How can I make TextField's suffix/suffixIcon height resize? - user-interface

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
body: Column(
children: [
Container(
color: Colors.orange,
child: TextField(
decoration: InputDecoration(
suffix: IconButton(
icon: Icon(Icons.check_circle),
onPressed: () {
print('222');
}),
),
),
),
],
),
),
),
);
}
}
How can I force the check_circle icon to automatically resize to match the height of the actual TextField, i.e., wrt its cursor height?

Use suffixIcon instead.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
body: Column(
children: [
Container(
color: Colors.orange,
child: TextField(
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(Icons.check_circle),
onPressed: () {
print('222');
}),
),
),
),
],
),
),
),
);
}
}

Very good question...
The basics, is to reset all the paddings in the TextField, and not using a IconButton (as all Material components have predefined and internals paddings that you can't modify).
Seems like suffix gets baseline aligned with the text, preventing the material ink interaction, while suffixIcons get properly centered in the text area, BUT propagates the Ink to the TextField.
So, so far I couldn't find a way of doing it properly, maybe there's a widget/logic that I'm missing.
Check screenshot at the bottom that shows why the suffix will not be able to align with the text, as it sits within the baseline itself, and the caret generates a bigger height.....
in the first 2 textfields, the GREY boxes are suffix, and yellow, suffixIcon (which centers properly).
Solution 1: (in screenshotm is red background with 2 checkboxes)
If you can (design-wise), make a row, and put the TextField and the icon:
var inputBorderDecoration = OutlineInputBorder(
borderRadius: BorderRadius.zero,
borderSide: BorderSide(width: 1, color: Colors.black));
double textHeight = 40;
// define a width if you want, or let the constrains of the parent define it.
double inputWidth = double.infinity;
return Center(
child: Container(
width: inputWidth,
height: textHeight,
color: Colors.green.withOpacity(.2),
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Flexible(
child: TextField(
controller: TextEditingController(text: 'hello world'),
style: TextStyle(fontSize: textHeight),
decoration: InputDecoration(
contentPadding: EdgeInsets.zero,
enabledBorder: inputBorderDecoration,
focusedBorder: inputBorderDecoration,
filled: true,
fillColor: Colors.red.withOpacity(.5),
),
),
),
FittedBox(
child: InkWell(
onTap: () => print("touch button"),
child: Icon(Icons.check_circle),
),
),
],
)),
);
Solution 2: (in screenshot, last textfield, green box with white icon)
Wrap the icon decoration, is the better UI approach, but the TextField will .still receive touch events.
var inputBorderDecoration = OutlineInputBorder(
borderRadius: BorderRadius.zero,
borderSide: BorderSide(width: 1, color: Colors.black));
double fontSize = 24;
return GestureDetector(
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: Container(
color: Colors.green.shade50,
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 300,
height: fontSize,
color: Colors.orange,
child: TextField(
style: TextStyle(fontSize: fontSize, color: Colors.white),
decoration: InputDecoration(
fillColor: Colors.purple.withOpacity(.5),
filled: true,
border: inputBorderDecoration,
focusedBorder: inputBorderDecoration,
enabledBorder: inputBorderDecoration,
contentPadding: EdgeInsets.zero,
suffixIcon: GestureDetector(
onTap: () => print('on tap'),
child: Container(
color: Colors.green,
child: FittedBox(
alignment: Alignment.center,
fit: BoxFit.fitHeight,
child: IconTheme(
data: IconThemeData(),
child: Icon(
Icons.check_circle,
color: Colors.white,
),
),
),
),
),
),
),
),
],
),
),
),
);
Solution 3:
Build the decorations yourself using EditableText

Used Stack
Stack(
children: [
TextField(),
Positioned.fill(
right: 10,
child: Align(
alignment: Alignment.centerRight,
child: InkWell(
onTap: () {
searchController.clear();
},
child: Icon(Icons.clear))))
],
),

Related

Move textfield up when keyboard appears in Flutter

I want to make my textfield go up when the keyboard appears. The keyboard is in front of textfield so I can't see what I write, I didn't found many solution to my problem or there were not very clean.
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
conseil(text),
Spacer(),
InkWell(
onTap: () => [
pic.getImage().then((a) {
setState(() {
myimg = myimage;
});
})
],
child: Container(
decoration: BoxDecoration(
border: Border.all(width: 2.0, color: mygreen),
boxShadow: <BoxShadow>[
BoxShadow(
color: mygreen, blurRadius: 0, offset: Offset(7, 3))
],
shape: BoxShape.circle),
child: ClipOval(
child: SizedBox(
width: 140,
height: 140,
child: (myimg != null)
? Image.file(myimg, fit: BoxFit.fill)
: Image(
image: AssetImage('assets/images/others/add.png'),
fit: BoxFit.fill,
),
),
),
),
),
(myimage == null)?
Text("Choisir une photo"): SizedBox(height: 1),
Spacer(),
SizedBox(
width: 250,
child: TextField(
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white),
decoration: InputDecoration(
enabledBorder: OutlineInputBorder(
borderSide:
BorderSide(color: Color(0xFF37cd41), width: 2)),
hintText: 'TON PRENOM',
hintStyle: TextStyle(color: Colors.white)),
controller: name,
),
),
Spacer(),
button(mypink, 'CONTINUER', widget.admin, context, name),
Spacer(),
],
),
),
);
}
}
Try using SingleChildScrollView and ConstrainedBox.
Scaffold(
body: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height),
child: yourWidget()
Checkout following answer: https://stackoverflow.com/a/59783374/12709039
Try out this one
Column(
children: <Widget>[
Expanded(
child: SingleChildScrollView(
child: Column(
(Your other Widgets)
import 'dart:async';
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import '../weight/boostrap/flutter_bootstrap.dart';
import '../weight/boostrap/bootstrap_widgets.dart';
/*
TextEditingController txtname = TextEditingController();
showModalBottomSheet(
context: context,
isScrollControlled: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20),
topRight: Radius.circular(20),
),
),
builder: (context) => SingleChildScrollView(
padding: EdgeInsets.only(
bottom: MediaQuery.of(context).padding.bottom),
child: new AddItem(
tektk: 'Category',
tektd: 'Add',
txtname: txtname,
ismultik:false,
onPressed: () {}),
),
);
*/
class AddItem extends StatelessWidget {
const AddItem(
{Key? key,
required this.ismultik,
required this.tektd,
required this.tektk,
required this.txtname,
required this.onPressed})
: super(key: key);
final bool ismultik;
final String tektk;
final String tektd;
final VoidCallback? onPressed;
final TextEditingController txtname;
#override
Widget build(BuildContext context) {
final MediaQueryData mediaQueryData = MediaQuery.of(context);
bootstrapGridParameters(gutterSize: 10);
return Padding(
padding: mediaQueryData.viewInsets,
child: Container(
padding: EdgeInsets.only(bottom: 90.0, left: 10.0, right: 10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ListTile(
trailing: SizedBox.fromSize(
size: Size(35, 35),
child: ClipOval(
child: Material(
color: Colors.indigo,
child: InkWell(
splashColor: Colors.white,
onTap: () {
Navigator.pop(context);
},
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(Icons.close, color: Colors.white),
],
),
),
),
),
),
),
BootstrapRow(height: 0, children: [
BootstrapCol(
sizes: 'col-md-12',
child: TextField(
style: TextStyle(color: Colors.black),
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderSide: new BorderSide(color: Colors.white)),
labelText: tektk,
),
keyboardType: ismultik == true
? TextInputType.multiline
: TextInputType.text,
maxLines: null,
minLines: 1,
controller: txtname,
),
),
BootstrapCol(
sizes: 'col-md-12',
child: ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green, // background
onPrimary: Colors.white, // foreground
),
onPressed: onPressed,
child: Text(tektd)),
),
]),
],
),
),
);
}
}
try to add scroll padding from Bottom for textfield
TextField(
scrollPadding: const EdgeInsets.only(bottom: 50), //add this line replace 50 with your required padding
),

Images load by themselves, but not as a randomized list. - Flutter

and thank you in advance for any assistance.
So, I have images load properly when I use them within a container in other areas of the code, but I also want some of those images to display randomly within the AppBar.
Given that they do load in other locations within the code, I don't suspect a Pubyaml error.
I'm still fairly new to flutter, and lists in general. So I wouldn't be surprised if I messed up something with the list itself, or the way it's called.
It gives me this error:
Syncing files to device iPhone...
Reloaded 8 of 502 libraries in 411ms.
════════ Exception caught by image resource service ════════════════════════════════════════════════
The following assertion was thrown resolving an image codec:
Unable to load asset: Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)
When the exception was thrown, this was the stack:
#0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
<asynchronous suspension>
#1 AssetBundleImageProvider._loadAsync (package:flutter/src/painting/image_provider.dart:484:44)
#2 AssetBundleImageProvider.load (package:flutter/src/painting/image_provider.dart:469:14)
#3 ImageProvider.resolve.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:flutter/src/painting/image_provider.dart:327:17)
...
Image provider: AssetImage(bundle: null, name: "Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)")
Image key: AssetBundleImageKey(bundle: PlatformAssetBundle#c99db(), name: "Image(image: AssetImage(bundle: null, name: "images/Mem2.JPG"), frameBuilder: null, loadingBuilder: null, alignment: center, this.excludeFromSemantics: false, filterQuality: low)", scale: 1.0)
════════════════════════════════════════════════════════════════════════════════════════════════════
Here's the code:
class ContactProfilePage extends StatefulWidget {
#override
_ContactProfilePageState createState() => _ContactProfilePageState();
}
class _ContactProfilePageState extends State<ContactProfilePage> {
List<Attr> attr = [
Attr(name: ''),
];
dynamic randAppBarImg = [
"images/Mem2.JPG",
"images/Mem3.JPG",
"images/Mem4.JPG",
"images/Mem6.jpg",
"images/memory - 1.jpeg",
"images/memory - 2.jpeg",
"images/memory - 3.jpeg",
"images/memory - 4.jpeg",
"images/memory - 5.jpeg",
"images/memory - 6.jpeg",
];
Random rnd;
Image img() {
int min = 0;
int max = randAppBarImg.length - 1;
rnd = Random();
int r = min + rnd.nextInt(max - min);
String image_name = randAppBarImg[r].toString();
return Image.asset(image_name);
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.lightBlueAccent,
child: Icon(Icons.add),
onPressed: () {
//Modal sheet brings up the whole bottom pane when the plus button is pressed.
showModalBottomSheet(
context: context,
builder: (context) => AddAttrScreen(
(newAttrTitle) {
setState(() {
//adds the Attr to the list anytime the user presses "Add"
attr.add(Attr(name: newAttrTitle));
});
Navigator.pop(context);
//Hides the floating add Attr screen after pressing "Add"
},
),
);
//TODO Change it so the categories don't have to be selected every time. Instead, have the add button WITHIN each category.
// This floating button should instead create a new category.
},
),
drawer: DrawerMain(),
body: NestedScrollView(
//This allows for the top bar to collapse, while retaining the image.
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
expandedHeight: 200.0,
floating: true,
snap: true,
pinned: true,
flexibleSpace: Stack(
children: <Widget>[
Positioned.fill(
child: Image.asset(
img().toString(),
fit: BoxFit.cover,
))
],
),
),
];
},
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),
child: CircleAvatar(
maxRadius: 50.0,
backgroundImage: AssetImage("images/fox.jpeg")),
),
Container(
//TODO ADD ON PRESSED FUNCTION TO SOCIAL ICONS
margin: EdgeInsets.all(15.0),
child: Icon(
FontAwesomeIcons.facebook,
size: 40.0,
color: Color(0xFF306060),
),
),
Container(
margin: EdgeInsets.all(15.0),
child: Icon(
FontAwesomeIcons.instagram,
size: 40.0,
color: Color(0xFF306060),
),
),
],
),
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'Armando Pacheco Ortiz',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Color(0xFF306060)),
),
],
),
),
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'Freelance App Developer from Puerto Rico',
style: TextStyle(
fontSize: 20.0,
fontStyle: FontStyle.italic,
color: Color(0xFF306060)),
),
SizedBox(
child: Divider(),
),
],
),
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text('Memories',
style: TextStyle(
fontSize: 20.0,
fontStyle: FontStyle.italic,
color: Color(0xFF306060),
fontWeight: FontWeight.bold))
],
),
),
//Horizontal scrolling images.
//TODO These need to update based on uploads, perhaps use something like google's face detection to auto add?
Padding(
padding: const EdgeInsets.all(15.0),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: 310,
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: (Image.asset(
'images/Mem6.jpg',
fit: BoxFit.cover,
)),
),
),
SizedBox(
width: 20,
),
Container(
height: 310,
width: 200,
//ClipRRect allows for it to have the border radius. Container is painted behind the image.
//For that reason, adding a border radius to the container doesn't work.
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: (Image.asset(
'images/Mem2.JPG',
fit: BoxFit.cover,
)),
),
),
SizedBox(
width: 20,
),
Container(
height: 310,
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: (Image.asset(
'images/memory - 4.jpeg',
fit: BoxFit.cover,
)),
),
),
I pasted the code as far down as the first image, to show how I have it set up in the other locations.
I'm not sure if the issue is with random images within the appBar, or maybe some code I'm missing.
Hopefully, someone can shed some light on this!
Many thanks.
UPDATE:
So that helped a ton and definitely got things running! But I did notice two new problems cropping up.
I had to rename all the images from: "memory - 6" to "Mem6", and that finally allowed them to show up.
Otherwise, sometimes it would revert back to the default teal color, and not display anything, besides an error about not being able to load the asset again. I imagine it's just a naming error I was unknowingly causing?
Scrolling down will cause the Appbar to "refresh" again, and randomize the pictures with the slightest scrolling until you stop. If I scroll back up, it'll do it again. It doesn't create an error, but it does crash the app eventually from so much refreshing I guess.
How would I get around this? Is there an override, or should I simply create the widget with some Finals, or stateless/stateful widgets? I'm still learning the lingo and all that, so my apologies for the ignorance.
You can copy paste run full code below
Your img() has bug, you return an Image.asset and wrap in Image.asset again cause duplicate
Image.asset(
img().toString(),
fit: BoxFit.cover,
))
code snippet just return String of image_name will work
and do not include space in image name
String img() {
int min = 0;
int max = randAppBarImg.length - 1;
rnd = Random();
int r = min + rnd.nextInt(max - min);
String image_name = randAppBarImg[r].toString();
//return Image.asset(image_name);
return image_name;
}
working demo
full code
import 'package:flutter/material.dart';
import 'dart:math';
import 'package:font_awesome_flutter/font_awesome_flutter.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: ContactProfilePage(),
);
}
}
class Attr {
String name;
Attr({this.name});
}
class ContactProfilePage extends StatefulWidget {
#override
_ContactProfilePageState createState() => _ContactProfilePageState();
}
class _ContactProfilePageState extends State<ContactProfilePage> {
List<Attr> attr = [
Attr(name: ''),
];
dynamic randAppBarImg = [
"images/Mem2.JPG",
"images/Mem3.JPG",
/*"images/Mem4.JPG",
"images/Mem6.jpg",
"images/memory-1.jpeg",
"images/memory-2.jpeg",
"images/memory-3.jpeg",
"images/memory-4.jpeg",
"images/memory-5.jpeg",
"images/memory-6.jpeg",*/
];
Random rnd;
String img() {
int min = 0;
int max = randAppBarImg.length - 1;
rnd = Random();
int r = min + rnd.nextInt(max - min);
String image_name = randAppBarImg[r].toString();
//return Image.asset(image_name);
return image_name;
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.lightBlueAccent,
child: Icon(Icons.add),
onPressed: () {
//Modal sheet brings up the whole bottom pane when the plus button is pressed.
/* showModalBottomSheet(
context: context,
builder: (context) => AddAttrScreen(
(newAttrTitle) {
setState(() {
//adds the Attr to the list anytime the user presses "Add"
attr.add(Attr(name: newAttrTitle));
});
Navigator.pop(context);
//Hides the floating add Attr screen after pressing "Add"
},
),
);*/
//TODO Change it so the categories don't have to be selected every time. Instead, have the add button WITHIN each category.
// This floating button should instead create a new category.
},
),
//drawer: DrawerMain(),
body: NestedScrollView(
//This allows for the top bar to collapse, while retaining the image.
headerSliverBuilder:
(BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverAppBar(
expandedHeight: 200.0,
floating: true,
snap: true,
pinned: true,
/*flexibleSpace: FlexibleSpaceBar(
centerTitle: true,
title: Text("",
style: TextStyle(
color: Colors.white,
fontSize: 16.0,
)),
background: Image.asset(
"images/Mem2.JPG",
fit: BoxFit.cover,
)),*/
flexibleSpace: Stack(
children: <Widget>[
Positioned.fill(
child: Image.asset(
img().toString(),
fit: BoxFit.cover,
))
],
),
),
];
},
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(15.0),
child: CircleAvatar(
maxRadius: 50.0,
backgroundImage: AssetImage("images/fox.jpeg")),
),
Container(
//TODO ADD ON PRESSED FUNCTION TO SOCIAL ICONS
margin: EdgeInsets.all(15.0),
child: Icon(
FontAwesomeIcons.facebook,
size: 40.0,
color: Color(0xFF306060),
),
),
Container(
margin: EdgeInsets.all(15.0),
child: Icon(
FontAwesomeIcons.instagram,
size: 40.0,
color: Color(0xFF306060),
),
),
],
),
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'Armando Pacheco Ortiz',
style: TextStyle(
fontSize: 25.0,
fontWeight: FontWeight.bold,
color: Color(0xFF306060)),
),
],
),
),
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Text(
'Freelance App Developer from Puerto Rico',
style: TextStyle(
fontSize: 20.0,
fontStyle: FontStyle.italic,
color: Color(0xFF306060)),
),
SizedBox(
child: Divider(),
),
],
),
),
Padding(
padding: const EdgeInsets.all(15.0),
child: Row(
children: <Widget>[
Text('Memories',
style: TextStyle(
fontSize: 20.0,
fontStyle: FontStyle.italic,
color: Color(0xFF306060),
fontWeight: FontWeight.bold))
],
),
),
//Horizontal scrolling images.
//TODO These need to update based on uploads, perhaps use something like google's face detection to auto add?
Padding(
padding: const EdgeInsets.all(15.0),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Container(
height: 310,
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: (Image.asset(
'images/Mem6.jpg',
fit: BoxFit.cover,
)),
),
),
SizedBox(
width: 20,
),
Container(
height: 310,
width: 200,
//ClipRRect allows for it to have the border radius. Container is painted behind the image.
//For that reason, adding a border radius to the container doesn't work.
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: Image.asset(
'images/Mem2.JPG',
fit: BoxFit.cover,
),
),
),
SizedBox(
width: 20,
),
Container(
height: 310,
width: 200,
child: ClipRRect(
borderRadius: BorderRadius.circular(20.0),
child: (Image.asset(
'images/memory-4.jpeg',
fit: BoxFit.cover,
)),
),
),
])))
]))));
}
}

Why are Icon-Buttons not centered?

I'm working on a Flutter application and I can't figure out why my icon-buttons are not centered in the middle of the page.
I wrapped my code in a Center()
This is my page :
https://imgur.com/a/YlCW3Xu
This is my code:
import "package:flutter/material.dart";
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class LogInScreen extends StatefulWidget {
#override
_LogInScreenState createState() => new _LogInScreenState();
}
class _LogInScreenState extends State<LogInScreen> {
String _email, _password;
#override
Widget build(BuildContext context) {
return new Scaffold(
body: Center(
child: ListView(
children: <Widget>[
Column(children: <Widget>[
new Container(
padding: (EdgeInsets.only(top: 50)),
child: Text(
"Sign In",
style: TextStyle(
fontSize: 40,
),
),
),
new Container(
padding: (EdgeInsets.only(top: 50, left: 35, right: 35)),
child: Column(children: <Widget>[
new Form(
child: new Column(children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 20),
child: new RaisedButton(
onPressed: () {},
color: Colors.blue,
textColor: Colors.white,
child: const Text('Login'),
),
),
])),
])),
new Container(
padding: EdgeInsets.only(top: 40),
child: Column(
children: <Widget>[
new Text("Or login with"),
],
),
),
]),
new Center(
child: new Row(
children: <Widget>[
new IconButton(
icon: Icon(FontAwesomeIcons.facebookF),
color: Colors.blue,
),
new IconButton(
icon: Icon(FontAwesomeIcons.google),
color: Colors.blue,
),
],
)),
],
)),
);
}
}
I removed the texts field so the code would fit.
I hope you can help me,
Thank you for your help !
Set the padding for IconButton to 0, like so:
IconButton(
padding: EdgeInsets.zero,
...
)
None of the listed solution will work. The Only solution for me is to put IconButton inside SizedBox.
SizedBox(
width: double.infinity,
child: IconButton(
icon: FaIcon(FontAwesomeIcons.moneyBillWave),
iconSize: 80,
onPressed: () {},
),
),
A few changes :
Add shrinkWrap true to your ListView
ListView(
shrinkWrap: true,
...
Add mainAxisAlignment MainAxisAlignment.center to your Row
new Center(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new IconButton(
...
Basically Center() widget only center the row itself not the widgets within the row.
To align children in your row use mainAxisAlignment: MainAxisAlignment.centerfor horizontal alignment and crossAxisAlignment: CrossAxisAlignment.center for Vertical alignment see more here
so for your code it would be:
` new Center(
child: new Row(
mainAxisAlignment: MainAxisAlignment.center
children: <Widget>[
new IconButton(
icon: Icon(FontAwesomeIcons.facebookF),
color: Colors.blue,
),
new IconButton(
icon: Icon(FontAwesomeIcons.google),
color: Colors.blue,
),
],
)),`
You don't need Center the icon because the problem was the Icon it self. Maybe the icon design contained padding or margin. My problem is on back button:
Container(
color: Colors.lightGreen,
child: Icon(
Icons.arrow_back_ios,
color: Colors.black,
size: 15,
),
),
When i change to Icons.arrow_back_ios_new, it back to normal:
Container(
color: Colors.lightGreen,
child: Icon(
Icons.arrow_back_ios_new,
color: Colors.black,
size: 15,
),
),
You need to find an icon that contained no padding/margin.

Flutter how to handle image with fixed size inside box?

I am new to Flutter and I like it but I am not comfortable building layouts.
I am working on an app that contains a ListView of Cards.
Each card is inside a Container and contains an image (with fixed height and width) and a text.
I am not able to place the image correctly inside the Card. I want the image to cover the width of box.
Thanks.
This is the code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final title = 'MyApp';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ListView(
children: <Widget>[
Container(
margin:EdgeInsets.all(8.0),
child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
child: InkWell(
onTap: () => print("ciao"),
child: Column(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(8.0),
topRight: Radius.circular(8.0),
),
child: Image.asset(
'img/britannia.jpg',
width: 300,
height: 150,
fit:BoxFit.fill
),
),
ListTile(
title: Text('Pub 1'),
subtitle: Text('Location 1'),
),
],
),
),
),
),
],
),
),
);
}
}
You need to add - crossAxisAlignment: CrossAxisAlignment.stretch, in Column so that children can take up horizontal space.
Working Code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
final title = 'MyApp';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ListView(
children: <Widget>[
Container(
margin:EdgeInsets.all(8.0),
child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
child: InkWell(
onTap: () => print("ciao"),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch, // add this
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(8.0),
topRight: Radius.circular(8.0),
),
child: Image.network(
'https://placeimg.com/640/480/any',
// width: 300,
height: 150,
fit:BoxFit.fill
),
),
ListTile(
title: Text('Pub 1'),
subtitle: Text('Location 1'),
),
],
),
),
),
),
Container(
margin:EdgeInsets.all(8.0),
child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
child: InkWell(
onTap: () => print("ciao"),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(8.0),
topRight: Radius.circular(8.0),
),
child: Image.network(
'https://placeimg.com/640/480/any',
// width: 300,
height: 150,
fit:BoxFit.fill
),
),
ListTile(
title: Text('Pub 1'),
subtitle: Text('Location 1'),
),
],
),
),
),
),
Container(
margin:EdgeInsets.all(8.0),
child: Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
child: InkWell(
onTap: () => print("ciao"),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(8.0),
topRight: Radius.circular(8.0),
),
child: Image.network(
'https://placeimg.com/640/480/any',
// width: 300,
height: 150,
fit:BoxFit.fill
),
),
ListTile(
title: Text('Pub 1'),
subtitle: Text('Location 1'),
),
],
),
),
),
),
],
),
),
);
}
}
output:
I don't know how.. But this really worked to keep image with fixed size in container
Just add Alignment in container
Container(
height: double.infinity,
alignment: Alignment.center, // This is needed
child: Image.asset(
Constants.ASSETS_IMAGES + "logo.png",
fit: BoxFit.contain,
width: 300,
),
);
This worked for me
Image.network(imageUrl, fit: BoxFit.fitWidth,),
Put Image widget inside container and give alignment center to container and specific width-height to the image.
return Container(
alignment: Alignment.center,// use aligment
color: Color.fromRGBO(0, 96, 91, 1),
child: Image.asset('assets/images/splash_logo.png',
height: 150,
width: 150,
fit: BoxFit.cover),
);
Image.asset(
'assets/images/desert.jpg',
height: 150,
width: MediaQuery.of(context).size.width,
fit:BoxFit.cover
)
child: Container(
alignment: Alignment.center,// use aligment
child: Image.asset(
'assets/images/call.png',
height: 45,
width: 45,
fit: BoxFit.cover,
),
),
Use this if you want with border
Center(
child: Container(
margin: EdgeInsets.only(top: 75),
width: 120,
height: 120,
alignment: Alignment.center,
child: Image.asset(
"assets/images/call.png",
fit: BoxFit.cover,
height: 45,
width: 45,
),
decoration: new BoxDecoration(
color: Colors.white,
borderRadius: new BorderRadius.all(new Radius.circular(120)),
border: new Border.all(
color: Colors.blue,
width: 4.0,
),
),
),
)
I used this and worked fine with me!
Container(
width: MediaQuery.of(context).size.width,
height: 175,
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(YOUTUBE_THUMBNAIL_PART_ONE +
video.key +
YOUTUBE_THUMBNAIL_PART_TWO),
),
)),
What you want to do is probably use the size of the bigger container.
In that case your media should occupy the whole dedicate space:
return Container(
alignment: Alignment.center,
height: double.infinity,
width: double.infinity,
child: Image.asset(
'', //TODO fill path
height: double.infinity,
width: double.infinity,
fit: BoxFit.cover,
),
);
You can play with the fit value:
BoxFit.cover will cover the whole container
BoxFit.fitWidth will fit the width and eventually put horizontal white bars to fill the space
BoxFit.fitHeight will fit the height and eventually put vertical white bars to fill the space
If doable with the fit property, I let this very clear cheat sheet (chapter fit Property) detail everything: https://medium.com/jlouage/flutter-boxdecoration-cheat-sheet-72cedaa1ba20
All you need is fit property of Image class:
Image.asset(
'your_image_asset',
fit: BoxFit.fill, // Expands to fill parent (changes aspect ratio)
)
or
Image.asset(
'your_image_asset',
fit: BoxFit.cover, // Zooms the image (maintains aspect ratio)
)
I had the same problem, I just added in the Image.asset class the fit:BoxFit.fill after using the MediaQuery class to get the width of the screen**
Container(
child:Image.asset(link,fit: BoxFit.fill,)
width: screensize.width,
height: 150,
))

Change Flutter Drawer Background Color

How can I change the background color of a flutter nav drawer?
There doesn't seem to be a color or background-color property.
When you build your ListView in the child property of your Drawer, you can wrap your different sections of the Drawer inside a Container and use the color property of the Container.
drawer: new Drawer(
child: new ListView(
children: <Widget>[
new Container(child: new DrawerHeader(child: new CircleAvatar()),color: Colors.tealAccent,),
new Container (
color: Colors.blueAccent,
child: new Column(
children: new List.generate(4, (int index){
return new ListTile(
leading: new Icon(Icons.info),
);
}),
),
)
],
),
),
A better alternative if you already have a consistent coloring design in your mind, is to define your ThemeData under the theme property of the root of your app, the DrawerHeader and the body will follow your canvasColor, so you need to override the value of one of them to change the color:
return new MaterialApp(
....
theme: new ThemeData(
canvasColor: Colors.redAccent,
....),
)
Best way to wrap Drawer with Theme,
For example:
#override
Widget build(BuildContext context) {
return Scaffold(
//other scaffold items
drawer: Theme(
data: Theme.of(context).copyWith(
canvasColor: Colors.blue, //This will change the drawer background to blue.
//other styles
),
child: Drawer(
child: Column(
children: <Widget>[
//drawer stuffs
],
),
),
);
}
The easiest way would probably be to just wrap the ListView inside a Container and specify its color like following:
drawer: Drawer(
child: Container(color: Colors.red,
child: new ListView(
...
)
)
)
For changing Drawer Header color use blow code
UserAccountsDrawerHeader(
accountName: Text("Ashish Rawat"),
accountEmail: Text("ashishrawat2911#gmail.com"),
decoration: BoxDecoration(
color: const Color(0xFF00897b),
),
currentAccountPicture: CircleAvatar(
backgroundColor: Theme.of(ctxt).platform == TargetPlatform.iOS
? const Color(0xFF00897b)
: Colors.white,
child: Text(
"A",
style: TextStyle(fontSize: 40.0),
),
),
),
You can just use this code;
drawer: Drawer(
child: Container(
//child: Your widget,
color: Colors.red,
width: double.infinity,
height: double.infinity,
),
)
PLAIN BACKGROUND
Just set your desired theme color using primarySwatch: Colors.brown property in ThemeData
class MyApp extends StatelessWidget {
final appTitle = 'Drawer Demo';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: appTitle,
theme: new ThemeData(
primarySwatch: Colors.brown, // Your app THEME-COLOR
),
home: MyHomePage(title: appTitle),
);
}
}
GRADIENT BACKGROUND
Add the gradient property to AppBar.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("profyl.org",
style: TextStyle(color: Colors.white),
textDirection: TextDirection.ltr),
flexibleSpace: Container(
decoration: new BoxDecoration(
gradient: new LinearGradient(
colors: [
const Color(0xFF3366FF),
const Color(0xFF00CCFF),
],
begin: const FractionalOffset(0.0, 0.0),
end: const FractionalOffset(1.0, 0.0),
stops: [0.0, 1.0],
tileMode: TileMode.clamp),
),
),
),
body: HomeListPage(),
drawer: DrawerPage());
}
Try This.
#override
Widget build(BuildContext context) {
return Drawer(
child: Container(
color: Colors.black,
child: ListView(
padding: const EdgeInsets.all(0),
children: [
],
),
),
);
}
}
This will help
drawer: Drawer(
child: Container(
color: Colors.blueAccent,
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
UserAccountsDrawerHeader(
decoration: BoxDecoration(
color: Color(0xFF56ccf2),
),
accountName: Text("User Name Goes"),
accountEmail: Text("emailaddress#gmail.com"),
currentAccountPicture: CircleAvatar(
backgroundColor:
Theme.of(context).platform == TargetPlatform.iOS
? Color(0xFF56ccf2)
: Colors.white,
child: Text("TK",
style: TextStyle(fontSize: 50,
color: Colors.lightGreenAccent,),),
),
),
ListTile(
title: Text('Home',
style: TextStyle(
color: Colors.white,
fontSize: 18,
)),
contentPadding: EdgeInsets.fromLTRB(20, 5, 0, 5),
trailing: Icon(Icons.arrow_right,
color: Colors.white,),
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => HomeScreen()));
},
),
],
),
),
),
The simplest way:
Drawer(
child: ListView(
padding: EdgeInsets.zero,
children: <Widget>[
DrawerHeader(
decoration: BoxDecoration(color:Theme.of(context).bottomAppBarColor),
)],
),
)
You can wrap whatever you have in your drawer with a container wrapped with expanded widget. Thus you can change the color of the container there. Something like this will work.
Drawer(
child: Expanded(
child: Container(
color: Colors.red,
child: Text('Tabs'),
),
),
)

Resources