TextFormField obscureText in AlertDialog don't change - flutter

I want to change the obscureText mode of a TextFormField in an AlertDialog but it doesn't work
Clicking the IconButton does not change
the obscureText to TextFormField in AlertDialog
I want to change the obscureText mode of a TextFormField in an AlertDialog but it doesn't work
Clicking the IconButton does not change
the obscureText to TextFormField in AlertDialog
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final username = TextEditingController(text: '');
final password = TextEditingController(text: '');
final formKey = GlobalKey<FormState>();
late bool obscure;
#override
void initState() {
obscure = true;
super.initState();
}
#override
void dispose() {
username.dispose();
password.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
IconButton(
onPressed: () {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) {
return AlertDialog(
title: const Text('Connection'),
content: SizedBox(
height: 400,
width: 400,
child: Form(
key: formKey,
child: Column(
children: <Widget>[
TextFormField(
cursorColor: Colors.grey,
textInputAction: TextInputAction.next,
maxLines: 1,
controller: username,
validator: (value) {
return null;
},
decoration: const InputDecoration(
isDense: true,
prefixIcon: Icon(
Icons.person_outlined,
),
labelText: 'username',
),
),
const SizedBox(
height: 20.0,
),
TextFormField(
cursorColor: Colors.grey,
controller: password,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.key),
labelText: 'password',
suffixIcon: IconButton(
icon: const Icon(
Icons.remove_red_eye_outlined),
onPressed: () {
// CHAGE OBSCURE
setState(() {
obscure = !obscure;
if (kDebugMode) {
print(obscure); // OK
}
});
}),
),
obscureText: obscure, // NOT OK
obscuringCharacter: '*',
validator: (String? value) {
return null;
},
),
],
),
)),
actions: [
TextButton(
child: const Text('Send'),
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.of(context).pop();
}
},
),
],
);
});
},
icon: const Icon(Icons.person_outline_outlined),
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text(
'You have pushed the button this many times:',
),
],
),
),
);
}
}

For that you have to use StatefulBuilder to use setState inside Dialog and update Widgets only inside of it.
Reason: setState is having different context inside the AlertDialog, so If you want to maintain the state of AlertDialog you must have to use StatefulBuilder. It will maintain another state for your AlertDialog
Full Working Code:
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final username = TextEditingController(text: '');
final password = TextEditingController(text: '');
final formKey = GlobalKey<FormState>();
late bool obscure;
#override
void initState() {
obscure = true;
super.initState();
}
#override
void dispose() {
username.dispose();
password.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
IconButton(
onPressed: () {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) {
return StatefulBuilder(
builder: (context, setState)
{
return AlertDialog(
title: const Text('Connection'),
content: SizedBox(
height: 400,
width: 400,
child: Form(
key: formKey,
child: Column(
children: <Widget>[
TextFormField(
cursorColor: Colors.grey,
textInputAction: TextInputAction.next,
maxLines: 1,
controller: username,
validator: (value) {
return null;
},
decoration: const InputDecoration(
isDense: true,
prefixIcon: Icon(
Icons.person_outlined,
),
labelText: 'username',
),
),
const SizedBox(
height: 20.0,
),
TextFormField(
cursorColor: Colors.grey,
controller: password,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.key),
labelText: 'password',
suffixIcon: IconButton(
icon: const Icon(Icons.remove_red_eye_outlined),
onPressed: () {
// CHAGE OBSCURE
setState(() {
obscure = !obscure;
if (kDebugMode) {
print(obscure); // OK
}
});
}),
),
obscureText: obscure,
// NOT OK
obscuringCharacter: '*',
validator: (String? value) {
return null;
},
),
],
),
)),
actions: [
TextButton(
child: const Text('Send'),
onPressed: () {
if (formKey.currentState!.validate()) {
Navigator.of(context).pop();
}
},
),
],
);
});
});
},
icon: const Icon(Icons.person_outline_outlined),
),
],
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const <Widget>[
Text(
'You have pushed the button this many times:',
),
],
),
),
);
}
}

Related

Trying to convert TextFormField

I am trying to convert TextEditingController into int because I want to delete the user ID from database by using TextEditingController.
look at: (<-------) in the code to understand.
and here is my code:
import 'package:flutter/material.dart';
import 'package:untitled/database.dart';
import './model/columns.dart';
import './database.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
void dispose() {
textController.dispose();
super.dispose();
}
final textController = TextEditingController();
int? selectedId;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("App"),
),
body: Form(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: TextField(
controller: textController,
decoration: InputDecoration(
labelText: "Insert row",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25))),
),
),
ElevatedButton(
child: Icon(Icons.save),
onPressed: () async {
await DatabaseHelper.instance
.insert(Users(name: textController.text));
setState(() {
textController.clear();
});
print("Inserted!");
},
),
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
//controller: selectedId, // <-------
decoration: InputDecoration(
labelText: "Delete ID",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25))),
keyboardType: TextInputType.number,
),
),
ElevatedButton(
child: Icon(Icons.delete),
onPressed: () async {
DatabaseHelper.instance.delete(selectedId!); // <-------
},
),
ElevatedButton(
child: Text("Check all rows"),
onPressed: () async {
print(await DatabaseHelper.instance.queryAll());
},
),
],
),
)),
);
}
}
Create another controller then pass as the entered data as int by converting with int.parse(yourcontroller.text)
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final textController = TextEditingController();
final numberController = TextEditingController();
#override
void dispose() {
textController.dispose();
numberController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
controller: numberController,
decoration: InputDecoration(
labelText: "Delete ID",
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(25))),
keyboardType: TextInputType.number,
),
),
ElevatedButton(
child: Icon(Icons.delete),
onPressed: () async {
DatabaseHelper.instance.delete(int.parse(numberController.text));
print(int.parse(numberController.text));
},
),
],
),
),
);
}
}

Flutter showTextInputDialog usage

I'm new to Flutter and I'm stuck here.
I'm trying to use Dialog box to get user input but I don't know how to process the data after submitting the value.
I'm using adaptive_dialog: ^1.0.0 dependency here.
child: ListTile(
title: Text('Change Age'),
onTap: () {
showTextInputDialog(
context: context,
title: 'Enter your Age!',
textFields: [
DialogTextField(
keyboardType: TextInputType.number,
hintText: '18',
)
],
okLabel: 'Submit',
cancelLabel: 'Cancel',
);
},
),
Dialog box to get user input
import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int age = 0;
TextEditingController ageController = new TextEditingController();
Future<void> _displayTextInputDialog(BuildContext context) async {
return showDialog(
context: context,
builder: (context) {
ageController.text="";
return AlertDialog(
title: Text('Enter your age'),
content: TextField(
onChanged: (value) {
setState(() {
age = int.parse(value);
});
},
controller: ageController,
decoration: InputDecoration(hintText: "18"),
),
actions: <Widget>[
// ignore: deprecated_member_use
FlatButton(
//color: Colors.red,
//textColor: Colors.white,
child: Text('CANCEL'),
onPressed: () {
setState(() {
Navigator.pop(context);
});
},
),
// ignore: deprecated_member_use
FlatButton(
//color: Colors.green,
//textColor: Colors.white,
child: Text('OK'),
onPressed: () {
setState(() {
// age = int.parse(value);
Navigator.pop(context);
});
},
),
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: [
ListTile(
title: Text('Change Age'),
onTap: () {
_displayTextInputDialog(context);
},
),
Text(age.toString())
],
),
),
);
}
}
You can use .then and the index of the textField to get the value
showTextInputDialog(
context: context,
title: "Enter your Age!",
message: 'Age here',
okLabel: "Submit",
cancelLabel: "Cancel",
barrierDismissible: false,
textFields: [
const DialogTextField(
keyboardType: TextInputType.number,
hintText: '18',
)
],
).then((value) {
return debugPrint(value![0]);
}
);

Flutter - Choose text from TopDownMenu with a number attached to it and take this number into a calculation

I am here once again asking for your support. I have no idea how to do this.
I have a code that multiplys values from textfields, now i want to add a value from a dropdown menu into the calculation.
Can you please show me how? I have already made a list for the values:
final _materials = const [
{
'Type': [
{'material': 'Stahl', 'dichte': 7.87},
{'material': 'Zamak', 'dichte': 6.7},
{'material': 'Aluminium', 'dichte': 2.7},
],
}
];
I don't know if this is the correct format. The goal is, if you e.g. take "Stahl" from the Dropdown:
DropdownButton(items: null, onChanged: null),
the value "dichte" (7.87) should be put into the calculation:
void _calculation() {
setState(
() {
_volume = int.parse(lenCon.text) *
int.parse(widCon.text) *
int.parse(higCon.text) *
'dichte';
},
);
print(_volume);
}
Here is the complete Code:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _volume;
#override
initState() {
_volume = 0;
}
void _calculation() {
setState(
() {
_volume = int.parse(lenCon.text) *
int.parse(widCon.text) *
int.parse(higCon.text) *
'dichte';
},
);
print(_volume);
}
final lenCon = TextEditingController();
final widCon = TextEditingController();
final higCon = TextEditingController();
final _materials = const [
{
'Type': [
{'material': 'Stahl', 'dichte': 7.87},
{'material': 'Zamak', 'dichte': 6.7},
{'material': 'Aluminium', 'dichte': 2.7},
],
}
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: lenCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Länge',
),
),
TextField(
controller: widCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Breite',
),
),
TextField(
controller: higCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Höhe',
),
),
DropdownButton(items: null, onChanged: null),
RaisedButton(
onPressed: (_calculation),
child: Text('Berechnen'),
),
Text('Your Volume is: $_volume'),
],
),
),
),
);
}
}
Thanks in advance!
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double _volume = 0;
double dropValue = 0.0;
var selectedValue;
void _calculation() {
print(lenCon.text +
" " +
widCon.text +
" " +
higCon.text +
" " +
dropValue.toString());
setState(
() {
_volume = int.parse(lenCon.text) *
int.parse(widCon.text) *
int.parse(higCon.text) *
dropValue;
},
);
print(_volume);
}
final lenCon = TextEditingController();
final widCon = TextEditingController();
final higCon = TextEditingController();
final _materialsTypes = [
{'material': 'Stahl', 'dichte': 7.87},
{'material': 'Zamak', 'dichte': 6.7},
{'material': 'Aluminium', 'dichte': 2.7}
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: lenCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Länge',
),
),
TextField(
controller: widCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Breite',
),
),
TextField(
controller: higCon,
keyboardType: TextInputType.number,
decoration: InputDecoration(
hintText: 'Höhe',
),
),
DropdownButton(
hint: new Text("Select a Material"),
value: selectedValue,
items: _materialsTypes.map((value) {
return new DropdownMenuItem(
value: value["dichte"],
child: new Text(value["material"]),
);
}).toList(),
onChanged: (item) {
setState(() {
try {
dropValue = item;
selectedValue = item;
} catch (e) {
print(e);
}
});
print(item);
}),
// DropdownButton(items: null, onChanged: null),
RaisedButton(
onPressed: (_calculation),
child: Text('Berechnen'),
),
Text('Your Volume is: $_volume'),
],
),
),
),
);
}
}
here is your solution bro.

Flutter - Change text input type and input formatters dynamically on tap

I want to change the text input type and input formatters of a text field dynamically on tap. But the problem is once the text input type is done it is not changed on tap whereas the label text acts as expected.
I have done like below
bool joinlinkname = false;
joinchanged() {
if (joinlinkname == false) {
setState(() {
joinlinkname = true;
});
} else {
setState(() {
joinlinkname = false;
});
}
}
TextField(
keyboardType: joinlinkname? TextInputType.text : TextInputType.phone,
labelText: joinlinkname ? 'num' : "text",
inputFormatters: [joinlinkname ?
FilteringTextInputFormatter.allow(RegExp('[azAZ09]')):FilteringTextInputFormatter.allow(RegExp('[0-9]')),
],
),
GestureDetector(
onTap: () {
joinchanged();
},
child: Text(joinlinkname ? 'number' : 'text',
style: TextStyle(
color: Colors.blue,
fontSize: 12,
),
),
),
Please can anyone tell how to do it?
You can copy paste run full code below
You can use ValueListenableBuilder and ValueNotifier
You also need FocusNode to control keyboard
You can see working demo below
code snippet
final ValueNotifier<bool> joinlinkname = ValueNotifier<bool>(false);
...
joinchanged() async {
FocusManager.instance.primaryFocus.unfocus();
joinlinkname.value = !joinlinkname.value;
await Future.delayed(Duration(milliseconds: 500), () {});
myFocusNode.requestFocus();
}
...
ValueListenableBuilder(
builder: (BuildContext context, bool value, Widget child) {
return Column(
children: [
GestureDetector(
onTap: () {
joinchanged();
},
child: Text(
joinlinkname.value ? 'number' : 'text',
style: TextStyle(
color: Colors.blue,
fontSize: 12,
),
),
),
TextField(
focusNode: myFocusNode,
keyboardType: joinlinkname.value
? TextInputType.phone
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final ValueNotifier<bool> joinlinkname = ValueNotifier<bool>(false);
FocusNode myFocusNode;
#override
void initState() {
super.initState();
myFocusNode = FocusNode();
}
#override
void dispose() {
myFocusNode.dispose();
super.dispose();
}
joinchanged() async {
FocusManager.instance.primaryFocus.unfocus();
joinlinkname.value = !joinlinkname.value;
await Future.delayed(Duration(milliseconds: 500), () {});
myFocusNode.requestFocus();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Center(
child: ValueListenableBuilder(
builder: (BuildContext context, bool value, Widget child) {
return Column(
children: [
GestureDetector(
onTap: () {
joinchanged();
},
child: Text(
joinlinkname.value ? 'number' : 'text',
style: TextStyle(
color: Colors.blue,
fontSize: 12,
),
),
),
TextField(
focusNode: myFocusNode,
keyboardType: joinlinkname.value
? TextInputType.phone
: TextInputType.text,
decoration: InputDecoration(
labelText: joinlinkname.value ? 'num' : "text",
),
inputFormatters: [
joinlinkname.value
? FilteringTextInputFormatter.allow(RegExp('[0-9]'))
: FilteringTextInputFormatter.allow(RegExp('[azAZ09]')),
],
),
],
);
},
valueListenable: joinlinkname,
),
),
);
}
}

My setState does not refresh after receiving user input. I'm trying to build a chat page

`final myController = TextEditingController();
#override
void dispose() {
myController.dispose();
}`
This creates a controller for the text input
`Widget textField(String hint, TextInputType type) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: CupertinoTextField(
minLines: 1,
maxLines: null,
controller: myController,
textCapitalization: TextCapitalization.sentences,
placeholder: hint,
placeholderStyle: TextStyle(color: hintcolor),
keyboardType: type,
style: TextStyle(color: secondarycolor),
),
);
}`
This creates the text field with the controller
`Expanded(child: textField('Type a message', TextInputType.multiline)),
IconButton(
icon: Icon(
Icons.send,
color: profilesecondarycolor,
),
onPressed: () {
messagesTo.add(myController.text);
Future.delayed(Duration(seconds: 1), () {
return setState(() {
messages = messagesTo.map((content) {
Card(child: Text(content));
}).toList();
});
});
})`
This is the button that is supposed to add the text to the list
`body: ListView(children: messagesTo == null ? chats : messages),`
This is supposed to show the list
`List<Widget> messages;
List<String> messagesTo;
List<Widget> chats = [Text('Welcome')];`
Defining the terms
It just shows welcome and when i click the button, nothing happens... please help
You can copy paste run full code below
Some parts of your code need to change, you can check full code for detail
code snippet
List<Widget> messages = [];
List<String> messagesTo = [];
Widget chats = Text('Welcome');
onPressed: () {
messagesTo.add(myController.text);
Future.delayed(Duration(seconds: 1), () {
setState(() {
messages = [];
messagesTo.forEach((content) =>
messages.add(Card(child: Text(content))));
});
});
}
...
messages.length == 0
? chats
: Container(
height: 200,
child: ListView(shrinkWrap: true, children: messages)),
working demo
full code
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final myController = TextEditingController();
List<Widget> messages = [];
List<String> messagesTo = [];
Widget chats = Text('Welcome');
Widget textField(String hint, TextInputType type) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: CupertinoTextField(
minLines: 1,
maxLines: null,
controller: myController,
textCapitalization: TextCapitalization.sentences,
placeholder: hint,
placeholderStyle: TextStyle(color: Colors.blue),
keyboardType: type,
style: TextStyle(color: Colors.red),
),
);
}
#override
void dispose() {
myController.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: true,
//resizeToAvoidBottomPadding: true,
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
messages.length == 0
? chats
: Container(
height: 200,
child: ListView(shrinkWrap: true, children: messages)),
Container(
height: 50,
child: textField('Type a message', TextInputType.multiline)),
IconButton(
icon: Icon(
Icons.send,
color: Colors.yellow,
),
onPressed: () {
messagesTo.add(myController.text);
Future.delayed(Duration(seconds: 1), () {
setState(() {
messages = [];
messagesTo.forEach((content) =>
messages.add(Card(child: Text(content))));
});
});
}),
],
),
),
);
}
}