错误只出现在第一次调用,一旦屏幕再次打开,错误就会消失,

问题描述

根据屏幕截图,一旦我打开屏幕,它就会给我错误getter 'email' was called on null”。但是如果我只是点击后退按钮,然后再次打开屏幕,它运行良好,没有任何错误

屏幕的目的是帐户所有者看到从管理员帐户发送给他的笔记

This is the error appears only one time after opening the app

Here the same screen without any error

这是 dart 中存在点击屏幕的代码

import 'package:Flutter/cupertino.dart' show CupertinoIcons;
import 'package:Flutter/material.dart';
import 'package:notification_permissions/notification_permissions.dart';
import 'package:provider/provider.dart';
import 'package:rate_my_app/rate_my_app.dart';
import 'package:font_awesome_Flutter/font_awesome_Flutter.dart';
import '../../app.dart';
import '../../common/config.dart';
import '../../common/constants.dart';
import '../../common/tools.dart';
import '../../generated/l10n.dart';
import '../../models/index.dart' show AppModel,User,usermodel,WishListModel;
import '../../routes/flux_navigate.dart';
import '../../screens/blogs/post_screen.dart';
import '../../services/index.dart';
import '../../widgets/common/webview.dart';
import '../custom/smartchat.dart';
import '../index.dart';
import '../users/user_point.dart';
import 'currencies.dart';
import 'language.dart';
import 'notification.dart';
import '../../common/config.dart' as config;
import 'package:cespohm/screens/bywaleed/booking_admin_screen.dart';
import 'package:cespohm/screens/bywaleed/docor_note_tap.dart';
import 'package:cespohm/screens/bywaleed/user_search_new_screen.dart';
import 'package:cespohm/screens/bywaleed/doctor_notes_user_screen.dart';

class SettingScreen extends StatefulWidget {
  final List<dynamic> settings;
  final String background;
  final User user;
  final VoidCallback onlogout;
  final bool showChat;

  SettingScreen({
    this.user,this.onlogout,this.settings,this.background,this.showChat,});

  @override
  _SettingScreenState createState() {
    return _SettingScreenState();
  }
}

class _SettingScreenState extends State<SettingScreen>
    with
        TickerProviderStateMixin,WidgetsBindingObserver,AutomaticKeepAliveClientMixin<SettingScreen> {
  @override
  bool get wantKeepAlive => true;

  final bannerHigh = 150.0;
  bool enablednotification = true;
  final RateMyApp _rateMyApp = RateMyApp(
      // rate app on store
      minDays: 7,minLaunches: 10,remindDays: 7,remindLaunches: 10,googlePlayIdentifier: kStoreIdentifier['android'],appStoreIdentifier: kStoreIdentifier['ios']);

  void showRateMyApp() {
    _rateMyApp.showRateDialog(
      context,title: S.of(context).rateTheApp,// The dialog title.
      message: S.of(context).rateThisAppDescription,// The dialog message.
      rateButton: S.of(context).rate.toupperCase(),// The dialog "rate" button text.
      noButton: S.of(context).noThanks.toupperCase(),// The dialog "no" button text.
      laterButton: S.of(context).maybeLater.toupperCase(),// The dialog "later" button text.
      listener: (button) {
        // The button click listener (useful if you want to cancel the click event).
        switch (button) {
          case RateMyAppDialogButton.rate:
            break;
          case RateMyAppDialogButton.later:
            break;
          case RateMyAppDialogButton.no:
            break;
        }

        return true; // Return false if you want to cancel the click event.
      },// Set to false if you want to show the native Apple app rating dialog on iOS.
      dialogStyle: const DialogStyle(),// Custom dialog styles.
      // Called when the user dismissed the dialog (either by taping outside or by pressing the "back" button).
      // actionsBuilder: (_) => [],// This one allows you to use your own buttons.
    );
  }

  @override
  void initState() {
    super.initState();

    Future.delayed(Duration.zero,() async {
      await checkNotificationPermission();
    });
    _rateMyApp.init().then((_) {
      // state of rating the app
      if (_rateMyApp.shouldOpenDialog) {
        showRateMyApp();
      }
    });
  }

  // @override
  // void dispose() {
  //   Utils.setStatusBarWhiteForeground(false);
  //   super.dispose();
  // }

  Future<void> checkNotificationPermission() async {
    if (!isAndroid || isIos) {
      return;
    }

    try {
      await NotificationPermissions.getNotificationPermissionStatus()
          .then((status) {
        if (mounted) {
          setState(() {
            enablednotification = status == PermissionStatus.granted;
          });
        }
      });
    } catch (err) {
      printLog('[Settings Screen] : ${err.toString()}');
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      checkNotificationPermission();
    }
  }

  /// Render the Admin vendor Menu
  Widget rendervendorAdmin() {
    if (!(widget.user != null ? widget.user.isvendor ?? false : false)) {
      return Container();
    }

    return Card(
      color: Theme.of(context).backgroundColor,margin: const EdgeInsets.only(bottom: 2.0),elevation: 0,child: ListTile(
        onTap: () {
          final String langCode =
              Provider.of<AppModel>(context,listen: false).langCode;

          if (unsupportedLanguages.contains(langCode)) {
            final snackBar = SnackBar(
              content: Text(
                  S.of(context).thisFeatureDoesNotSupportTheCurrentLanguage),duration: const Duration(seconds: 1),);
            Scaffold.of(context).showSnackBar(snackBar);
            return;
          }
          FluxNavigate.push(
            MaterialPageRoute(
              builder: (context) =>
                  Services().widget.getAdminvendorScreen(context,widget.user),),forceRootNavigator: true,);
        },leading: Icon(
          Icons.dashboard,size: 24,color: Theme.of(context).accentColor,title: Text(
          S.of(context).vendorAdmin,style: const TextStyle(fontSize: 16),trailing: Icon(
          Icons.arrow_forward_ios,size: 18,);
  }

  /// Render the custom profile link via Webview
  /// Example show some special profile on the woocommerce site: wallet,wishlist...
  Widget renderWebViewProfile() {
    if (widget.user == null) {
      return Container();
    }

    var base64Str = Utils.encodeCookie(widget.user.cookie);
    var profileURL = '${serverConfig["url"]}/my-account?cookie=$base64Str';

    return Card(
      color: Theme.of(context).backgroundColor,child: ListTile(
        onTap: () {
          Navigator.push(
            context,MaterialPageRoute(
              builder: (context) => WebView(
                  url: profileURL,title: S.of(context).updateUserInfor),leading: Icon(
          CupertinoIcons.profile_circled,title: Text(
          S.of(context).updateUserInfor,);
  }

  Widget renderItem(value) {
    IconData icon;
    String title;
    Widget trailing;
    Function() onTap;
    bool isMultivendor = kFluxStoreMV.contains(serverConfig['type']);
    switch (value) {
      case 'bookingAdmin':
        if (widget.user == null ) {
          return Container();
        }
        else if(widget.user.email == config.adminemail || widget.user.email == config.adminemailTwo && widget.user != null )
        {
          icon = FontAwesomeIcons.keyboard;
          title = S.of(context).checkout;
          trailing =
          const Icon(Icons.arrow_forward_ios,color: kGrey600);
          onTap = () => Navigator.push(
            context,MaterialPageRoute(builder: (context) =>  const BookingAdminScreen()),);

        }
        else {
          return Container();
        }
        break;

      case 'addDoctorNote':
        if (widget.user == null ) {
          return Container();
        }
        else if(widget.user.isvendor && widget.user != null )
        {
          icon = FontAwesomeIcons.edit;
          title = S.of(context).continuetoShipping;
          trailing =
          const Icon(Icons.arrow_forward_ios,MaterialPageRoute(builder: (context) =>  const UserSearchNewScreen()),);

        }
        else {
          return Container();
        }
        break;
/// here is the tap to the screen where there is the error
      case 'yourDoctorNotes':
        if (widget.user == null || widget.user.email == config.adminemail || widget.user.email == config.adminemailTwo ) {
          return Container();
        }
        else if(!widget.user.isvendor)
        {

          icon = FontAwesomeIcons.notesMedical;
          title = S.of(context).french;
          trailing =
          const Icon(Icons.arrow_forward_ios,MaterialPageRoute(builder: (context) =>   DoctorNoteUserScreen(senderUser: widget.user,)),);

        }
        else {
          return Container();
        }
        break;


      case 'chat':
       

这是屏幕的飞镖代码错误在哪里

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:date_format/date_format.dart';
import 'package:Flutter/material.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_model.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_provider.dart';
import 'package:cespohm/models/entities/user.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase_auth;
import 'package:provider/provider.dart';
import '../../generated/l10n.dart' as word;
import '../../models/index.dart' show AppModel,Store,usermodel ;

final _fireStore = FirebaseFirestore.instance;
firebase_auth.User loggedInUser;
class DoctorNoteUserScreen extends StatelessWidget {
  final User senderUser;
   DoctorNoteUserScreen({
    Key key,this.senderUser,}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final userSearchProvider = Provider.of<UserSearchProvider>(context);

    return Scaffold(
      appBar: AppBar(
        title: Text(
          word.S.of(context).french,style: TextStyle(
              color: Colors.white,fontSize: 18.0,fontWeight: FontWeight.w400),leading: Center(
          child: GestureDetector(
            child: const Icon(
              Icons.arrow_back_ios,color: Colors.white,onTap: () => Navigator.pop(context),body: StreamBuilder<List<UserSearchModel>>(
          stream: userSearchProvider.userstwo,builder: (context,snapshot) {
            if (!snapshot.hasData  ) {
              return Center(
                child: CircularProgressIndicator(
                  valueColor: AlwaysstoppedAnimation<Color>(
                      Theme.of(context).primaryColor),);
            }   else {
              return ListView.builder(
                  itemCount: snapshot.data.length,itemBuilder: (context,index) {
                    return Padding(
                      padding: const EdgeInsets.all(7.0),child: Column(
                        children: [
                          Padding(
                            padding: const EdgeInsets.all(8.0),child: Column(
                              children: [
                                SizedBox(
                                  height: 40.0,Text(word.S.of(context).french,style: TextStyle(fontSize: 18.0)),SizedBox(
                                  height: 15.0,Divider(
                                  thickness: 1.0,)
                              ],Container(
                            child: ListTile(
                              title: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,children: [
                                  SizedBox(
                                    width: 15.0,Container(
                                    child: Text(snapshot.data[index].doctorNote!=null?snapshot.data[index].doctorNote: 'No Notes Yet',style: TextStyle(fontSize: 20.0)),],);
                  });
            }
          }),);
  }
}

这里是服务的dart代码

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_model.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_provider.dart';
import 'package:cespohm/models/user_model.dart';

class UserSearchService {
  final FirebaseFirestore _db = FirebaseFirestore.instance;
  final usermodel = usermodel();

  //Get Entries
  Stream<List<UserSearchModel>> getEntries(){
    return _db
        .collection('users')
        .orderBy('firstName',descending: false)
        .snapshots()
        .map((snapshot) => snapshot.docs
        .map((doc) => UserSearchModel.fromJson(doc.data()))
        .toList());
  }

/// here is the firebase collection where the error exists 
  Stream<List<UserSearchModel>> getEntriesTwo(){
    return _db
        .collection('users').where('email',isEqualTo: usermodel.user.email)
        .snapshots()
        .map((snapshot) => snapshot.docs
        .map((doc) => UserSearchModel.fromJson(doc.data()))
        .toList());
  }

}

这是模型

import 'package:cloud_firestore/cloud_firestore.dart';

class UserSearchModel {
  final String date;
  final String firstName;
  final String lastName;
  final String phone;
  final String email;
  final String searchKey;
  final String doctorNote;
  final String bYDoctor;
  final String uID;




  UserSearchModel(
      {this.date,this.firstName,this.lastName,this.phone,this.email,this.searchKey,this.doctorNote,this.bYDoctor,this.uID});

  // creating a Trip object from a firebase snapshot
  UserSearchModel.fromSnapshot(DocumentSnapshot snapshot) :
        date = snapshot['date'],firstName = snapshot['firstName'].toDate(),lastName = snapshot['lastName'].toDate(),phone = snapshot['phone'],email = snapshot['email'],searchKey = snapshot['searchKey'],doctorNote = snapshot['doctorNote'],bYDoctor = snapshot['bYDoctor'],uID = snapshot.id;

  factory UserSearchModel.fromJson(Map<String,dynamic> json) {
    return UserSearchModel(
        date: json['createdAt'],firstName: json['firstName'],lastName: json['lastName'],phone: json['phone'],email: json['email'],searchKey: json['searchKey'],doctorNote: json['doctorNote'],bYDoctor: json['bYDoctor'],uID: json['uID']);
  }

  Map<String,dynamic> toMap() {
    return {
      'createdAt': date,'firstName': firstName,'lastName': lastName,'phone': phone,'email': email,'searchKey': searchKey,'doctorNote': doctorNote,'bYDoctor': bYDoctor,'uID': uID,};
  }
}

这里是提供者

import 'package:Flutter/material.dart';
import 'package:cespohm/models/bywaleed_model/user_search_new_model.dart';
import 'package:cespohm/models/user_model.dart';
import 'package:cespohm/services/bywaleed/user_search_new_service.dart';
import 'package:uuid/uuid.dart';

class UserSearchProvider with ChangeNotifier {
  final userSearchService = UserSearchService();
  final usermodel = usermodel();
  DateTime _date;
  String _firstName;
  String _lastName;
  String _phone;
  String _email;
  String _searchKey;
  String _doctorNote;
  String _bYDoctor;
  String _uID;



  var uuid = Uuid();

//Getters
  DateTime get date => _date;
  String get firstName => _firstName;
  String get lastName => _lastName;
  String get phone => _phone;
  String get email => _email;
  String get searchKey => _searchKey;
  String get doctorNote => _doctorNote;
  String get byDoctor => _bYDoctor;
  String get uID => _uID;


  Stream<List<UserSearchModel>> get users => userSearchService.getEntries();
  Stream<List<UserSearchModel>> get userstwo => userSearchService.getEntriesTwo();

  //Setters
  set changeDate(DateTime date) {
    _date = date;
    notifyListeners();
  }

  set changeFirstName(String firstName) {
    _firstName = firstName;
    notifyListeners();
  }

  set changeLastName(String lastName) {
    _lastName = lastName;
    notifyListeners();
  }

  set changePhone(String phone) {
    _phone = phone;
    notifyListeners();
  }

  set changeEmail(String email) {
    _email = email;
    notifyListeners();
  }

  set changeSearchKey(String searchKey) {
    _searchKey = searchKey;
    notifyListeners();
  }

  set changeDoctorNote(String doctorNote) {
    _doctorNote = doctorNote;
    notifyListeners();
  }

  set changeBYDoctor(String bYDoctor) {
    _bYDoctor = bYDoctor;
    notifyListeners();
  }

  set changeuID(String uID) {
    _uID = uID;
    notifyListeners();
  }


  //Functions
  loadAll(UserSearchModel userSearchModel) {
    if (userSearchModel != null) {
      _date = DateTime.parse(userSearchModel.date);
      _firstName = userSearchModel.firstName;
      _lastName = userSearchModel.lastName;
      _phone = userSearchModel.phone;
      _email = userSearchModel.email;
      _searchKey = userSearchModel.searchKey;
      _doctorNote = userSearchModel.doctorNote;
      _bYDoctor = usermodel.user.email;
      _uID = userSearchModel.uID;


    } else {
      _date = DateTime.Now();
      _firstName = null;
      _lastName = null;
      _phone = null;
      _email = null;
      _searchKey = null;
      _doctorNote = null;
      _bYDoctor = null;
      _uID = null;



    }
  }

  saveEntry() {
    if (_email == null) {
      //Add
      var newusermodel = UserSearchModel(
          date: _date.toIso8601String(),firstName: _firstName,lastName: _lastName,phone: _phone,email: _email,searchKey: _searchKey,doctorNote: _doctorNote,bYDoctor: _bYDoctor,uID: _uID);


      print(newusermodel.email);
      userSearchService.setEntry(newusermodel);
    } else {
      //Edit
      var updatedEntry = UserSearchModel(
          date: _date.toIso8601String(),uID: _uID);
      userSearchService.setEntry(updatedEntry);
    }
  }

  removeEntry(String entryId) {
    userSearchService.removeEntry(entryId);
  }
}

解决方法

您需要确保您的 User 对象已初始化。出现此错误是因为访问了 user.email,但您的 User 对象是 null。确保您的代码考虑用户对象的加载时间(如果它来自 API),并针对 user == null 的情况进行适当的检查。