Related
Hello any flutter experts is here who can help solving little issue i want implement flutter voice recognition. flutter speech_to_text: ^5.4.3. plugin which is work fine but problem is that i want implement like native voice recognition on top bar when user click on mic button its appears alert dialog showing in picture below and when user speak its shows text like image below anyone know about here is picture click on it
I also used custom dialog builder for this purpose but my text is not update in dialog text check code below
import 'dart:math';
import 'package:bibleapp/Dbhelper.dart';
import 'package:bibleapp/chapters.dart';
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> {
var booknames=['Genesis','Exodus','Leviticus','Numbers',
'Deuteronomy','Joshua',
'Judges','Ruth','1 Samuel','2 Samuel','1 Kings','2 Kings',
'1 Chronicles','2 Chronicles','Ezra','Nehemiah','Esther',
'Job','Psalms','Proverbs','Ecclesiastes','Song of Solomon','Isaiah','Jeremiah',
'Lamentations','Ezekiel','Daniel','Hosea','Joel','Amos','Obadiah','Jonah','Micah',
'Nahum','Habakkuk','Zephaniah','Haggai','Zechariah','Malachi','Matthew',
'Mark','Luke','John','Acts','Romans','1 Corinthians','2 Corinthians','Galatians',
'Ephesians','Philippians','Colossians','1 Thessalonians','2 Thessalonians','1 Timothy',
'2 Timothy','Titus','Philemon','Hebrews','James','1 Peter',
'2 Peter','1 John','2 John','3 John','Jude','Revelation'];
Dbhelper dbhelper=new Dbhelper();
stt.SpeechToText speechToText=stt.SpeechToText();
bool islistening=false;
//this text i want change after listening
String text='Example:Gensis Chapter 1 verse 5';
#override
void initState() {
// TODO: implement initState
super.initState();
dbhelper.db;
_initSpeech();
}
/// This has to happen only once per app
void _initSpeech() async {
speechToText.initialize();
}
///this dialog when user press on mic button it show alert alert dialog button
showAlertDialog() {
Widget okButton = TextButton(
child: Text("CANCEL VOICE"),
onPressed: () => Navigator.of(context).pop(false),
);
AlertDialog alert = AlertDialog(
title: Text("Search by voice"),
content: Container(
height: 180,
child: Column(
children: [
AvatarGlow(
glowColor: Colors.blue,
endRadius: 75,
duration: Duration(milliseconds: 2500),
repeat: true,
showTwoGlows: islistening,
repeatPauseDuration: Duration(milliseconds: 150),
child: Material(
elevation: 5,
shape: CircleBorder(),
child: CircleAvatar(
backgroundColor: Colors.white,
child: Icon(Icons.mic, color: Colors.blue, size: 30,),
radius: 50,
),
),
),
Expanded(child: Container(
child: Text(text),
)),
],
),
),
actions: [
okButton,
],
);
// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
new IconButton(
///when user clickec on mic button dialog and speech rcoginition methods calll
icon: new Icon(islistening?Icons.mic:Icons.mic_none),
highlightColor: Colors.pink,
onPressed:(){
setState(() {
showAlertDialog();
_listen();
});
},
),
],
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: booknames.length,
separatorBuilder: (BuildContext context, int index) =>
Divider(height: 1),
itemBuilder: (context, index) {
return Column(
children: [
GestureDetector(
onTap: () {
int increment = index + 1;
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (context, animation1, animation2) =>
chapters(increment, booknames[index]),
transitionDuration: Duration(seconds: 0),
),
);
// Navigator.push(
// context,
// MaterialPageRoute(builder: (context) => chapters(increment)),
// );
},
child: ListTile(
leading: CircleAvatar(
radius: 20,
backgroundColor: Colors.primaries[Random().nextInt(
Colors.primaries.length)],
child: Text(
booknames[index].substring(0, 1), style: TextStyle(
fontSize: 17,
fontWeight: FontWeight.bold,
color: Colors.white
),),
),
title: Text(
booknames[index], style: TextStyle(
color: Colors.black,
fontSize: 20
),
),
),
),
],
);
},
),
),
],
),
);
}
//this voice listener method
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(() {
//this text is not updating in dialog
text=result.recognizedWords;
//but this print method continues printing spkoen word in console
print('result.recognizedWords')
})
);
}
} else {
setState(() => islistening = false
);
speechToText.stop();
}
}
}
I think this is a common problem, setState does not work for dialog, because Dialog is not the part of the tree.
this is showDialog()'s document:
/// This function takes a `builder` which typically builds a [Dialog] widget.
/// Content below the dialog is dimmed with a [ModalBarrier]. The widget
/// returned by the `builder` does not share a context with the location that
/// `showDialog` is originally called from. Use a [StatefulBuilder] or a
/// custom [StatefulWidget] if the dialog needs to update dynamically.
you can use StatefulBuilder, refer to How to refresh an AlertDialog in Flutter?
I implement to add to cart functionality items added into cart successfully but the number of count in the cart badge is not updated when I reload dart page than the number of count updates.can anyone help me?
I implement to add to cart functionality items added into cart successfully but the number of count in the cart badge is not updated when I reload dart page than the number of count updates.can anyone help me?
This is my Homepage.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:badges/badges.dart';
import 'package:hospital/BestDeatProducts/best_deal_product_page.dart';
import 'package:hospital/CartPage/pages/cartPage.dart';
import 'package:hospital/Drawer/dropdown_menu.dart';
import 'package:hospital/FirstSection/carousel.dart';
import 'package:hospital/Drawer/drawercontent.dart';
import 'package:hospital/FloatingActionButton/ConsultWithDoctor/consult_with_doctor.dart';
import 'package:hospital/MedicineCateory/medicine_category_page.dart';
import 'package:hospital/SecondSection/second_page.dart';
import 'package:hospital/ThirdSection/third_page.dart';
import 'package:hospital/TrendingProducts/trending_product_page.dart';
import 'package:hospital/constant.dart';
import 'package:hospital/customApiVariable.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'No Internet/connectivity_provider.dart';
import 'No Internet/no_internet.dart';
import 'package:http/http.dart' as http;
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
SharedPreferences loginData;
// late String username;
Future getUsername() async {
loginData = await SharedPreferences.getInstance();
setState(() {
// print("uname" + uname.toString());
print("dddpppuu1 : responceData_un" +
loginData.getString('responceData_un').toString());
print("dddpppuu2 : responceData_ue" +
loginData.getString('responceData_ue').toString());
print("dddpppuu3 : responceData_status" +
loginData.getString('responceData_status').toString());
String responceData_uid =
loginData.getString('responceData_uid').toString();
fetchData(responceData_uid);
});
}
var response;
var addToCartApi;
#override
void initState() {
// TODO: implement initState
//
super.initState();
Provider.of<ConnectivityProvider>(context, listen: false).startMonitering();
// for loading
getUsername();
}
fetchData(String argResponceData_uid) async {
var api = Uri.parse(
'$ecommerceBaseUrl/addToCartApi.php?a2rTokenKey=$a2rTokenKey&action=addToCartList&uid=${argResponceData_uid}');
print('cartpage' + api.toString());
response = await http.get(api);
print("Carousel" + response.body);
addToCartApi = jsonDecode(response.body);
print('addToCartApi' + addToCartApi['total'].toString());
print('totalPriceAfterOffer' + totalPriceAfterOffer.toString());
setState(() {});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: kGreen,
title: Text(
"BK Arogyam",
style: TextStyle(fontStyle: FontStyle.italic),
),
actions: [
response != null
? Badge(
position: BadgePosition.topEnd(top: 3, end: 18),
animationDuration: Duration(milliseconds: 300),
animationType: BadgeAnimationType.slide,
badgeContent: Text(
addToCartApi['total']['num'].toString(),
style: TextStyle(color: Colors.white),
),
child: IconButton(
icon: Icon(Icons.shopping_cart),
padding: EdgeInsets.only(right: 30.0),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Cartpage()),
);
}),
)
: IconButton(
icon: Icon(Icons.shopping_cart),
// onPressed: () => print("open cart"),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Cartpage()),
);
},
),
DropDownMenu(),
],
),
floatingActionButton: FloatingActionButton(
backgroundColor: kGreen,
onPressed: () => Navigator.push(context,
MaterialPageRoute(builder: (context) => ConsultWithDoctor())),
tooltip: 'Consult With Doctor',
child: Container(
child: Image(
image: AssetImage(
"assets/icons/cwd.png",
),
color: Colors.white,
width: 40,
height: 40,
),
),
),
drawer: Drawer(
child: DrawerContent(),
),
body: pageUI());
}
Widget pageUI() {
return Consumer<ConnectivityProvider>(
builder: (consumerContext, model, child) {
if (model.isOnline != null) {
return model.isOnline
? ListView(
children: [
Carousel(),
SizedBox(
height: 10.0,
),
MedicineCategoryPage(),
SizedBox(
height: 10.0,
),
SecondPage(),
SizedBox(
height: 10.0,
),
ThirdPage(),
SizedBox(
height: 10.0,
),
TrendingProductPage(),
SizedBox(
height: 16.0,
),
BestDealProductPage(),
SizedBox(
height: 10.0,
),
],
)
: NoInternet();
}
return Container(
child: Center(
child: CircularProgressIndicator(),
),
);
},
);
}
}
You can use the change notifier provide by provider package.
And watch the video on how to use, exactly for ur use case search YouTube change notifier provider by the growing developer
Hope it helps 🙂
You can use provider(provider: ^5.0.0) or Getx(get: ^4.1.4) to handle this kind of case.
There are lots of examples are available for GetX and Provider.
If you don't want to use any of them, Then store your cart/badge count to tempCartCount variable(Example: int cartCount = 0) and set it to the badge count instead of "addToCartApi['total']['num'].toString()" , Make sure to setState on update/addCart Item.
Here I provide a simple example of how to update count on appBar.
if you want to change from any other screen make cartCount to global otherwise you can set it local/private.
import 'package:badges/badges.dart';
import 'package:flutter/material.dart';
class UpdateCountExample extends StatefulWidget {
#override
_UpdateCountExampleState createState() => _UpdateCountExampleState();
}
int cartCount = 0;
class _UpdateCountExampleState extends State<UpdateCountExample> {
List<String> cartArray = [];
#override
void initState() {
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
setState(() {
cartCount = 0;
});
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("App Bar"),
actions: [
Padding(
padding: const EdgeInsets.only(right: 18.0, top: 5.0),
child: Badge(
badgeContent: Text(cartCount.toString()),
child: Icon(Icons.add_shopping_cart),
),
)
],
),
body: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Add item in cart",
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 18, decoration: TextDecoration.none, color: Colors.black),
),
SizedBox(
height: 20,
),
InkWell(
onTap: () {
setState(() {
cartArray.add("value ${cartArray.length}");
cartCount = cartArray.length;
});
},
child: Container(
padding: const EdgeInsets.all(10.0),
color: Colors.amber,
child: Text(
"Add Item",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 15, decoration: TextDecoration.none, color: Colors.black),
),
),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount: cartArray.length,
itemBuilder: (context, index) {
return Text(
cartArray[index],
style: TextStyle(fontSize: 20, color: Colors.black),
);
}),
)
],
),
),
);
}
}
I have used StreamBuilder to update cart items instantly.
You can use the code from this post
How to use Streambuilder in flutter
I am working on a custom sidebar for my app since I dont like the default drawer that flutter comes with.
Everything works fine, that is, the sidebar takes the entire height of the mobile phone
until I render the page contents along the sidebar as shown below
Here's the Main contents code:
import 'package:api_example_app/LandingScreen/components/control_button.dart';
import 'package:api_example_app/LandingScreen/components/default_button.dart';
import 'package:api_example_app/SensorScreen/charts/GasChart.dart';
import 'package:api_example_app/SensorScreen/charts/HumChart.dart';
import 'package:api_example_app/SensorScreen/charts/MoisChart.dart';
import 'package:api_example_app/SensorScreen/charts/NurChart.dart';
import 'package:api_example_app/SensorScreen/charts/PhChart.dart';
import 'package:api_example_app/SensorScreen/charts/TemChart.dart';
import 'package:api_example_app/SensorScreen/charts/chartComponents/HumCard.dart';
import 'package:api_example_app/SensorScreen/components/sensor_screen.dart';
import 'package:api_example_app/constants.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class LandingScreenBody extends StatefulWidget {
#override
_LandingScreenBodyState createState() => _LandingScreenBodyState();
}
class _LandingScreenBodyState extends State<LandingScreenBody> {
#override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Padding(
padding: EdgeInsets.symmetric(horizontal: size.width * 0.05),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
SizedBox(height: size.height * 0.1),
Center(
child: Text(
'ngDAQ',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black,
fontSize: 25,
),
),
),
SizedBox(height: size.height * 0.01),
Center(
child: Text(
'The ngDAQ is a Smart Agriculture solution based on IoT, seeking to increase farm productivity by automation and monitoring.',
textAlign: TextAlign.center,
style: TextStyle(color: kDarkGreyColor, fontSize: 12),
),
),
SizedBox(height: size.height * 0.05),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CardsParent(
size: size,
icon: FontAwesomeIcons.temperatureHigh,
title: 'Tem',
subtitle: '33C',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => new TemChart()));
},
),
CardsParent(
size: size,
title: 'Hum ',
subtitle: '75%',
icon: FontAwesomeIcons.cloudShowersHeavy,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => new HumChart()));
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CardsParent(
size: size,
icon: FontAwesomeIcons.hourglass,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => new MoisChart()));
},
title: 'Mos',
subtitle: '40',
),
CardsParent(
size: size,
title: 'PH ',
subtitle: '14',
icon: FontAwesomeIcons.meteor,
onTap: () {
Navigator.push(context,
MaterialPageRoute(builder: (context) => new PhChart()));
},
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
CardsParent(
size: size,
icon: FontAwesomeIcons.leaf,
title: 'Nur',
subtitle: 'Good',
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => new NurChart()));
},
),
CardsParent(
size: size,
title: 'Gas ',
subtitle: 'Good',
icon: FontAwesomeIcons.flask,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => new GasChart()));
},
),
],
),
SizedBox(height: size.height * 0.05),
// DefaultButton(
// size: size,
// title: "Next",
// press: () {
// Navigator.push(
// context,
// CupertinoPageRoute(
// builder: (context) => SensorScreen(),
// ),
// );
// },
// ),
],
),
),
);
}
}
Heres' the Sidebar Code:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
// import 'package:rxdart/rxdart.dart';
import '../../constants.dart';
class SideBar extends StatefulWidget {
// const SideBar({Key ? key}) : super(key: key);
#override
_SideBarState createState() => _SideBarState();
}
class _SideBarState extends State<SideBar>
with SingleTickerProviderStateMixin<SideBar> {
AnimationController _animationController;
StreamController<bool> isSidebarOpenedStreamController;
Stream<bool> isSidebarOpenedStream;
StreamSink<bool> isSidebarOpenedSink;
// final bool isSidebarOpened = true;
final _animationDuration = const Duration(milliseconds: 500);
#override
void initState() {
super.initState();
_animationController =
AnimationController(vsync: this, duration: _animationDuration);
isSidebarOpenedStreamController = PublishSubject<bool>();
isSidebarOpenedStream = isSidebarOpenedStreamController.stream;
isSidebarOpenedSink = isSidebarOpenedStreamController.sink;
}
#override
void dispose() {
_animationController.dispose();
isSidebarOpenedStreamController.close();
isSidebarOpenedSink.close();
super.dispose();
}
void onIconPressed() {
final animationStatus = _animationController.status;
final isAnimationCompleted = animationStatus == AnimationStatus.completed;
if (isAnimationCompleted) {
isSidebarOpenedSink.add(false);
_animationController.reverse();
} else {
isSidebarOpenedSink.add(true);
_animationController.forward();
}
}
#override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return StreamBuilder<bool>(
initialData: false,
stream: isSidebarOpenedStream,
builder: (context, isSideBarOpenedAsync) {
return AnimatedPositioned(
duration: _animationDuration,
top: 0,
bottom: 0,
left: isSideBarOpenedAsync.data ? 0 : 0,
right: isSideBarOpenedAsync.data ? 0 : screenWidth - 45,
child: Row(
children: <Widget>[
Expanded(
child: Container(
color: kOrangeColor,
child: Column(
children: <Widget>[],
),
),
),
Align(
alignment: Alignment(0, -0.9),
child: GestureDetector(
onTap: () {
onIconPressed();
},
child: Container(
width: 35,
height: 80,
color: kOrangeColor,
alignment: Alignment.centerLeft,
child: AnimatedIcon(
progress: _animationController.view,
icon: AnimatedIcons.menu_close,
color: Colors.white,
size: 30,
),
),
),
),
],
),
);
},
);
}
}
The Layout Where the render is done:
import 'package:api_example_app/LandingScreen/components/body.dart';
import 'package:flutter/material.dart';
import '../../constants.dart';
import 'sidebar.dart';
class SideBarLayout extends StatelessWidget {
// const SideBarLayout({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
LandingScreenBody(),
SideBar(),
],
),
);
}
}
I dont know what I did wrong.
Inside SideBar, you need to surround it with Container widget, and set its height to double.infinity;
//Inside SideBar
return Container(
width: 200,
height: double.infinity,
child: StreamBuilder<bool> (
...
);
);
I solved it, thanks to #eyoeldefare.
From the main home, where I returned padding, I [return container instead, then, add:
return Container(
height: double.infinity,
(
...
),
);
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.
I am working on my first Flutter App. There is an Activity/Screen which is showing a countdown time. I want, when time is 00:00 then hit an API.
I tried and search on it but i didn't find anything best about this problem.
Please tell me how to resolve this ?
Thank you.
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
String time;
String topicName;
Future<String> getTime() async{
final response = await http.post(Constant.TestTime,
body: {
"topic_id" : widget.valueTopicId,
});
Map<String,dynamic> respons = jsonDecode(response.body);
setState(() {
time=respons['test_time'];
topicName=respons['topic_name'];
controller = AnimationController(
vsync: this,
duration: Duration(minutes:int.parse(time) ,seconds: 00),
);
if (controller.isAnimating)
controller.stop();
else {
controller.reverse(
from: controller.value == 0.0
? 1.0
: controller.value);
}
});
print(respons.toString());
setState(() {
isLoading=false;
});
}
Widget _buildAppBar (BuildContext context){
return PreferredSize (preferredSize: Size.fromHeight(MediaQuery.of(context).size.height * 0.085),
child: AppBar(
backgroundColor: Colors.blue,
title: Text("Questions"),
centerTitle: true,
iconTheme: IconThemeData(
color: Colors.white
),
actions: <Widget>[
new Container(
margin: const EdgeInsets.only(top: 25.0, left: 25.0),
child: new Text(topicName,
style: TextStyle(color: Colors.white, fontSize: 26,
fontWeight: FontWeight.bold),),
),
SizedBox(width: 20),
new Padding(padding: EdgeInsets.all(20.0)),
new Padding(padding: EdgeInsets.only(bottom: 40, top: 50)),
Expanded(
flex: 1,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Align(
alignment: FractionalOffset.center,
child: AspectRatio(aspectRatio: 1.0,
child: Stack(
children: <Widget>[
Positioned.fill(child:
AnimatedBuilder(
animation: controller,
builder: (BuildContext context,
Widget child) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: CustomPaint(
painter: TimerPainter(
animation: controller,
backgroundColor: Colors.white,
color: Colors.blue,
),
),
);
},
),
),
Align(
alignment: FractionalOffset.center,
child: Column(
mainAxisAlignment: MainAxisAlignment
.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment
.center,
children: <Widget>[
AnimatedBuilder(
animation: controller,
builder: (BuildContext context,
Widget child) {
return Text(
timerString, style: TextStyle(
color: Colors.white),
);
}
)
],
),
)
],
),
)
),
),
],
)
)
],
) ,);
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: onBackPressed,
child: isLoading
? Center(child: CircularProgressIndicator(),)
:MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
resizeToAvoidBottomPadding: false,
appBar: _buildAppBar(context),
body: Questions(widget.valueTopicId,widget.noOfQuestions,widget.difficulty,time),
)
),
);
}
}
Here i posted my code and an API getTime() is hitting on initState(). So, when my time is 00:00 then an another API should hit. I tried with FutureBuilder but it did not work. May be I did something wrong but so confusing in this.
You can user Timer, you need to import dart:async
Timer(Duration(seconds: 5), () {
getTime();
});
You, need to register your timer in initState.
Timer.periodic() will be executed at a particular duration after specified time.
Timer _timer;
#override
void initState()
{
_timer = Timer.periodic(
const Duration(seconds: 1), (Timer t) => handleAPICall(),
);
super.initState();
}
#override
void dispose()
{
_timer?.cancel();
super.dispose();
}
void handleAPICall()
{
// here you need to check if its time to make the API call.
// I am assuming that you will have some datetime that will tell you
// if duration time is 00:00
if(duration_time == 00:00) // you need to write your correct logic
{
// then, make the HTTP Call.
}
}