Trying to convert TextFormField - flutter

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));
},
),
],
),
),
);
}
}

Related

setState() or markNeedsBuild() called during build. (TextInputSettingsTile)

I'm new and I'm writing the settings section of my app in Flutter (I'm using this package: https://pub.dev/packages/flutter_settings_screens).
I get this error "setState() or markNeedsBuild() called during build." when the value of my TextInputSettingsTile changes.
I read a lot of information on the net but I still don't understand what is the problem.
This is my main.dart:
import 'package:flutter/material.dart';
import 'pages/home.dart';
import 'pages/settings_page.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
Future main() async {
await Settings.init(cacheProvider: SharePreferenceCache());
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const LoginPage(title: 'TEST'),
);
}
}
class LoginPage extends StatefulWidget {
const LoginPage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<LoginPage> createState() => LoginPageState();
}
class LoginPageState extends State<LoginPage> {
final _username = TextEditingController();
final _password = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('TEST'),
actions: <Widget>[
IconButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SettingsPage()),
);
},
icon: const Icon(Icons.settings))
],
),
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(
20, 0, 20, 10),
child: TextField(
controller: _username,
decoration: InputDecoration(
icon: const Icon(Icons.email),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'username'),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(
20, 5, 20, 10),
child: TextField(
controller: _password,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: InputDecoration(
icon: const Icon(Icons.password_rounded),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
labelText: 'password'),
)),
ElevatedButton(
onPressed: () => {},
child: const Text('LOGIN'))
],
),
),
);
}
}
This is my settings general page:
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'settings/connection_page.dart';
class SettingsPage extends StatefulWidget {
#override
SettingsPageState createState() => SettingsPageState();
}
class SettingsPageState extends State<SettingsPage> {
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Settings')
),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.all(12),
children: [
const SizedBox(height: 5,),
SettingsGroup(
title: 'GENERAL', children: const <Widget>[
ConnectionPage()
]
),
],
),
),
);
}
This is my settings specific page (where I'm getting the error):
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class ConnectionPage extends StatelessWidget {
const ConnectionPage({Key? key}) : super(key: key);
static const keyServer = 'key-server';
#override
Widget build(BuildContext context) => SimpleSettingsTile(
title: 'Connection',
subtitle: 'Parameters',
leading: const FaIcon(FontAwesomeIcons.clipboardList),
child: SettingsScreen(
title: 'Connection',
children: <Widget>[
buildServer(),
],
),
);
Widget buildServer() => TextInputSettingsTile(
settingKey: keyServer,
title: 'Server',
initialValue: ''
);
}
What can I do in order to fix this error?
Thank you all.
Some method underneath it is calling a setState during a build. Identify it and use the addPostFrameCallback method.
Example:
import 'package:flutter/material.dart';
import 'package:flutter_settings_screens/flutter_settings_screens.dart';
import 'settings/connection_page.dart';
class SettingsPage extends StatefulWidget {
#override
SettingsPageState createState() => SettingsPageState();
}
class SettingsPageState extends State<SettingsPage> {
#override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Settings')
),
body: SafeArea(
child: ListView(
padding: const EdgeInsets.all(12),
children: [
const SizedBox(height: 5,),
WidgetsBinding.instance.addPostFrameCallback((_){
SettingsGroup(
title: 'GENERAL', children: const <Widget>[
ConnectionPage()
]),
});
],
),
),
);
}
Try verify as ths example. Try wrapping it into WidgetsBinding.instance.addPostFrameCallback((_)

TextFormField obscureText in AlertDialog don't change

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:',
),
],
),
),
);
}
}

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.

Geting inserted data of text field into a listview in the previous screen

I am new in flutter , i am trying to get the data inserted in the text field into a list and show this list into the previous screen.
I had made two screen in first screen we navigate to the first screen and on second screen i have three text fields from witch i want to fetch the data into a new list and show this list into the previous screen someone if getting what i am trying to say please help thanks in advance.
this is my main page
import "package:flutter/material.dart";
import 'second.dart';
void main() {
runApp(new MaterialApp(home: new MyApp(),
routes: <String, WidgetBuilder>{
"/Data": (BuildContext context) => new Data()
}));
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("NOTE bOOK"),
),
body: new Container(
),
floatingActionButton: new FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed("/Data");
},
child: new Icon(Icons.add))),
);
}
this is my second page
import 'package:flutter/material.dart';
import 'package:flutter_apptasktwo/main.dart';
class Data extends StatefulWidget {
#override
_DataState createState() => _DataState();
}
class _DataState extends State<Data> {
List<String> messages = List();
var _textController = new TextEditingController();
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Color(0xff84FFFF),
appBar: AppBar(
title: Text("List"),
),
body: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new
TextField(
controller : _textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Hint text '
)
),
new
TextField(
controller : _textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Hint date'
)
),
new
TextField(
controller : _textController,
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Hint discription '
),
),
FloatingActionButton(
onPressed: () {
Navigator.pop(context ,MyApp());
},
child: Icon(Icons.save),
backgroundColor: Colors.green,
),
],
)
),
);
}
}
}
class HomeScreen extends StatefulWidget {
#override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String returned = 'Retuned text will appear here..';
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Text('Returning Data Demo'),
),
body: Center(
child: Column(children: [
Text(returned, style: TextStyle(color: Colors.black)),
RaisedButton(
onPressed: () async {
var someValue = await Navigator.of(context)
.push(MaterialPageRoute(builder: (con) => SelectionScreen()));
print(someValue);
if (someValue != null && someValue.toString().isNotEmpty) {
setState(() {
returned = someValue.toString();
});
}
},
child: Text('Get Values', style: TextStyle(color: Colors.white)),
)
])),
);
}
}
class SelectionScreen extends StatefulWidget {
#override
_SelectionScreenState createState() => _SelectionScreenState();
}
class _SelectionScreenState extends State<SelectionScreen> {
TextEditingController c1, c2, c3;
//and son on....
#override
void initState() {
super.initState();
c1 = TextEditingController();
c2 = TextEditingController();
c3 = TextEditingController();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Pick an option'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
controller: c1,
),
TextField(
controller: c2,
),
TextField(
controller: c3,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
onPressed: () {
// Close the screen and return "Nope!" as the result.
Navigator.pop(context, [c1.text, c2.text, c3.text]);
},
child: Text('Submit'),
),
)
],
),
),
);
}
}

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))));
});
});
}),
],
),
),
);
}
}