面试题答案
一键面试主要思路
- 条件判断:利用Flutter提供的
Platform
类来判断当前运行的平台是iOS还是Android。 - 抽象通知创建方法:定义一个抽象方法来创建通知,在不同平台的实现类中实现该方法以创建对应样式的通知。
- 依赖注入或工厂模式:使用依赖注入或者工厂模式来根据平台选择合适的通知创建类。
关键代码示例
- 导入必要的包
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
- 抽象通知创建类
abstract class NotificationCreator {
void createNotification();
}
- iOS通知创建类
class iOSNotificationCreator implements NotificationCreator {
@override
void createNotification() {
// 实现iOS简洁样式通知逻辑
print('创建iOS简洁样式通知');
}
}
- Android通知创建类
class AndroidNotificationCreator implements NotificationCreator {
@override
void createNotification() {
// 实现Android详细图文样式通知逻辑
print('创建Android详细图文样式通知');
}
}
- 使用工厂模式选择创建类
NotificationCreator getNotificationCreator() {
if (defaultTargetPlatform == TargetPlatform.iOS) {
return iOSNotificationCreator();
} else if (defaultTargetPlatform == TargetPlatform.android) {
return AndroidNotificationCreator();
}
throw UnimplementedError('Unsupported platform');
}
- 在合适的地方调用
void main() {
final creator = getNotificationCreator();
creator.createNotification();
}
实际应用中,创建通知逻辑需结合Flutter的通知相关插件(如flutter_local_notifications
)来实现具体的通知功能。例如:
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
class iOSNotificationCreator implements NotificationCreator {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
@override
void createNotification() async {
const iOSPlatformChannelSpecifics = DarwinNotificationDetails(
title: '简洁标题',
subtitle: '简洁副标题',
);
const platformChannelSpecifics = NotificationDetails(iOS: iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'iOS通知',
'这是一个iOS简洁样式通知',
platformChannelSpecifics,
);
}
}
class AndroidNotificationCreator implements NotificationCreator {
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
@override
void createNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails(
'channel_id',
'channel_name',
channelDescription: 'channel_description',
importance: Importance.max,
priority: Priority.high,
autoCancel: true,
largeIcon: DrawableResourceAndroidBitmap('ic_launcher'),
);
const platformChannelSpecifics = NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Android通知',
'这是一个Android详细图文样式通知',
platformChannelSpecifics,
);
}
}