首页 > 解决方案 > 将数据传递给 API 助手类的更好方法

问题描述

您好,我有一个 api 帮助程序类,我在其中获取通知数据。一切正常,但我想知道将数据传递给该助手类的更好方法。

所以我想知道如何将 id 传递给辅助类,

API 帮助类,

class NotificationStore = _NotificationStore with _$NotificationStore;

abstract class _NotificationStore with Store {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  _NotificationStore({String id}) { //<<<<<<<< id which I want
    foreGroundMessage();
    fetchToken(id);
  }

  @observable
  ObservableList<Notification> notifications = ObservableList<Notification>();

  Future<String> fetchToken(String id) async {
    if (Platform.isIOS) checkIOSPermission();
    var token = await _firebaseMessaging.getToken();
    _firebaseMessaging.subscribeToTopic(id);
    return token;
  }

}

我如何从小部件传递id ,

class _NotificationTabState extends State<NotificationTab> {
  NotificationStore notificationStore;

  @override
  void initState() {
    super.initState();
    final user = Provider.of<User>(context,listen: false);//<<<<< getting id from provider
    notificationStore = NotificationStore(id: user.id); //<<<<<< passing the id
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        enableBackIcon: false,
        title: AppStrings.notifications,
      ),
      body: GradientBackground(...)

所以我想让这个小部件无状态,所以有什么办法可以做到,因为我只是让这个小部件有状态,因为我可以在initState()

标签: flutterdart

解决方案


在你的statelessWidget

将这些行放在您的build()方法中


final user = Provider.of<User>(context,listen: false);
notificationStore = NotificationStore(id: user.id); 


@override
  Widget build(BuildContext context) {

    final user = Provider.of<User>(context,listen: false);
    notificationStore = NotificationStore(id: user.id); 

    return Scaffold(
      appBar: CustomAppBar(
        enableBackIcon: false,
        title: AppStrings.notifications,
      ),
      body: GradientBackground(...)


推荐阅读