Everytime provider updates setState() or markNeedsBuild() called during build - flutter

Evertime the setCountDown method is called i get an exception SetStateCalled during build ,,, please help! . I have to display this countdown in a previous screen too , Lets call it screen A and from A i pushReplaced and came to this Charging Screen which displays countdown and uses provider too . But everytime I update the provider value I get an error . It works fine in the debug mode but as soon as build a release it works weirdly . Please help!!!!
import 'dart:async';
import 'dart:developer';
import 'package:chargeapp_master/ChangeNotifiers/ChargeTimeNotifier.dart';
import 'package:chargeapp_master/Screens/main_map_screen.dart';
import 'package:chargeapp_master/Screens/navigation.dart';
import 'package:chargeapp_master/Screens/profile_screens/profile_screen.dart';
import 'package:chargeapp_master/Screens/wallet_screens/wallet_screen.dart';
import 'package:chargeapp_master/assistants/assistant_methods.dart';
import 'package:chargeapp_master/assistants/bluetooth_assistants.dart';
import 'package:chargeapp_master/widgets/bottbar.dart';
import 'package:circular_countdown_timer/circular_countdown_timer.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import '../User Details.dart';
import '../main.dart';
import 'Charging_summary_screen.dart';
import 'package:provider/provider.dart';
class Charging_screen extends StatefulWidget {
int duration;
String amount;
Charging_screen({Key? key, required this.duration, required this.amount})
: super(key: key);
#override
_Charging_screenState createState() => _Charging_screenState();
}
class _Charging_screenState extends State<Charging_screen> with ChangeNotifier {
double h(double height) {
return MediaQuery.of(context).size.height * height;
}
double w(double width) {
return MediaQuery.of(context).size.width * width;
}
void showNotification(String dat) {
flutterLocalNotificationsPlugin.show(
0,
"Powerstrip",
"Charging $dat",
NotificationDetails(
android: AndroidNotificationDetails(channel.id, channel.name,
importance: Importance.high,
color: Colors.blue,
playSound: true,
icon: '#mipmap/ic_launcher')));
}
CountDownController _controller = CountDownController();
Timer? countdownTimer;
Duration myDuration = Duration();
#override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
Provider.of<ChargeTimeProvider>(context, listen: false)
.setDuration(Duration(minutes: widget.duration));
startTimer();
});
}
void setCountDown() {
final reduceSecondsBy = 1;
var seconds = Provider.of<ChargeTimeProvider>(context, listen: false)
.getDuration()
.inSeconds -
reduceSecondsBy;
log("got seconds from provider " + seconds.toString());
if (seconds < 0) {
countdownTimer?.cancel();
showNotification("Stopped");
log("$charging");
} else {
Provider.of<ChargeTimeProvider>(context, listen: false)
.setDuration(Duration(seconds: seconds));
// myDuration = Duration(seconds: seconds);
}
// setState(() {
// final seconds = myDuration.inSeconds - reduceSecondsBy;
// });
}
void startTimer() {
showNotification("Started");
context.read<ChargeTimeProvider>().setChargeStatus(true);
countdownTimer =
Timer.periodic(Duration(seconds: 1), (_) => setCountDown());
}
void stoptimer() {
Provider.of<ChargeTimeProvider>(context, listen: false)
.setChargeStatus(false);
// context.read<ChargeTimeProvider>().setChargeStatus(false);
log("$charging");
countdownTimer?.cancel();
}
String mins = "";
String sec = "";
var minutesChargedfor;
Future<bool> _onWillPop() async {
return (await showDialog(
barrierDismissible: true,
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.black,
title: Text(
'Are you sure?',
style: GoogleFonts.sulphurPoint(color: Colors.white),
),
content: Text(
'Do you want to go to home screen',
style: GoogleFonts.sulphurPoint(color: Colors.white),
),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.pop(context);
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext) => Navigation()));
},
child: const Text('Yes'),
),
],
),
)) ??
false;
}
#override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () => _onWillPop(),
child: Scaffold(
backgroundColor: Color(0xff1B1D20),
body: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 70),
Center(
child: Container(
padding: EdgeInsets.all(12),
// margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(7),
),
child: Text(
"Congratulations, you've added Green milesπŸ€",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Colors.green.shade600),
),
),
),
const SizedBox(
height: 20,
),
Center(
child: Column(
children: [
Center(
child: CircularCountDownTimer(
duration: widget.duration * 60,
controller: _controller,
width: MediaQuery.of(context).size.width / 2,
height: MediaQuery.of(context).size.height / 2,
ringColor: Colors.grey[400]!,
ringGradient: const LinearGradient(
colors: [Colors.white10, Colors.white70]),
fillColor: Colors.blue,
fillGradient: LinearGradient(colors: [
Colors.blue.shade300,
Colors.blue.shade900
]),
backgroundColor: Colors.grey[500],
backgroundGradient: LinearGradient(colors: [
Colors.grey.shade900,
Colors.grey.shade500
]),
strokeWidth: 20.0,
strokeCap: StrokeCap.round,
textStyle: const TextStyle(
fontSize: 33.0,
color: Colors.white,
fontWeight: FontWeight.bold),
// textFormat: CountdownTextFormat.MM_SS,
isTimerTextShown: true,
isReverse: false,
onComplete: () async {
var secondsChargedfor = widget.duration * 60;
var res = AssistantMethods.stopCharging(
secondsChargedfor, "0");
if (res != "failure") {
await Ble.disconnectDevice(connectedDevice);
stoptimer();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => Charging_summary(
amount: widget.amount,
duration: widget.duration,
mins: mins,
sec: sec)));
} else {
Fluttertoast.showToast(msg: res);
}
Ble.disconnectDevice(connectedDevice);
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (_) => Charging_summary(
amount: widget.amount,
duration: widget.duration,
mins: mins,
sec: sec)));
},
),
),
// SizedBox(height: 10,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.flash_on,
size: 30,
color: Colors.blue,
),
SizedBox(
width: 7,
),
Text(
"Charging",
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.w400),
)
],
),
BuildTime(),
],
),
),
const SizedBox(
height: 40,
),
Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Container(
padding: EdgeInsets.all(15),
// height: 130,
// width:MediaQuery.of(context).size.width ,
decoration: const BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.only(
topRight: Radius.circular(10.0),
topLeft: Radius.circular(10.0)),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
user_device_id.toString(),
style: const TextStyle(
fontSize: 14,
color: Colors.white,
fontWeight: FontWeight.w400),
),
],
),
device_type == 0
? Text(
"β‚Ή${widget.amount}",
style: const TextStyle(
fontWeight: FontWeight.w500,
fontSize: 18,
color: Colors.white),
)
: const Text(""),
],
),
const SizedBox(
height: 10,
),
Row(
children: [
Expanded(
child: ElevatedButton(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
primary: Colors.red.shade900,
padding: const EdgeInsets.symmetric(
horizontal: 50, vertical: 15),
// minimumSize: Size(50,20 ),
),
child: const Text(
"Stop",
style: TextStyle(
fontSize: 15, color: Colors.white),
),
onPressed: () async {
var secondsChargedfor = widget.duration * 60;
secondsChargedfor = secondsChargedfor -
(int.parse(mins) * 60 + int.parse(sec));
log(secondsChargedfor.toString());
var res = AssistantMethods.stopCharging(
secondsChargedfor, "1");
if (res != "failure") {
await Ble.startStopTimer(services,
0.toString()); // to stop the charging
_controller.pause();
await Ble.disconnectDevice(connectedDevice);
stoptimer();
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>
Charging_summary(
amount: widget.amount,
duration: widget.duration,
mins: mins,
sec: sec)));
} else {
Fluttertoast.showToast(msg: res);
}
},
),
),
],
),
],
),
),
),
],
),
],
),
//bottomNavigationBar: bottbar(),
),
);
}
Widget BuildTime() {
String twoDigits(int n) => n.toString().padLeft(2, '0');
final hours = twoDigits(
context.read<ChargeTimeProvider>().getDuration().inHours.remainder(24));
final minutes = twoDigits(context
.read<ChargeTimeProvider>()
.getDuration()
.inMinutes
.remainder(60));
final seconds = twoDigits(context
.read<ChargeTimeProvider>()
.getDuration()
.inSeconds
.remainder(60));
mins = minutes;
sec = seconds;
Provider.of<ChargeTimeProvider>(context, listen: true)
.setTime("$hours:$minutes:$seconds");
return Consumer<ChargeTimeProvider>(
builder: (context, chargetimenotifier, child) => Text(
"${chargetimenotifier.getTime()} Time Remaining",
style: TextStyle(fontSize: 14, color: Colors.white),
));
}
#override
void dispose() {
super.dispose();
}
}

Add Some Delay
Future.delayed(const Duration(milliseconds: 500), () {
// Here you can write your code
setState(() {
// Here you can write your code for open new view
});
});

Related

Flutter - ScrollController was used after being disposed

class HomeScreen extends StatefulWidget {
final userName;
HomeScreen(this.userName);
#override
State<HomeScreen> createState() => _HomeScreenState();
}
Future<ClientDashboardModel?>? _meterReadingResponse;
BatchSummaryModel? _batchResponse;
AMRDashboardModel? _amrDashboardResponse;
String _userName = '';
int? qcAssignedReads = 0;
int? qcMrCompleted = 0;
int? qcCompletedReads = 0;
int? qcPendingReads = 0;
int? qcApprovedReads = 0;
int? qcRejectedReads = 0;
bool isFirstTimeCalled = false;
Timer? _timer;
int _currentIndex = 0;
final pages = [
const MDMScreen(),
const AMRDashboard(whichScreen: 0),
const AMRDashboard(whichScreen: 1),
const AMRDashboard(whichScreen: 2)
];
class _HomeScreenState extends State<HomeScreen> {
#override
void initState() {
setUpTimedFetch();
super.initState();
if (widget.userName != null) _userName = (widget.userName!);
}
#override
void dispose() {
isFirstTimeCalled = false;
_timer?.cancel();
super.dispose();
}
void setUpTimedFetch() {
if (!isFirstTimeCalled) {
_meterReadingResponse = _getDashboardData();
}
isFirstTimeCalled = true;
}
Future<ClientDashboardModel?> _getDashboardData() async {
ClientDashboardModel? meterReadingResponse;
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('token')!;
var responseData = await Dashboard().getClientDashboard(token);
if (responseData.statusCode == 200) {
String data = responseData.body;
var decodedData = jsonDecode(data);
meterReadingResponse = null;
meterReadingResponse = ClientDashboardModel.fromJson(decodedData);
return meterReadingResponse;
}
return null;
}
void logout() async {
SharedPreferences.getInstance().then((value) {
value.remove('token');
value.remove('userName');
});
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) {
return const LoginScreen();
}));
}
Future<void> _showMyDialog() async {
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: const Text(Strings.kLogoutLabel),
content: const Text(Strings.kConfirmLogout),
actions: <Widget>[
TextButton(
child: const Text(Strings.kCancelLabel),
onPressed: () {
Navigator.of(context).pop();
},
),
TextButton(
child: const Text(Strings.kOKLabel),
onPressed: () {
Navigator.of(context).pop();
logout();
},
)
],
);
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
currentIndex: _currentIndex,
backgroundColor: const Color(0XFF116AFF),
unselectedItemColor: Colors.white,
selectedLabelStyle: const TextStyle(color: Colors.white),
showUnselectedLabels: false,
onTap: (value) {
setState(() => _currentIndex = value);
},
items: [
BottomNavigationBarItem(
label: 'MDM',
icon: Container(
decoration: BoxDecoration(
color:
_currentIndex == 0 ? Colors.white : Colors.transparent,
shape: BoxShape.circle),
child: const Padding(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.electric_meter_outlined),
),
),
),
BottomNavigationBarItem(
label: 'Site Survey',
icon: Container(
decoration: BoxDecoration(
color:
_currentIndex == 1 ? Colors.white : Colors.transparent,
shape: BoxShape.circle),
child: const Padding(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.location_city_outlined),
),
),
),
BottomNavigationBarItem(
label: 'Meter Replace',
icon: Container(
decoration: BoxDecoration(
color:
_currentIndex == 2 ? Colors.white : Colors.transparent,
shape: BoxShape.circle),
child: const Padding(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.library_books_outlined),
),
),
),
BottomNavigationBarItem(
label: 'TroubleShoot',
icon: Container(
decoration: BoxDecoration(
color:
_currentIndex == 3 ? Colors.white : Colors.transparent,
shape: BoxShape.circle),
child: const Padding(
padding: EdgeInsets.all(10.0),
child: Icon(Icons.info_outline),
),
),
),
],
),
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text(Strings.kMRDLabel),
actions: [
IconButton(
onPressed: () {
_showMyDialog();
},
icon: const Icon(Icons.power_settings_new))
],
),
body: childView());
}
Widget childView() {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
Strings.kWelcome2Label,
style: TextStyle(
color: Colors.amber.shade700,
fontSize: 16.0,
fontWeight: FontWeight.w600),
),
Text(
_userName.toTitleCase(),
style: const TextStyle(
color: Colors.black,
fontSize: 16.0,
fontWeight: FontWeight.w400),
)
],
),
const Spacer(),
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(color: Colors.grey.shade200),
child: SvgPicture.asset(
'images/profile.svg',
height: 54.0,
width: 54.0,
),
),
),
],
),
const SizedBox(
height: 30,
),
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [pages[_currentIndex]],
),
],
),
));
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:manager/components/dotted_line.dart';
import 'package:manager/model/lookup_cycle.dart';
import 'package:manager/model/mr_report_model.dart';
import 'package:manager/services/dashboard_service.dart';
import 'package:manager/utils/debouncer.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:manager/utils/string_captialize.dart';
class MRPerformance extends StatefulWidget {
const MRPerformance({super.key});
#override
State<MRPerformance> createState() => _MRPerformanceState();
}
bool isFilter = false;
bool isPerformingRequest = false;
int pageNumber = 0;
String _chosenValue = '';
List<MRReportResult> users = [];
Future<List<String>?>? dropDownValue;
ScrollController _scrollController = ScrollController();
final _debouncer = Debouncer(milliseconds: 500);
class _MRPerformanceState extends State<MRPerformance> {
#override
void initState() {
super.initState();
_getMoreData(_chosenValue);
dropDownValue = getAllCategory();
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
pageNumber++;
_getMoreData(_chosenValue);
}
});
}
Future<List<String>?>? getAllCategory() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('token')!;
var cycleResponse = await Dashboard().getAllCycle(token);
try {
if (cycleResponse.statusCode == 200) {
List<String> items = [];
var jsonData = json.decode(cycleResponse.body) as List;
List<LookUpCycle> lookupCycle = jsonData
.map<LookUpCycle>((json) => LookUpCycle.fromJson(json))
.toList();
items.add('Select');
for (var element in lookupCycle) {
if (element.name != null) {
items.add(element.name!);
}
}
return items;
}
} catch (ex) {
throw (ex.toString());
}
return null;
}
#override
void dispose() {
super.dispose();
_scrollController.dispose();
}
void _getMoreData(String searchCycle) async {
List<MRReportResult>? resultResponse = [];
if (!isPerformingRequest) {
setState(() {
isPerformingRequest = true;
});
SharedPreferences prefs = await SharedPreferences.getInstance();
String token = prefs.getString('token')!;
debugPrint(token);
var responseData =
await Dashboard().getMRReport(token, pageNumber, 10, searchCycle);
if (responseData.statusCode == 200) {
String data = responseData.body;
var decodedData = jsonDecode(data);
MRReportModel newEntries = MRReportModel.fromJson(decodedData);
if (newEntries.result == null) {
if (newEntries.result!.isEmpty) {
double edge = 50.0;
double offsetFromBottom =
_scrollController.position.maxScrollExtent -
_scrollController.position.pixels;
if (offsetFromBottom < edge) {
_scrollController.animateTo(
_scrollController.offset - (edge - offsetFromBottom),
duration: const Duration(milliseconds: 500),
curve: Curves.easeOut);
}
}
}
setState(() {
users.addAll(newEntries.result!);
isPerformingRequest = false;
});
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: AppBar(title: const Text('MR Performance')),
body: filterView());
}
void setFilterState() {
setState(() {
if (isFilter == true) {
isFilter = false;
} else {
isFilter = true;
}
});
}
Widget _buildProgressIndicator() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: Opacity(
opacity: isPerformingRequest ? 1.0 : 0.0,
child: const CircularProgressIndicator(),
),
),
);
}
Widget filterView() {
return Column(
children: [
Row(
children: [
Visibility(
visible: isFilter ? true : false,
child: Flexible(
child: Card(
shape: RoundedRectangleBorder(
side: const BorderSide(color: Color(0XFFDCDCDC)),
borderRadius: BorderRadius.circular(10)),
elevation: 2,
child: Column(
children: [
Row(
children: [
Expanded(
child: TextField(
textInputAction: TextInputAction.search,
decoration: const InputDecoration(
border: InputBorder.none,
prefixIcon: InkWell(
child: Icon(Icons.search),
),
contentPadding: EdgeInsets.all(8.0),
hintText: 'Search ',
),
onChanged: (string) {
_debouncer.run(() {});
},
),
),
],
),
],
),
),
),
),
Visibility(
visible: isFilter ? false : true,
child: Flexible(
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
side: const BorderSide(color: Color(0XFFDCDCDC)),
borderRadius: BorderRadius.circular(10)),
child: Padding(
padding: const EdgeInsets.only(
left: 10,
),
child: FutureBuilder<List<String>?>(
future: dropDownValue,
builder: (context, snapshot) {
if (snapshot.connectionState ==
ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Something wrong');
} else if (snapshot.hasData) {
var data = snapshot.data!;
return DropdownButtonHideUnderline(
child: DropdownButton<String>(
icon: const Icon(
Icons.expand_more_outlined,
size: 35,
color: Color(0XFF116AFF),
),
borderRadius: BorderRadius.circular(10),
isExpanded: true,
// value: _chosenValue.isNotEmpty ? _chosenValue : null,
elevation: 16,
style: const TextStyle(
color: Colors.black,
fontSize: 14,
fontWeight: FontWeight.w400),
items: data.map((String value) {
return DropdownMenuItem(
value: value, child: Text(value));
}).toList(),
hint: Padding(
padding: const EdgeInsets.all(15),
child: Text(
_chosenValue.isEmpty
? 'Cycle'
: _chosenValue,
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w400),
),
),
onChanged: (String? value) {
setState(() {
if (value != null) {
pageNumber = 0;
users.clear();
if (value == 'Select') {
_chosenValue = '';
} else {
_chosenValue = value;
}
_getMoreData(_chosenValue);
}
});
},
),
);
}
}
return const CircularProgressIndicator();
},
)),
),
),
),
InkWell(
onTap: () => {setFilterState()},
child: Card(
elevation: 4,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10)),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: isFilter
? const Icon(Icons.filter_alt, color: Color(0XFF116AFF))
: const Icon(
Icons.search,
color: Color(0XFF116AFF),
),
),
),
),
],
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: users.length + 1,
controller: _scrollController,
itemBuilder: (BuildContext context, int index) {
if (index == users.length) {
return _buildProgressIndicator();
} else {
return cardView(users, index);
}
}),
),
],
);
}
Widget cardView(List<MRReportResult>? users, int index) {
return Card(
shape: RoundedRectangleBorder(
side: const BorderSide(color: Color(0XFFDCDCDC)),
borderRadius: BorderRadius.circular(10)),
margin: const EdgeInsets.all(8),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Container(
decoration: BoxDecoration(
border: Border.all(
color: Colors.orange,
),
borderRadius: const BorderRadius.all(Radius.circular(20))),
margin: const EdgeInsets.all(10),
padding: const EdgeInsets.all(10),
child: Row(
children: [
Text(
'${users?[index].mRNumber}: ',
style: const TextStyle(
color: Colors.orange,
fontSize: 10,
fontWeight: FontWeight.w600),
),
Text(
'${users?[index].meterReaderName}'.toTitleCase(),
style: const TextStyle(
color: Colors.black,
fontSize: 10,
fontWeight: FontWeight.w400),
),
],
),
),
Padding(
padding: const EdgeInsets.only(left: 20),
child: Row(
children: [
const Text(
'Supervisor: ',
style: TextStyle(
color: Color(0XFF004AC6),
fontSize: 10,
fontWeight: FontWeight.w600),
),
Expanded(
child: Text(
'${users?[index].supervisor}'.toTitleCase(),
overflow: TextOverflow.fade,
style: const TextStyle(
color: Colors.black,
fontSize: 10,
fontWeight: FontWeight.w400),
),
),
],
),
),
const SizedBox(height: 10),
const MySeparator(),
const SizedBox(height: 10),
Padding(
padding: const EdgeInsets.only(left: 30, right: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Column(
children: [
Text(
'${users?[index].unreadPercenatge}%',
style: const TextStyle(
color: Colors.orange,
fontSize: 10,
fontWeight: FontWeight.w600),
),
const Text(
'Unread',
style: TextStyle(
color: Color(0XFF004AC6),
fontSize: 12,
fontWeight: FontWeight.w400),
)
],
)
],
),
Row(
children: [
Column(
children: [
Text(
'${users?[index].readPercenatge}%',
style: const TextStyle(
color: Colors.green,
fontSize: 10,
fontWeight: FontWeight.w600),
),
const Text(
'Read',
style: TextStyle(
color: Color(0XFF004AC6),
fontSize: 12,
fontWeight: FontWeight.w400),
)
],
)
],
),
Row(
children: [
Column(
children: [
Text(
'${users?[index].plusorMinusTwoReadPercentage}%',
style: const TextStyle(
color: Colors.green,
fontSize: 10,
fontWeight: FontWeight.w600),
),
const Text(
'+/- 2',
style: TextStyle(
color: Color(0XFF004AC6),
fontSize: 12,
fontWeight: FontWeight.w400),
)
],
)
],
),
Row(
children: [
Column(
children: [
Text(
'${users?[index].above32ReadPercentage}%',
style: const TextStyle(
color: Colors.orange,
fontSize: 10,
fontWeight: FontWeight.w600),
),
const Text(
'>32',
style: TextStyle(
color: Color(0XFF004AC6),
fontSize: 12,
fontWeight: FontWeight.w400),
)
],
)
],
),
],
),
),
],
),
),
);
}
}
════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building Builder:
A ScrollController was used after being disposed.
Once you have called dispose() on a ScrollController, it can no longer be used.
The relevant error-causing widget was
MaterialApp
lib/main.dart:13
When the exception was thrown, this was the stack
You have declared _getMoreData two times in init(), so remove it before _scrollController as shown below
void initState() {
super.initState();
_getMoreData(_chosenValue);-------------> remove this from here
dropDownValue = getAllCategory();
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
pageNumber++;
_getMoreData(_chosenValue);
}
});
}
OR
Declare ScrollController _scrollController = ScrollController(); in state class _MRPerformanceState as below code:
class _MRPerformanceState extends State<MRPerformance> {
ScrollController _scrollController = ScrollController();

making my flutter music player play in background

i am fairly new in flutter and i am trying to make a music player app.
the app works fine and all but the problem is it doesnot play in background/lockscreen.
i went through some docs and it says to use audio_service package for that but i am currently using flutter_audio_query package...all the docs i went through shows a solution which results in entirely changing the code...
so my question is ...is there any way to make the app play in background without changing the code entirely?
heres what my code looks like
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_audio_query/flutter_audio_query.dart';
import 'package:just_audio/just_audio.dart';
class MusicPlayer extends StatefulWidget {
SongInfo songInfo;
Function changeTrack;
final GlobalKey<MusicPlayerState> key;
MusicPlayer({required this.songInfo, required this.changeTrack, required this.key}):super(key: key);
#override
MusicPlayerState createState() => MusicPlayerState();
}
class MusicPlayerState extends State<MusicPlayer> {
double minimumValue = 0.0, maximumValue = 0.0, currentValue = 0.0;
String currentTime = '', endTime = '';
bool isPlaying = false;
final AudioPlayer player = AudioPlayer();
void initState() {
super.initState();
setSong(widget.songInfo);
}
void dispose(){
super.dispose();
player?.dispose();
}
void setSong(SongInfo songInfo) async {
widget.songInfo = songInfo;
await player.setUrl(widget.songInfo.uri);
currentValue = minimumValue;
maximumValue = player.duration!.inMilliseconds.toDouble();
setState(() {
currentTime = getDuration(currentValue);
endTime = getDuration(maximumValue);
});
isPlaying=false;
changeStatus();
player.positionStream.listen((duration) {
currentValue=duration.inMilliseconds.toDouble();
setState((){
currentTime=getDuration(currentValue);
});
});
}
void changeStatus(){
setState((){
isPlaying=!isPlaying;
});
if(isPlaying){
player.play();
}else{
player.pause();
}
}
String getDuration(double value) {
Duration duration = Duration(milliseconds: value.round());
return [duration.inMinutes, duration.inSeconds]
.map((e) => e.remainder(60).toString().padLeft(2, '0'))
.join(':');
}
Widget build(context) {
return Scaffold(
backgroundColor: Colors.black38,
appBar: AppBar(
backgroundColor: Colors.black,
leading: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(
Icons.arrow_back,
color: Colors.white,
),
),
title: const Text(
'Now Playing',
style: TextStyle(color: Colors.white),
),
),
body: Container(
margin: EdgeInsets.fromLTRB(15, 50, 5, 0),
child: Column(
children: <Widget>[
CircleAvatar(
backgroundImage: widget.songInfo.albumArtwork == null
? AssetImage('assets/images/album_image.jpg')
: FileImage(
File(widget.songInfo.albumArtwork),
) as ImageProvider,
radius: 95,
),
Container(
color: Colors.black,
margin: EdgeInsets.fromLTRB(0, 10, 0, 7),
child: Text(
widget.songInfo.title,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600),
),
),
Container(
color: Colors.black,
margin: EdgeInsets.fromLTRB(0, 0, 0, 15),
child: Text(
widget.songInfo.artist,
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500),
),
),
Slider(
value: currentValue,
min: minimumValue,
max: maximumValue,
onChanged: (value) {
currentValue = value;
player.seek(Duration(milliseconds: currentValue.round()));
},
inactiveColor: Colors.grey,
activeColor: Colors.green,
),
Container(
transform: Matrix4.translationValues(0, -5, 0),
margin: EdgeInsets.fromLTRB(5, 0, 5, 15),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
currentTime,
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500),
),
Text(
endTime,
style: TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.w500),
),
],
),
),
Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
GestureDetector(
child: Icon(Icons.skip_previous,
color: Colors.white, size: 55,),
behavior: HitTestBehavior.translucent,
onTap: () {
widget.changeTrack(false);
},
),
GestureDetector(
child: Icon(isPlaying?Icons.pause:Icons.play_arrow,
color: Colors.white, size: 75,),
behavior: HitTestBehavior.translucent,
onTap: () {
changeStatus();
},
),
GestureDetector(
child: Icon(Icons.skip_next,
color: Colors.white, size: 55,),
behavior: HitTestBehavior.translucent,
onTap: () {
widget.changeTrack(true);
},
),
],
),
),
],
),
),
);
}
}
appreciate any help that i can get...thank you
The description of "flutter_audio_query" says clearly that it is no audio player. It is a library to fetch music albums and covers.
"audio_service" on the other hand says clearly that it is for playing audio.
I would suggest to start again if you won't cause problems which could be avoided
Use the dependency assets_audio_player. it has a built-in function for this no need to even code. there is a little one-screen player for you. Just copy paste the code below and must add all the dependencies. Music will be played in background, on notification bar and on lock screen.
import 'dart:convert';
import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:musiccontrol/MusicPlayerModel.dart';
class Home extends StatefulWidget {
Home({
super.key,
t,
});
MusicPlaylist? _musicPlaylist;
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
List SongsList = [];
bool MuteVolume = false;
// Fetch content from the json file
final AssetsAudioPlayer audioplayer = AssetsAudioPlayer();
double screenwidth = 0;
double screenheight = 0;
#override
void initState() {
super.initState();
setupPlaylist();
}
// songs paths and links
void setupPlaylist() async {
await audioplayer.open(
showNotification: true,
Playlist(audios: [
// Audio(SongsList[2].,
// metas: Metas(
// title: "Bazz01",
// artist: 'Talha',
// )),
Audio.network(
'https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview125/v4/09/17/bb/0917bbe1-58c3-6252-d00e-9b70d42ef5dc/mzaf_2269500085377778268.plus.aac.p.m4a',
metas: Metas(
id: 'Online',
title: 'Online',
artist: 'Florent Champigny',
album: 'OnlineAlbum',
// image: MetasImage.network('https://www.google.com')
image: const MetasImage.network(
'https://i.dawn.com/large/2021/09/61399fb500900.png'),
),
),
Audio.network(
'https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview125/v4/09/17/bb/0917bbe1-58c3-6252-d00e-9b70d42ef5dc/mzaf_2269500085377778268.plus.aac.p.m4a',
metas: Metas(
id: 'Online',
title: 'Online',
artist: 'Florent Champigny',
album: 'OnlineAlbum',
// image: MetasImage.network('https://www.google.com')
image: const MetasImage.network(
'https://i.dawn.com/large/2021/09/61399fb500900.png'),
),
),
]),
autoStart: true,
loopMode: LoopMode.playlist,
);
}
var forward= AssetImage('assets/forward.png');
#override
void dispose() {
super.dispose();
setupPlaylist();
}
Widget slider(RealtimePlayingInfos realtimePlayingInfos) {
return SliderTheme(
data: const SliderThemeData(
thumbShape: RoundSliderThumbShape(enabledThumbRadius: 8),
),
child: Slider.adaptive(
activeColor: const Color.fromARGB(255, 241, 241, 241),
inactiveColor: const Color.fromARGB(255, 219, 217, 217),
thumbColor: const Color.fromARGB(255, 255, 255, 255),
value: realtimePlayingInfos.currentPosition.inSeconds.toDouble(),
max: realtimePlayingInfos.duration.inSeconds.toDouble(),
onChanged: (value) {
audioplayer.seek(Duration(seconds: value.toInt()));
}));
}
Widget timeStamps(RealtimePlayingInfos realtimePlayingInfos) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
transformString(realtimePlayingInfos.currentPosition.inSeconds),
style: const TextStyle(color: Colors.white),
),
Text(transformString(realtimePlayingInfos.duration.inSeconds),
style: const TextStyle(color: Colors.white)),
],
);
}
// slider timings
String transformString(int seconds) {
String minuteString =
'${(seconds / 60).floor() < 10 ? 0 : ''}${(seconds / 60).floor()}';
String secondString = '${seconds % 60 < 10 ? 0 : ' '}${seconds % 60}';
return '$minuteString:$secondString';
}
//control buttons of music player
Widget playBar(RealtimePlayingInfos realtimePlayingInfos) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Icon_Button(
icon: Icons.compare_arrows_rounded,
size: 21,
passedfunc: () {
audioplayer.toggleShuffle();
}),
Icon_Button(
icon: Icons.fast_rewind_rounded,
size: 21,
passedfunc: () {
audioplayer.seekBy(const Duration(seconds: -15));
}),
Icon_Button(
icon: Icons.skip_previous_rounded,
size: 21,
passedfunc: () => audioplayer.previous()),
Icon_Button(
icon: realtimePlayingInfos.isPlaying
? Icons.pause_circle_filled_rounded
: Icons.play_circle_fill_rounded,
size: 50,
passedfunc: () => audioplayer.playOrPause()),
Icon_Button(
icon: Icons.skip_next_rounded,
size: 21,
passedfunc: () => audioplayer.next()),
Icon_Button(
icon: Icons.fast_forward_rounded,
size: 21,
passedfunc: () {
setState(() {
audioplayer.seekBy(const Duration(seconds: 15));
});
}),
Icon_Button(
icon: MuteVolume == true
? Icons.volume_off_outlined
: Icons.volume_up,
size: 21,
passedfunc: () {
if (MuteVolume == true) {
setState(() {
audioplayer.setVolume(1);
MuteVolume = !MuteVolume;
});
} else {
audioplayer.setVolume(0);
MuteVolume = !MuteVolume;
}
},
),
],
),
);
}
#override
Widget build(BuildContext context) {
// screenheight = MediaQuery.of(context).size.height;
// screenwidth = MediaQuery.of(context).size.width;
return Scaffold(
backgroundColor: const Color.fromARGB(31, 142, 111, 253),
body: audioplayer.builderRealtimePlayingInfos(
builder: (context, realtimePlayingInfos) {
// ignore: unnecessary_null_comparison
if (realtimePlayingInfos != null) {
return Column(
//Designing Texts and image
children: [
Padding(
padding: const EdgeInsets.all(23.0),
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: Image.network(
'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTUyCn1ItXdchQzeH8MkPEtQJcKttTplAw7oDrBuQI&s',
height: 70,
width: 70,
)),
Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Sound Cloud',
style: TextStyle(color: Colors.white, fontSize: 18),
),
const Text(
'Name Goes',
style: TextStyle(color: Colors.white, fontSize: 15),
),
const Text(
'Song Name Goes here',
style: TextStyle(color: Colors.white, fontSize: 20),
),
],
),
),
],
),
),
// slider code is here
Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
slider(realtimePlayingInfos),
SizedBox(
height: screenheight * 0.05,
),
timeStamps(realtimePlayingInfos),
SizedBox(
height: screenheight * 0.05,
),
playBar(realtimePlayingInfos),
],
)
],
),
],
);
} else {
return Column();
}
}),
);
}
}
// Icon_Button custom widget
// ignore: camel_case_types, must_be_immutable
class Icon_Button extends StatelessWidget {
Icon_Button(
{super.key,
required this.icon,
required this.size,
required this.passedfunc});
IconData icon;
double size;
final passedfunc;
#override
Widget build(BuildContext context) {
return IconButton(
onPressed: passedfunc,
icon: Icon(icon),
iconSize: size,
color: Colors.grey,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
);
}
}

Why is Flutter BloC UI not updating after app restart despite state change in observer?

I concede that there are many questions similar to mine, but I have not found a satisfactory answer from those questions. So I decided to make my own question specifying my problem. I have 3 BloCs in my program each with different purposes. They all share similar problems, as such I will ask on one of those BloCs with the hope that one solution will fix all of the BloCs.
The problem is this, if I just started the application and have logged in, the BloC will update the UI. If I have logged in, exited the app, and restarted it, the Bloc will not update the UI. The Bloc in question is called DetailpersonilBloc with 1 event called Detail and 2 states called DetailpersonilInitial and Loaded. At the event of Detail, the state Loaded should be emitted.
I called Detail at LoginPage and at GajiPage at initState. This works when I just opened the app, but does not work when I restart the app. I also have equatable thinking that it will help me but apparently it changes nothing.
Note: The "..." at the GajiPage is just some code that I believe is not necessary for reproduction.
DetailpersonilBloc
part 'detailpersonil_event.dart';
part 'detailpersonil_state.dart';
class DetailpersonilBloc
extends Bloc<DetailpersonilEvent, DetailpersonilState> {
DetailpersonilBloc() : super(const DetailpersonilInitial()) {
on<Detail>((event, emit) async {
SharedPreferences pref = await SharedPreferences.getInstance();
String name = pref.getString('nama');
String nrp = pref.getString('NRP');
String pangkat = pref.getString('pangkat');
String jabatan = pref.getString('jabatan');
String satker = pref.getString('satker');
String polda = pref.getString('polda');
String npwp = pref.getString('NPWP');
String rekening = pref.getString('rekening');
String bank = pref.getString('bank');
emit(Loaded(
name,
nrp,
pangkat,
jabatan,
satker,
polda,
npwp,
rekening,
bank,
));
});
}
}
DetailpersonilEvent
part of 'detailpersonil_bloc.dart';
#immutable
abstract class DetailpersonilEvent extends Equatable {}
class Detail extends DetailpersonilEvent {
#override
List<Object> get props => [];
}
DetailpersonilState
part of 'detailpersonil_bloc.dart';
#immutable
abstract class DetailpersonilState extends Equatable {
final String nama;
final String nrp;
final String pangkat;
final String jabatan;
final String satker;
final String polda;
final String npwp;
final String rekening;
final String bank;
const DetailpersonilState(
{this.nama,
this.nrp,
this.pangkat,
this.jabatan,
this.satker,
this.polda,
this.npwp,
this.rekening,
this.bank});
}
class DetailpersonilInitial extends DetailpersonilState {
const DetailpersonilInitial()
: super(
nama: 'Nama',
nrp: 'NRP',
pangkat: 'Pangkat',
jabatan: 'Jabatan',
satker: 'Satker',
polda: 'Polda',
npwp: 'NPWP',
rekening: 'No Rekening',
bank: 'Nama Bank',
);
#override
List<Object> get props =>
[nama, nrp, pangkat, jabatan, satker, polda, npwp, rekening, bank];
}
class Loaded extends DetailpersonilState {
const Loaded(
String nama,
String nrp,
String pangkat,
String jabatan,
String satker,
String polda,
String npwp,
String rekening,
String bank,
) : super(
nama: nama,
nrp: nrp,
pangkat: pangkat,
jabatan: jabatan,
satker: satker,
polda: polda,
npwp: npwp,
rekening: rekening,
bank: bank);
#override
List<Object> get props =>
[nama, nrp, pangkat, jabatan, satker, polda, npwp, rekening, bank];
}
LoginPage
class LoginPage extends StatefulWidget {
const LoginPage({Key key}) : super(key: key);
#override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
double width = 0;
double height = 0;
TextEditingController nrpController = TextEditingController();
TextEditingController sandiController = TextEditingController();
final formKey = GlobalKey<FormState>();
DetailpersonilBloc detailPersonilBloc;
GajiBloc gajiBloc;
TunkinBloc tunkinBloc;
bool passwordVisible = false;
#override
void initState() {
super.initState();
checkToken();
}
void checkToken() async {
SharedPreferences pref = await SharedPreferences.getInstance();
if (pref.getString('token') != null) {
detailPersonilBloc = DetailpersonilBloc();
gajiBloc = GajiBloc();
tunkinBloc = TunkinBloc();
detailPersonilBloc.add(Detail());
gajiBloc.add(Gaji());
tunkinBloc.add(Tunkin());
Navigator.push(
context, MaterialPageRoute(builder: (context) => const MainPage()));
}
}
onLogin(DetailpersonilBloc detailPersonilBloc) async {
if (formKey.currentState.validate()) {
var token = await APIService.generateToken(
nrpController.text, sandiController.text);
if (token != null) {
SharedPreferences pref = await SharedPreferences.getInstance();
await pref.setString('token', token.token);
var detail = await APIService.getDetailPersonil(token.token);
await pref.setString('nama', detail.nMPEG);
await pref.setString('NRP', detail.nRP);
await pref.setString('pangkat', detail.nMGOL1);
await pref.setString('jabatan', detail.sEBUTJAB);
await pref.setString('satker', detail.nMSATKER);
await pref.setString('polda', detail.nMUAPPAW);
await pref.setString('NPWP', detail.nPWP);
await pref.setString('rekening', detail.rEKENING);
await pref.setString('bank', detail.nMBANK);
nrpController.clear();
sandiController.clear();
detailPersonilBloc.add(Detail());
Navigator.push(
context, MaterialPageRoute(builder: (context) => const MainPage()));
} else {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text('Error'),
content: Text('Login Gagal'),
actions: [
ElevatedButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('Tutup'),
),
],
);
},
);
}
}
}
#override
Widget build(BuildContext context) {
var detailPersonilBloc = BlocProvider.of<DetailpersonilBloc>(context);
width = MediaQuery.of(context).size.width;
height = MediaQuery.of(context).size.height;
return Scaffold(
body: Stack(
children: [
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: const [
Opacity(
opacity: 0.5,
child: Image(
image: AssetImage('images/bg-map-min.png'),
),
),
],
),
SingleChildScrollView(
padding: EdgeInsets.only(top: 100),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
SizedBox(
height: 100,
width: width,
child: const Image(
image: AssetImage('images/login-logo.png'),
alignment: Alignment.center,
),
),
Container(
padding: const EdgeInsets.all(15),
child: const Text(
'GAJI DAN TUNKIN',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
Form(
key: formKey,
child: Column(
children: [
Container(
margin: const EdgeInsets.all(20 - 2.6),
child: Card(
elevation: 10,
child: Container(
padding: const EdgeInsets.all(20),
child: Column(
children: [
Container(
alignment: Alignment.topLeft,
padding: const EdgeInsets.only(bottom: 20),
child: const Text(
'LOGIN',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Container(
padding: const EdgeInsets.only(bottom: 25),
child: TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Masukkan NRP/NIP';
}
return null;
},
controller: nrpController,
decoration: InputDecoration(
labelText: 'NRP/NIP',
hintText: 'Masukkan NRP/NIP',
prefixIcon: Icon(Icons.person,
color: Colors.blue.shade700),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
),
TextFormField(
obscureText: !passwordVisible,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Masukkan Kata Sandi';
}
return null;
},
controller: sandiController,
decoration: InputDecoration(
labelText: 'Kata Sandi',
hintText: 'Masukkan Kata Sandi',
prefixIcon: Icon(Icons.lock,
color: Colors.blue.shade700),
suffixIcon: IconButton(
onPressed: () {
setState(() {
passwordVisible = !passwordVisible;
});
},
icon: Icon(
passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: Colors.blue.shade700,
),
),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),
),
)
],
),
),
),
),
ElevatedButton(
onPressed: () async {
await onLogin(detailPersonilBloc);
},
child: const Text('LOGIN'),
style: ElevatedButton.styleFrom(
primary: Colors.blue.shade700,
minimumSize: const Size(200, 40),
),
)
],
),
),
],
),
),
],
),
);
}
}
GajiPage
class GajiPage extends StatefulWidget {
const GajiPage({Key key}) : super(key: key);
#override
_GajiPageState createState() => _GajiPageState();
}
class _GajiPageState extends State<GajiPage> {
double width = 0;
double height = 0;
var currentYear = DateTime.now().year;
var currentMonth = DateTime.now().month;
DetailpersonilBloc detailPersonilBloc;
GajiBloc gajiBloc;
#override
void initState() {
setState(() {
detailPersonilBloc = DetailpersonilBloc();
detailPersonilBloc.add(Detail());
setMonth();
setYear();
gajiBloc = GajiBloc();
gajiBloc.add(Gaji());
});
super.initState();
}
#override
Widget build(BuildContext context) {
var detailPersonilBloc = BlocProvider.of<DetailpersonilBloc>(context);
width = MediaQuery.of(context).size.width;
height = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Image(
image: const AssetImage('images/header-logo.png'),
width: width / 2,
),
flexibleSpace: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: [
Color.fromARGB(255, 170, 177, 175),
Color.fromARGB(255, 197, 217, 212)
],
),
),
),
),
body: Stack(
children: [
BlocBuilder<GajiBloc, GajiState>(
builder: (context, state) {
return state is GajiLoaded
? ListView(
children: [
Container(
height: 100,
),
Card(
color: const Color.fromARGB(255, 74, 50, 152),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
margin: const EdgeInsets.all(10),
child: const Text(
'Gaji Bersih',
style: TextStyle(
fontSize: 20,
color: Colors.white,
),
),
),
Container(
margin: const EdgeInsets.all(10),
child: Text(
NumberFormat.currency(
locale: 'en',
symbol: 'RP ',
decimalDigits: 0)
.format(state.bersih),
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 40,
color: Colors.white,
),
),
),
],
),
),
Card(
child: Column(
children: [
Container(
color: const Color.fromARGB(255, 238, 238, 238),
width: width,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
margin: const EdgeInsets.fromLTRB(
10, 10, 0, 10),
width: (width / 2) - 25,
child: const Text(
'Detail Gaji',
textAlign: TextAlign.start,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
),
),
),
Container(
margin: const EdgeInsets.fromLTRB(
5, 10, 20, 10),
width: (width / 2) - 18,
child: Text(
'${state.bulan} - ${state.tahun}',
textAlign: TextAlign.end,
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 20,
),
),
)
],
),
),
...
],
),
),
Container(
height: 50,
),
],
)
: Center(
child: Text(
'Tidak ada data. Data gaji bulan ${state.bulan} belum diproses'),
);
},
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Center(
child: BlocBuilder<DetailpersonilBloc, DetailpersonilState>(
builder: (context, state) {
return Card(
child: Row(
children: [
Container(
margin: const EdgeInsets.all(10),
child: const CircleAvatar(
backgroundImage: AssetImage('images/Profpic.PNG'),
radius: 30,
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 250,
padding: const EdgeInsets.all(5),
child: Text(
state.nama,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold),
)),
Container(
padding: const EdgeInsets.all(5),
child: Text(
state.nrp,
style: const TextStyle(fontSize: 15),
)),
],
),
GestureDetector(
onTap: () {
detailPersonilBloc.add(Detail());
showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (context) => detailsBottomSheet(),
);
},
child: const Text(
'DETAILS',
style: TextStyle(color: Colors.blue),
),
)
],
),
);
},
),
),
GestureDetector(
onTap: () {
showModalBottomSheet(
backgroundColor: Colors.transparent,
isScrollControlled: true,
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, StateSetter setState) {
return filterBottomSheet();
},
);
},
);
},
child: Container(
height: 50,
width: width,
decoration: const BoxDecoration(
color: Color.fromARGB(255, 244, 244, 244),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
margin: const EdgeInsets.only(right: 3),
child: const Icon(
Icons.tune,
color: Color.fromARGB(255, 45, 165, 217),
),
),
const Text(
'Filter',
textAlign: TextAlign.center,
style: TextStyle(
fontWeight: FontWeight.w500,
fontSize: 20,
color: Color.fromARGB(255, 45, 165, 217),
),
),
],
),
),
)
],
)
],
),
);
}
}
Note 2: The "..." is a bunch of code not needed for reproduction.
The answer is surprisingly simple as I would learn from my internship. The reason the Bloc is not updating is because I was not using the context of the application. So when I generated a new Bloc inside my pages, it was "empty". So the solution is to use context.read().add(BlocEvent()) or create a new bloc with BlocProvider.of(context) then add the event. Basically the bloc has to be provided with the original context of the application.

Calling a page using a provider inside a bottom navigation bar in flutter

Am using a provider for each page in my flutter application like so :
class HolidayListState extends State<HolidayListView>{
#override
Widget build(BuildContext context) {
final vm = Provider.of<HolidayListViewModel>(context);
if(vm.holidaysviews == null){
return Align(child: CircularProgressIndicator());
}else if(vm.holidaysviews.isEmpty) {
return Align(child: Text("No holidays found."));
}else{
return Scaffold(
backgroundColor: Color(0xfff0f0f0),
body:SingleChildScrollView(
child: Container(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Stack(
children: [
Container(
padding: EdgeInsets.only(top: 145),
height: MediaQuery.of(context).size.height,
width: double.infinity,
child: ChangeNotifierProvider(
create: (_) => HolidayListViewModel(),
child: ListView.builder(
itemCount: vm.holidaysviews.length,
itemBuilder: (context, index) {
final holiday = vm.holidaysviews[index];
final item = holiday.toString();
return Dismissible(
key: UniqueKey(),
background: Container(
alignment: AlignmentDirectional.centerEnd,
color: Colors.red,
child: Icon(
Icons.delete,
color: Colors.white,
),
),
direction: DismissDirection.endToStart,
confirmDismiss:
(DismissDirection direction) async {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Confirm"),
content: const Text(
"Are you sure you wish to delete this item?"),
actions: <Widget>[
FlatButton(
onPressed: () async {
await HolidayWebServices().deleteHoliday(holiday.id.toString());
Navigator.of(context).pop(true);
},
child: const Text("DELETE")),
FlatButton(
onPressed: () =>
Navigator.of(context).pop(false),
child: const Text("CANCEL"),
),
],
);
},
);
},
onDismissed: (direction) {
if (!mounted) {
setState(() {
vm.holidaysviews.removeAt(index);
});
}
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Colors.white,
),
width: double.infinity,
height: 110,
margin: EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
padding: EdgeInsets.symmetric(
vertical: 10, horizontal: 20),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
width: 30,
height: 30,
margin: EdgeInsets.only(right: 15),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
border: Border.all(
width: 3, color: Colors.deepPurple),
),
child: Text(
holiday.duration
.toString(),
textAlign: TextAlign.center,
),
),
Expanded(
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
ConditionalBuilder(
condition:
holiday.status ==
"PENDING",
builder: (context) {
return Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(25),
color: Colors.white,
),
foregroundDecoration:
BadgeDecoration(
badgeColor: Colors.orange,
badgeSize: 70,
textSpan: TextSpan(
text:holiday.status,
style: TextStyle(
color: Colors.white,
fontSize: 12),
),
),
);
},
),
ConditionalBuilder(
condition:
holiday.status ==
"ACCEPTED",
builder: (context) {
return Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(25),
color: Colors.white,
),
foregroundDecoration:
BadgeDecoration(
badgeColor: Colors.green,
badgeSize: 70,
textSpan: TextSpan(
text: holiday.status,
style: TextStyle(
color: Colors.white,
fontSize: 12),
),
),
);
},
),
ConditionalBuilder(
condition:
holiday.status ==
"REFUSED",
builder: (context) {
return Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(25),
color: Colors.white,
),
foregroundDecoration:
BadgeDecoration(
badgeColor: Colors.red,
badgeSize: 70,
textSpan: TextSpan(
text: holiday.status,
style: TextStyle(
color: Colors.white,
fontSize: 12),
),
),
);
},
),
Row(
children: <Widget>[
Icon(
Icons.calendar_today,
color: Colors.deepPurple,
size: 20,
),
Text(
holiday.startDate,
style: TextStyle(
color: primary,
fontSize: 13,
letterSpacing: .3)),
],
),
SizedBox(
height: 6,
),
Row(
children: <Widget>[
Icon(
Icons.calendar_today,
color: Colors.deepPurple,
size: 20,
),
Text(holiday.endDate,
style: TextStyle(
color: primary,
fontSize: 13,
letterSpacing: .3)),
],
),
SizedBox(
height: 6,
),
Row(
children: <Widget>[
Icon(
Icons.assignment,
color: Colors.deepPurple,
size: 20,
),
SizedBox(
width: 5,
),
Text(holiday.type,
style: TextStyle(
color: primary,
fontSize: 13,
letterSpacing: .3)),
],
),
],
),
)
],
),
),
);
},
),
),
),
Container(
height: 140,
width: double.infinity,
decoration: BoxDecoration(
color: primary,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30))),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Holidays",
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 24),
),
],
),
),
),
Container(
child: Column(
children: <Widget>[
SizedBox(
height: 110,
),
],
),
)
],
),
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
backgroundColor: kPrimaryColor,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return StepperDemo();
},
),
);
},
)
);
}}
}
class BadgeDecoration extends Decoration {
final Color badgeColor;
final double badgeSize;
final TextSpan textSpan;
const BadgeDecoration(
{#required this.badgeColor,
#required this.badgeSize,
#required this.textSpan});
#override
BoxPainter createBoxPainter([onChanged]) =>
_BadgePainter(badgeColor, badgeSize, textSpan);
}
class _BadgePainter extends BoxPainter {
static const double BASELINE_SHIFT = 1;
static const double CORNER_RADIUS = 4;
final Color badgeColor;
final double badgeSize;
final TextSpan textSpan;
_BadgePainter(this.badgeColor, this.badgeSize, this.textSpan);
#override
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
canvas.save();
canvas.translate(
offset.dx + configuration.size.width - badgeSize, offset.dy);
canvas.drawPath(buildBadgePath(), getBadgePaint());
// draw text
final hyp = math.sqrt(badgeSize * badgeSize + badgeSize * badgeSize);
final textPainter = TextPainter(
text: textSpan,
textDirection: TextDirection.ltr,
textAlign: TextAlign.center);
textPainter.layout(minWidth: hyp, maxWidth: hyp);
final halfHeight = textPainter.size.height / 2;
final v = math.sqrt(halfHeight * halfHeight + halfHeight * halfHeight) +
BASELINE_SHIFT;
canvas.translate(v, -v);
canvas.rotate(0.785398); // 45 degrees
textPainter.paint(canvas, Offset.zero);
canvas.restore();
}
Paint getBadgePaint() => Paint()
..isAntiAlias = true
..color = badgeColor;
Path buildBadgePath() => Path.combine(
PathOperation.difference,
Path()
..addRRect(RRect.fromLTRBAndCorners(0, 0, badgeSize, badgeSize,
topRight: Radius.circular(CORNER_RADIUS))),
Path()
..lineTo(0, badgeSize)
..lineTo(badgeSize, badgeSize)
..close());
}
and I want to call the page in a navigation bar , right now this is the navigation bar page :
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:helium/views/holiday/holidayList.dart';
import 'package:helium/views/login/login_screen.dart';
import 'package:helium/views/profile/profile_home.dart';
import 'package:helium/views/time_tracking/time_tracking_home.dart';
class MainMenu extends StatefulWidget {
#override
_MainMenuState createState() => _MainMenuState();
void signOut() {}
}
class _MainMenuState extends State<MainMenu> {
PageController _pageController;
int _page = 0;
List icons = [
Icons.home,
Icons.event,
Icons.beach_access_rounded
// Icons.ac_unit,
];
List<Widget> _widgetOptions = <Widget>[
Profile(),
MyCalendarPage(),
HolidayListView()
];
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).primaryColor,
actions: <Widget>[
IconButton(
onPressed: () {
signOut();
},
icon: Icon(Icons.lock_open),
)
],
),
body: PageView(
physics: NeverScrollableScrollPhysics(),
controller: _pageController,
onPageChanged: onPageChanged,
children: _widgetOptions,
),
bottomNavigationBar: bottomMenu(),
floatingActionButtonAnimator: FloatingActionButtonAnimator.scaling,
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
Widget bottomMenu(){
return BottomAppBar(
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
SizedBox(width: 2),
buildTabIcon(0),
buildTabIcon(1),
buildTabIcon(2),
SizedBox(width: 2),
],
),
color: Theme.of(context).primaryColor,
shape: CircularNotchedRectangle(),
);
}
void navigationTapped(int page) {
_pageController.jumpToPage(page);
}
signOut() {
setState(() {
widget.signOut();
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => LoginScreen()),
);
print("signed out");
});
}
#override
void initState() {
super.initState();
// getPref();
_pageController = PageController();
}
#override
void dispose() {
super.dispose();
_pageController.dispose();
}
void onPageChanged(int page) {
setState(() {
this._page = page;
});
}
buildTabIcon(int index) {
return IconButton(
icon: Icon(
icons[index],
size: 24.0,
),
color: Colors.grey,
//_page == index
//? Theme.of(context).accentColor
//: Theme.of(context).textTheme.caption.color,
onPressed: () => _pageController.jumpToPage(index),
);
}
}
apparently I have to call the provider somewhere in the bottom nav bar page but I don't know how to do it , right now am getting this error , so if anyone knows what seems to be wrong , I would appreciate so me help , here's the stack trace :
Error: Could not find the correct Provider<HolidayListViewModel> above this HolidayListView Widget
This happens because you used a `BuildContext` that does not include the provider
of your choice. There are a few common scenarios:
- You added a new provider in your `main.dart` and performed a hot-reload.
To fix, perform a hot-restart.
- The provider you are trying to read is in a different route.
Providers are "scoped". So if you insert of provider inside a route, then
other routes will not be able to access that provider.
- You used a `BuildContext` that is an ancestor of the provider you are trying to read.
Make sure that HolidayListView is under your MultiProvider/Provider<HolidayListViewModel>.
This usually happens when you are creating a provider and trying to read it immediately.
For example, instead of:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// Will throw a ProviderNotFoundError, because `context` is associated
// to the widget that is the parent of `Provider<Example>`
child: Text(context.watch<Example>()),
),
}
consider using `builder` like so:
Widget build(BuildContext context) {
return Provider<Example>(
create: (_) => Example(),
// we use `builder` to obtain a new `BuildContext` that has access to the provider
builder: (context) {
// No longer throws
return Text(context.watch<Example>()),
}
),
}

flutter alarm clock not getting sound

I'm working currently on a flutter project
the app is working fine but i have some issues:
1-i get the notification but i don't get any sound from the notification, i don't know if this is flutter_local_notifications dependency problem because when i tried to update it to the latest version i got few errors from main page and alarm page
2-i can't access these options(Repeat,Sound,Title):
https://i.ibb.co/4fj7x16/s3.png
here is the alarm page:
import 'package:clock_app/alarm_helper.dart';
import 'package:clock_app/constants/theme_data.dart';
import 'package:clock_app/data.dart';
import 'package:clock_app/models/alarm_info.dart';
import 'package:dotted_border/dotted_border.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:intl/intl.dart';
import '../main.dart';
class AlarmPage extends StatefulWidget {
#override
_AlarmPageState createState() => _AlarmPageState();
}
class _AlarmPageState extends State<AlarmPage> {
DateTime _alarmTime;
String _alarmTimeString;
AlarmHelper _alarmHelper = AlarmHelper();
Future<List<AlarmInfo>> _alarms;
#override
void initState() {
_alarmTime = DateTime.now();
_alarmHelper.initializeDatabase().then((value) {
print('------database intialized');
loadAlarms();
});
super.initState();
}
void loadAlarms() {
_alarms = _alarmHelper.getAlarms();
if (mounted) setState(() {});
}
#override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 64),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Alarm',
style: TextStyle(
fontFamily: 'avenir',
fontWeight: FontWeight.w700,
color: CustomColors.primaryTextColor,
fontSize: 24),
),
Expanded(
child: FutureBuilder<List<AlarmInfo>>(
future: _alarms,
builder: (context, snapshot) {
if (snapshot.hasData)
return ListView(
children: snapshot.data.map<Widget>((alarm) {
var alarmTime =
DateFormat('hh:mm aa').format(alarm.alarmDateTime);
var gradientColor = GradientTemplate
.gradientTemplate[alarm.gradientColorIndex].colors;
return Container(
margin: const EdgeInsets.only(bottom: 32),
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 8),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: gradientColor,
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
boxShadow: [
BoxShadow(
color: gradientColor.last.withOpacity(0.4),
blurRadius: 8,
spreadRadius: 2,
offset: Offset(4, 4),
),
],
borderRadius: BorderRadius.all(Radius.circular(24)),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
children: <Widget>[
Icon(
Icons.label,
color: Colors.white,
size: 24,
),
SizedBox(width: 8),
Text(
alarm.title,
style: TextStyle(
color: Colors.white,
fontFamily: 'avenir'),
),
],
),
Switch(
onChanged: (bool value) {},
value: true,
activeColor: Colors.white,
),
],
),
Text(
'Mon-Fri',
style: TextStyle(
color: Colors.white, fontFamily: 'avenir'),
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
alarmTime,
style: TextStyle(
color: Colors.white,
fontFamily: 'avenir',
fontSize: 24,
fontWeight: FontWeight.w700),
),
IconButton(
icon: Icon(Icons.delete),
color: Colors.white,
onPressed: () {
_alarmHelper.delete(alarm.id);
},
),
],
),
],
),
);
}).followedBy([
if (alarms.length < 5)
DottedBorder(
strokeWidth: 2,
color: CustomColors.clockOutline,
borderType: BorderType.RRect,
radius: Radius.circular(24),
dashPattern: [5, 4],
child: Container(
width: double.infinity,
decoration: BoxDecoration(
color: CustomColors.clockBG,
borderRadius:
BorderRadius.all(Radius.circular(24)),
),
child: FlatButton(
padding: const EdgeInsets.symmetric(
horizontal: 32, vertical: 16),
onPressed: () {
_alarmTimeString =
DateFormat('HH:mm').format(DateTime.now());
showModalBottomSheet(
useRootNavigator: true,
context: context,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(24),
),
),
builder: (context) {
return StatefulBuilder(
builder: (context, setModalState) {
return Container(
padding: const EdgeInsets.all(32),
child: Column(
children: [
FlatButton(
onPressed: () async {
var selectedTime =
await showTimePicker(
context: context,
initialTime:
TimeOfDay.now(),
);
if (selectedTime != null) {
final now = DateTime.now();
var selectedDateTime =
DateTime(
now.year,
now.month,
now.day,
selectedTime.hour,
selectedTime
.minute);
_alarmTime =
selectedDateTime;
setModalState(() {
_alarmTimeString =
selectedTime
.toString();
});
}
},
child: Text(
_alarmTimeString,
style:
TextStyle(fontSize: 32),
),
),
ListTile(
title: Text('Repeat'),
trailing: Icon(
Icons.arrow_forward_ios),
),
ListTile(
title: Text('Sound'),
trailing: Icon(
Icons.arrow_forward_ios),
),
ListTile(
title: Text('Title'),
trailing: Icon(
Icons.arrow_forward_ios),
),
FloatingActionButton.extended(
onPressed: () async {
DateTime
scheduleAlarmDateTime;
if (_alarmTime
.isAfter(DateTime.now()))
scheduleAlarmDateTime =
_alarmTime;
else
scheduleAlarmDateTime =
_alarmTime.add(
Duration(days: 1));
var alarmInfo = AlarmInfo(
alarmDateTime:
scheduleAlarmDateTime,
gradientColorIndex:
alarms.length,
title: 'alarm',
);
_alarmHelper
.insertAlarm(alarmInfo);
scheduleAlarm(
scheduleAlarmDateTime);
},
icon: Icon(Icons.alarm),
label: Text('Save'),
),
],
),
);
},
);
},
);
// scheduleAlarm();
},
child: Column(
children: <Widget>[
Image.asset(
'assets/add_alarm.png',
scale: 1.5,
),
SizedBox(height: 8),
Text(
'Add Alarm',
style: TextStyle(
color: Colors.white,
fontFamily: 'avenir'),
),
],
),
),
),
)
else
Text('Only 5 alarms allowed!'),
]).toList(),
);
return Center(
child: Text(
'Loading..',
style: TextStyle(color: Colors.white),
),
);
},
),
),
],
),
);
}
void scheduleAlarm(DateTime scheduledNotificationDateTime) async {
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'alarm_notif',
'alarm_notif',
'Channel for Alarm notification',
icon: 'logo',
sound: RawResourceAndroidNotificationSound('a_long_cold_sting'),
largeIcon: DrawableResourceAndroidBitmap('logo'),
);
var iOSPlatformChannelSpecifics = IOSNotificationDetails(
sound: 'a_long_cold_sting.wav',
presentAlert: true,
presentBadge: true,
presentSound: true);
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.schedule(
0,
'Office',
'Good morning! Time for office.',
scheduledNotificationDateTime,
platformChannelSpecifics);
}
}
and here is the main page:
import 'package:clock_app/enums.dart';
import 'package:clock_app/models/menu_info.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:provider/provider.dart';
import 'views/homepage.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
void main() async {
WidgetsFlutterBinding.ensureInitialized();
var initializationSettingsAndroid =
AndroidInitializationSettings('logo');
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification:
(int id, String title, String body, String payload) async {});
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
});
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: ChangeNotifierProvider<MenuInfo>(
create: (context) => MenuInfo(MenuType.clock),
child: HomePage(),
),
);
}
}
and the dependencies:
flutter_local_notifications: ^1.4.4+2
i am still learning and following a tutorial, so please if you know what is the problem and how to solve it explain to me
Thanks in advance
in flutter local notification, you can set the alarm to be insisted by setting extra flag 4, and thus keep the alarm repeat until user tap on it
for more detail click here