繁体   English   中英

如何从 static 方法 flutter 获取上下文

[英]How to get context from static method flutter

有没有办法从 flutter 中的 static 方法获取context 假设我有一个需要context的 function ,例如Navigator.pop(context) ,则无法识别上下文属性。 那么,是否可以将当前 class 上下文传递给该 static 方法,以便我可以使用它的context

//static method

Future<dynamic> _myBackgroundMessageHandler
    (Map<String, dynamic> message) async {
  print("onBackground Message called");
  print(message);
  PushNotificationService().fetchRideInfo(message["data"]["orderId"],
      PushNotificationService._context,
      "onBackground");
//need to access context from here but not working
  print("onBackground");
  return PushNotificationService().showNotification(message);
}


class PushNotificationService{
  static BuildContext _context;

  static init({@required BuildContext context}) {
    _context = context;
  }

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        fetchRideInfo(message['data']['orderId'], context, "onMessage");
      },
    onBackgroundMessage: Platform.isIOS ? null:_myBackgroundMessageHandler,

      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        fetchRideInfo(message['data']['orderId'], context, "onResume");
      },
    );
    ///fetch user messaging token here
    getToken();
  }
  void fetchRideInfoInBackground() {
    print("incoming Request");
    assetsAudioPlayer.open(
      Audio('sounds/alert.mp3'),
    );
    assetsAudioPlayer.play();
  }
  Future<String> getToken() async{
    print("fetching token");
    token = await _firebaseMessaging.getToken();
    print('token got as: $token');
    return token;

  }

  void fetchRideInfo(orderId, context, String type) {
    print("fetching info");
    showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) =>
          CustomProgressDialog(status:'Fetching details',),);
    if(type!="onResume"){
      assetsAudioPlayer.open(
        Audio('sounds/alert.mp3'),
      );
      assetsAudioPlayer.play();
      print(orderId);
    }

    orderIdString = orderId;

      Provider.of<MainBloc>(context, listen: false).
      fetchRideInfo(context, orderId).then((value){
        Navigator.pop(context);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) =>
              RideRequestPage(orderId: orderId)),
        );
      }).catchError((error) {
        Navigator.pop(context);
        AlertManager.showToast(error.toString());
      });

  }

}

如果你想有上下文,你可以使用 Builder class:

Builder(
builder: (BuildContext context) => "Here you can put everything and use the Context";
 ),

要了解有关 Builder 的更多信息: https://api.flutter.dev/flutter/widgets/Builder-class.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM