【发布时间】: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