#flutter #dart #notifications #local #alarm
#флаттер #dart #уведомления #Местные новости #тревога
Вопрос:
В настоящее время я работаю над проектом flutter
приложение работает нормально, но у меня есть некоторые проблемы:
1-я получаю уведомление, но я не получаю никакого звука от уведомления, я не знаю, является ли это проблемой зависимости flutter_local_notifications, потому что, когда я попытался обновить его до последней версии, я получил несколько ошибок с главной страницы и страницы будильника
2-я не могу получить доступ к этим параметрам (повтор, звук, заголовок):
https://i.ibb.co/4fj7x16/s3.png
вот страница будильника:
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);
}
}
и вот главная страница:
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(),
),
);
}
}
и зависимости:
flutter_local_notifications: ^1.4.4 2
я все еще учусь и следую руководству, поэтому, пожалуйста, если вы знаете, в чем проблема и как ее решить, объясните мне
Заранее спасибо
Ответ №1:
в локальном уведомлении flutter вы можете настроить настойчивый будильник, установив дополнительный флаг 4, и, таким образом, повторять будильник, пока пользователь не нажмет на него
для получения более подробной информации нажмите здесь