I have just started learning flutter, I have a screen that contains a form, I'd like to know how to reduce the width of button and put it in center.
This the code:
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Ajouter note'),
centerTitle: true,
backgroundColor: Colors.pink,
),
body: Container(
padding: EdgeInsets.all(10.0),
child: Form(
key: _formKey,
child: ListView(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
hintText: 'Saisir un titre',
),
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
SizedBox(
height: 10.0,
),
TextFormField(
minLines: 10,
maxLines: 10,
decoration: InputDecoration(
hintText: 'Saisir une déscription',
),
// The validator receives the text that the user has entered.
validator: (value) {
if (value.isEmpty) {
return 'Please enter some text';
}
return null;
},
),
SizedBox(
height: 10.0,
),
RaisedButton.icon(
onPressed: () {
if (_formKey.currentState.validate()) {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Processing Data')));
}
},
label: Text(
'Enregistrer',
style: TextStyle(
fontSize: 16.0,
color: Colors.white,
),
),
icon: Icon(
Icons.save,
color: Colors.white,
),
color: Colors.pink,
),
],
),
),
),
);
}
One way could be wrapping the RaisedButton in a Padding.
You can apply padding only horizontal axis.
Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: // your RaisedButton
}
There are a lot of ways of doing it. One option is to limit the size of your button like this:
Center(
child: SizedBox(
width: 100,
child: RaisedButton(
...
),
),
)
Related
I'm having bottom overflowed by pixels flutter when showing keyboard, i tried SingleChildSCrollView and still couldn't find the solution for it. my aim to make the Get.defaultDialog scrollable.
here my code :
class AddCard extends StatelessWidget {
final homeCtrl = Get.find<HomeController>();
AddCard({super.key});
#override
Widget build(BuildContext context) {
final icons = getIcons();
var squareWidth = Get.width - 12.0.wp;
return Container(
width: squareWidth / 2,
height: squareWidth / 2,
margin: EdgeInsets.all(3.0.wp),
child: InkWell(
onTap: () async {
await Get.defaultDialog(
titlePadding: EdgeInsets.symmetric(vertical: 5.0.wp),
radius: 5,
title: 'Task Type',
content: Form(
key: homeCtrl.formKey,
child: Column(
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 3.0.wp),
child: TextFormField(
controller: homeCtrl.editCtrl,
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'title',
),
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Please enter your task title';
}
return null;
},
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 5.0.wp),
child: Wrap(
spacing: 2.0.wp,
children: icons
.map((e) => Obx(() {
final index = icons.indexOf(e);
return ChoiceChip(
selectedColor: Colors.grey[200],
pressElevation: 0,
backgroundColor: Colors.white,
label: e,
selected: homeCtrl.chipIndex.value == index,
onSelected: (bool selected) {
homeCtrl.chipIndex.value =
selected ? index : 0;
},
);
}))
.toList(),
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
minimumSize: const Size(150, 40),
),
onPressed: () {
if (homeCtrl.formKey.currentState!.validate()) {
int icon =
icons[homeCtrl.chipIndex.value].icon!.codePoint;
String color =
icons[homeCtrl.chipIndex.value].color!.toHex();
var task = Task(
title: homeCtrl.editCtrl.text,
icon: icon,
color: color,
);
}
},
child: const Text("Confirm"),
),
],
),
));
},
child: DottedBorder(
color: Colors.grey[400]!,
dashPattern: const [8, 4],
child: Center(
child: Icon(
Icons.add,
size: 10.0.wp,
color: Colors.grey,
),
)),
),
);
}
}
The widget that makes the error is the Get.defaultDialog().
There are two ways:
You can use the resizeToAvoidBottomInset property on the Scaffold widget.
You can use ListView instead Column:
onTap: () async {
await Get.defaultDialog(
radius: 5,
titlePadding: EdgeInsets.symmetric(vertical: 5.0),
title: Text('Task Type'),
content: SizedBox(
height: 500,//your height
width: 300, //your width
child:
Form(
child: ListView(
children: [
Padding(
padding: EdgeInsets.symmetric(horizontal: 3.0),
child: TextFormField(
decoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'title',
),
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: 5.0),
child: Wrap(
spacing: 2.0,
children: List.generate(//replace with your content
100,
(index) => Container(
height: 20,
width: 50,
padding: EdgeInsets.all(20),
color: Colors.red,
))),
),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.blue,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
minimumSize: const Size(150, 40),
),
onPressed: () {},
child: const Text("Confirm"),
),
],
),
),
),
),
);
It`s important to give your dialog a fixed height and width, in this defined area it's possible to make a scrollable widget work.
If your aim is to make the dialog scrollable, Use ListView with defined height.
Further for your SizedBox to work as expected in case of any overplexes use the Flexible widget
Try the code structure:
GetDialog
|_Flexible
|_SizedBox đDefine proper height and width here
|_ListView
I can't really understand your question well because you only posted part of the codes, but try wrapping your Scaffold body with SingleChildScrollView.
maybe you're using the SingleChildScrollView at a wrong place.
In our application, SOMETIMES space input doesn't work in textFields (f.e. adding a new message in a chat), but after refreshing the page it works again. This situation is causing unstable environment for our users and thus a lot of complaints. Is there any official documentation, or solution by flutter for this "sometimes space button cannot be used" problem. What we notices that, when this problem occurs, fonts are different than it supposed to be, like it's not loaded. It is not browser specific because problem occurs at Chrome & Edge.
The real problem is that the bug is not easy to detect because it happens only few times so i don't know how to detect and solve it.
In particular i noted that it happens only in production ( i never spotted it during development) .
Flutter doctor:
This is an example widget that have the bug
Widget build(BuildContext context) {
return CustomAlertDialog(
title: const Text(
"Aggiungi un messaggio",
style: TextStyle(fontSize: 16),
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
"Annulla",
style: TextStyle(color: Colors.grey.shade700),
)),
TextButton(
onPressed: () {
},
child: const Text("Invia"))
],
content: Container(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.only(top: 10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(16)),
border: Border.all(
color: Colors.green,
width: 2,
),
),
width: 800,
child: TextField(
minLines: 8,
maxLines: 8,
autofocus: false,
controller: _chatController,
//keyboardType: TextInputType.multiline,
onChanged: (text) {
setState(() {
textValue = text;
});
},
decoration: const InputDecoration(
contentPadding: EdgeInsets.all(8),
hintText: "Scrivi qui il tuo messaggio",
border: InputBorder.none,
),
),
),
SizedBox(
height: 10,
),
CheckboxListTile(
value: _hiddenMessage,
onChanged: (value) {
setState(() {
_hiddenMessage = value!;
});
},
title: const Text("Nascondi"),
)
],
),
),
));
}
CustomAlertDialog:
class _CustomAlertDialogState extends State<CustomAlertDialog> {
#override
Widget build(BuildContext context) {
return AlertDialog(
insetPadding: widget.insetPadding ??
EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
title: widget.title ??
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: const [
Icon(
Icons.cancel,
color: Colors.red,
size: 30,
),
SizedBox(width: 5),
Text('Errore'),
],
),
elevation: widget.elevation ?? 24.0,
actions: widget.actions ??
[
TextButton(
child: const Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
)
],
content: widget.content ??
const Text(
"Errore di connessione al server",
style: TextStyle(fontSize: 20),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
),
);
}
}
Thank you for the help!
Widget build(BuildContext context) {
return MaterialApp(
shortcuts: {
LogicalKeySet(LogicalKeyboardKey.space): ActivateIntent(),
},
title: 'title of your app',
//....
);
}
I'm having a little challenge displaying selected file image in a bottomSheet form. The image simply doesn't display immediately until I tap any field in the form, then the image shows. I'm not sure what's causing this if it is because the form is outside scaffold or what? I want the image to display as soon as it is picked.
Below is what the form widget looks like.
//Form is outside scaffold
Widget bottomSheetSeller() {
return Form(
key: formKey,
onChanged: () => setState(() => value = value),
child: Container(
height: 400,
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.symmetric(horizontal: 20.0, vertical: 20.0),
child: SingleChildScrollView(
child: Column(
children: [
Container(
height: 4.0,
width: 50.0,
decoration: BoxDecoration(
color: globalDefault,
borderRadius: BorderRadius.circular(50.0),
),
alignment: Alignment.center,
),
const SizedBox(height: 45.0),
Container(
child: Text(
'Seller Form',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: globalHeading,
),
textAlign: TextAlign.center,
),
alignment: Alignment.topLeft,
),
const SizedBox(height: 25.0),
FormWithValidation(
initialValue: value,
hint: 'First Name',
keyboardType: TextInputType.text,
validate: (value) {
if (value!.isEmpty) {
return "fill this field";
} else if (value.length <= 2) {
return "too short!";
} else {
return null;
}
},
onSaved: (value) => setState(() => firstName = value!)),
const SizedBox(height: 10.0),
FormWithValidation(
initialValue: value,
hint: 'Last Name',
keyboardType: TextInputType.text,
validate: (value) {
if (value!.isEmpty) {
return "fill this field";
} else if (value.length <= 2) {
return "too short!";
} else {
return null;
}
},
onSaved: (value) => setState(() => lastName = value!)),
const SizedBox(height: 15.0),
//File upload
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
yourLogo.isEmpty
? TextButton(
style: ButtonStyle(
padding: MaterialStateProperty.all(
const EdgeInsets.all(15)),
side: MaterialStateProperty.all(
BorderSide(
width: 1,
color: globalInfoColor,
style: BorderStyle.solid),
),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(0),
),
),
),
onPressed: () async {
selectImage(ImageSource.gallery);
},
child: Unicon(
Unicons.uniPlus,
size: bigHeader,
color: globalInfoColor,
),
)
: setPicture(),
const SizedBox(width: 5.0),
const Text('Company logo'),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 10.0),
child: Text(
'Allowed image format: jpg, jpeg, png',
style: TextStyle(
color: globalInfoColor,
fontStyle: FontStyle.italic,
),
),
),
const SizedBox(height: 30.0),
ButtonWidget(),
//some fields are not added to avoid too much code. If there is a need for more information I will gladly provide them.
the images below describe the situation:
Image 1: Image is already selected but appears not to be
Image 2: I tapped a field in the form and the image is now seen
Wrap your Form with StatefulBuilder and use its setState to update on bottom Sheet UI.
return StatefulBuilder(builder: (context, setState) {
return Form(child:
},)
On my login screen : user is asked to type in login and password. I save these value in two variables : email and password. Then the user must tap a button to actually log in.
The problem is that for some reason (that I really can't figure out...) email and password are always empty when user hits the button....
Here's the full code :
class SeConnecterScreen extends StatelessWidget {
static const String id = 'se_connecter_screen';
#override
Widget build(BuildContext context) {
var uD = Provider.of<UdProvider>(context);
String email = '';
String passWord = '';
final Connectivity _connectivity = Connectivity();
var scaffold = Scaffold(
extendBody: true,
extendBodyBehindAppBar: true,
backgroundColor: Colors.indigo[900],
body: Column(
children: [
Expanded(
flex: 4,
child: Container(
margin: const EdgeInsets.only(bottom: 12),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/start2.jpg'), fit: BoxFit.cover),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(50),
),
),
height: MediaQuery.of(context).size.height / 4,
),
),
Expanded(
flex: 6,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Container(
height: MediaQuery.of(context).size.height -
(MediaQuery.of(context).size.height / 4),
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
width: 1.0,
color: Colors.white,
),
borderRadius: BorderRadius.circular(10.0),
),
child: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: [
Text(
'WORD CHAMPIONS',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.indigo[900],
fontSize: 28.0,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 50,
),
TextField(
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
focusColor: Colors.white,
border: OutlineInputBorder(),
labelText: 'Tape ton adresse email'),
onChanged: (value) {
email = value;
print(email);
},
),
SizedBox(
height: 25.0,
),
TextField(
obscureText: true,
keyboardType: TextInputType.name,
decoration: InputDecoration(
focusColor: Colors.white,
border: OutlineInputBorder(),
labelText: 'Tape ton mot de passe'),
onChanged: (value) {
passWord = value;
print(passWord);
},
),
SizedBox(
height: 35.0,
),
ElevatedButton.icon(
label: Text('Se connecter'),
icon: Icon(Icons.library_add_check_rounded),
style: ElevatedButton.styleFrom(
minimumSize: Size(30, 45),
primary: Colors.green[800],
onPrimary: Colors.white,
),
onPressed: () async {
print('Email : $email');
print('passWord : $passWord');
if (await _connectivity.checkConnectivity() ==
ConnectivityResult.none) {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
'Oups!',
style: TextStyle(fontSize: 22.0),
),
content: Text(
'Il faut te connecter Ă Internet !',
style: TextStyle(fontSize: 18.0),
),
actions: [
TextButton(
onPressed: () {
Navigator.pushReplacementNamed(
context, StartingScreen.id);
},
child: Text(
'OK',
style: TextStyle(fontSize: 18.0),
),
),
],
),
);
} else {
String accountVerif =
await uD.checkAccountId(email, passWord);
if (accountVerif == '') {
DialogBuilder(context).showLoadingIndicator(
text: 'Téléchargement des bases',
color: Colors.black45);
await uD.downLoadUserInfo(email);
DialogBuilder(context).hideOpenDialog();
Navigator.pushReplacementNamed(
context, ProfileScreen.id);
} else {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: Text(
'Oups!',
style: TextStyle(fontSize: 22.0),
),
content: Text(
'Ce compte n\'existe pas, ou le mot de passe est incorrect.',
style: TextStyle(fontSize: 18.0),
),
actions: [
TextButton(
onPressed: () {
Navigator.pushReplacementNamed(
context, StartingScreen.id);
},
child: Text(
'OK',
style: TextStyle(fontSize: 18.0),
),
),
],
),
);
}
}
}),
],
),
),
),
),
)),
],
),
);
return scaffold;
}
}
Please Try to define you password and email variables outside build method. It may solve issue.
See it works for me, May be you should do
stop execution
run 'flutter clean'
run 'flutter pub get'
execute it
Define the variables just below the override instead of below the build method
Add the textediting controller to it
so that your problem will be solved
Below is my flutter code and I would like to make the leading calendar icon launch a calendar widget for date selection in the last textfield just before the raised button as marked below in code.
** widget starts inside stateful class**
#override
Widget build(BuildContext context) {
var db = DBHelper();
return Scaffold(
appBar: AppBar(
title: Text('Add'),
),
body: Container(
padding: EdgeInsets.only(top: 30, left: 50, right: 50),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
TextField(
keyboardType: TextInputType.text,
decoration: InputDecoration(
icon: Icon(Icons.bookmark), hintText: 'nickname'),
controller: nameController,
),
const SizedBox(height: 15),
TextField(
decoration: InputDecoration(
icon: Icon(Icons.date_range), hintText: 'date created'),
controller: otherController,
),
const SizedBox(height: 50),
RaisedButton(
onPressed: () {
db.saveAssets(Asset(
name: nameController.text,
other: otherController.text));
Navigator.push(
context,
MaterialPageRoute(builder: (context) => MyAssetsList()),
);
},
padding: EdgeInsets.only(left: 18, right: 18),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
textColor: Colors.white,
color: Colors.lightGreen,
splashColor: Colors.lightGreenAccent,
child: const Text(
'Save',
style: TextStyle(fontSize: 20),
),
),
],
),
),
),
);
}
}
One more solution.
If you want only the calendar icon to be tapable (while still having similar design to the one you've provided):
Row(
children: <Widget>[
IconButton(
icon: Icon(Icons.date_range),
padding: EdgeInsets.zero,
onPressed: () {
print('Yay!');
},
),
Expanded(
child: TextField(
decoration: InputDecoration(
hintText: 'Date Created',
),
readOnly: true, // Or wrap the input with AbsorbPointer if you do not want the field to get highlighted by taping on it
),
),
],
)
If you want to let the user input the date by typing - just remove the readOnly attribute from the input.