You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter跨类变量调用:如何在其他类中使用randomName变量?

解决方案

方案一:直接在showNotification中实现需求(推荐)

既然你希望通知的body直接使用方法内生成的randomName,可以简化方法参数,去掉外部传入的body,直接在方法内部生成并使用:

修改showNotification方法:

Future<void> showNotification(int id, String title) async {
  final random = Random();
  final randomName = names[random.nextInt(names.length)];

  await flutterLocalNotificationsPlugin.periodicallyShow(
    id,
    title,
    randomName, // 直接用生成的随机名作为通知内容
    RepeatInterval.everyMinute,
    const NotificationDetails(
      android: AndroidNotificationDetails('main_channel', 'Main Channel',
          channelDescription: "hello",
          importance: Importance.max,
          priority: Priority.max),
      iOS: DarwinNotificationDetails(
        sound: 'default.wav',
        presentAlert: true,
        presentBadge: true,
        presentSound: true,
      ),
    ),
    androidAllowWhileIdle: true,
  );
}

调用时无需再传'You'参数:

onPressed: () {
  setState(() {
    showToast();
    NotificationService().showNotification(1, 'Hello ${widget.userPost}');
  });
},

方案二:将生成的randomName返回给调用方

如果需要把生成的随机名传递到其他类或做额外处理,可以让showNotification返回这个字符串:

修改方法返回值:

Future<String> showNotification(int id, String title) async {
  final random = Random();
  final randomName = names[random.nextInt(names.length)];

  await flutterLocalNotificationsPlugin.periodicallyShow(
    id,
    title,
    randomName,
    RepeatInterval.everyMinute,
    const NotificationDetails(
      android: AndroidNotificationDetails('main_channel', 'Main Channel',
          channelDescription: "hello",
          importance: Importance.max,
          priority: Priority.max),
      iOS: DarwinNotificationDetails(
        sound: 'default.wav',
        presentAlert: true,
        presentBadge: true,
        presentSound: true,
      ),
    ),
    androidAllowWhileIdle: true,
  );
  return randomName; // 返回生成的随机名
}

调用时获取返回值:

onPressed: () async {
  setState(() {
    showToast();
  });
  // 获取生成的随机名,可用于传递给其他类或后续操作
  String generatedName = await NotificationService().showNotification(1, 'Hello ${widget.userPost}');
},

补充说明

你之前尝试的@override在这里不适用,因为@override是用来重写父类的方法,而你的需求是方法内部生成值或向外传递值,和方法重写无关。

内容的提问来源于stack exchange,提问作者Marian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 05:05:30