How can I add a container widget by pressing the button? - android

As shown in the picture below, there is a container widget with image and text field, and I would like to create an additional container when I click the button.
I have no idea how to implement this.
Can you suggest a way to implement this?
Container _productForm() {
return Container(
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_productImage(),
_productImage(),
],
),
_heightPadding(15),
_inputText("input text", _controller2),
_heightPadding(15),
_inputText("input text", _controller3),
],
),
);
}
Widget _inputText(String hint, TextEditingController textEditingController) {
return Container(
width: double.infinity,
// height: 200,
child: TextField(
controller: textEditingController,
//엔터키 이벤트
onSubmitted: (value) {},
//높이를 부모 위젯의 높이로 설정 (컨테이너 전체를 텍스트필드로 사용)
// expands: true,
maxLines: null,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(5),
),
hintText: hint,
),
),
);
}
Widget _addButton() {
return Container(
width: 200,
height: 65,
child: ElevatedButton(
onPressed: () {
//상품썸네일 아래에 상품썸네일 하나 더 추가
},
child: Text(
'Add Container',
style: TextStyle(
fontSize: 17, fontWeight: FontWeight.bold),
),
style: ElevatedButton.styleFrom(
primary: Colors.blue, // background
onPrimary: Colors.white, // foregro// und
),
),
);
}

try put in the List:
List<Container> _containers = [_productForm(),_productForm(),];
onPressed: () {
//상품썸네일 아래에 상품썸네일 하나 더 추가
_containers.add(_productForm());
setState((){});
},
then Load your _containers list with ListView

create list of widget
List<Container> _containers = [_productForm(),_productForm(),];
set dynamic children in row
Row(
children: _containers
.map((_) => _productForm())
.toList(),
)
on press of your button
onPressed: () {
_containers.add(_productForm());
setState((){});
},

Related

Why is nothing displayed in my flutter widget?

return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text("Se connecter"),
backgroundColor: Colors.red,
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child:
Container(
margin: EdgeInsets.all(24),
decoration: BoxDecoration(color: Colors.white),
child :
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Container(
width: 160.0,
color: Colors.red,
),
Container(
width: 160.0,
color: Colors.blue,
),
]
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter email',
contentPadding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
),
),
TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter Password',
contentPadding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
),
),
Text(
'10',
style: Theme.of(context).textTheme.headlineMedium,
),
// ↓ Add this.
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: () async {
print('button pressed!');
Map<String,String?> infos = {
'app_id' : dotenv.env['app_id'],
'database' : dotenv.env['database'],
'mail' : dotenv.env['mail'],
'pass' : dotenv.env['pass'],
//'debug-mr' : dotenv.env['debug-mr'],
};
var a = await HttpGet('/auth', infos);
Map<String, dynamic> map = jsonDecode(a.body);
print(map['auth_mode']);
},
child: Text('Next'),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: null,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
I want first to create a column in 2 columns in the first row of the view, then display in differents rows differents components after the second row... each one one row
..but there is not that
I expect that it appears anything of my screen view, or nothing is displayed, all is white
Thanks in advance if you are able to help me
Please add shrinkWrap = true inside ListView,
Or Wrap Expand widget outside ListView,
If scrollDirection = axis.horizontal, Please Wrap LisView in SizeBox and set Height for SizeBox
Because of Column [ ListView...] Firstly check Unbounded height / width | Decoding Flutter.
For your case, Container doesn't have any height.
try providing height.
You can wrap the ListView with Expanded widget, it will get available space for ListView.
class _FR43State extends State<FR43> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text("Se connecter"),
backgroundColor: Colors.red,
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Container(
margin: EdgeInsets.all(24),
decoration: BoxDecoration(color: Colors.white),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
Container(
width: 160.0,
height: 200,
color: Colors.red,
),
Container(
width: 160.0,
height: 200,
color: Colors.blue,
),
]),
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Email',
hintText: 'Enter email',
contentPadding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
),
),
TextField(
obscureText: true,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: 'Password',
hintText: 'Enter Password',
contentPadding: EdgeInsets.fromLTRB(10.0, 10.0, 10.0, 10.0),
),
),
Text(
'10',
style: Theme.of(context).textTheme.headlineMedium,
),
// ↓ Add this.
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.red,
),
onPressed: () async {
// print('button pressed!');
// Map<String,String?> infos = {
// 'app_id' : dotenv.env['app_id'],
// 'database' : dotenv.env['database'],
// 'mail' : dotenv.env['mail'],
// 'pass' : dotenv.env['pass'],
// //'debug-mr' : dotenv.env['debug-mr'],
// };
// var a = await HttpGet('/auth', infos);
// Map<String, dynamic> map = jsonDecode(a.body);
// print(map['auth_mode']);
},
child: Text('Next'),
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: null,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

TextField unfocuses when the soft keyboard appears

For some reason, when I press the TextField, it focuses for a split second and then unfocuses immediately as the soft keyboard comes up. I can still type and submit, but the labelText doesn't disappear like it's supposed to and most importantly, FocusManager.instance.primaryFocus?.unfocus() doesn't let the keyboard disappear.
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(5),
child: Row(
children: [
Expanded(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
),
child: Container(
margin: const EdgeInsets.only(left: 10, bottom: 10, top: 10),
child: TextField(
onTap: () => myFocusNode.requestFocus(),
decoration: const InputDecoration(
labelText: ' Enter task',
border: InputBorder.none,
floatingLabelBehavior: FloatingLabelBehavior.never,
),
controller: textController,
focusNode: myFocusNode,
onSubmitted: (_) {
submit();
myFocusNode.requestFocus();
textController.clear();
},
),
),
),
),
CircleAvatar(
child: TextButton(
onPressed: () {
submit();
myFocusNode.requestFocus();
textController.clear();
},
child: const FittedBox(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
),
),
),
],
),
);
}
I think this may be because the app is rebuilt when the soft keyboard shows up, but I'm not sure. What can I do to fix this?
I think you need to remove this:
onTap: () => myFocusNode.requestFocus(),
If you need, you can control the focus action when filed si submitted with the textInputAction property:
// Go to next field
textInputAction: TextInputAction.next
// Go to previous field
textInputAction: TextInputAction.previous
// Don't move focus
textInputAction: TextInputAction.none
// Many other possible values, check the doc ...
UPDATE
When i try your build code on a MediaPad tablet, it work like a charm, here is my implementation:
import 'package:flutter/material.dart';
class DoorMeasure extends StatefulWidget {
const DoorMeasure({Key? key}) : super(key: key);
#override
State<DoorMeasure> createState() => _DoorMeasureState();
}
class _DoorMeasureState extends State<DoorMeasure> {
var myFocusNode;
var textController = TextEditingController()..text = '';
#override
void initState() {
myFocusNode = new FocusNode();
}
#override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(5),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(100),
),
child: Container(
margin: const EdgeInsets.only(left: 10, bottom: 10, top: 10),
child: TextField(
onTap: () => myFocusNode.requestFocus(),
decoration: const InputDecoration(
labelText: ' Enter task',
border: InputBorder.none,
floatingLabelBehavior: FloatingLabelBehavior.never,
),
controller: textController,
focusNode: myFocusNode,
onSubmitted: (_) {
myFocusNode.requestFocus();
textController.clear();
},
),
),
),
),
CircleAvatar(
child: TextButton(
onPressed: () {
myFocusNode.requestFocus();
textController.clear();
},
child: const FittedBox(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
),
),
),
],
),
);
}
}

Why i gonna null of the String in Flutter?

I have a problem with a simple thing but I don't how is it happening in the code.
Below is the code:
Widget build(BuildContext context) {
String newTaskTitle;
return Container(
color: Color(0xff757575),
child: Container(
padding: EdgeInsets.all(20.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Add Task',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30.0,
color: Colors.lightBlueAccent,
),
),
TextField(
autofocus: true,
textAlign: TextAlign.center,
onChanged: (newText) {
newTaskTitle = newText;
},
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
print(newTaskTitle);
},
),
],
),
),
);
}
I try to get the value of the text field input and pass it to another screen but when I type something then press the button, it gives me the null.
You can also achieve this using controllers. just initialize one and specify the controller in the TextField widget. To access the text, just do _controlller.text as you can see below:
final _controller = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Color(0xff757575),
child: Container(
padding: EdgeInsets.all(20.0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(20.0),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Text(
'Add Task',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 30.0,
color: Colors.lightBlueAccent,
),
),
TextField(
controller: _controller,
autofocus: true,
textAlign: TextAlign.center,
),
FlatButton(
child: Text(
'Add',
style: TextStyle(
color: Colors.white,
),
),
color: Colors.lightBlueAccent,
onPressed: () {
print(_controller.text);
},
),
],
),
),
),
);
}
You have defined String newTaskTitle inside the build() method try removing it from inside the build method and try defining it inside the StatefulWidget.
This is happening because TextField on change method calls build() method every time the text is changed

How to use column inside single child scroll view flutter

I have a column inside a single child scroll view. I need to make my login screen scroll when I type using the keyboard because the keyboard hides the password text field.
class UserRegistration extends StatefulWidget {
#override
_UserRegistrationState createState() => _UserRegistrationState();
}
class _UserRegistrationState extends State<UserRegistration> {
#override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Color(0xFF6C62FF)
));
return SafeArea(
child: GestureDetector(
onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
child: Scaffold(
resizeToAvoidBottomInset: false,
resizeToAvoidBottomPadding: false,
backgroundColor: Color(0xFF6C62FF),
body: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: 30),
child: Column([![enter image description here][1]][1]
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Center(child: FittedBox(child: Text('Welcome', style: TextStyle(fontFamily: 'SourceSans', fontSize: 50, fontWeight: FontWeight.w600, color: Color(0xFFFFD700)),))),
Container(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Register', style: TextStyle(fontFamily: 'SourceSans', fontSize: 40, fontWeight: FontWeight.w600, color: Colors.white)),
SizedBox(height: 5,),
Text('Start from today', style: TextStyle(fontFamily: 'SourceSans', fontSize: 25, letterSpacing: 1.5,fontWeight: FontWeight.w600, color: Colors.white), overflow: TextOverflow.ellipsis,),
],
),
),
Form(
child: Column(
children: [
EditTextNormal(hintText: 'Email', iconData: Icons.email, textInputType: TextInputType.emailAddress, validate: false, errorText: 'Enter your email',),
SizedBox(height: 20,),
EditTextObscure(hintText: 'Password', iconData: Icons.lock, textInputType: TextInputType.text, validate: false, errorText: 'Enter your password',),
SizedBox(height: 50,),
Container(
height: 50,
width: 180,
child: FlatButton(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8)
),
onPressed: () {},
color: Colors.white,
child: Text('Register', style: TextStyle(color: Color(0xFF6C62FF), fontSize: 20), overflow: TextOverflow.ellipsis,),
),
)
],
),
),
Center(
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: 'Login', style: TextStyle(color: Color(0xFFFFD700), letterSpacing: 1, wordSpacing: 1.5))
],
text: 'Have an account? ',
style: TextStyle(fontSize: 18, fontFamily: 'SourceSans', fontWeight: FontWeight.bold, letterSpacing: 1, wordSpacing: 1.5)
),
),
),
],
),
),
),
),
);
}
}
This is my code but here when I use a column inside a single child scroll view space evenly does not work. Please give me a solution.
My output:
Expected Output:
Try This
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minWidth: MediaQuery.of(context).size.width,
minHeight: MediaQuery.of(context).size.height,
),
child: IntrinsicHeight(
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
// CONTENT HERE
],
),
),
),
),
);
}
Add Container inside SingleChildScrollView and assign it height based on your keyboard open or not.
Add Dependency:
dependencies:
keyboard_visibility: ^0.5.6
Initialize keyboard listener in initState() for callback
bool _isKeyBoardShown = false;
#protected
void initState() {
super.initState();
KeyboardVisibilityNotification().addNewListener(
onChange: (bool visible) {
setState(() {
_isKeyBoardShown = visible;
});
},
);
}
Based on _isKeyBoardShown value decide whether to add additional height on the screen or not.
Container(
width: MediaQuery.of(context).size.width,
height: _isKeyBoardShown
? MediaQuery.of(context).size.height +
MediaQuery.of(context).size.height / 2
: MediaQuery.of(context).size.height,
child: Column(....)
)
Note: Use MediaQuery to decide additional height don't use hard-coded values
here I used MediaQuery.of(context).size.height / 2

Flutter overflow bottom when keyboard appears

i got this error and i cant get why, in a new screen i got a simple form on top (start of the column), when i focus the textfield the keyboard appears and overflow the date select and the button, but i dont know why.
Here is the initial state whiout focus on the textfield
and here is when i focus the textfield.
This is the widget i got to do this.
return Scaffold(
body: SafeArea(
child: Column(
children: <Widget>[
TopBarWidget(page: 'New Event', title: 'Nuevo Evento'),
Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
onChanged: (value) {
eDisplayName = value;
},
maxLength: 18,
keyboardType: TextInputType.text,
textCapitalization: TextCapitalization.sentences,
cursorColor: Color(0xFFFC4A1A),
decoration: InputDecoration(
labelText: "Nombre del Evento",
fillColor: Colors.white,
border: new OutlineInputBorder(
borderRadius: new BorderRadius.circular(5.0),
),
),
),
SizedBox(
height: 16.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
OutlineButton(
focusColor: Theme.of(context).primaryColor,
highlightedBorderColor: Theme.of(context).primaryColor,
borderSide: BorderSide(
color: Theme.of(context).primaryColor,
),
textColor: Theme.of(context).primaryColor,
onPressed: () => _selectDate(context),
child: Text('Cambiar Fecha'),
),
Text(
"${formatedDate(selectedDate.toLocal())}",
style: TextStyle(
fontSize: 18.0,
fontWeight: FontWeight.w500,
color: Theme.of(context).primaryColor),
),
// Text("${selectedDate.toLocal()}"),
],
),
SizedBox(
height: 16.0,
),
RaisedButton(
disabledColor: Colors.grey[200],
disabledTextColor: Colors.black,
color: Theme.of(context).primaryColor,
textColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0)),
onPressed: eDisplayName.length == 0
? null
: () {
// print(newEvent);
Navigator.pop(context);
},
child: Text(
'ACEPTAR',
// style: TextStyle(fontSize: 20),
),
),
],
),
),
],
)),
);
Yo can set to false the resizeToAvoidBottomInset in your Scaffold()
Like this
return Scaffold(
resizeToAvoidBottomInset: false,
body: // ...
// ...
)
Documentation reference: Scaffold - resizeToAvoidBottomInset
It's beginner level problem. Don't know why most tutorial don't cover this problem before showing TextField Widget.
Column widget is fixed and does not scroll. So change Column to ListView. And do nothing else. The Widget will gain scroll feature and overflow problem will not happen anymore.

Categories

Resources