I want to show alert dialog based on a condition. Not based on user interaction such as button press event.
If a flag is set in app state data alert dialog is shown
Simply override initState
and call your _showDialog
method inside Timer.run()
@override
void initState() {
super.initState();
Timer.run(() => _showDialog());
}
I would place it in initState
of a State
(of a StatefulWidget
).
Placing it in the build
method of a Stateless
widget is tempting, but that will trigger your alert multiple times.
In this example below, it displays an alert when the device is not connected to the Wifi, showing a [try again] button if it's not.
import 'package:flutter/material.dart';
import 'package:connectivity/connectivity.dart';
void main() => runApp(MaterialApp(title: "Wifi Check", home: MyPage()));
class MyPage extends StatefulWidget {
@override
_MyPageState createState() => _MyPageState();
}
class _MyPageState extends State<MyPage> {
bool _tryAgain = false;
@override
void initState() {
super.initState();
_checkWifi();
}
_checkWifi() async {
// the method below returns a Future
var connectivityResult = await (new Connectivity().checkConnectivity());
bool connectedToWifi = (connectivityResult == ConnectivityResult.wifi);
if (!connectedToWifi) {
_showAlert(context);
}
if (_tryAgain != !connectedToWifi) {
setState(() => _tryAgain = !connectedToWifi);
}
}
@override
Widget build(BuildContext context) {
var body = Container(
alignment: Alignment.center,
child: _tryAgain
? RaisedButton(
child: Text("Try again"),
onPressed: () {
_checkWifi();
})
: Text("This device is connected to Wifi"),
);
return Scaffold(
appBar: AppBar(title: Text("Wifi check")),
body: body
);
}
void _showAlert(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text("Wifi"),
content: Text("Wifi not detected. Please activate it."),
)
);
}
}
This is how I achieved this in a simple way:
Add https://pub.dev/packages/shared_preferences
Above the build method of your main screen (or any desired widget):
Future checkFirstRun(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool isFirstRun = prefs.getBool('isFirstRun') ?? true;
if (isFirstRun) {
// Whatever you want to do, E.g. Navigator.push()
prefs.setBool('isFirstRun', false);
} else {
return null;
}
}
Then on your widget's initState:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => checkFirstRun(context));
}
This ensures the function is run after the widget is built.
I solved it using a package developed by Flutter Community. here https://pub.dev/packages/after_layout
Add this to your pubspec.yaml
after_layout: ^1.0.7+2
And try below example
import 'package:after_layout/after_layout.dart';
import 'package:flutter/material.dart';
class DialogDemo extends StatefulWidget {
@override
_DialogDemoState createState() => _DialogDemoState();
}
class _DialogDemoState extends State<DialogDemo>
with AfterLayoutMixin<DialogDemo> {
@override
void initState() {
super.initState();
}
@override
void afterFirstLayout(BuildContext context) {
_neverSatisfied();
}
@override
Widget build(BuildContext context) {
return SafeArea(
child: Container(
decoration: BoxDecoration(color: Colors.red),
),
);
}
Future<void> _neverSatisfied() async {
return showDialog<void>(
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return AlertDialog(
title: Text('Rewind and remember'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('You will never be satisfied.'),
Text('You\’re like me. I’m never satisfied.'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('Regret'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
}
You have to wrap the content inside another Widget
(preferably Stateless).
Example:
Change From:
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('List scroll')),
body: Container(
child: Text("Hello world"),
)));
}
}
to this:
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('List scroll')), body: new MyHome()));
}
}
class MyHome extends StatelessWidget { // Wrapper Widget
@override
Widget build(BuildContext context) {
Future.delayed(Duration.zero, () => showAlert(context));
return Container(
child: Text("Hello world"),
);
}
void showAlert(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text("hi"),
));
}
}
Note: Refer here for wrapping show alert inside Future.delayed(Duration.zero,..)