【问题标题】:Update state each time after notification is received每次收到通知后更新状态
【发布时间】:2021-07-21 22:35:33
【问题描述】:

我有一个应用程序使用包含一些数据的本地通知。在这种情况下,它是从 JSON 文件中读取的一些引号。

我正在尝试做的是每分钟阅读另一个报价并在主屏幕上更新它。

void main() {
  runApp(ChangeNotifierProvider<QuotesRepository>(
    create: (context) => QuotesRepository.instance(),
    child: MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyApp(),
    ),
  ));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var quote = Provider.of<QuotesRepository>(context);
    quote.showScheduledNotification();

    return Scaffold(
      appBar: new AppBar(
        backgroundColor: Colors.red,
        title: new Text('Flutter notification demo'),
      ),
      body: new Center(
        child: Text(
          quote.lastMessage.toString(),
          style: GoogleFonts.clickerScript(fontSize: 40.0),
        ),
      ),
    );
  }
}

这是定义提供者的地方:

class QuotesRepository with ChangeNotifier {
  String? lastMessage;

  QuotesRepository.instance();

  Future<void> loadJson(int index) async {
    String data = await rootBundle.loadString('assets/quotes.json');
    Map<String, dynamic> userMap = jsonDecode(data);

    this.lastMessage = userMap['quotes'][index]['quote'];
  }

  Future<void> showScheduledNotification() async {
    int randomValue = 42;
    await loadJson(randomValue).then((value) => showNotificationBody());

    notifyListeners();
  }

  Future<void> showNotificationBody() async {
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
        FlutterLocalNotificationsPlugin();
    print("Function called");
    const androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'channel id',
      'channel name',
      'channel description',
      icon: 'flutter_devs',
      largeIcon: DrawableResourceAndroidBitmap('flutter_devs'),
    );

    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
    );
    flutterLocalNotificationsPlugin.periodicallyShow(0, '365<3',
        this.lastMessage, RepeatInterval.everyMinute, platformChannelSpecifics,
        payload: this.lastMessage);
  }
}

但是,这会每秒调用一次函数并导致应用程序崩溃。 我知道这是因为我调用quote.showScheduledNotification();notifyListeners() 会导致它进入无限循环。

但是如何防止呢?如何只加载一次,然后每次通知到达时更新lastMessage

为简单起见,我每次都显示相同的报价 (42)。

【问题讨论】:

    标签: flutter dart flutter-provider


    【解决方案1】:

    似乎您正在寻找初始化功能。如果您将MyApp 转换为有状态小部件,您将能够使用stateful 小部件的init 方法。这应该解决问题的一部分。您几乎不应该在 build 函数中包含 init 功能,因为它会经常被调用。

    
    class MyApp extends StatefulWidget {
      const MyApp();
    
      @override
      _MyAppState createState() => _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      @override
      void initState() {
        super.initState();
        var quote = Provider.of<QuotesRepository>(context);
        quote.showScheduledNotification();
      }
    
      @override
      Widget build(BuildContext context) {
    
        return Scaffold(
          appBar: new AppBar(
            backgroundColor: Colors.red,
            title: new Text('Flutter notification demo'),
          ),
          body: new Center(
            child: Text(
              Provider.of<QuotesRepository>(context).lastMessage.toString(),
              style: GoogleFonts.clickerScript(fontSize: 40.0),
            ),
          ),
        );
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-12-20
      • 2023-03-16
      • 1970-01-01
      • 2018-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多