I cant update the UI or widgets even with the StatefulWidget - flutter

I want to update the height of the first alertDialog right after I press the "increse the height" in the secoundDialog but it didn't change
this is my code:
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
// this is the firt value of the height
double heightSize = 200;
#override
Widget build(BuildContext context) {
return Container(
child: FloatingActionButton(
onPressed: () async {
setState(() {
print('the size0 is $heightSize');
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Container(
padding: EdgeInsets.only(
left: 10, right: 10, top: 5, bottom: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Download File',
style: TextStyle(
color: Color.fromARGB(255, 83, 82, 82),
fontSize: 20),
),
],
),
),
content: Container(
// I want to change to 500 right after I press the button
height: heightSize,
child: Column(
children: [
IconButton(
onPressed: () {
setState(() {
print('the size1 is $heightSize');
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
content: GestureDetector(
child: Text(
'increase the height '),
onTap: () {
setState(() {
// this is the button I want to change to 500
heightSize = 500;
print(
'the size2 is $heightSize');
Navigator.pop(context);
});
},
),
);
},
);
},
);
});
},
icon: Icon(FontAwesomeIcons.paste))
],
),
),
);
},
);
},
);
});
},
),
);
}
}
if I close the two of the alert-dialog and press floating button it work but I want to change right after I press the increase Size button
I try the set state but it doesnt work

Try to use async method like
onPressed: () async {
await showDialog(...);
setState(() {});
print('the size1 is $heightSize');
},
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
#override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
double heightSize = 200;
#override
Widget build(BuildContext context) {
return Container(
child: FloatingActionButton(
onPressed: () async {
setState(() {
print('the size0 is $heightSize');
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
title: Container(
padding: EdgeInsets.only(
left: 10, right: 10, top: 5, bottom: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Download File',
style: TextStyle(
color: Color.fromARGB(255, 83, 82, 82),
fontSize: 20),
),
],
),
),
content: Container(
// I want to change to 500 right after I press the button
height: heightSize,
child: Column(
children: [
IconButton(
onPressed: () async {
await showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
content: GestureDetector(
child:
Text('increase the height '),
onTap: () {
setState(() {
// this is the button I want to change to 500
heightSize = 500;
print(
'the size2 is $heightSize');
Navigator.pop(context);
});
},
),
);
},
);
},
);
setState(() {});
print('the size1 is $heightSize');
},
icon: Icon(Icons.paste))
],
),
),
);
},
);
},
);
});
},
),
);
}
}

Related

how can I make the item made in listview by user clickable into a new page? in flutter

hi I have a page that you can create an item in the listview and give it a name, now I want to when you click on that item, it goes to own dedicated page made with its name on the app bar.
(https://i.stack.imgur.com/5jS0x.png)
here is the listview code:
import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';
import 'package:attendance/insideList.dart';
class lists extends StatefulWidget {
const lists({super.key});
#override
State<lists> createState() => _listsState();
}
class _listsState extends State<lists> {
List<String> _items = [];
late TextEditingController _textController;
#override
void initState() {
super.initState();
_textController = TextEditingController();
}
#override
void dispose() {
_textController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
_items.sort();
return Scaffold(
body: _items.length > 0
? ListView.separated(
itemCount: _items.length,
itemBuilder: (_, index) {
return ListTile(
leading: const Icon(Icons.school),
trailing: const Icon(Icons.arrow_forward),
title: Center(child: Text('${_items[index]}')),
**//here the attempt I made that didnt work**
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => InsideList(index))));
},
onLongPress: (() async {
await showDialog(
context: context,
builder: ((context) {
return AlertDialog(
title: const Text(
"Are you sure you want to delete this class?",
style: TextStyle(fontSize: 15),
),
actions: [
TextButton(
child: Text("cancel"),
onPressed: (() {
Navigator.pop(context);
})),
TextButton(
child: Text('Delete'),
onPressed: () {
setState(() {
_items.removeAt(index);
Navigator.pop(context);
});
},
),
],
);
}));
}),
);
},
separatorBuilder: (BuildContext context, int index) =>
const Divider(
color: Colors.black,
),
)
: const Center(
child: Text("You currently have no classes. Add from below."),
),
floatingActionButton: SpeedDial(
animatedIcon: AnimatedIcons.menu_arrow,
spacing: 6,
spaceBetweenChildren: 6,
backgroundColor: const Color.fromARGB(255, 22, 37, 50),
foregroundColor: const Color.fromARGB(255, 255, 255, 255),
children: [
SpeedDialChild(
child: const Icon(Icons.group_add), label: "add student"),
SpeedDialChild(
child: const Icon(Icons.school),
label: "add class",
onTap: () async {
final result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: const Text('Add a new class'),
content: TextField(
controller: _textController,
autofocus: true,
decoration: const InputDecoration(
hintText: "Enter the name of the class."),
),
actions: [
TextButton(
child: Text('Cancel'),
onPressed: () {
Navigator.pop(context);
},
),
TextButton(
child: Text('Add'),
onPressed: () {
Navigator.pop(context, _textController.text);
_textController.clear();
},
),
],
);
},
);
if (result != null) {
result as String;
setState(() {
_items.add(result);
});
}
},
)
],
),
);
}
}
and this is the new dart file I made for the new page:
import 'package:flutter/material.dart';
class InsideList extends StatelessWidget {
final int index;
InsideList(this.index);
List<String> _students = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("attendance"),
centerTitle: true,
backgroundColor: const Color.fromARGB(255, 22, 37, 50),
toolbarHeight: 65,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(30),
),
),
),
body: _students.length > 0
? Center(child: Text("hi"))
: Center(
child:
Text("You currently have no students. Add from below.")));
}
}
Instead of passing index, you can pass the item itself,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => InsideList(_items[index])),
),
);
},
And
class InsideList extends StatelessWidget {
final String name;
InsideList(this.name); // use key constructor
List<String> _students = [];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("attendance $name"),

Flutter Sqflite Toggling between Screens based on Login Status creates null operator used on null value error

I am trying to toggle between Login Screen and HomeScreen based on the user status. The logic seems to be working as long as I don't put HomeScreen.
I replaced HomeScreen with a different screen to check and the app works as it should. It displays different screens on hot restart based on the user's login status. But as soon as I try to put HomeScreen I get null operator used on null value error.
Here is the toggle logic.
class Testing extends StatefulWidget {
const Testing({super.key});
#override
State<Testing> createState() => _TestingState();
}
class _TestingState extends State<Testing> {
#override
Widget build(BuildContext context) {
return FutureBuilder(
future: TodoServiceHelper().checkifLoggedIn(),
builder: ((context, snapshot) {
if (!snapshot.hasData) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
}
if (snapshot.hasError) {
print(snapshot.hasError);
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
}
if (snapshot.data!.isNotEmpty) {
print(snapshot.data);
return RegisterPage();
// returning HomePage gives null check operator used on null value error
} else
return Login();
}),
);
}
}
Here is the HomeScreen
class HomePage extends StatefulWidget {
String? username;
HomePage({this.username});
#override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final GlobalKey<FormState> formKey = GlobalKey();
TextEditingController termController = TextEditingController();
void clearText() {
termController.clear();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(
onPressed: () {
User loginUser =
User(username: widget.username.toString(), isLoggedIn: false);
TodoServiceHelper().updateUserName(loginUser);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (BuildContext context) => Login()));
},
icon: Icon(Icons.logout),
color: Colors.white,
)
],
title: FutureBuilder(
future: TodoServiceHelper().getTheUser(widget.username!),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
}
return Text(
'Welcome ${snapshot.data!.username}',
style: TextStyle(color: Colors.white),
);
}),
),
body: SingleChildScrollView(
child: Column(children: [
Column(
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: Form(
key: formKey,
child: Column(
children: <Widget>[
TextFormField(
controller: termController,
decoration: InputDecoration(
filled: true,
fillColor: Colors.white,
enabledBorder: OutlineInputBorder(),
labelText: 'search todos',
),
),
TextButton(
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ShowingSerachedTitle(
userNamee: widget.username!,
searchTerm: termController.text,
)),
);
print(termController.text);
clearText();
setState(() {});
},
child: Text(
'Search',
)),
Divider(
thickness: 3,
),
],
),
),
),
],
),
Container(
child: Stack(children: [
Positioned(
bottom: 0,
child: Text(
' done Todos',
style: TextStyle(fontSize: 12),
),
),
IconButton(
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
CheckingStuff(userNamee: widget.username!)),
);
setState(() {});
},
icon: Icon(Icons.filter),
),
]),
),
Divider(
thickness: 3,
),
Container(
child: TodoListWidget(name: widget.username!),
height: 1000,
width: 380,
)
]),
),
floatingActionButton: FloatingActionButton(
backgroundColor: Color.fromARGB(255, 255, 132, 0),
onPressed: () async {
await showDialog(
barrierDismissible: false,
context: context,
builder: ((context) {
return AddNewTodoDialogue(name: widget.username!);
}),
);
setState(() {});
},
child: Icon(Icons.add),
),
);
}
}
The function used to return user with loginStatus true
Future<List<User>> checkifLoggedIn() async {
final Database db = await initializeDB();
final List<Map<String, Object?>> result = await db.query(
'users',
where: 'isLoggedIn = ?',
whereArgs: ['1'],
);
List<User> filtered = [];
for (var item in result) {
filtered.add(User.fromMap(item));
}
return filtered;
}
the problem is here
you used ! sign on a nullable String , and this string is nullable,
try to use this operation (??) so make it
widget.username??"" by this line you will check if the user name is null it will be replaced by an empty string.

How to automatically close a dialog box without clicking in flutter?

I have a dialog box, when I click on the Send Again button, I make a request to the server and, if successful, another _emailSentDialog dialog box opens from above. How can I make the first EmailVerifyDialog automatically close when the second _emailSentDialog is opened?
class EmailVerifyDialog extends StatelessWidget {
final CurrentEmailCubit cubit;
const EmailVerifyDialog({Key? key, required this.cubit}) : super(key: key);
#override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return AlertDialogGradientBorder(
height: size.height * .5,
child: SizedBox(
width: size.width,
child: Padding(
padding: const EdgeInsets.only(bottom: 35),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 45),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
children: [
WidgetSpan(
child: FittedBox(
child: Row(
children: [
const Text(
'Didn’t recieve a link? ',
style: constants.Styles.smallBookTextStyleWhite,
),
TextButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero),
onPressed: () async {
await cubit
.sendConfirmationCode(
email: cubit.currentEmail)
.then((value) => {
if (value)
{
_emailSentDialog(context),
}
else
{
_errorNotification(context),
}
});
log(cubit.currentEmail);
},
child: const Text(
'Send Again',
style: constants
.Styles.smallBookUnderlineTextStyleWhite,
),
),
],
),
),
),
],
),
),
),
],
),
),
),
);
}
void _closeDialog(BuildContext context) {
Navigator.pop(context);
}
void _emailSentDialog(context) async {
showDialog(
context: context,
builder: (BuildContext context) => const EmailSentDialog(),
);
}
I was referring this way
onPressed: () async {
setState(() {
text = "checking on Server";
});
final showSecondDialog = await serverResult();
if (showSecondDialog) {
if (!mounted) return;
Navigator.of(context).pop();
showDialog2(context);
}
},
class TestDialogActivity extends StatefulWidget {
const TestDialogActivity({Key? key}) : super(key: key);
#override
State<TestDialogActivity> createState() => _TestDialogActivityState();
}
class _TestDialogActivityState extends State<TestDialogActivity> {
showDialog2(context) async {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () async {
Navigator.of(context).pop();
},
child: Text(" close Second dialog "))
],
),
),
);
}
Future<bool> serverResult() async {
await Future.delayed(Duration(seconds: 1));
return true;
}
showDialog1(context) async {
String text = "sendAgain";
showDialog(
context: context,
builder: (context) => StatefulBuilder(
builder: (context, setState) => AlertDialog(
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextButton(
onPressed: () async {
setState(() {
text = "checking on Server";
});
final showSecondDialog = await serverResult();
if (showSecondDialog) {
if (!mounted) return;
Navigator.of(context).pop();
showDialog2(context);
}
},
child: Text("$text"))
],
),
),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () => showDialog1(context),
),
);
}
}

Flutter Speech to text navigate next Sacreen after finishing up the speech

Hello friends my problem is that I want perform task there small icon on menu bar mic icon when user click on Mic it show dialog box and when they speak text word appear on dialog box when user finished up there speech it's goes to next screen I have done all thing but problem is that when user finishing there speech i unable to go on next sacreen this only issue any expert can help here is picture below what i actually i want
Here is when user speech
When they complete their speech go next sacreen
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
import 'package:speech_to_text/speech_to_text.dart';
import 'package:avatar_glow/avatar_glow.dart';
class Booknames extends StatefulWidget {
const Booknames({Key? key}) : super(key: key);
#override
_BooknamesState createState() => _BooknamesState();
}
class _BooknamesState extends State<Booknames> {
stt.SpeechToText speechToText = stt.SpeechToText();
bool islistening = false;
late String text = 'Example:Gensis chapter verse 5';
bool complete=false;
#override
void initState() {
// TODO: implement initState
super.initState();
_initSpeech();
}
/// This has to happen only once per app
void _initSpeech() async {
speechToText.initialize();
}
final GlobalKey _dialogKey = GlobalKey();
_showDialog() async {
showDialog(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return StatefulBuilder(
key: _dialogKey,
builder: (context, setState) {
return Container(
child: Dialog(
child: Padding(
padding: EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AvatarGlow(
glowColor: Colors.blue,
endRadius: 80,
duration: Duration( milliseconds: 2500),
repeat: true,
showTwoGlows: true,
repeatPauseDuration: Duration( milliseconds: 150),
child: Material(
elevation: 5,
shape: CircleBorder(),
child: CircleAvatar(
backgroundColor: Colors.white,
child: Icon(Icons.mic, color: Colors.blue, size: 40,),
radius: 40,
),
),
),
Text(text),
SizedBox(height: 10),
TextButton(
onPressed: () => Navigator.pop(context, false), // passing false
child: Text('Cancel Voice'),
),
],
),
),
),
);
},
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
new IconButton(
icon: new Icon(islistening ? Icons.mic : Icons.mic_none),
highlightColor: Colors.pink,
onPressed: () {
setState(() {
_listen();
_showDialog();
});
},
),
],
elevation: 0,
title: Text('The Bible Multiversion', style: TextStyle(
fontSize: 20
),),
centerTitle: true,
),
body: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: ListView.separated(
shrinkWrap: true,
itemCount: 1,
separatorBuilder: (BuildContext context, int index) =>
Divider(height: 1),
itemBuilder: (context, index) {
return Column(
children: [
],
);
},
),
),
],
),
);
}
void _listen() async {
if (!islistening) {
bool available = await speechToText.initialize(
onStatus: (val) => print('onStatus: $val'),
onError: (val) => print('onError: $val'),
);
if (available) {
setState(() {
islistening = true;
});
speechToText.listen(
onResult: (result) =>
setState(() {
text = result.recognizedWords;
if (_dialogKey.currentState != null && _dialogKey.currentState!.mounted) {
_dialogKey.currentState!.setState(() {
text =result.recognizedWords;
});
}
})
);
}
} else {
setState(() => islistening = false
);
speechToText.stop();
}
}
}

Flutter, how to call Dialog function from another class

what is the proper way to call Dialog function from another class.
I have been searching this topic for a while but seems none of them are my answer.
my Dialog has a little complicated logic for server communicating and some paginations
so this code is going to be long for just one dart file. so I want to separate them.
and I need the some dialog animations so I picked the showGeneralDialog()
I also saw the example dialog implementaion using StatefulBuilder() which can use setState,
but this problem is it is not able to use initState()
for now, what I did is below
dart1 file
import 'package:aaa/bbb/some_dialog_file.dart'
as someDialog;
GestureDetector(
onTap: () async{
var result =
await someDialog.displayDialogOKCallBack(
context,
);
},
child: Container(
width: 60,
height: 60,
child: Icon(
Icons.comment,
size: 38,
),
),
)
dart2 file
Future<dynamic> displayDialogOKCallBack(BuildContext context) async {
return await showGeneralDialog(
barrierLabel: "Label",
barrierDismissible: true,
// barrierColor: ,
transitionDuration: Duration(milliseconds: 400),
context: context,
pageBuilder: (context, anim1, anim2) {
return StatefulBuilder(builder: (context, setState) {
return Scaffold(
body: SafeArea(
),
);
});
},
transitionBuilder: (context, anim1, anim2, child) {
return SlideTransition(
position:
Tween(begin: Offset(0, 1), end: Offset(0, -0.02)).animate(anim1),
child: child,
);
},
);
}
so my question is I want to build very clean animation dialog
which is logically separated from base class file and it has to have initState(), and setState()
how could I acheive this ? thanks
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
onPressed: () {
someDialog(context);
},
child: Text("click"),
),
);
}
Future<dynamic> someDialog(BuildContext context) async {
return await showGeneralDialog(
barrierLabel: "Label",
barrierDismissible: true,
context: context,
pageBuilder: (context, anim1, anim2) {
return Scaffold(
backgroundColor: Colors.transparent,
body: SafeArea(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
// List
AnotherClassDialog(),
],
),
],
),
),
),
);
});
}
}
class AnotherClassDialog extends StatefulWidget {
#override
_AnotherClassDialogState createState() => _AnotherClassDialogState();
}
class _AnotherClassDialogState extends State<AnotherClassDialog> {
Color color;
#override
void initState() {
// TODO: implement initState
super.initState();
color = Colors.black;
}
#override
Widget build(BuildContext context) {
return Center(
child: Column(
children: [
RaisedButton(
onPressed: () {
setState(() {
color = Colors.red;
});
},
),
Container(
width: 100,
height: 100,
color: color,
),
RaisedButton(
onPressed: () {
setState(() {
color = Colors.green;
});
},
)
],
),
);
}
}
I use a custom dialog in my app in some classes and had the same problem.
You should define a dialog and pass context and other variables to it and call it everywhere you want.
You can define a dialog like this :
showCustomDialog(BuildContext context, String title, String description) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(
title,
textAlign: TextAlign.right,
),
content: SingleChildScrollView(
child: Text(
description,
style: Theme.of(context).textTheme.bodyText1,
textAlign: TextAlign.right,
),
),
actions: [
FlatButton(
child: Text(
'ok',
style: Theme.of(context).textTheme.bodyText2.copyWith(
color: Theme.of(context).accentColor,
),
),
onPressed: () => Navigator.of(context).pop(),
),
],
actionsPadding: EdgeInsets.symmetric(
horizontal: 10,
vertical: 5,
),
);
});
}
and use it everywhere you want like this :
InkWell(
child: Icon(
Icons.error_outline,
size: 17,
),
onTap: () => showCustomDialog(context,"text1" , "text2") ,
),
I hope my answer will help you.