Функция расписания флаттера локальное оповещение не работает, кто-нибудь знает, что это может быть? - PullRequest
0 голосов
/ 08 апреля 2020
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:ouvinos_caprinos/animal/db/animal_database.dart';
import 'package:ouvinos_caprinos/tratamento/class/tratamento.dart';
import 'package:ouvinos_caprinos/util/funcoes.dart';

class TratamentoPage extends StatefulWidget {
  final Tratamento tratamento;
  final int animalId;

  TratamentoPage({this.tratamento, this.animalId});

  @override
  _TratamentoPageState createState() => _TratamentoPageState();
}

class _TratamentoPageState extends State<TratamentoPage> {
FlutterLocalNotificationsPlugin localNotificationsPlugin =
      FlutterLocalNotificationsPlugin();
  initializeNotifications() async {
    var initializeAndroid = AndroidInitializationSettings('@mipmap/ic_launcher');
    var initializeIOS = IOSInitializationSettings();
    var initSettings = InitializationSettings(initializeAndroid, initializeIOS);
    await localNotificationsPlugin.initialize(initSettings);
  }

  @override
  void initState() {
    super.initState();
    initializeNotifications();
    if (widget.tratamento == null) {
      _tratamentoCadastrado = Tratamento();
      _tratamentoCadastrado.animalId = widget.animalId;
      _tratamentoCadastrado.dataTratamento =
          _dataFormatada(_dataTratamentoSelecionada);
    } else {
      _tratamentoCadastrado = Tratamento.fromMap(widget.tratamento.toMap());
      _selectedMotivo.text = _tratamentoCadastrado.motivo;
      _selectedMedicacaoVacinacao.text = _tratamentoCadastrado.medicacao;
      _selectedCusto.text = _tratamentoCadastrado.custo;
      _selectedPeriodoCarencia.text = _tratamentoCadastrado.periodoCarencia;
      _selectedAnotacoes.text = _tratamentoCadastrado.anotacoes;
    }
  }

  Future singleNotification(
      DateTime datetime, String message, String subtext, int hashcode,
      {String sound}) async {
    var androidChannel = AndroidNotificationDetails(
      'channel-id',
      'channel-name',
      'channel-description',
      importance: Importance.Max,
      priority: Priority.Max,
    );

    var iosChannel = IOSNotificationDetails();
    var platformChannel = NotificationDetails(androidChannel, iosChannel);
    localNotificationsPlugin.schedule(
        hashcode, message, subtext, datetime, platformChannel,
        payload: hashcode.toString());
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.green,
            title: Text("Registrar Tratamento"),
            centerTitle: true,
          ),
          body: Form(
            key: _formKey,
            child: Container(
              padding: EdgeInsets.all(13.0),
              child: ListView(
                children: [
                  Container(
                    child: Text("Data de Tratamento*"),
                    padding: EdgeInsets.only(top: 10.0),
                  ),
                  RaisedButton(
                    child: Text(exibicaoDataPadrao(
                        _dataFormatada(_dataTratamentoSelecionada))),
                    onPressed: () {
                      _selectDataTratamento(context, 0);
                      setState(() {
                        _edited = true;
                        // _editedAnimal.dataNascimento = _dataNascimentoFormatada;
                      });
                    },
                  ),
                  espacamentoPadrao(),
                  TextFormField(
                    controller: _selectedMotivo,
                    decoration: estiloPadrao("Motivo*", 1),
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Por favor, insira o Motivo';
                      }
                      return null;
                    },
                    onChanged: (text) {
                      setState(() {
                        _tratamentoCadastrado.motivo = text;
                        _edited = true;
                        // _editedAnimal.nome = text;
                      });
                    },
                  ),
                  espacamentoPadrao(),
                  TextFormField(
                    decoration: estiloPadrao("Medicação/Vacinação*", 1),
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Por favor, insira a Medicação/Vacinação';
                      }
                      return null;
                    },
                    controller: _selectedMedicacaoVacinacao,
                    onChanged: (text) {
                      setState(() {
                        _tratamentoCadastrado.medicacao = text;
                        _edited = true;
                        // _editedAnimal.nome = text;
                      });
                    },
                  ),
                  espacamentoPadrao(),
                  TextFormField(
                    keyboardType:
                        TextInputType.numberWithOptions(decimal: true),
                    decoration: estiloPadrao("Periodo de Carência*", 1),
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Por favor, insira o Periodo de Carência';
                      }
                      return null;
                    },
                    controller: _selectedPeriodoCarencia,
                    onChanged: (text) {
                      setState(() {
                        _tratamentoCadastrado.periodoCarencia = text;
                        _edited = true;
                        // _editedAnimal.nome = text;
                      });
                    },
                  ),
                  espacamentoPadrao(),
                  TextFormField(
                    keyboardType:
                        TextInputType.numberWithOptions(decimal: true),
                    decoration: estiloPadrao("Custo*", 2),
                    validator: (value) {
                      if (value.isEmpty) {
                        return 'Por favor, insira o Custo';
                      }
                      return null;
                    },
                    controller: _selectedCusto,
                    onChanged: (text) {
                      setState(() {
                        _tratamentoCadastrado.custo = text;
                        _edited = true;
                        // _editedAnimal.nome = text;
                      });
                    },
                  ),
                  espacamentoPadrao(),
                  TextField(
                    decoration: estiloPadrao("Anotações", 1),
                    controller: _selectedAnotacoes,
                    onChanged: (text) {
                      setState(() {
                        _tratamentoCadastrado.anotacoes = text;
                        _edited = true;
                        // _editedAnimal.nome = text;
                      });
                    },
                  ),
                  Column(
                    children: <Widget>[
                      Text("Agendamento"),
                      Checkbox(
                        value: agendamento,
                        onChanged: (bool value) {
                          setState(() {
                            agendamento = value;
                          });
                        },
                      ),
                    ],
                  ),
                  agendar(agendamento),
                ],
              ),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            child: Icon(Icons.check),
            backgroundColor: Colors.green,
            onPressed: () async {
              DateTime now = DateTime.now().toUtc().add(
                    Duration(seconds: 10),
                  );
              await singleNotification(
                now,
                "Notificacao",
                "Corpo da notificacao",
                98123871,
              );
              Navigator.pop(context,_tratamentoCadastrado);
            },
          ),
        ),
        onWillPop: _requestPop);
  }
}

Отладка не сообщает об ошибке, но уведомление не отображается, может кто-нибудь сказать мне, почему это происходит?

Я использовал библиотеку локальных уведомлений в моем коде, но они не ' Если они не работают, они даже не показывают ошибку или указатель, говорящий о том, что что-то не так.

Мне нужно планировать уведомление каждый раз, когда пользователь выбирает эту опцию планирования, так что, когда событие приближается к дате, он получает уведомление о близости или сама дата.

Я искал и нашел уведомление о расписании, которое именно то, что я хотел бы.

Я хочу, чтобы пользователь назначил дату следующей вакцинации / лекарства ...

пример: 04/09/2020 приложение: 04/09/2020 отправляет уведомление: вакцинация X должна применяться сегодня.

...