簡體   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