Send scheduled notifications with separate content for each day - Flutter

72 views Asked by At

I want to send notifications with different content for each day. However, the same content is sent in the notification every day, depending on the value content it first selects. How can I send a scheduled notification at a certain time every day, the content of which will be different each time?

This is my code:



`import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  tz.initializeTimeZones();
  tz.setLocalLocation(tz.getLocation("Europe/Istanbul"));
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  MyHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Bildirim Uygulaması'),
      ),
      body: Center(
        child: Column(
          children: [
            ElevatedButton(
              onPressed: () async {
                await _scheduleDailyNotification();
              },
              child: const Text('Günlük Bildirim Gönder'),
            ),
            ElevatedButton(
              onPressed: () async {
                await unScheduleAllNotifications();
              },
              child: const Text('iptal'),
            ),
          ],
        ),
      ),
    );
  }

  // Tüm zamanlanmış fonksiyonları iptal etme.
  Future unScheduleAllNotifications() async => await flutterLocalNotificationsPlugin.cancelAll();

  Future<void> _scheduleDailyNotification() async {
    var androidDetails = const AndroidNotificationDetails(
      'channelId',
      'channelName',
      importance: Importance.high,
    );

    var generalNotificationDetails = NotificationDetails(android: androidDetails);

    // Saat 10:00 için bir DateTime nesnesi oluştur
    tz.TZDateTime scheduledDate = tz.TZDateTime(
      tz.local,
      DateTime.now().year,
      DateTime.now().month,
      DateTime.now().day,
      20,
      38,
      1,
    );

    String selectedMessage = "ilk deger";
    int id = 1;

    // Eğer bu saat geçtiyse, bir sonraki gün için planla
    if (scheduledDate.isBefore(tz.TZDateTime.now(tz.local))) {
      print("bu kisim bakalim hep calisiyor mu olursa sorun aha burada lutfen ol");

      scheduledDate = scheduledDate.add(const Duration(days: 1));
      // Günlük bildirim içeriği listesi
      List<String> dailyMessages = [
        'Bugün harika bir gün!',
        'Yeni bir şeyler öğrenmeye hazır mısınız?',
        'Hayalinizdeki projeye başlama zamanı!',
        'Güzel anları değerlendirin!',
        'Bugün bir gülümsemeyle başlayın!',
      ];

      // Rastgele bir mesaj seç
      Random random = Random();
      final a = random.nextInt(dailyMessages.length);
      selectedMessage = dailyMessages[random.nextInt(dailyMessages.length)];
      id = a;
    }

    await flutterLocalNotificationsPlugin.zonedSchedule(
      id,
      'Günlük Hatırlatma',
      selectedMessage,
      scheduledDate,
      generalNotificationDetails,
      androidScheduleMode: AndroidScheduleMode.alarmClock,
      uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime,
      matchDateTimeComponents: DateTimeComponents.time,
    );
  }
}
0

There are 0 answers