有没有办法从 flutter 中的静态方法中获取 context
?假设我有一个需要 context
的函数,例如 Navigator.pop(context)
,上下文属性不会被识别。那么,是否可以将当前类上下文传递给该静态方法,以便我可以使用它的 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());
});
}
}
答案 0 :(得分:0)
如果你想要上下文,你可以使用 Builder 类:
Builder(
builder: (BuildContext context) => "Here you can put everything and use the Context";
),
要了解有关 Builder 的更多信息: https://api.flutter.dev/flutter/widgets/Builder-class.html