AlertDialog function runs on everypage in flutter - flutter

theAlertDialog in this code should run only when the user access the Account page (obviously), but while testing it, it runs on the Account page and all the next pages, and it is even duplicated, i mean when i head from Account page to another page the AlertDialog will be displayed twice
class Account extends StatefulWidget {
#override
_AccountState createState() => _AccountState();
}
class _AccountState extends State<Account> {
#override
Widget build(BuildContext context) {
Future.delayed(Duration.zero, () => FirstRun(context));
return Scaffold(
//there are alot of widgets here like drawer but all of it works fine
//i don't think its necessary to write it
);
}
FirstRun(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool first = (prefs.getBool('firstUse'));
print('Pressed $first');
if (first == null) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: Color(0xaa6b6b6b),
elevation: 10,
content: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
'first run dialog',
overflow: TextOverflow.ellipsis,
maxLines: 6,
style: TextStyle(
color: Colors.white,
fontSize: 24,
),
textAlign: TextAlign.center,
),
Container(
child: MaterialButton(
onPressed: () {
prefs.setBool('firstUse', false);
Navigator.of(context).pop();
print('Pressed $first');
},
child: Text(
'ok',
),
))
],
),
);
},
);
}
}
}

maybe it happens because you start showing the alert on build method. try to show it on initState method of the Account widget.
class _AccountState extends State<Account> {
#override
initState() {
Future.delayed(Duration.zero, () => FirstRun(this.context));
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
//there are alot of widgets here like drawer but all of it works fine
//i don't think its necessary to write it
);
}

as a work around i call the next page using Navigator.Replace instead of Navigator.push , but i dont think this is a real solution

Related

Main app widget: setState call -> build() builds all widgets but screen not updated

App is a simple memory/guessing game with a grid of squares. Floating action button triggers a "New game" dialog, and a Yes response triggers setState() on the main widget. The print() calls show it is building all the Tile widgets in the grid, but as it returns, the old grid values are still showing. Probably done something stupid but not seeing it. Basic code is below. TIA if anyone can see what is missing/invalid/broken/etc.
Main.dart is the usual main() that creates a stateless HomePage which creates a stateful widget which uses this State:
class MemHomePageState extends State<MemHomePage> {
GameBoard gameBoard = GameBoard();
GameController? gameController;
int gameCount = 0, winCount = 0;
#override
void initState() {
super.initState();
gameController = GameController(gameBoard, this);
}
#override
Widget build(BuildContext context) {
if (kDebugMode) {
print("MemHomepageState::build");
}
gameBoard.newGame(); // Resets secrets and grids
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: GridView.count(
crossAxisCount: Globals.num_columns,
children: List.generate(Globals.num_columns * Globals.num_rows, (index) {
int x = index~/Globals.NR, y = index%Globals.NR;
int secret = gameBoard.secretsGrid![x][y];
var t = Tile(x, y, Text('$secret'), gameController!);
gameBoard.tilesGrid![x].add(t);
if (kDebugMode) {
print("Row $x is ${gameBoard.secretsGrid![x]} ${gameBoard.tilesGrid![x][y].secret}");
}
return t;
}),
),
// Text("You have played $gameCount games and won $winCount."),
),
floatingActionButton: FloatingActionButton(
onPressed: () => newGameDialog("Start a new game?"),
tooltip: 'New game?',
child: const Icon(Icons.refresh_outlined),
),
);
}
/** Called from the FAB and also from GameController "won" logic */
void newGameDialog(String message) {
showDialog<void>(
context: context,
barrierDismissible: false, // means the user must tap a button to exit the Alert Dialog
builder: (BuildContext context) {
return AlertDialog(
title: Text("New game?"),
content: Text(message),
//),
actions: <Widget>[
TextButton(
child: const Text('Yes'),
onPressed: () {
setState(() {
gameCount++;
});
Navigator.of(context).pop();
},
),
TextButton(
child: const Text('No'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
}
);
}
The Tile class is a StatefulWidget whose state determines what that particular tile should show:
import 'package:flutter/material.dart';
import 'gamecontroller.dart';
enum TileMode {
SHOWN,
HIDDEN,
CLEARED,
}
/// Represents one Tile in the game
class Tile extends StatefulWidget {
final int x, y;
final Widget secret;
final GameController gameController;
TileState? tileState;
Tile(this.x, this.y, this.secret, this.gameController, {super.key});
#override
State<Tile> createState() => TileState(x, y, secret);
setCleared() {
tileState!.setCleared();
}
}
class TileState extends State<Tile> {
final int x, y;
final Widget secret;
TileMode tileMode = TileMode.HIDDEN;
TileState(this.x, this.y, this.secret);
_unHide() {
setState(() => tileMode = TileMode.SHOWN);
widget.gameController.clicked(widget);
}
reHide() {
print("rehiding");
setState(() => tileMode = TileMode.HIDDEN);
}
setCleared() {
print("Clearing");
setState(() => tileMode = TileMode.CLEARED);
}
_doNothing() {
//
}
#override
Widget build(BuildContext context) {
switch(tileMode) {
case TileMode.HIDDEN:
return ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.teal,
),
onPressed: _unHide,
child: Text(''));
case TileMode.SHOWN:
return ElevatedButton(
onPressed: _doNothing,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
),
child: secret);
case TileMode.CLEARED:
return ElevatedButton(
onPressed: _doNothing,
style: ElevatedButton.styleFrom(
backgroundColor: Colors.black12,
),
child: const Icon(Icons.check));
}
}
}
it looks like you are calling the following in your build function. That would cause everything to reset everytime it builds. Perhaps it belongs in init instead?
gameBoard.newGame(); // Resets secrets and grids
The original problem is that the Tile objects, although correctly created and connected to the returned main widget, did not have distinct 'key' values so they were not replacing the originals. Adding 'key' to the Tile constructor and 'key: UniqueKey()' to each Tile() in the loop, solved this problem. It exposed a related problem but is out of scope for this question. See the github link in the OP for the latest version.

Flutter Navigator operation requested with a context that does not include a Navigator. on splash screen

so I'm trying to implement a splash screen where for two reasons.
the time given to the splash screen will be used to load all the data
For beautification
I'm using flutter_spinkit
So here's my code:
class _SplashScreenState extends State<SplashScreen> {
void initState() {
super.initState();
navigateToHomeScreen();
}
Future navigateToHomeScreen() async {
return Timer(
const Duration(milliseconds: 4000),
() {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) => App())); ---> doesn't go to new screen
},
);
}
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
backgroundColor: Color(0xff75c760),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildAppName(),
SizedBox(height: 20),
_buildSpinner(),
],
),
),
);
}
Widget _buildAppName() {
return Text(
"MasterChef",
style: GoogleFonts.robotoMono(
color: Colors.black,
fontStyle: FontStyle.normal,
fontSize: 30,
fontWeight: FontWeight.bold,
),
);
}
Widget _buildSpinner() {
return SpinKitDoubleBounce(
color: Colors.white,
);
}
}
and here's the App() from app.dart:
class _AppState extends State<App> {
//Contains the simple drawer with switch case for navigation
//Taken directly from the flutter docs
}
The basic idea is to load the splash screen for 4000 milliseconds in which the app will load all the necessary data and then navigate to App() which contains the navigation routes and all. But for some reason I'm getting Unhandled Exception: Navigator operation requested with a context that does not include a Navigator.
I cannot be certain to what the cause is as cannot see your entire app structure but I am guessing the cause is that you do not have a MaterialApp() at the root of your app.
If this doesn't work please update your question to contain more code of how you get the splash screen app to be displayed.
This is because you used return Timer() so remove the return keyword so, try changing your code to:
Future navigateToHomeScreen() async {
Timer(
const Duration(milliseconds: 4000),
() {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) => App()));
},
);
}
Alternatively, you can use Future instead of Timer
Future navigateToHomeScreen() async {
Future.delayed(
const Duration(milliseconds: 4000),
() {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (BuildContext context) => App()));
},
);
}

How to rebuild a screen if confirm is pressed on bottom sheet?

I have built a home screen with is rendering cards using ListView.builder. These cards have a confirm button which fetches the confirmation status from firestore. When I tap on the confirm button, a bottom sheet appears asking whether I am sure. Once I tap Yes on the bottom sheet, I want the card on homepage to be rebuilt and change the button from confirm to confirm.
I used the setState to change the value at the onPressed event and it is successfully changing it but, the confirm button is not changing to confirmed.
Any leads on how to solve this issue would be really appreciated.
Homepage cards layout
class HomepageCards extends StatefulWidget {
final FirebaseUser user;
final Map cardDetails;
HomepageCards({#required this.user, this.cardDetails});
#override
_HomepageCardsState createState() => _HomepageCardsState();
}
class _HomepageCardsState extends State<HomepageCards> {
#override
Widget build(BuildContext context) {
// Confirmation status from firebase about the captain
bool isConfirmed = widget.cardDetails['c'];
final screenHeight = MediaQuery.of(context).size.height;
final screenWidth = MediaQuery.of(context).size.width;
return SingleChildScrollView(
padding: EdgeInsets.fromLTRB(screenHeight / 60, screenHeight / 90,
// UI Code here......
Container(
height: screenHeight / 80,
),
// Confirm Button checking condition and building UI accordingly
isConfirmed == true
? captainConfirmed(context, isConfirmed) // if confirmed then different button style widget
: confirmAndCancelButton(context, isConfirmed), //if not confirmed then show confirm and cancel button in the card
],
),
// Some UI
);
}
}
Once clicking on cancel, the bottom sheet:
Widget confirmCaptainBookingBottomSheet(
BuildContext context, bool isConfirmed) {
final screenHeight = MediaQuery.of(context).size.height;
final screenWidth = MediaQuery.of(context).size.width;
showModalBottomSheet(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Container(
// UI Code
Text(
'Do you want to confirm?',
style: TextStyle(
color: black.color,
fontSize: headSize.fontSize,
),
),
child: FlatButton(
child: Text(
'YES',
style: TextStyle(
color: cyan.color,
fontSize: headSize.fontSize),
),
onPressed: () {
print(isConfirmed);
setState(() {
// change the value of is confirmed which is used to build different buttons in the UI as shown in the above code
isConfirmed = true;
});
print(isConfirmed);
Navigator.pop(context);
}),
),
child: FlatButton(
child: Text(
'NO',
style: TextStyle(
color: cyan.color,
fontSize: headSize.fontSize),
),
onPressed: () {
Navigator.pop(context);
}),
),
});
}
You can create a function in _HomepageCardsState class which change state of isConfirmed and pass that function to widget where you want change the state. Then on onPressed of yes just give that function. it will change state of isConfirmed in _HomepageCardsState widget so you can see captainConfirmed widget.
I am leaving small demo which simulates how you can do that in your case.
I hope following code clear your idea.
class DeleteWidget extends StatefulWidget {
#override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
bool isConfirmed = false;
changeconfirmed() {
setState(() {
isConfirmed = !isConfirmed;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: Center(
child: isConfirmed
? Home1()
: Home2(
function: changeconfirmed,
),
)),
);
}
}
class Home1 extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
child: Text("confirmed Widget"),
);
}
}
class Home2 extends StatelessWidget {
final Function function;
Home2({this.function});
#override
Widget build(BuildContext context) {
return RaisedButton(
child: Text("press"),
onPressed: function,
);
}
}

Flutter - using TextEditingController to detect if last characters typed info field matches specific charater

I'm attempting to build a text field which triggers certain events which a user types in specific characters. For example, if a user types the '#' symbol, it will automatically trigger an event (in my case open an alert box). I've created a TextEditingController (_basicController) which adds a listener to the field and calls a function which looks for the last character typed into the field and detects matches to the symbol '#':
_detectLatestValue() {
var userInput = _basicController.text;
if(userInput.characters.last == "#"){
print("call to action");
_tagHandleSelect(_basicController.text);
}
}
It seems to print ("call to action") when it's supposed to, however when i call the _tagHandleSelect function (which opens a generic dialogue box), it seems to get stuck in a loop ie each time i close the alert box it opens another.
Here is the full page code:
import 'package:flutter/material.dart';
import 'package:characters/characters.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Welcome to Flutter',
home: TextEditingControllerExample(),
);
}
}
class TextEditingControllerExample extends StatefulWidget {
#override
_TextEditingControllerExampleState createState() {
return _TextEditingControllerExampleState();
}
}
class _TextEditingControllerExampleState extends State<TextEditingControllerExample> {
final _basicController = TextEditingController();
#override
void initState() {
super.initState();
_basicController.addListener(detectLatestValue);
}
#override
void dispose() {
_basicController.dispose();
super.dispose();
}
_detectLatestValue() {
var userInput = _basicController.text;
if(userInput.characters.last == "#"){
print("call to action");
_tagHandleSelect(_basicController.text);
}
}
Future<void> _tagHandleSelect(text) async {
return showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
content: Text(text),
actions: <Widget>[
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
Form(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
child: TextField(
controller: _basicController,
),
],
),
),
],
)
)
),
);
}
}```
Adding a listener to the controller can be a little hard to manage.
If you only want to listen to changes on a specific TextField, you can do something like this:
child: TextField(
onChanged: (value) {
if (value.endsWith("#")) {
print("call to action");
_tagHandleSelect(value);
}
},
),
This way you know onChanged will only be triggered once.
The listener to the TextEditingController will be triggered whenever the controller changes, which can be more than once for every text edit (for example, when the Text is focused or unfocused, it will be triggered).
I hope this can help you and you can develop your idea further!!

How to implement a Slider within an AlertDialog in Flutter?

I am learning app development on Flutter and can't get my Slider to work within the AlertDialog. It won't change it's value.
I did search the problem and came across this post on StackOverFlow:
Flutter - Why slider doesn't update in AlertDialog?
I read it and have kind of understood it. The accepted answer says that:
The problem is, dialogs are not built inside build method. They are on a different widget tree. So when the dialog creator updates, the dialog won't.
However I am not able to understand how exactly does it have to be implemented as not enough background code is provided.
This is what my current implementation looks like:
double _fontSize = 1.0;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(qt.title),
actions: <Widget>[
IconButton(
icon: Icon(Icons.format_size),
onPressed: () {
getFontSize(context);
},
),
],
),
body: ListView.builder(
padding: EdgeInsets.symmetric(vertical: 15.0),
itemCount: 3,
itemBuilder: (context, index) {
if (index == 0) {
return _getListTile(qt.scripture, qt.reading);
} else if (index == 1) {
return _getListTile('Reflection:', qt.reflection);
} else {
return _getListTile('Prayer:', qt.prayer);
}
})
);
}
void getFontSize(BuildContext context) {
showDialog(context: context,builder: (context){
return AlertDialog(
title: Text("Font Size"),
content: Slider(
value: _fontSize,
min: 0,
max: 100,
divisions: 5,
onChanged: (value){
setState(() {
_fontSize = value;
});
},
),
actions: <Widget>[
RaisedButton(
child: Text("Done"),
onPressed: (){},
)
],
);
});
}
Widget parseLargeText(String text) {...}
Widget _getListTile(String title, String subtitle) {...}
I understand that I will need to make use of async and await and Future. But I am not able to understand how exactly. I've spent more than an hour on this problem and can't any more. Please forgive me if this question is stupid and noobish. But trust me, I tried my best.
Here is a minimal runnable example. Key points:
The dialog is a stateful widget that stores the current value in its State. This is important because dialogs are technically separate "pages" on your app, inserted higher up in the hierarchy
Navigator.pop(...) to close the dialog and return the result
Usage of async/await
import 'package:flutter/material.dart';
void main() => runApp(App());
class App extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
double _fontSize = 20.0;
void _showFontSizePickerDialog() async {
// <-- note the async keyword here
// this will contain the result from Navigator.pop(context, result)
final selectedFontSize = await showDialog<double>(
context: context,
builder: (context) => FontSizePickerDialog(initialFontSize: _fontSize),
);
// execution of this code continues when the dialog was closed (popped)
// note that the result can also be null, so check it
// (back button or pressed outside of the dialog)
if (selectedFontSize != null) {
setState(() {
_fontSize = selectedFontSize;
});
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text('Font Size: ${_fontSize}'),
RaisedButton(
onPressed: _showFontSizePickerDialog,
child: Text('Select Font Size'),
)
],
),
),
);
}
}
// move the dialog into it's own stateful widget.
// It's completely independent from your page
// this is good practice
class FontSizePickerDialog extends StatefulWidget {
/// initial selection for the slider
final double initialFontSize;
const FontSizePickerDialog({Key key, this.initialFontSize}) : super(key: key);
#override
_FontSizePickerDialogState createState() => _FontSizePickerDialogState();
}
class _FontSizePickerDialogState extends State<FontSizePickerDialog> {
/// current selection of the slider
double _fontSize;
#override
void initState() {
super.initState();
_fontSize = widget.initialFontSize;
}
#override
Widget build(BuildContext context) {
return AlertDialog(
title: Text('Font Size'),
content: Container(
child: Slider(
value: _fontSize,
min: 10,
max: 100,
divisions: 9,
onChanged: (value) {
setState(() {
_fontSize = value;
});
},
),
),
actions: <Widget>[
FlatButton(
onPressed: () {
// Use the second argument of Navigator.pop(...) to pass
// back a result to the page that opened the dialog
Navigator.pop(context, _fontSize);
},
child: Text('DONE'),
)
],
);
}
}
You just need to warp the AlertDialog() with a StatefulBuilder()