let me tell you the process I want and what is happening
Process:
Press the ElevatedButton then show adScreenLoadingDialog till _isAdLoaded=true then display the ad and go to the next screen.
What is happening: there are two conditions:
First, if the user opens the screen and scrolls or waits for maybe 5 seconds, Then clicks on ElevatedButton, The process works fine everything is ok.
Second, if the user opens the screen and clicks on ElevatedButton immediately, Then adScreenLoadingDialog appears but the process stops because _isAdLoaded is not true yet and the process goes wrong.
What I need your help for:
How to make onPressed display adScreenLoadingDialog and wait till _isAdLoaded become true so the ad is ready to display and go to the next screen.
I tried to use while loop but it didn't work.
I really appreciate it if someone could help.
Thanks
This is my screen code
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
class BusTest extends StatefulWidget {
#override
_BusTestState createState() => _BusTestState();
}
class _BusTestState extends State<BusTest> {
////////////////////ADS////////////////
InterstitialAd _interstitialAd;
bool _isAdLoaded = false;
///ToDo Interstitial Ad Unite
void _initAd() {
InterstitialAd.load(
adUnitId: 'ca-app-pub-3940256099942544/1033173712',
request: AdRequest(),
adLoadCallback: InterstitialAdLoadCallback(
onAdLoaded: onAdLoaded,
onAdFailedToLoad: (error) {
print(error);
},
),
);
}
void onAdLoaded(InterstitialAd ad) {
_interstitialAd = ad;
_isAdLoaded = true;
_interstitialAd.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
_initAd();
//_interstitialAd.dispose();
},
onAdFailedToShowFullScreenContent: (ad, error) {
_initAd();
//_interstitialAd.dispose();
},
);
}
////////////////////ADS////////////////
#override
void initState() {
super.initState();
_initAd();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: Text(
"Bus Test",
style: TextStyle(
fontSize: 20,
),
),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
child: Column(
children: [
ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
maximumSize: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.disabled)) {
return Size(double.infinity, 60);
}
return Size(double.infinity, 60);
},
),
padding: MaterialStateProperty.all(EdgeInsets.all(0)),
backgroundColor: MaterialStateProperty.resolveWith(
(states) {
// If the button is pressed, return green, otherwise blue
if (states.contains(MaterialState.pressed)) {
return Color(0xff795368);
}
return Color(0xff3E2A35);
},
),
),
onPressed: () async {
adScreenLoadingDialog(context);
if (_isAdLoaded) {
await _interstitialAd.show();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BusTest1(),
),
);
}
},
child: Container(
height: 40,
child: Center(
child: Text(
'Bus Test 1',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
textAlign: TextAlign.center,
),
),
),
),
SizedBox(
height: 10,
),
ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
maximumSize: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.disabled)) {
return Size(double.infinity, 60);
}
return Size(double.infinity, 60);
},
),
padding: MaterialStateProperty.all(EdgeInsets.all(0)),
backgroundColor: MaterialStateProperty.resolveWith(
(states) {
// If the button is pressed, return green, otherwise blue
if (states.contains(MaterialState.pressed)) {
return Color(0xff795368);
}
return Color(0xff3E2A35);
},
),
),
onPressed: () async {
adScreenLoadingDialog(context);
if (_isAdLoaded) {
await _interstitialAd.show();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BusTest2(),
),
);
}
},
child: Container(
height: 40,
child: Center(
child: Text(
'Bus Test 2',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
textAlign: TextAlign.center,
),
),
),
),
SizedBox(
height: 10,
),
ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
maximumSize: MaterialStateProperty.resolveWith(
(states) {
if (states.contains(MaterialState.disabled)) {
return Size(double.infinity, 60);
}
return Size(double.infinity, 60);
},
),
padding: MaterialStateProperty.all(EdgeInsets.all(0)),
backgroundColor: MaterialStateProperty.resolveWith(
(states) {
// If the button is pressed, return green, otherwise blue
if (states.contains(MaterialState.pressed)) {
return Color(0xff795368);
}
return Color(0xff3E2A35);
},
),
),
onPressed: () async {
adScreenLoadingDialog(context);
if (_isAdLoaded) {
await _interstitialAd.show();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BusTest3(),
),
);
}
},
child: Container(
height: 40,
child: Center(
child: Text(
'Bus Test 3',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
),
textAlign: TextAlign.center,
),
),
),
),
SizedBox(
height: 10,
),
],
),
),
],
),
),
);
}
}
adScreenLoadingDialog(context) {
return showDialog(
barrierDismissible: false,
context: context,
builder: (context) {
return AlertDialog(
elevation: 0,
backgroundColor: Colors.transparent,
content: Container(
height: 100,
width: 100,
child: SpinKitCircle(
color: Color(0xffd88820),
size: 100,
),
),
);
});
}
so
Since you just want to make onPressed display adScreenLoadingDialog and wait till _isAdLoaded become true, you can use this Function to add delays until _isAdLoaded is true.
Future<void> checkIfAdLoaded() async {
if (_isAdLoaded) {
return;
} else {
await Future.delayed(const Duration(seconds: 1));
checkIfAdLoaded();
}
}
Add it to onPressed like this,
onPressed: () async {
adScreenLoadingDialog(context);
checkIfAdLoaded();
if (_isAdLoaded) {
await _interstitialAd.show();
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => BusTest2(),
),
);
}
},
You can also use use a Completer but that would need more code changes.
Also, wrap _isAdLoaded = true; in setState((){}),
void onAdLoaded(InterstitialAd ad) {
setState((){
_interstitialAd = ad;
_isAdLoaded = true;
});
_interstitialAd.fullScreenContentCallback = FullScreenContentCallback(
onAdDismissedFullScreenContent: (ad) {
_initAd();
//_interstitialAd.dispose();
},
onAdFailedToShowFullScreenContent: (ad, error) {
_initAd();
//_interstitialAd.dispose();
},
);
}
Related
I have created a dialog with StatefulBuilder. Setstate works perfectly within the StatefulBuilder. But I want to change that state from initstate too. But the set state from initstate is not called.
My code:
#override
void initState() {
super.initState();
rest_controller = AnimationController(
vsync: this,
duration: Duration(seconds: 15),
);
rest_controller.addListener(() {
if (rest_controller.isAnimating) {
setState(() {
print("rp"+rest_progress.toString());
rest_progress = rest_controller.value;
});
} else {
setState(() {
print("rp2"+rest_progress.toString());
rest_progress = 1.0;
rest_isPlaying = false;
});
}
});
}
Dialog open function:
showDataAlert() {
showDialog(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setState) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(
20.0,
),
),
),
backgroundColor: kMainColor,
contentPadding: EdgeInsets.only(
top: 10.0,
),
title: Text(
"Take Rest",
style: TextStyle(fontSize: 24.0, color: kTextColor),
),
content:
Center(
child: Column(
children: [
SizedBox(
height: 10,
),
Expanded(
child: Stack(
alignment: Alignment.center,
children: [
SizedBox(
width: 260,
height: 260,
child: CircularProgressIndicator(
backgroundColor: Colors.grey.shade300,
value: rest_progress,
strokeWidth: 6,
),
),
AnimatedBuilder(
animation: rest_controller,
builder: (context, child) => Text(
restCountText,
style: TextStyle(
fontSize: 50,
fontWeight: FontWeight.bold,
color: kTextColor,
),
),
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () {
if (rest_controller.isAnimating) {
rest_controller.stop();
setState(() {
rest_isPlaying = false;
});
} else {
rest_controller.reverse(from: rest_controller.value == 0 ? 1.0 : rest_controller.value);
setState(() {
rest_isPlaying = true;
});
}
},
child: RoundButton(
icon: rest_isPlaying == true ? Icons.pause : Icons.play_arrow,
),
),
GestureDetector(
onTap: () {
rest_controller.reset();
setState(() {
rest_isPlaying = false;
});
},
child: RoundButton(
icon: Icons.stop,
),
),
],
),
)
],
),
),
);
}
);
});
}
Basically, setstate from the initstate is not changing the state. I have tried to change the state from showDataAlert function also, but no luck. Only the state changes if I click the button inside the showdialog.
I have a widget which is return an alertDialog, and according to the result of the http request, I show another alertDialog. Nut I got the below error:
[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: 'package:flutter/src/widgets/localizations.dart': Failed assertion: line 447 pos 12: 'context != null': is not true.
import 'dart:io';
import 'package:Zabatnee/common_app/provider/user_details_provider.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class ForgetPasswordDialog extends StatefulWidget {
static const routeName = '/customeDialog';
final String title,description;
ForgetPasswordDialog({
this.title,
this.description,
});
#override
_ForgetPasswordDialogState createState() => _ForgetPasswordDialogState();
}
class _ForgetPasswordDialogState extends State<ForgetPasswordDialog> {
final emailController = TextEditingController();
var _isLoading = false;
_showDialog(String title, String message) {
showDialog(
barrierDismissible: false,
context: context,
builder: (ctx) => WillPopScope(
onWillPop: () async => false,
child: new AlertDialog(
elevation: 15,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8))),
title: Text(
title,
style: TextStyle(color: Colors.white),
),
content: Text(
message,
style: TextStyle(color: Colors.white),
),
backgroundColor: Theme.of(context).primaryColor,
actions: <Widget>[
FlatButton(
child: Text(
'OK',
style: TextStyle(color: Theme.of(context).accentColor),
),
onPressed: () {
Navigator.of(context).pop();
setState(
() {
_isLoading = false;
},
);
},
)
],
),
),
);
}
Future<void> _forgetPassword (String email) async {
try{
if(mounted)
setState(() {
_isLoading = true;
});
await Provider.of<UserDetailsProvider>(context, listen: false).forgetPassword(email);
print('code are sent via email');
_showDialog('Conguratulations', 'code send successfully');
} on HttpException catch (error) {
_showDialog('Authentication Failed', error.message);
} on SocketException catch (_) {
_showDialog('An error occured',
'please check your internet connection and try again later');
} catch (error) {
_showDialog('Authentication Failed',
'Something went wrong, please try again later');
}
if(mounted)
setState(() {
_isLoading = false;
});
}
#override
void dispose() {
emailController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16)
),
elevation: 8,
backgroundColor: Theme.of(context).accentColor,
child: dialogContent(context),
);
}
dialogContent(BuildContext context){
return Container(
padding: EdgeInsets.only(
top: 50,
right: 16,
left: 16,
bottom: 16,
),
margin: EdgeInsets.all(8),
width: double.infinity,
decoration: BoxDecoration(
color: Theme.of(context).accentColor,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.circular(17),
boxShadow: [
BoxShadow(
color: Colors.black87,
blurRadius: 10.0,
offset: Offset(0.0,10.0),
)
]
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
widget.title,
style: TextStyle(
fontSize: 24,
),
),
SizedBox(
height: 20,
),
Text(widget.description, style: TextStyle(fontSize: 16),
),
SizedBox(
height: 20,
),
TextField(
controller: emailController,
style: TextStyle(color: Colors.white),
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide: BorderSide(color:Theme.of(context).primaryColor)
),
fillColor: Colors.black87,
hintStyle: TextStyle(color:Colors.grey),
hintText: 'please enter your email',
labelText: 'Email',
labelStyle: TextStyle(color:Colors.white)
),
),
SizedBox(
height: 20,
),
Container(
width: double.infinity,
child: RaisedButton(
child: Text('Send'),
onPressed: (){
_isLoading
? CircularProgressIndicator()
: print(emailController.text);
_forgetPassword(emailController.text);
Navigator.of(context).pop();
}
),
),
Container(
width: double.infinity,
child: RaisedButton(
child: Text('Cancel'),
onPressed: (){
Navigator.of(context).pop();
}
),
),
],
),
);
}
}
In your showDialog, you haven't passed the context(in the parameters).
Do it like this,
_showDialog(String title, String message, BuildContext context) {
showDialog(
barrierDismissible: false,
context: context,
builder: (ctx) => WillPopScope(
onWillPop: () async => false,
child: new AlertDialog(
elevation: 15,
)
Then, when calling the function, pass the context too,
_showDialog('Conguratulations', 'code send successfully', context);
In your _showDialog() method, add one more parameter:
BuildContext context
Future<void> _showDialog(String title, String message, BuildContext context) async{
await showDialog(
barrierDismissible: false,
context: context,
builder: (ctx) => WillPopScope(
onWillPop: () async => false,
child: new AlertDialog(
elevation: 15,
.
.
)
Then, when calling the function, pass the context too,
_showDialog('Congratulations', 'code send successfully', context);
Also, make your method asynchronous by adding the async keyword before the curly braces, return type Future<void> and await keyword before showDialog() as showDialog is a future.
Im making a counter app and want to be able to change the title of the appbar by taking input from the user using an popup input box.
I am trying to have the user input a name(string) in an AlertDialog with textfield in it and trying to recieve the string in the main page by defining a function for the popup which returns the inputted string when confirm button is pressed. I'm assigning a variable to this function using await in the onPressed() of the main page and then displaying the string variable change in a snackbar. however, the snackbar is appearing as soon i tap on the textfield without even submitting or hitting the confirm button. it looks like either the await isnt working or for some reason the Alertdialog's parent function is returning null as soon as I tap on the textfield.
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
home: CounterApp(),
));
class CounterApp extends StatefulWidget {
#override
_CounterAppState createState() => _CounterAppState();
}
class _CounterAppState extends State<CounterApp> {
int num = 0;
String name = 'MyCounter-1';
Future<String> changeName() async {
final _controller = TextEditingController();
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)
),
title: Text('Change counter name'),
content: TextField(
controller: _controller,
onSubmitted: (str) {
//Navigator.of(context).pop(str);
},
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop(_controller.text.toString());
},
child: Text(
'Confirm',
style: TextStyle(
fontSize: 18.0,
),
),
),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Cancel',
style: TextStyle(
fontSize: 18.0,
),
),
),
],
);
},
);
}
void snackBar(BuildContext context, String string) {
final snackbar = SnackBar(content: Text('Counter renamed to $string'),);
Scaffold.of(context).showSnackBar(snackbar);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(name),
centerTitle: true,
actions: <Widget>[
IconButton(
onPressed: () {
setState(() {
num = 0;
});
},
icon: Icon(
Icons.refresh,
size: 35.0,
),
),
Builder(
builder: (context) => IconButton(
onPressed: () async {
setState(() async {
name = await changeName();
snackBar(context, name);
});
},
icon: Icon(
Icons.edit,
size: 35.0,
),
),
),
],
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Expanded(
flex: 2,
child: Container(
child: Center(child: Text(
'$num',
style: TextStyle(
fontSize: 75,
),
)),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 10),
child: RaisedButton(
onPressed: () {
setState(() {
num += 1;
});
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0)
),
color: Colors.blue,
child: Text(
'+',
style: TextStyle(
fontSize: 100.0,
),
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
child: RaisedButton(
onPressed: () {
setState(() {
num -= 1;
});
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(25.0)
),
color: Colors.grey,
child: Text(
'-',
style: TextStyle(
fontSize: 100.0,
),
),
),
)
],
),
);
}
}
As Soon as I tap on the edit button, this happens:
Image of problem
Just Add await keyword before showDialog() and add return statement at last as shown in the below code.
Future<String> changeName() async {
final _controller = TextEditingController();
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
title: Text('Change counter name'),
content: TextField(
controller: _controller,
onSubmitted: (str) {
//Navigator.of(context).pop(str);
},
),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop(_controller.text.toString());
},
child: Text(
'Confirm',
style: TextStyle(
fontSize: 18.0,
),
),
),
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(
'Cancel',
style: TextStyle(
fontSize: 18.0,
),
),
),
],
);
},
);
return _controller.text;
}
i'm trying to write a flutter application wHich takes two themes dark and brightness switch case device settings like this:
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Selectable GridView',
theme: ThemeData(
brightness: Brightness.dark,
),
home:HomePage(),
);
with the Brightness.light i have no problem but with the Brightness.dark it works correctly to some alert and when the app have an alert the alert color didn't change to dark and after the alert all the app change theme and color primaryColor:Colors.blue without any code written from me
import 'package:backback/Resultat/testclass.dart' as globals;
import 'package:flutter/cupertino.dart';
import 'package:hardware_buttons/hardware_buttons.dart' as HardwareButtons;
import 'dart:async';
import 'package:flutter/material.dart';
import 'ecouteurT.dart';
import 'flashT.dart';
class Boutontest extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<Boutontest> {
String _latestHardwareButtonEvent;
StreamSubscription<HardwareButtons.VolumeButtonEvent>
_volumeButtonSubscription;
StreamSubscription<HardwareButtons.HomeButtonEvent> _homeButtonSubscription;
StreamSubscription<HardwareButtons.LockButtonEvent> _lockButtonSubscription;
int a, b, c, d;
#override
void initState() {
super.initState();
new Future.delayed(Duration.zero, () {
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) => Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)), //this right here
child: Container(
height: 110,
child: Padding(
padding: EdgeInsets.all(0),
child: ListView(
children:
ListTile.divideTiles(context: context, tiles: [
ListTile(
title: Text(
'essayez de appyeez sur les boutons l\'un apres l\'autre et verifiez que tout bouton appyez ets montrez',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onTap: null,
),
ListTile(
title: Text(
'OK',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.deepOrange),
),
onTap: () {
Navigator.of(context).pop(false);
},
)
]).toList())))));
});
_volumeButtonSubscription =
HardwareButtons.volumeButtonEvents.listen((event) {
setState(() {
_latestHardwareButtonEvent = event.toString();
});
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_DOWN') {
b = 0;
}
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_UP') {
c = 0;
}
});
_homeButtonSubscription = HardwareButtons.homeButtonEvents.listen((event) {
setState(() {
a = 0;
_latestHardwareButtonEvent = 'HOME_BUTTON';
});
});
_lockButtonSubscription = HardwareButtons.lockButtonEvents.listen((event) {
setState(() {
d = 0;
_latestHardwareButtonEvent = 'LOCK_BUTTON';
});
});
}
#override
void dispose() {
super.dispose();
_volumeButtonSubscription?.cancel();
_homeButtonSubscription?.cancel();
_lockButtonSubscription?.cancel();
}
#override
Widget build(BuildContext context) {
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: const Text(
'Hi',
style: TextStyle(color: Colors.black),
),
),
body: Container(
child: Column(children: <Widget>[
Container(
height: height * 0.01,
),
Card(
child: ListTile(
leading: CircularProgressIndicator(
valueColor:
new AlwaysStoppedAnimation<Color>(Colors.deepOrange)),
title: Text(
'Detection des Boutons...',
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text('Element 1/1'),
trailing: InkWell(
onTap: () {
globals.Data.etatbouton('ignore');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Flash()),
);
},
child: Text(
'Ignore>',
style: TextStyle(color: Colors.deepOrange),
),
),
)),
Container(
height: height * 0.02,
),
if (_latestHardwareButtonEvent == 'HOME_BUTTON' || a == 0)
Card(
child: ListTile(
title: Text('Le Bouton Home'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
if (_latestHardwareButtonEvent == 'LOCK_BUTTON' || d == 0)
Card(
child: ListTile(
title: Text('Le Bouton Home'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_DOWN' ||
b == 0)
Card(
child: ListTile(
title: Text('Le Volume Down'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
if (_latestHardwareButtonEvent == 'VolumeButtonEvent.VOLUME_UP' ||
c == 0)
Card(
child: ListTile(
title: Text('Le Volume Up'),
trailing: Icon(
Icons.check,
color: Colors.deepOrange,
),
),
),
Container(
margin: const EdgeInsets.all(15.0),
padding: const EdgeInsets.all(3.0),
decoration: BoxDecoration(
border: Border.all(
width: 3.0,
color: Colors.deepOrange,
),
borderRadius: BorderRadius.all(Radius.circular(
30.0) // <--- border radius here
),
),
child: FlatButton(
child: Text(
'Passer au test suivant',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
onPressed: () {
Future.delayed(Duration.zero, () {
showDialog(
barrierDismissible: false,
context: context,
builder: (BuildContext context) =>
Dialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
20.0)), //this right here
child: Container(
height: 180,
child: Padding(
padding: EdgeInsets.all(0),
child: ListView(
children: ListTile.divideTiles(
context: context,
tiles: [
ListTile(
title: Text(
'Tout les boutons appyez sont montrez',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
onTap: null,
),
ListTile(
title: Text(
'Oui',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.deepOrange),
),
onTap: () {
globals.Data.etatbouton('1');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Flash()),
);
},
),
ListTile(
title: Text(
'Non',
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.deepOrange),
),
onTap: () {
globals.Data.etatbouton('0');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Flash()),
);
},
)
]).toList())))));
});
},
))
]),
),
);
}
}
That's the code of one of the alert I need some help.
import 'package:flutter/material.dart';
import 'package:lamp/lamp.dart';
import 'dart:async';
import 'package:backback/Resultat/testclass.dart' as globals;
import 'batterieT.dart';
class Flash extends StatefulWidget {
#override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<Flash> {
bool _hasFlash = false;
bool _isOn = false;
double _intensity = 1.0;
#override
initState() {
super.initState();
initPlatformState();
}
initPlatformState() async {
bool hasFlash = await Lamp.hasLamp;
print("Device has flash ? $hasFlash");
setState(() { _hasFlash = hasFlash; });
}
#override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: Text('hi'),
),
body: Container(
//
child: Column(
children: <Widget>[
Container(
height: height*0.01,
),
Card(child:ListTile(
leading: CircularProgressIndicator(valueColor:
new AlwaysStoppedAnimation<Color>(Colors.deepOrange)),
title: Text('Detection Connexion et deconnexion des ecouteurs...',style:TextStyle(fontWeight: FontWeight.bold,color: Colors.deepOrange),),
subtitle: Text('Element 1/1'),
trailing: InkWell(
onTap: (){
globals.Data.etatkit('ignore');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Batterie()),
);
},
child: Text('Ignore>',style: TextStyle(color: Colors.deepOrange),),
),
)),
Container(
height: height*0.02,
),
Container(
margin: const EdgeInsets.only(left: 20.0, right: 20.0),
child:Text(
'Veuillez branchez les ecouteurs plusieurs fois tout en verifiant si le texte afffiche correspond a l\'etat reel',
textAlign: TextAlign.center,)),
if(_isOn==false)
new InkWell(child: Image.asset('assets/flash.jpg'),
onTap:(){_turnFlash();} ,) ,
if(_isOn==true)
new InkWell(child: Image.asset('assets/flashO.jpg'),
onTap:(){_turnFlash();} ,),
Divider(),
Container(
margin: const EdgeInsets.only(left: 20.0, right: 20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell (child:Text('Ne correspond pas',style: TextStyle(color: Colors.deepOrange),)
, onTap: (){
globals.Data.etatkit('0');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Batterie()),
);
},),
InkWell(child: Text('Correspond',style: TextStyle(color: Colors.deepOrange),),
onTap: (){
globals.Data.etatkit('1');
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Batterie()),
);
},)
],
),
)
],
),
),
);
}
Future _turnFlash() async {
_isOn ? Lamp.turnOff() : Lamp.turnOn(intensity: _intensity);
var f = await Lamp.hasLamp;
setState((){
_hasFlash = f;
_isOn = !_isOn;
});
}
_intensityChanged(double intensity) {
Lamp.turnOn(intensity : intensity);
setState((){
_intensity = intensity;
});
}
}
and in this class when the navigator pass to this class I lost dark theme.
How do I return data from CupertinoTimerPicker(timerpicker.dart) back to showModalBottomSheet(form.dart) on flutter?
I wanted to use navigator.pop or sth but its doesnt sth like a ondismissed() function?
timerpicker.dart
class TimerModal extends StatefulWidget {
#override
_TimerModalState createState() => _TimerModalState();
}
class _TimerModalState extends State<TimerModal> {
Duration _initialtimer = new Duration();
#override
Widget build(BuildContext context) {
return Container(
height: MediaQuery.of(context).copyWith().size.height / 3,
child: SizedBox.expand(
child: CupertinoTimerPicker(
mode: CupertinoTimerPickerMode.hm,
minuteInterval: 1,
secondInterval: 1,
initialTimerDuration: _initialtimer,
onTimerDurationChanged: (Duration changedtimer) {
setState(() {
_initialtimer = changedtimer;
});
},
),
)
);
}
}
form.dart
FlatButton _timerPickerModal() {
return FlatButton(
color: Colors.white,
textColor: Colors.grey,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
// padding: EdgeInsets.all(8.0),
// splashColor: Colors.blueAccent,
onPressed: () async {
final result = await showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
backgroundColor: Colors.white,
context: context,
builder: (builder) => TimerModal()
);
print(result);
// setState(() {
// _newTimer = result;
// });
},
child: Row(
children: <Widget>[
Expanded(
child: Text(
"Timer: " + _checkTimerText(_newTimer),
style: TextStyle(fontSize: 20.0),
),
),
Icon(Icons.arrow_forward_ios),
],
),
);
}
You have to provide a callback onDateTimeChanged to CupertinoDatePicker.
Every time a date is selected, the callback will be executed.
In this case you could add a callback to TimerModal and provide it to CupertinoDatePicker. Something like this:
FlatButton _timerPickerModal() {
return FlatButton(
color: Colors.white,
textColor: Colors.grey,
disabledColor: Colors.grey,
disabledTextColor: Colors.black,
onPressed: () async {
final result = await showModalBottomSheet(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
backgroundColor: Colors.white,
context: context,
builder: (builder) => TimerModal(
onDateTimeChanged: (DateTime date) {
// In date variable you have the new date selected
// Here you can do anything you need with it
print(date);
},
),
);
print(result);
// setState(() {
// _newTimer = result;
// });
},
child: Row(
children: <Widget>[
Expanded(
child: Text(
"Timer: " + _checkTimerText(_newTimer),
style: TextStyle(fontSize: 20.0),
),
),
Icon(Icons.arrow_forward_ios),
],
),
);
}