没有为类型类定义方法

时间:2021-06-17 14:31:46

标签: flutter dart

当我尝试从另一个类中获取函数时出现此错误:

error: The method 'sheduledNotification' isn't defined for the type '_MedicinesState'. (undefined_method at [epicare] lib\Medicines.dart:73)

我正在将我的药物详细信息保存到 firebase,现在我想显示已保存在 firebase 中的所有药物当时的提醒,因此我正在使用 for 循环来一一获取所有药物并显示提醒,但是当我尝试获取 Medicinies Class 中 'sheduledNotification' 类的函数 NotificationService 时,它给了我错误。请帮助我如何避免此错误并获取药物类中的函数

我使用函数调用本地通知的代码,该函数位于void loadData()

import 'package:epicare/AddMedicineScreen.dart';
import 'package:epicare/Homepage.dart';
import 'package:epicare/services/notifications.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'services/notifications.dart';


import 'MedicneClass.dart';

class Medicines extends StatefulWidget {
  @override
  _MedicinesState createState() => _MedicinesState();
}

class _MedicinesState extends State<Medicines> with TickerProviderStateMixin {
  TabController _tabController;
  var _selectedIndex = 0;
  //Firebase
  FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  final ref = FirebaseDatabase.instance.reference();
  User cuser = FirebaseAuth.instance.currentUser;
  final fb = FirebaseDatabase.instance.reference().child("User_data");

  void loadData()
  {
    fb.reference()
      ..child(cuser.uid)
          .child('Medicines')
          .once()
          .then((DataSnapshot snapshot) {
        var data = snapshot.value;
        med_list = List();
        if (data != null) {
          data.forEach((key, value) {
            MedicineList med_history = new MedicineList(
              userMed: value['medicine_name'],
              userDosage: value['dosage'],
              userFreq: value['frequency'],
              userReminder: value['reminder'],
              userSdate: value['medicine_start_date'],
              userEdate: value['medicine_end_date'],
              key: key,
            );
            med_list.add(med_history);
          });
          setState(() {
            print("Medicines Present");
          });
          for(int i = 0; i<med_list.length; i++)
          {
            String result = med_list[i].userReminder.replaceAll(RegExp('\\s+'), ' ');
            print(result);
            // parse date
            //DateTime time= DateFormat.jm().parse(result);
            DateTime date2= DateFormat("hh:mma").parse(result);
            // format date
            //print(DateFormat("HH:mm").format(time));
            print(DateFormat("HH:mm").format(date2));
            String ti = DateFormat("HH:mm").format(date2);
            var hms = ti.split(':');
            var hours = int.parse(hms[0]);
            var m = hms[1];
            var min = m.split(' ');
            var minutes = int.parse(min[0]);
            var time = Time(hours, minutes, 0);
            String name = med_list[i].userMed;
            String k = med_list[i].key;
            sheduledNotification(time,name,k);
          }
        }
      });
  }
  List<MedicineList> med_list = List();
  @override
  void initState() {

    loadData();
    super.initState();
    _tabController = TabController(length: 2, vsync: this)
      ..addListener(() {
        setState(() {
          _selectedIndex = _tabController.index;
        });
      });
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: const Color(0xffE5E0A1),
        elevation: 0,
        centerTitle: true,
        title: Text(
          "Medicines",
          style: TextStyle(
            fontSize: 15.0,
            color: Colors.black,
            fontFamily: 'Montserrat',
            fontWeight: FontWeight.normal,
          ),
        ),
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back,
            color: Colors.black,
          ),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) {
                  return Homepage();
                },
              ),
            );
          },
        ),
      ),
      body: Column(
        children: [
          // give the tab bar a height [can change height to preferred height]
          Container(
            margin: EdgeInsets.only(top: 32, right: 45, left: 45),
            height: 45,
            decoration: BoxDecoration(
              color: const Color(0xffE5E0A1),
              borderRadius: BorderRadius.circular(
                18.0,
              ),
              border: Border.all(width: 1.0, color: const Color(0xff2f363d)),
            ),
            child: TabBar(
              controller: _tabController,
              // give the indicator a decoration (color and border radius)
              indicator: BoxDecoration(
                borderRadius: BorderRadius.circular(
                  17.0,
                ),
                color: Colors.black,
              ),
              labelColor: const Color(0xffd4d411),
              unselectedLabelColor: Colors.black,
              tabs: [
                // first tab [you can add an icon using the icon property]
                Tab(
                  child: Text(
                    'Medicine',
                    style: TextStyle(
                      fontFamily: 'Montserrat',
                      fontSize: 16,
                      //color: const Color(0xffd4d411),
                      letterSpacing: 0.48,
                    ),
                    textAlign: TextAlign.left,
                  ),
                ),

                // second tab [you can add an icon using the icon property]
                Tab(
                  child: Text(
                    'History',
                    style: TextStyle(
                      fontFamily: 'Montserrat',
                      fontSize: 16,
                      //color: const Color(0xffd4d411),
                      letterSpacing: 0.48,
                    ),
                    textAlign: TextAlign.left,
                  ),
                ),
              ],
            ),
          ),
          // tab bar view her
          Expanded(
            child: TabBarView(
              controller: _tabController,
              children: <Widget>[
                  med_list.length == 0
                      ? noMedicine()
                      : ListView.separated(
                          physics: NeverScrollableScrollPhysics(),
                          shrinkWrap: true,
                          primary: false,
                          itemBuilder: (context, index) {
                            return MedicinesList(
                                med_list[index].userSdate,
                                med_list[index].userReminder,
                                med_list[index].userEdate,
                                med_list[index].userFreq,
                                med_list[index].userDosage,
                                med_list[index].userMed,
                                med_list[index].key);
                          },
                          separatorBuilder: (_, __) => Container(),
                          itemCount: med_list.length,
                        ),

                // second tab bar view widget
                Container(
                  padding: EdgeInsets.only(right: 32, left: 32),
                  child: MedHistory(),
                ),
              ],
            ),
          ),
        ],
      ),
      floatingActionButton: _selectedIndex > 0
          ? Container()
          : FloatingActionButton(
              child: Icon(
                Icons.add,
                size: 40,
              ),
              backgroundColor: const Color(0xffd4d411),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) {
                      return AddMedicine();
                    },
                  ),
                );
              },
            ),
    );
  }

  // Widget Medicine() {
  //   print("MedicineList ${med_list.length}");
  //   med_list.length == 0
  //       ? noMedicine()
  //       : ListView.separated(
  //           physics: NeverScrollableScrollPhysics(),
  //           padding: EdgeInsets.symmetric(vertical: 11, horizontal: 20),
  //           shrinkWrap: true,
  //           primary: false,
  //           itemBuilder: (context, index) {
  //             return MedicinesList(
  //                 med_list[index].userSdate,
  //                 med_list[index].userReminder,
  //                 med_list[index].userEdate,
  //                 med_list[index].userFreq,
  //                 med_list[index].userDosage,
  //                 med_list[index].userMed,
  //                 med_list[index].key);
  //           },
  //           separatorBuilder: (_, __) => Container(),
  //           itemCount: med_list.length,
  //         );
  // }

  Widget noMedicine() {
    return Center(
      child: Column(
          mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(("assets/images/Medicine-amico.png")),
          SizedBox(
            height: 20,
          ),
          Text(
            'Hurray! You don\'t have any pending medicines to take!',
            style: TextStyle(
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.w600,
              fontSize: 14,
              color: const Color(0x78000000),
              height: 1.4285714285714286,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget MedicinesList(String start_date, String reminder, String end_date,
      String frequency, String dosage, String medicine_name, String key) {
    if(frequency == null)
      {
        frequency = 'Take when needed';
      }
    Size size = MediaQuery.of(context).size;
    return GestureDetector(
      onTap: ()
      {
        Deletedata(context, key);
      },
      child: Container(
        margin: EdgeInsets.only(top: 25, left: 32, right: 32),
        width: size.width * 0.80,
        height: 54,
        padding: EdgeInsets.symmetric(vertical: 11, horizontal: 20),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(9.0),
          color: Colors.white,
          boxShadow: [
            BoxShadow(
              color: const Color(0x29000000),
              offset: Offset(0, 3),
              blurRadius: 6,
            ),
          ],
        ),
        child: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '$medicine_name',
                  style: TextStyle(
                    fontFamily: 'Montserrat',
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                    color: const Color(0xff232425),
                  ),
                  textAlign: TextAlign.left,
                ),
                Text(
                  '$frequency',
                  style: TextStyle(
                    fontFamily: 'Montserrat',
                    fontSize: 10,
                    color: const Color(0x80232425),
                    fontWeight: FontWeight.w500,
                  ),
                  textAlign: TextAlign.left,
                ),
              ],
            ),
            Container(
              width: size.width,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '$dosage',
                    style: TextStyle(
                      fontFamily: 'Montserrat',
                      fontSize: 10,
                      fontWeight: FontWeight.w600,
                      color: const Color(0x80515559),
                    ),
                    textAlign: TextAlign.left,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget MedHistory() {
    return Center(
      child: Column(
        children: [
          Image.asset(("assets/images/Time management-pana.png")),
          Text(
            'You have no data here!\nPlease complete your prescriptions',
            style: TextStyle(
              fontFamily: 'Montserrat',
              fontWeight: FontWeight.w600,
              fontSize: 14,
              color: const Color(0x78000000),
              height: 1.4285714285714286,
            ),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Deletedata(BuildContext context, String key) {
    Widget DeleteButton = FlatButton(
      onPressed: () {
        setState(() {
          fb.child(cuser.uid).child('Medicines').child(key).remove();
          Navigator.of(context).pop();
          loadData();
        });
      },
      child: Text("YES"),
    );
    Widget DonotDeleteButton = FlatButton(
      onPressed: () {
        Navigator.of(context).pop();
      },
      child: Text("NO"),
    );

    AlertDialog alert = AlertDialog(
      title: Text("Delete History"),
      content: Text("Do you want to delete this seizure history"),
      actions: [
        DeleteButton,
        DonotDeleteButton,
      ],
    );
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }
}

NotificationService 类中定义的函数:

import 'package:flutter/cupertino.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class NotificationService extends ChangeNotifier {
  final FlutterLocalNotificationsPlugin _flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();

  //initilize

  Future initialize() async {
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

    AndroidInitializationSettings androidInitializationSettings =
    AndroidInitializationSettings("pulse");

    IOSInitializationSettings iosInitializationSettings =
    IOSInitializationSettings();

    final InitializationSettings initializationSettings =
    InitializationSettings(androidInitializationSettings, iosInitializationSettings);

    await flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  //Scheduled Notification

  Future sheduledNotification(Time time, String name, String key) async {
    //var time = Time(00, 35, 0);
    var androidPlatformChannelSpecifics =
    AndroidNotificationDetails(key,
        'repeatDailyAtTime channel name', 'repeatDailyAtTime description');
    var iOSPlatformChannelSpecifics =
    IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await _flutterLocalNotificationsPlugin.showDailyAtTime(
        0,
        'Reminder',
        'Time to eat your medicine  ${(time.hour)}:${(time.minute)}:${(time.second)}',
        time,
        platformChannelSpecifics);
  }

}

1 个答案:

答案 0 :(得分:0)

如果您正在使用提供程序包,并已声明 ChangeNotifierProvider,请使用 Provider.of<NotificationService>(context).sheduledNotification(..)Consumer 小部件。