repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/doctor_app_ui/lib | mirrored_repositories/doctor_app_ui/lib/model/medical_services_model.dart | import 'package:flutter/material.dart';
class MedicalServicesModel {
final Color color;
final String title;
final String image;
MedicalServicesModel({
required this.color,
required this.title,
required this.image,
});
}
| 0 |
mirrored_repositories/doctor_app_ui/lib | mirrored_repositories/doctor_app_ui/lib/model/doctor_information_model.dart | class DoctorInformationModel {
final String id;
final String image;
final String title;
final String specialist;
final String hospital;
final String star;
DoctorInformationModel({
required this.id,
required this.image,
required this.title,
required this.specialist,
required this.hospital,
required this.star,
});
}
| 0 |
mirrored_repositories/doctor_app_ui/lib | mirrored_repositories/doctor_app_ui/lib/model/model.dart | export 'doctor_information_model.dart';
export 'medical_services_model.dart';
| 0 |
mirrored_repositories/doctor_app_ui/lib | mirrored_repositories/doctor_app_ui/lib/screens/doctor_screen.dart | import 'package:doctor_app_ui/data/data.dart';
import 'package:doctor_app_ui/model/model.dart';
import 'package:flutter/material.dart';
import 'package:doctor_app_ui/widgets/widgets.dart';
class DoctorScreen extends StatelessWidget {
final List<DoctorInformationModel> doctorInformations = doctorInformation;
final DoctorInformationModel doctorInformationModel;
DoctorScreen({
Key? key,
required this.doctorInformationModel,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DoctorImage(doctorInformationModel: doctorInformationModel),
DoctorDescription(doctorInformationModel: doctorInformationModel),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/doctor_app_ui/lib | mirrored_repositories/doctor_app_ui/lib/screens/screens.dart | export 'doctor_screen.dart';
export 'home_screen.dart';
| 0 |
mirrored_repositories/doctor_app_ui/lib | mirrored_repositories/doctor_app_ui/lib/screens/home_screen.dart | import 'package:doctor_app_ui/constants/constants.dart';
import 'package:doctor_app_ui/data/data.dart';
import 'package:doctor_app_ui/model/model.dart';
import 'package:doctor_app_ui/widgets/widgets.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatelessWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final List<MedicalServicesModel> medicalServices = medicalService;
final List<DoctorInformationModel> doctorInformations = doctorInformation;
return Scaffold(
backgroundColor: AppColors.white,
body: SafeArea(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 20.h),
CustomAppBar(
backButton: false,
profile: true,
icon: Icons.sort,
),
SizedBox(height: 20.h),
Text(
AppText.findDoctor,
style: Theme.of(context).textTheme.headline1,
),
SizedBox(height: 20.h),
const CustomTextBox(),
SizedBox(height: 20.h),
MedicalServices(medicalServices: medicalServices),
SizedBox(height: 20.h),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
AppText.topDoctors,
style: Theme.of(context).textTheme.headline3,
),
Text(
AppText.viewAll,
style: Theme.of(context).textTheme.headline6!.copyWith(
color: AppColors.blue, fontWeight: FontWeight.bold),
),
],
),
SizedBox(height: 20.h),
DoctorInformation(doctorInformations: doctorInformations),
SizedBox(height: 20.h),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/doctor_app_ui | mirrored_repositories/doctor_app_ui/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:doctor_app_ui/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Counter | mirrored_repositories/Counter/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(const HomePage());
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Contador de pessoas',
home: const CounterPage(),
theme: ThemeData(
fontFamily: 'Poppins',
useMaterial3: true,
),
);
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<StatefulWidget> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _people = 0;
String _infoText = 'Entre!';
void _changePeople(int delta) {
setState(() {
_people += delta;
if (_people < 0) {
_infoText = 'Isso não é possível';
} else if (_people <= 5) {
_infoText = 'Entre';
} else {
_infoText = 'Espere um pouco';
}
});
}
final kLabelStyle = const TextStyle(
color: Colors.white,
fontFamily: 'Poppins',
fontWeight: FontWeight.bold,
fontSize: 36,
decoration: TextDecoration.none,
height: 1.5,
);
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
return Stack(
children: <Widget>[
Image.asset(
'assets/images/background.jpg',
fit: BoxFit.cover,
height: double.infinity,
width: double.infinity,
alignment: Alignment.bottomCenter,
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: Image.asset(
'assets/images/people.png',
height: 175,
),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 32),
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.black38,
borderRadius: BorderRadius.circular(120.0),
),
child: Wrap(
children: [
Center(
child: Text(
'Quantidade:',
textAlign: TextAlign.center,
style: kLabelStyle,
),
),
Center(
child: Text(
'$_people',
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: 'Poppins',
fontSize: 54,
decoration: TextDecoration.none,
color: Colors.white,
height: 1.5,
),
),
),
const Center(
child: SizedBox(
height: 24.0,
width: double.maxFinite,
child: Divider(
thickness: 1.2,
color: Colors.white70,
indent: 100,
endIndent: 100,
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
minimumSize: const Size(0, 75),
),
child: const Icon(
Icons.add_circle,
size: 36,
color: Colors.greenAccent,
),
onPressed: () => _changePeople(1),
),
const SizedBox(width: 8),
ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.transparent,
minimumSize: const Size(0, 75),
),
child: Icon(
Icons.remove_circle,
size: 36,
color: Colors.redAccent[400],
),
onPressed: () => _changePeople(-1),
),
],
),
],
),
),
const Center(
child: SizedBox(
height: 16,
width: double.maxFinite,
child: Divider(
thickness: 1,
color: Colors.white70,
indent: 120,
endIndent: 120,
),
),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 50, vertical: 12),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.black38,
borderRadius: BorderRadius.circular(32.0),
),
child: Text(
_infoText,
textAlign: TextAlign.center,
style: kLabelStyle,
),
),
],
)
],
);
}
}
| 0 |
mirrored_repositories/Counter | mirrored_repositories/Counter/test/widget_test.dart | import 'package:counter/main.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('HomePage Widget', (WidgetTester tester) async {
await tester.pumpWidget(const HomePage());
});
}
| 0 |
mirrored_repositories/Readar | mirrored_repositories/Readar/lib/main.dart | import 'dart:io';
import 'package:readar/Providers/global_provider.dart';
import 'package:readar/Screens/Content/article_detail_screen.dart';
import 'package:readar/Screens/Lock/pin_change_screen.dart';
import 'package:readar/Screens/Navigation/explore_screen.dart';
import 'package:readar/Screens/Navigation/read_later_screen.dart';
import 'package:readar/Screens/Navigation/star_screen.dart';
import 'package:readar/Screens/Navigation/tts_screen.dart';
import 'package:readar/Screens/Setting/backup_setting_screen.dart';
import 'package:readar/Screens/Setting/entry_setting_screen.dart';
import 'package:readar/Screens/Setting/experiment_setting_screen.dart';
import 'package:readar/Screens/Setting/extension_setting_screen.dart';
import 'package:readar/Screens/Setting/operation_setting_screen.dart';
import 'package:readar/Screens/Setting/select_theme_screen.dart';
import 'package:readar/Screens/Setting/setting_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:provider/provider.dart';
import 'Providers/provider_manager.dart';
import 'Screens/Lock/pin_verify_screen.dart';
import 'Screens/Navigation/article_screen.dart';
import 'Screens/Navigation/feed_screen.dart';
import 'Screens/Navigation/library_screen.dart';
import 'Screens/Setting/about_setting_screen.dart';
import 'Screens/Setting/backup_service_setting_screen.dart';
import 'Screens/Setting/general_setting_screen.dart';
import 'Screens/Setting/global_setting_screen.dart';
import 'Screens/Setting/service_setting_screen.dart';
import 'Screens/main_screen.dart';
import 'generated/l10n.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await ProviderManager.init();
SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
runApp(const MyApp());
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: ProviderManager.globalProvider),
ChangeNotifierProvider.value(value: ProviderManager.rssProvider),
],
child: Consumer<GlobalProvider>(
builder: (context, globalProvider, child) => MaterialApp(
title: 'Readar',
theme: globalProvider.getBrightness() == null ||
globalProvider.getBrightness() == Brightness.light
? globalProvider.lightTheme
: globalProvider.darkTheme,
darkTheme: globalProvider.getBrightness() == null ||
globalProvider.getBrightness() == Brightness.dark
? globalProvider.darkTheme
: globalProvider.lightTheme,
debugShowCheckedModeBanner: false,
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
locale: globalProvider.locale,
supportedLocales: S.delegate.supportedLocales,
localeResolutionCallback: (locale, supportedLocales) {
if (globalProvider.locale != null) {
return globalProvider.locale;
} else if (locale != null && supportedLocales.contains(locale)) {
return locale;
} else {
return Localizations.localeOf(context);
}
},
home: const MainScreen(),
builder: (context, widget) {
return MediaQuery(
data: MediaQuery.of(context)
.copyWith(textScaler: TextScaler.noScaling),
child: widget!,
);
},
routes: {
TTSScreen.routeName: (context) => const TTSScreen(),
ArticleScreen.routeName: (context) => const ArticleScreen(),
SettingScreen.routeName: (context) => const SettingScreen(),
StarScreen.routeName: (context) => const StarScreen(),
LibraryScreen.routeName: (context) => const LibraryScreen(),
ExploreScreen.routeName: (context) => const ExploreScreen(),
PinChangeScreen.routeName: (context) => const PinChangeScreen(),
ReadLaterScreen.routeName: (context) => const ReadLaterScreen(),
EntrySettingScreen.routeName: (context) =>
const EntrySettingScreen(),
SelectThemeScreen.routeName: (context) => const SelectThemeScreen(),
ArticleDetailScreen.routeName: (context) => ArticleDetailScreen(),
ExperimentSettingScreen.routeName: (context) =>
const ExperimentSettingScreen(),
FeedScreen.routeName: (context) => const FeedScreen(),
AboutSettingScreen.routeName: (context) =>
const AboutSettingScreen(),
OperationSettingScreen.routeName: (context) =>
const OperationSettingScreen(),
BackupSettingScreen.routeName: (context) =>
const BackupSettingScreen(),
BackupServiceSettingScreen.routeName: (context) =>
const BackupServiceSettingScreen(),
ServiceSettingScreen.routeName: (context) =>
const ServiceSettingScreen(),
GeneralSettingScreen.routeName: (context) =>
const GeneralSettingScreen(),
GlobalSettingScreen.routeName: (context) =>
const GlobalSettingScreen(),
ExtensionSettingScreen.routeName: (context) =>
const ExtensionSettingScreen(),
PinVerifyScreen.routeName: (context) => PinVerifyScreen(
onSuccess:
ModalRoute.of(context)!.settings.arguments as Function(),
),
},
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Providers/provider_manager.dart | import 'dart:io';
import 'package:readar/Database/database_manager.dart';
import 'package:readar/Providers/rss_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:jaguar/serve/server.dart';
import 'package:jaguar_flutter_asset/jaguar_flutter_asset.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sqflite/sqflite.dart';
import '../Database/rss_service_dao.dart';
import '../Handler/rss_service_manager.dart';
import '../Models/rss_service.dart';
import '../Utils/hive_util.dart';
import '../Utils/store.dart';
import 'global_provider.dart';
abstract class ProviderManager {
static bool _initialized = false;
static GlobalProvider globalProvider = GlobalProvider();
static RssProvider rssProvider = RssProvider();
static late Database db;
static late Jaguar server;
static const String address = "127.0.0.1";
static const int port = 4567;
static Future<void> init() async {
if (_initialized) return;
_initialized = true;
db = await DatabaseManager.getDataBase();
Store.sp = await SharedPreferences.getInstance();
await initHive();
await initData();
}
static Future<void> initHive() async {
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
await Hive.initFlutter(HiveUtil.database);
} else {
await Hive.initFlutter();
}
await HiveUtil.openHiveBox(HiveUtil.settingsBox);
await HiveUtil.openHiveBox(HiveUtil.servicesBox);
}
static Future<void> initData() async {
await insertData();
await RssServiceDao.queryAll().then((value) async {
rssProvider.rssServices = value;
List<RssServiceManager> tmpHandlers = [];
for (var rssService in value) {
var rssHandler = RssServiceManager(rssService);
rssHandler.init();
tmpHandlers.add(rssHandler);
}
rssProvider.rssServiceManagers = tmpHandlers;
rssProvider.currentRssServiceManager = rssProvider.rssServiceManagers[0];
});
server =
Jaguar(address: ProviderManager.address, port: ProviderManager.port);
server.addRoute(serveFlutterAssets());
await server.serve();
}
static Future<void> insertData() async {
await RssServiceDao.queryAll().then((value) async {
List<RssService> rssServices = [
RssService(
"https://theoldreader.com",
"Old Reader",
RssServiceType.theOldReader,
id: 1,
username: "[email protected]",
password: "6Jv#f9g@cXNPs9z",
fetchLimit: 500,
params: {"useInt64": false},
),
// RssService(
// "https://theoldreader.com",
// "Old Reader",
// RssServiceType.theOldReader,
// id: 2,
// username: "[email protected]",
// password: "6Jv#f9g@cXNPs9z",
// fetchLimit: 500,
// params: {"useInt64": false},
// ),
// RssService(
// "https://theoldreader.com",
// "Old Reader",
// RssServiceType.theOldReader,
// id: 3,
// username: "[email protected]",
// password: "6Jv#f9g@cXNPs9z",
// fetchLimit: 500,
// params: {"useInt64": false},
// ),
];
await RssServiceDao.insertAll(rssServices);
});
}
static Brightness currentBrightness(BuildContext context) {
return globalProvider.getBrightness() ??
MediaQuery.of(context).platformBrightness;
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Providers/groups_provider.dart | import 'package:flutter/cupertino.dart';
class GroupsProvider with ChangeNotifier {}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Providers/global_provider.dart | import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';
import '../Models/nav_entry.dart';
import '../Utils/hive_util.dart';
import '../Widgets/Scaffold/my_scaffold.dart';
import '../generated/l10n.dart';
enum ActiveThemeMode {
system,
light,
dark,
}
class GlobalProvider with ChangeNotifier {
GlobalKey<MyScaffoldState> homeScaffoldKey = GlobalKey();
ThemeData _lightTheme = HiveUtil.getLightTheme().toThemeData();
ThemeData get lightTheme => _lightTheme;
setLightTheme(int index) {
HiveUtil.setLightTheme(index);
_lightTheme = HiveUtil.getLightTheme().toThemeData();
notifyListeners();
}
ThemeData _darkTheme = HiveUtil.getDarkTheme().toThemeData();
ThemeData get darkTheme => _darkTheme;
setDarkTheme(int index) {
HiveUtil.setDarkTheme(index);
_darkTheme = HiveUtil.getDarkTheme().toThemeData();
notifyListeners();
}
bool _isDrawerOpen = false;
bool get isDrawerOpen => _isDrawerOpen;
set isDrawerOpen(bool value) {
if (value != _isDrawerOpen) {
_isDrawerOpen = value;
notifyListeners();
}
}
List<NavEntry> _navEntries = HiveUtil.getNavEntries();
List<NavEntry> get navEntries => _navEntries;
set navEntries(List<NavEntry> value) {
if (value != _navEntries) {
_navEntries = value;
notifyListeners();
HiveUtil.setNavEntries(value);
}
}
Locale? _locale = HiveUtil.getLocale();
Locale? get locale => _locale;
set locale(Locale? value) {
if (value != _locale) {
_locale = value;
notifyListeners();
HiveUtil.setLocale(value);
}
}
ActiveThemeMode _themeMode = HiveUtil.getThemeMode();
ActiveThemeMode get themeMode => _themeMode;
set themeMode(ActiveThemeMode value) {
if (value != _themeMode) {
_themeMode = value;
notifyListeners();
HiveUtil.setThemeMode(value);
}
}
static String getThemeModeLabel(ActiveThemeMode themeMode) {
switch (themeMode) {
case ActiveThemeMode.system:
return S.current.followSystem;
case ActiveThemeMode.light:
return S.current.lightTheme;
case ActiveThemeMode.dark:
return S.current.darkTheme;
}
}
static List<Tuple2<String, ActiveThemeMode>> getSupportedThemeMode() {
return [
Tuple2(S.current.followSystem, ActiveThemeMode.system),
Tuple2(S.current.lightTheme, ActiveThemeMode.light),
Tuple2(S.current.darkTheme, ActiveThemeMode.dark),
];
}
int _autoLockTime = HiveUtil.getInt(key: HiveUtil.autoLockTimeKey);
int get autoLockTime => _autoLockTime;
set autoLockTime(int value) {
if (value != _autoLockTime) {
_autoLockTime = value;
notifyListeners();
HiveUtil.put(key: HiveUtil.autoLockTimeKey, value: value);
}
}
static String getAutoLockOptionLabel(int time) {
if (time == 0)
return "立即锁定";
else
return "处于后台$time分钟后锁定";
}
static List<Tuple2<String, int>> getAutoLockOptions() {
return [
Tuple2("立即锁定", 0),
Tuple2("处于后台1分钟后锁定", 1),
Tuple2("处于后台5分钟后锁定", 5),
Tuple2("处于后台10分钟后锁定", 10),
];
}
Brightness? getBrightness() {
if (_themeMode == ActiveThemeMode.system) {
return null;
} else {
return _themeMode == ActiveThemeMode.light
? Brightness.light
: Brightness.dark;
}
}
int _keepItemsDays = 21;
int get keepItemsDays => _keepItemsDays;
set keepItemsDays(int value) {
_keepItemsDays = value;
}
bool _syncOnStart = true;
bool get syncOnStart => _syncOnStart;
set syncOnStart(bool value) {
_syncOnStart = value;
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Providers/rss_provider.dart | import 'package:flutter/cupertino.dart';
import '../Handler/rss_service_manager.dart';
import '../Models/rss_item_list.dart';
import '../Models/rss_service.dart';
enum ItemSwipeOption {
toggleRead,
toggleStar,
share,
openMenu,
openExternal,
// toggleReadLater,
// toggleTTS
}
///
/// Rss状态管理
///
class RssProvider extends ChangeNotifier {
/// 所有RSS服务对象
late List<RssService> rssServices;
/// 所有RSS服务管理对象
late List<RssServiceManager> rssServiceManagers;
/// 当前RSS服务管理对象
late RssServiceManager currentRssServiceManager;
/// 当前RSS文章列表
RssItemList currentRssItemList = RssItemList(fids: {});
set rssService(List<RssService> value) {
if (value != rssServices) {
rssServices = value;
notifyListeners();
}
}
ItemSwipeOption _swipeR = ItemSwipeOption.values[0];
ItemSwipeOption get swipeR => _swipeR;
set swipeR(ItemSwipeOption value) {
_swipeR = value;
notifyListeners();
}
ItemSwipeOption _swipeL = ItemSwipeOption.values[1];
ItemSwipeOption get swipeL => _swipeL;
set swipeL(ItemSwipeOption value) {
_swipeL = value;
notifyListeners();
}
///
/// 加载指定订阅源的文章
///
Future<void> loadRssItemListByFid(String fid) async {
Set<String> sidSet = {fid};
currentRssItemList = RssItemList(fids: sidSet);
await currentRssItemList.init();
notifyListeners();
}
///
/// 加载指定订阅源列表的文章
///
Future<void> loadRssItemListByFids(Iterable<String> fids) async {
Set<String> sidSet = Set.from(fids);
currentRssItemList = RssItemList(fids: sidSet);
await currentRssItemList.init();
notifyListeners();
}
///
/// 根据Rss服务获取服务管理对象
///
RssServiceManager getRssServiceManager(RssService? rssService) {
if (rssService == null) return currentRssServiceManager;
for (var manager in rssServiceManagers) {
if (manager.rssService == rssService) {
return manager;
}
}
return currentRssServiceManager;
}
// void mergeFetchedItems(Iterable<RssItem> items) {
// for (var rssItemList in [currentRssItemList]) {
// var lastDate = rssItemList.iids.isNotEmpty
// ? currentRssServiceManager.getItem(rssItemList.iids.last).date
// : null;
// for (var item in items) {
// if (!rssItemList.testItem(item)) continue;
// if (lastDate != null && item.date.isBefore(lastDate)) continue;
// var idx = Utils.binarySearch(rssItemList.iids, item.iid, (a, b) {
// return currentRssServiceManager
// .getItem(b)
// .date
// .compareTo(currentRssServiceManager.getItem(a).date);
// });
// rssItemList.iids.insert(idx, item.iid);
// }
// }
// notifyListeners();
// }
///
///
///
/// 此处为Group代码
///
///
///
///
Map<String, List<String>> _groups = {};
List<String>? uncategorized = [];
Map<String, List<String>> get groups => _groups;
set groups(Map<String, List<String>> groups) {
_groups = groups;
updateUncategorized();
notifyListeners();
}
void updateUncategorized({force = false}) {
if (uncategorized != null || force) {
final sids = Set<String>.from(
currentRssServiceManager.getFeeds().map<String>((s) => s.fid));
for (var group in _groups.values) {
for (var sid in group) {
sids.remove(sid);
}
}
uncategorized = sids.toList();
}
}
bool get showUncategorized => uncategorized != null;
set showUncategorized(bool value) {
if (showUncategorized != value) {
if (value) {
updateUncategorized(force: true);
} else {
uncategorized = null;
}
notifyListeners();
}
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/iprint.dart | import 'package:flutter/foundation.dart';
class IPrint {
static void debug(Object? text) {
if (kDebugMode) {
print(text);
}
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/locale_util.dart | import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';
import '../generated/l10n.dart';
class LocaleUtil with ChangeNotifier {
static List<Tuple2<String, Locale?>> localeLabels = <Tuple2<String, Locale?>>[
Tuple2(S.current.followSystem, null),
const Tuple2("Deutsch", Locale("de")),
const Tuple2("English", Locale("en")),
const Tuple2("Español", Locale("es")),
const Tuple2("Français", Locale("fr")),
const Tuple2("hrvatski", Locale("hr")),
const Tuple2("Português do Brasil", Locale("pt")),
const Tuple2("Türkçe", Locale("tr")),
const Tuple2("Українська", Locale("uk")),
const Tuple2("简体中文", Locale("zh", "CN")),
const Tuple2("繁体中文", Locale("zh", "CN")),
];
static Tuple2<String, Locale?>? getTuple(Locale? locale) {
if (locale == null) {
return LocaleUtil.localeLabels[0];
}
for (Tuple2<String, Locale?> t in LocaleUtil.localeLabels) {
if (t.item2.toString() == locale.toString()) {
return t;
}
}
return null;
}
static String? getLabel(Locale? locale) {
return getTuple(locale)?.item1;
}
static Locale? getLocale(String label) {
for (Tuple2<String, Locale?> t in LocaleUtil.localeLabels) {
if (t.item1 == label) {
return t.item2;
}
}
return null;
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/cache_util.dart | import 'dart:io';
import 'package:path_provider/path_provider.dart';
class CacheUtil {
static Future<String> loadCache() async {
Directory tempDir = await getTemporaryDirectory();
double value = await _getTotalSizeOfFilesInDir(tempDir);
tempDir.list(followLinks: false, recursive: true).listen((file) {});
return _renderSize(value);
}
static Future<double> _getTotalSizeOfFilesInDir(
final FileSystemEntity file) async {
if (file is File) {
int length = await file.length();
return double.parse(length.toString());
}
if (file is Directory) {
final List<FileSystemEntity> children = file.listSync();
double total = 0;
for (final FileSystemEntity child in children) {
total += await _getTotalSizeOfFilesInDir(child);
}
return total;
}
return 0;
}
static Future<void> delDir(FileSystemEntity file) async {
if (file is Directory) {
final List<FileSystemEntity> children = file.listSync();
for (final FileSystemEntity child in children) {
await delDir(child);
}
}
await file.delete();
}
static _renderSize(double value) {
List<String> unitArr = ['B', 'K', 'M', 'G'];
int index = 0;
while (value > 1024) {
index++;
value = value / 1024;
}
String size = value.toStringAsFixed(2);
if (size == '0.00') {
return '0M';
}
return size + unitArr[index];
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/store.dart | import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
abstract class StoreKeys {
static const GROUPS = "groups";
static const ERROR_LOG = "errorLog";
static const UNCATEGORIZED = "uncategorized";
static const UNREAD_SUBS_ONLY = "unreadSubsOnly";
// General
static const THEME = "theme";
static const LOCALE = "locale";
static const KEEP_ITEMS_DAYS = "keepItemsD";
static const SYNC_ON_START = "syncOnStart";
static const IN_APP_BROWSER = "inAppBrowser";
static const TEXT_SCALE = "textScale";
// Feed preferences
static const FEED_FILTER_ALL = "feedFilterA";
static const FEED_FILTER_SOURCE = "feedFilterS";
static const SHOW_THUMB = "showThumb";
static const SHOW_SNIPPET = "showSnippet";
static const DIM_READ = "dimRead";
static const FEED_SWIPE_R = "feedSwipeR";
static const FEED_SWIPE_L = "feedSwipeL";
static const UNREAD_SOURCE_TIP = "unreadSourceTip";
// Reading preferences
static const ARTICLE_FONT_SIZE = "articleFontSize";
// Syncing
static const SYNC_SERVICE = "syncService";
static const LAST_SYNCED = "lastSynced";
static const LAST_SYNC_SUCCESS = "lastSyncSuccess";
static const LAST_ID = "lastId";
static const ENDPOINT = "endpoint";
static const USERNAME = "username";
static const PASSWORD = "password";
static const API_ID = "apiId";
static const API_KEY = "apiKey";
static const FETCH_LIMIT = "fetchLimit";
static const FEVER_INT_32 = "feverInt32";
static const LAST_FETCHED = "lastFetched";
static const AUTH = "auth";
static const USE_INT_64 = "useInt64";
static const INOREADER_REMOVE_AD = "inoRemoveAd";
}
class Store {
static late SharedPreferences sp;
static Map<String, List<String>> getGroups() {
var groups = sp.getString(StoreKeys.GROUPS);
if (groups == null) return <String, List<String>>{};
Map<String, List<String>> result = {};
var parsed = jsonDecode(groups);
for (var key in parsed.keys) {
result[key] = List.castFrom(parsed[key]);
}
return result;
}
static void setGroups(Map<String, List<String>> groups) {
sp.setString(StoreKeys.GROUPS, jsonEncode(groups));
}
static int getArticleFontSize() {
return sp.getInt(StoreKeys.ARTICLE_FONT_SIZE) ?? 16;
}
static void setArticleFontSize(int value) {
sp.setInt(StoreKeys.ARTICLE_FONT_SIZE, value);
}
static String getErrorLog() {
return sp.getString(StoreKeys.ERROR_LOG) ?? "";
}
static void setErrorLog(String value) {
sp.setString(StoreKeys.ERROR_LOG, value);
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/hive_util.dart | import 'dart:convert';
import 'dart:io';
import 'package:readar/Resources/theme_color_data.dart';
import 'package:readar/Utils/iprint.dart';
import 'package:flutter/material.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import '../Models/nav_entry.dart';
import '../Providers/global_provider.dart';
class HiveUtil {
//Database
static const String database = "Readar";
//HiveBox
static const String settingsBox = "settings";
static const String servicesBox = "services";
//TTS
static const String ttsEnableKey = "ttsEnable";
static const String ttsEngineKey = "ttsEngine";
static const String ttsSpeedKey = "ttsSpeed";
static const String ttsSpotKey = "ttsSpot";
static const String ttsAutoHaveReadKey = "ttsAutoHaveRead";
static const String ttsWakeLockKey = "ttsWakeLock";
//Appearance
static const String localeKey = "locale";
static const String lightThemeIndexKey = "lightThemeIndex";
static const String darkThemeIndexKey = "darkThemeIndex";
static const String lightThemePrimaryColorIndexKey =
"lightThemePrimaryColorIndex";
static const String darkThemePrimaryColorIndexKey =
"darkThemePrimaryColorIndex";
static const String customPrimaryColorKey = "customPrimaryColor";
static const String customLightThemeListKey = "customLightThemeList";
static const String customDarkThemeListKey = "customDarkThemeListKey";
static const String themeModeKey = "themeMode";
static const String sidebarEntriesKey = "sidebarEntries";
static const String articleLayoutKey = "articleLayout";
static const String articleMetaKey = "articleMeta";
//AI Summary
static const String aiSummaryEnableKey = "aiSummaryEnable";
static const String aiSummaryUseOfficialKey = "aiSummaryUseOfficial";
//Translate
static const String translateEnableKey = "translateEnable";
//Experiment
static const String hardwareAccelerationKey = "hardwareAcceleration";
static const String previewVideoKey = "previewVideo";
//Privacy
static const String enableGuesturePasswdKey = "enableGuesturePasswd";
static const String guesturePasswdKey = "guesturePasswd";
static const String enableBiometricKey = "enableBiometric";
static const String autoLockKey = "autoLock";
static const String autoLockTimeKey = "autoLockTime";
static const String enableSafeModeKey = "enableSafeMode";
//System
static const String firstLoginKey = "firstLogin";
static const String skipGuideKey = "skipGuide";
//Mess
static const String apiUrlKey = "apiUrl";
static const String apiKeyKey = "apiKey";
static const String apiCustomUrlKey = "apiCustomUrl";
static const String apiCodeKey = "apiCode";
static bool isFirstLogin() {
if (getBool(key: firstLoginKey, defaultValue: true) == true) return true;
return false;
}
static Locale? stringToLocale(String? localeString) {
if (localeString == null || localeString.isEmpty) {
return null;
}
var splitted = localeString.split('_');
if (splitted.length > 1) {
return Locale(splitted[0], splitted[1]);
} else {
return Locale(localeString);
}
}
static Locale? getLocale() {
return stringToLocale(HiveUtil.getString(key: HiveUtil.localeKey));
}
static void setLocale(Locale? locale) {
if (locale == null) {
HiveUtil.delete(key: HiveUtil.localeKey);
} else {
HiveUtil.put(key: HiveUtil.localeKey, value: locale.toString());
}
}
static ActiveThemeMode getThemeMode() {
return ActiveThemeMode.values[HiveUtil.getInt(key: HiveUtil.themeModeKey)];
}
static void setThemeMode(ActiveThemeMode themeMode) {
HiveUtil.put(key: HiveUtil.themeModeKey, value: themeMode.index);
}
static int getLightThemeIndex() {
int index =
HiveUtil.getInt(key: HiveUtil.lightThemeIndexKey, defaultValue: 0);
if (index > ThemeColorData.defaultLightThemes.length) {
String? json = HiveUtil.getString(key: HiveUtil.customLightThemeListKey);
if (json == null || json.isEmpty) {
setLightTheme(0);
return 0;
} else {
List<dynamic> list = jsonDecode(json);
if (index > ThemeColorData.defaultLightThemes.length + list.length) {
setLightTheme(0);
return 0;
} else {
return index;
}
}
} else {
return index;
}
}
static int getDarkThemeIndex() {
int index =
HiveUtil.getInt(key: HiveUtil.darkThemeIndexKey, defaultValue: 0);
if (index > ThemeColorData.defaultDarkThemes.length) {
String? json = HiveUtil.getString(key: HiveUtil.customDarkThemeListKey);
if (json == null || json.isEmpty) {
setDarkTheme(0);
return 0;
} else {
List<dynamic> list = jsonDecode(json);
if (index > ThemeColorData.defaultDarkThemes.length + list.length) {
setDarkTheme(0);
return 0;
} else {
return index;
}
}
} else {
return index;
}
}
static ThemeColorData getLightTheme() {
int index =
HiveUtil.getInt(key: HiveUtil.lightThemeIndexKey, defaultValue: 0);
if (index > ThemeColorData.defaultLightThemes.length) {
String? json = HiveUtil.getString(key: HiveUtil.customLightThemeListKey);
if (json == null || json.isEmpty) {
setLightTheme(0);
return ThemeColorData.defaultLightThemes[0];
} else {
List<dynamic> list = jsonDecode(json);
if (index > ThemeColorData.defaultLightThemes.length + list.length) {
setLightTheme(0);
return ThemeColorData.defaultLightThemes[0];
} else {
return ThemeColorData.fromJson(
list[index - ThemeColorData.defaultLightThemes.length]);
}
}
} else {
return ThemeColorData.defaultLightThemes[index];
}
}
static ThemeColorData getDarkTheme() {
int index =
HiveUtil.getInt(key: HiveUtil.darkThemeIndexKey, defaultValue: 0);
if (index > ThemeColorData.defaultDarkThemes.length) {
String? json = HiveUtil.getString(key: HiveUtil.customDarkThemeListKey);
if (json == null || json.isEmpty) {
setDarkTheme(0);
return ThemeColorData.defaultDarkThemes[0];
} else {
List<dynamic> list = jsonDecode(json);
if (index > ThemeColorData.defaultDarkThemes.length + list.length) {
setDarkTheme(0);
return ThemeColorData.defaultDarkThemes[0];
} else {
return ThemeColorData.fromJson(
list[index - ThemeColorData.defaultDarkThemes.length]);
}
}
} else {
return ThemeColorData.defaultDarkThemes[index];
}
}
static void setLightTheme(int index) =>
HiveUtil.put(key: HiveUtil.lightThemeIndexKey, value: index);
static void setDarkTheme(int index) =>
HiveUtil.put(key: HiveUtil.darkThemeIndexKey, value: index);
static bool shouldAutoLock() =>
HiveUtil.getBool(key: HiveUtil.enableGuesturePasswdKey) &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey) != null &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey)!.isNotEmpty &&
HiveUtil.getBool(key: HiveUtil.autoLockKey);
static List<NavEntry> getNavEntries() {
String? json = HiveUtil.getString(key: HiveUtil.sidebarEntriesKey);
if (json == null || json.isEmpty) {
return NavEntry.changableEntries;
} else {
List<dynamic> list = jsonDecode(json);
return List<NavEntry>.from(
list.map((item) => NavEntry.fromJson(item)).toList());
}
}
static void setNavEntries(List<NavEntry> entries) =>
HiveUtil.put(key: HiveUtil.sidebarEntriesKey, value: jsonEncode(entries));
//Essential
static int getInt(
{String boxName = HiveUtil.settingsBox,
required String key,
bool autoCreate = true,
int defaultValue = 0}) {
final Box box = Hive.box(boxName);
if (!box.containsKey(key)) {
put(boxName: boxName, key: key, value: defaultValue);
}
return box.get(key);
}
static bool getBool(
{String boxName = HiveUtil.settingsBox,
required String key,
bool autoCreate = true,
bool defaultValue = true}) {
final Box box = Hive.box(boxName);
if (!box.containsKey(key)) {
put(boxName: boxName, key: key, value: defaultValue);
}
return box.get(key);
}
static String? getString(
{String boxName = HiveUtil.settingsBox,
required String key,
bool autoCreate = true,
String? defaultValue}) {
final Box box = Hive.box(boxName);
if (!box.containsKey(key)) {
if (!autoCreate) {
return null;
}
put(boxName: boxName, key: key, value: defaultValue);
}
return box.get(key);
}
static List<dynamic>? getList(
{String boxName = HiveUtil.settingsBox,
required String key,
bool autoCreate = true,
List<dynamic>? defaultValue}) {
final Box box = Hive.box(boxName);
if (!box.containsKey(key)) {
if (!autoCreate) {
return null;
}
put(boxName: boxName, key: key, value: defaultValue);
}
return box.get(key);
}
static Future<void> put(
{String boxName = HiveUtil.settingsBox,
required String key,
required dynamic value}) async {
final Box box = Hive.box(boxName);
return box.put(key, value);
}
static void delete(
{String boxName = HiveUtil.settingsBox, required String key}) {
final Box box = Hive.box(boxName);
box.delete(key);
}
static bool contains(
{String boxName = HiveUtil.settingsBox, required String key}) {
final Box box = Hive.box(boxName);
return box.containsKey(key);
}
static Future<void> openHiveBox(String boxName, {bool limit = false}) async {
final box = await Hive.openBox(boxName).onError((error, stackTrace) async {
IPrint.debug('Failed to open $boxName Box');
final Directory dir = await getApplicationDocumentsDirectory();
final String dirPath = dir.path;
File dbFile = File('$dirPath/$boxName.hive');
File lockFile = File('$dirPath/$boxName.lock');
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
dbFile = File('$dirPath/${HiveUtil.database}/$boxName.hive');
lockFile = File('$dirPath/${HiveUtil.database}/$boxName.lock');
}
await dbFile.delete();
await lockFile.delete();
await Hive.openBox(boxName);
throw 'Failed to open $boxName Box\nError: $error';
});
if (limit && box.length > 500) {
box.clear();
}
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/itoast.dart | import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class IToast {
static FToast show(
BuildContext context, {
required String text,
Icon? icon,
int seconds = 2,
ToastGravity gravity = ToastGravity.TOP,
}) {
FToast toast = FToast().init(context);
toast.showToast(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Theme.of(context).scaffoldBackgroundColor.withAlpha(240),
boxShadow: [
BoxShadow(
color: Theme.of(context).shadowColor,
offset: const Offset(0, 4),
blurRadius: 10,
spreadRadius: 0,
)
],
),
child: Text(
text,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyMedium,
),
),
gravity: gravity,
toastDuration: Duration(seconds: seconds),
);
return toast;
}
static FToast showTop(
BuildContext context, {
required String text,
Icon? icon,
}) {
return show(context, text: text, icon: icon);
}
static FToast showBottom(
BuildContext context, {
required String text,
Icon? icon,
}) {
return show(context, text: text, icon: icon, gravity: ToastGravity.BOTTOM);
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/utils.dart | import 'package:flutter/cupertino.dart';
import 'package:html/parser.dart';
import 'package:http/http.dart' as http;
import 'package:lpinyin/lpinyin.dart';
import 'package:url_launcher/url_launcher.dart';
abstract class Utils {
static const syncMaxId = 9007199254740991;
static void openExternal(String url) {
launch(url, forceSafariVC: false, forceWebView: false);
}
static int binarySearch<T>(
List<T> sortedList, T value, int Function(T, T) compare) {
var min = 0;
var max = sortedList.length;
while (min < max) {
var mid = min + ((max - min) >> 1);
var element = sortedList[mid];
var comp = compare(element, value);
if (comp == 0) return mid;
if (comp < 0) {
min = mid + 1;
} else {
max = mid;
}
}
return min;
}
static Future<bool> validateFavicon(String url) async {
var flag = false;
var uri = Uri.parse(url);
var result = await http.get(uri);
if (result.statusCode == 200) {
var contentType =
result.headers["Content-Type"] ?? result.headers["content-type"];
if (contentType != null && contentType.startsWith("image")) flag = true;
}
return flag;
}
static final _urlRegex = RegExp(
r"^https?://(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,63}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*$)",
caseSensitive: false,
);
static bool testUrl(String url) => _urlRegex.hasMatch(url.trim());
static bool notEmpty(String text) => text.trim().isNotEmpty;
static void showServiceFailureDialog(BuildContext context) {
showCupertinoDialog(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text("服务错误"),
content: const Text("服务发生错误,尝试重新登录"),
actions: [
CupertinoDialogAction(
child: const Text("关闭"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
);
}
static int localStringCompare(String a, String b) {
a = a.toLowerCase();
b = b.toLowerCase();
try {
String ap = PinyinHelper.getShortPinyin(a);
String bp = PinyinHelper.getShortPinyin(b);
return ap.compareTo(bp);
} catch (exp) {
return a.compareTo(b);
}
}
///
/// 获取某个网站的图标
///
static Future<String?> fetchFeedFavicon(String url) async {
try {
url = url.split("/").getRange(0, 3).join("/");
var uri = Uri.parse(url);
var result = await http.get(uri);
if (result.statusCode == 200) {
var htmlStr = result.body;
var dom = parse(htmlStr);
var links = dom.getElementsByTagName("link");
for (var link in links) {
var rel = link.attributes["rel"];
if ((rel == "icon" || rel == "shortcut icon") &&
link.attributes.containsKey("href")) {
var href = link.attributes["href"]!;
var parsedUrl = Uri.parse(url);
if (href.startsWith("//")) {
return "${parsedUrl.scheme}:$href";
} else if (href.startsWith("/")) {
return url + href;
} else {
return href;
}
}
}
}
url = "$url/favicon.ico";
if (await Utils.validateFavicon(url)) {
return url;
} else {
return null;
}
} catch (exp) {
return null;
}
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/http_util.dart | import 'dart:io';
import 'package:readar/Utils/iprint.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
class HttpUtil {
static HttpUtil instance = HttpUtil();
late Dio dio;
late BaseOptions options;
String baseUrl = "";
CancelToken cancelToken = CancelToken();
static HttpUtil getInstance() {
return instance;
}
HttpUtil() {
options = BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 10),
receiveTimeout: const Duration(seconds: 5),
headers: {},
contentType: Headers.jsonContentType,
responseType: ResponseType.json,
);
dio = Dio(options);
(dio.httpClientAdapter as IOHttpClientAdapter).validateCertificate =
(X509Certificate? cert, String host, int port) => true;
final cookieJar = CookieJar();
dio.interceptors.add(CookieManager(cookieJar));
dio.interceptors.add(InterceptorsWrapper(
onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
return handler.next(options);
}, onResponse: (Response response, ResponseInterceptorHandler handler) {
return handler.next(response);
}, onError: (DioException e, ErrorInterceptorHandler handler) {
return handler.next(e);
}));
}
static get(url, {data, options, cancelToken, bool useBase = true}) async {
return getInstance()
._get(url, data: data, options: options, cancelToken: cancelToken);
}
static post(url, {data, options, cancelToken}) async {
return getInstance()
._post(url, data: data, options: options, cancelToken: cancelToken);
}
_get(url, {data, options, cancelToken}) async {
Response? response;
try {
response = await dio.get(url,
queryParameters: data, options: options, cancelToken: cancelToken);
// IPrint.debug('[Get] [Success] [$url] : ${response.data}');
} on DioException catch (e) {
formatError(url, e);
}
return response?.data['data'];
}
_post(url, {data, options, cancelToken}) async {
Response? response;
try {
response = await dio.post(url,
data: data, options: options, cancelToken: cancelToken);
// IPrint.debug('[Post] [Success] [$url] : ${response.data}');
} on DioException catch (e) {
formatError(url, e);
}
if (response?.data['code'] == 1002 ||
response?.data['code'] == 1003 ||
response?.data['code'] == 1004) {
return response?.data['message'];
} else {
return response?.data['data'];
}
}
void formatError(String url, DioException e) {
IPrint.debug("${e.response}");
if (e.type == DioExceptionType.connectionTimeout) {
IPrint.debug("$url:连接超时");
} else if (e.type == DioExceptionType.sendTimeout) {
IPrint.debug("$url:请求超时");
} else if (e.type == DioExceptionType.receiveTimeout) {
IPrint.debug("$url:响应超时");
} else if (e.type == DioExceptionType.badResponse) {
IPrint.debug("$url:出现异常");
} else if (e.type == DioExceptionType.cancel) {
IPrint.debug("$url:请求取消");
} else {
IPrint.debug("$url:未知错误");
}
}
void cancelRequests(CancelToken token) {
token.cancel("cancelled");
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Utils/uri_util.dart | import 'package:readar/Utils/itoast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
class UriUtil {
static Future<bool> launchEmailUri(BuildContext context, String email,
{String subject = "", String body = ""}) async {
try {
if (!await launchUrl(
Uri.parse("mailto:$email?subject=$subject&body=$body"),
mode: LaunchMode.externalApplication,
)) {
Clipboard.setData(ClipboardData(text: email));
}
} on PlatformException catch (_) {
IToast.showTop(context, text: "尚未安装邮箱程序,已复制Email地址到剪贴板");
}
return true;
}
static void launchUrlUri(String url) async {
if (!await launchUrl(Uri.parse(url),
mode: LaunchMode.externalApplication)) {
Clipboard.setData(ClipboardData(text: url));
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Utils | mirrored_repositories/Readar/lib/Utils/Channel/android_back_desktop.dart | import 'package:readar/Utils/iprint.dart';
import 'package:flutter/services.dart';
class AndroidBackDesktopChannel {
static const String channel = "android/back/desktop";
static const String eventBackDesktop = "backDesktop";
static Future<bool> backToDesktop() async {
const platform = MethodChannel(channel);
try {
await platform.invokeMethod(eventBackDesktop);
} on PlatformException catch (e) {
IPrint.debug(e);
}
return Future.value(false);
}
}
| 0 |
mirrored_repositories/Readar/lib | mirrored_repositories/Readar/lib/Screens/main_screen.dart | import 'dart:async';
import 'package:readar/Models/nav_entry.dart';
import 'package:readar/Screens/Navigation/article_screen.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_windowmanager/flutter_windowmanager.dart';
import 'package:provider/provider.dart';
import '../Providers/global_provider.dart';
import '../Providers/provider_manager.dart';
import '../Utils/hive_util.dart';
import '../Widgets/Item/item_builder.dart';
import '../Widgets/Scaffold/my_scaffold.dart';
import '../generated/l10n.dart';
import 'Lock/pin_verify_screen.dart';
import 'Setting/about_setting_screen.dart';
import 'Setting/setting_screen.dart';
class MainScreen extends StatefulWidget {
const MainScreen({super.key});
static const String routeName = "/";
@override
State<MainScreen> createState() => MainScreenState();
}
class MainScreenState extends State<MainScreen>
with WidgetsBindingObserver, TickerProviderStateMixin {
List<Widget> _pageList = [];
List<NavEntry> _sideBarEntries = [];
Timer? _timer;
late bool isDark;
IconData? themeModeIcon;
bool isDrawerOpen = false;
final _pageController = PageController(keepPage: true);
late final AnimationController _drawerAnimationController;
@override
void initState() {
super.initState();
_drawerAnimationController = AnimationController(
vsync: this,
value: ProviderManager.globalProvider.isDrawerOpen ? 1.0 : 0.0,
duration: const Duration(milliseconds: 246),
);
WidgetsBinding.instance.addObserver(this);
if (HiveUtil.getBool(
key: HiveUtil.enableSafeModeKey, defaultValue: false)) {
FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE);
} else {
FlutterWindowManager.clearFlags(FlutterWindowManager.FLAG_SECURE);
}
WidgetsBinding.instance.addPostFrameCallback((_) {
goPinVerify();
initData();
refreshDarkState();
});
ProviderManager.globalProvider.addListener(() {
initData();
});
}
void initData() {
_pageList = [const ArticleScreen()];
_sideBarEntries = NavEntry.getShownEntries();
if (NavEntry.getHiddenEntries().isNotEmpty) {
_sideBarEntries.add(NavEntry.libraryEntry);
}
_sideBarEntries.addAll(NavEntry.defaultEntries);
for (NavEntry item in _sideBarEntries) {
_pageList.add(NavEntry.getPage(item.id));
}
setState(() {});
}
void onBottomNavigationBarItemTap(int index) {
_pageController.jumpToPage(index);
}
void goPinVerify() {
if (HiveUtil.shouldAutoLock()) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PinVerifyScreen(
onSuccess: () {},
isModal: true,
),
),
);
}
}
@override
Widget build(BuildContext context) {
initData();
return MyScaffold(
key: ProviderManager.globalProvider.homeScaffoldKey,
onDrawerChanged: (isOpened) {
ProviderManager.globalProvider.isDrawerOpen = isOpened;
},
drawerEdgeDragWidth: MediaQuery.of(context).size.width,
body: ScaleTransition(
scale: Tween<double>(begin: 1.0, end: 0.98)
.animate(_drawerAnimationController),
child: Selector<GlobalProvider, bool>(
selector: (context, globalProvider) => globalProvider.isDrawerOpen,
builder: (context, isSidebarOpen, _) => PageView(
controller: _pageController,
physics: const NeverScrollableScrollPhysics(),
children: _pageList,
),
),
),
drawer: _drawer(),
customAnimationController: _drawerAnimationController,
);
}
Widget _drawer() {
return Drawer(
width: MediaQuery.of(context).size.width * 0.8,
elevation: 0.0,
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: Column(
children: [
Expanded(
child: ListView(
padding: EdgeInsets.zero,
children: [
SizedBox(
height: MediaQuery.of(context).padding.top,
),
Container(
margin:
const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Column(
children: [
ItemBuilder.buildCaptionItem(
context: context, title: S.current.article),
..._feedEntries(),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.content),
..._contentEntries(),
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.setting,
padding: 15,
topRadius: true,
showLeading: true,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const SettingScreen()));
},
leading: Icons.settings_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.about,
bottomRadius: true,
showLeading: true,
padding: 15,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const AboutSettingScreen()));
},
leading: Icons.info_outline_rounded,
),
const SizedBox(height: 10),
],
),
),
const SizedBox(height: 10),
],
),
),
],
),
),
);
}
List<Widget> _contentEntries() {
List<Widget> widgets = [];
for (NavEntry entry in _sideBarEntries) {
widgets.add(
ItemBuilder.buildEntryItem(
context: context,
title: NavEntry.getLabel(entry.id),
showLeading: true,
padding: 15,
bottomRadius: _sideBarEntries.last == entry,
onTap: () {
setState(() {
if (mounted) {
_pageController.jumpToPage(_sideBarEntries.indexOf(entry) + 1);
}
});
Navigator.of(context).pop();
},
leading: NavEntry.getIcon(entry.id),
),
);
}
return widgets;
}
List<Widget> _feedEntries() {
List<Widget> widgets = [];
widgets.add(
ItemBuilder.buildEntryItem(
context: context,
title: S.current.allArticle,
showLeading: true,
padding: 15,
bottomRadius: true,
onTap: () {
setState(() {
if (mounted) {
_pageController.jumpToPage(0);
}
});
Navigator.of(context).pop();
},
leading: Icons.feed_outlined,
),
);
return widgets;
}
refreshDarkState() {
setState(() {
isDark = (ProviderManager.globalProvider.themeMode ==
ActiveThemeMode.system &&
MediaQuery.of(context).platformBrightness == Brightness.dark) ||
ProviderManager.globalProvider.themeMode == ActiveThemeMode.dark;
if (!isDark) {
themeModeIcon = Icons.dark_mode_outlined;
} else {
themeModeIcon = Icons.light_mode_outlined;
}
});
}
void cancleTimer() {
if (_timer != null) {
_timer!.cancel();
}
}
void setTimer() {
_timer = Timer(
Duration(minutes: ProviderManager.globalProvider.autoLockTime),
goPinVerify);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
switch (state) {
case AppLifecycleState.inactive:
break;
case AppLifecycleState.resumed:
cancleTimer();
break;
case AppLifecycleState.paused:
setTimer();
break;
case AppLifecycleState.detached:
break;
case AppLifecycleState.hidden:
break;
}
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Lock/pin_change_screen.dart | import 'package:readar/Utils/iprint.dart';
import 'package:readar/Utils/itoast.dart';
import 'package:readar/Widgets/Unlock/gesture_notifier.dart';
import 'package:readar/Widgets/Unlock/gesture_unlock_indicator.dart';
import 'package:readar/Widgets/Unlock/gesture_unlock_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/error_codes.dart' as auth_error;
import 'package:local_auth/local_auth.dart';
import 'package:local_auth_android/local_auth_android.dart';
import '../../Utils/hive_util.dart';
class PinChangeScreen extends StatefulWidget {
const PinChangeScreen({super.key});
static const String routeName = "/pin/change";
@override
PinChangeScreenState createState() => PinChangeScreenState();
}
AndroidAuthMessages andStrings = const AndroidAuthMessages(
cancelButton: '取消',
goToSettingsButton: '去设置',
biometricNotRecognized: '指纹识别失败',
goToSettingsDescription: '请设置指纹',
biometricHint: '',
biometricSuccess: '指纹识别成功',
signInTitle: '指纹验证',
deviceCredentialsRequiredTitle: '请先录入指纹!',
);
class PinChangeScreenState extends State<PinChangeScreen> {
String _gesturePassword = "";
final String? _oldPassword =
HiveUtil.getString(key: HiveUtil.guesturePasswdKey);
bool _isEditMode =
HiveUtil.getString(key: HiveUtil.guesturePasswdKey) != null &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey)!.isNotEmpty;
late final bool _isUseBiometric =
_isEditMode && HiveUtil.getBool(key: HiveUtil.enableBiometricKey);
late final GestureNotifier _notifier = _isEditMode
? GestureNotifier(status: GestureStatus.verify, gestureText: "绘制旧手势密码")
: GestureNotifier(status: GestureStatus.create, gestureText: "绘制新手势密码");
final GlobalKey<GestureState> _gestureUnlockView = GlobalKey();
final GlobalKey<GestureUnlockIndicatorState> _indicator = GlobalKey();
@override
void initState() {
super.initState();
if (_isUseBiometric) {
auth();
}
}
void auth() async {
LocalAuthentication localAuth = LocalAuthentication();
try {
await localAuth
.authenticate(
localizedReason: '进行指纹验证以使用APP',
authMessages: [andStrings, andStrings, andStrings],
options: const AuthenticationOptions(
biometricOnly: true,
useErrorDialogs: false,
stickyAuth: true))
.then((value) {
if (value) {
IToast.showTop(context, text: "验证成功");
setState(() {
_notifier.setStatus(
status: GestureStatus.create,
gestureText: "绘制新手势密码",
);
_isEditMode = false;
});
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.normal);
}
});
} on PlatformException catch (e) {
if (e.code == auth_error.notAvailable) {
IPrint.debug("not avaliable");
} else if (e.code == auth_error.notEnrolled) {
IPrint.debug("not enrolled");
} else if (e.code == auth_error.lockedOut ||
e.code == auth_error.permanentlyLockedOut) {
IPrint.debug("locked out");
} else {
IPrint.debug("other reason:$e");
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
right: false,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 100),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_notifier.gestureText,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 30),
GestureUnlockIndicator(
key: _indicator,
size: 30,
roundSpace: 4,
defaultColor: Colors.grey.withOpacity(0.5),
selectedColor: Theme.of(context).primaryColor.withOpacity(0.6),
),
Expanded(
child: GestureUnlockView(
key: _gestureUnlockView,
size: MediaQuery.of(context).size.width,
padding: 60,
roundSpace: 40,
defaultColor: Colors.grey.withOpacity(0.5),
selectedColor: Theme.of(context).primaryColor,
failedColor: Theme.of(context).colorScheme.error,
disableColor: Colors.grey,
solidRadiusRatio: 0.3,
lineWidth: 2,
touchRadiusRatio: 0.3,
onCompleted: _gestureComplete,
),
),
Visibility(
visible: _isEditMode,
child: Visibility(
visible: _isUseBiometric,
child: GestureDetector(
onTap: () {
auth();
},
child: Text(
"指纹识别",
style: Theme.of(context).textTheme.titleSmall,
),
),
),
),
],
),
),
),
);
}
void _gestureComplete(List<int> selected, UnlockStatus status) async {
switch (_notifier.status) {
case GestureStatus.create:
case GestureStatus.createFailed:
if (selected.length < 4) {
setState(() {
_notifier.setStatus(
status: GestureStatus.createFailed,
gestureText: "连接数不能小于4个,请重新设置",
);
});
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.failed);
} else {
setState(() {
_notifier.setStatus(
status: GestureStatus.verify,
gestureText: "请再次绘制解锁密码",
);
});
_gesturePassword = GestureUnlockView.selectedToString(selected);
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.success);
_indicator.currentState?.setSelectPoint(selected);
}
break;
case GestureStatus.verify:
case GestureStatus.verifyFailed:
if (!_isEditMode) {
String password = GestureUnlockView.selectedToString(selected);
if (_gesturePassword == password) {
IToast.showTop(context, text: "设置成功");
setState(() {
_notifier.setStatus(
status: GestureStatus.verify,
gestureText: "设置成功",
);
Navigator.pop(context);
});
HiveUtil.put(
key: HiveUtil.guesturePasswdKey,
value: GestureUnlockView.selectedToString(selected));
} else {
setState(() {
_notifier.setStatus(
status: GestureStatus.verifyFailed,
gestureText: "与上一次绘制不一致, 请重新绘制",
);
});
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.failed);
}
} else {
String password = GestureUnlockView.selectedToString(selected);
if (_oldPassword == password) {
setState(() {
_notifier.setStatus(
status: GestureStatus.create,
gestureText: "绘制新手势密码",
);
_isEditMode = false;
});
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.normal);
} else {
setState(() {
_notifier.setStatus(
status: GestureStatus.verifyFailed,
gestureText: "密码错误, 请重新绘制",
);
});
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.failed);
}
}
break;
case GestureStatus.verifyFailedCountOverflow:
break;
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Lock/pin_verify_screen.dart | import 'package:readar/Utils/iprint.dart';
import 'package:readar/Widgets/Unlock/gesture_notifier.dart';
import 'package:readar/Widgets/Unlock/gesture_unlock_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:local_auth/error_codes.dart' as auth_error;
import 'package:local_auth/local_auth.dart';
import 'package:local_auth_android/local_auth_android.dart';
import '../../Utils/hive_util.dart';
class PinVerifyScreen extends StatefulWidget {
const PinVerifyScreen({super.key, this.onSuccess, this.isModal = true});
final bool isModal;
final Function()? onSuccess;
static const String routeName = "/pin/verify";
@override
PinVerifyScreenState createState() => PinVerifyScreenState();
}
AndroidAuthMessages andStrings = const AndroidAuthMessages(
cancelButton: '取消',
goToSettingsButton: '去设置',
biometricNotRecognized: '指纹识别失败',
goToSettingsDescription: '请设置指纹',
biometricHint: '',
biometricSuccess: '指纹识别成功',
signInTitle: '指纹验证',
deviceCredentialsRequiredTitle: '请先录入指纹!',
);
class PinVerifyScreenState extends State<PinVerifyScreen> {
final String? _password = HiveUtil.getString(key: HiveUtil.guesturePasswdKey);
late final bool _isUseBiometric =
HiveUtil.getBool(key: HiveUtil.enableBiometricKey);
late final GestureNotifier _notifier =
GestureNotifier(status: GestureStatus.verify, gestureText: "验证密码");
final GlobalKey<GestureState> _gestureUnlockView = GlobalKey();
@override
void initState() {
super.initState();
if (_isUseBiometric) {
auth();
}
}
void auth() async {
LocalAuthentication localAuth = LocalAuthentication();
try {
await localAuth
.authenticate(
localizedReason: '进行指纹验证以使用APP',
authMessages: [andStrings, andStrings, andStrings],
options: const AuthenticationOptions(
biometricOnly: true,
useErrorDialogs: false,
stickyAuth: true))
.then((value) {
if (value) {
if (widget.onSuccess != null) widget.onSuccess!();
Navigator.pop(context);
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.normal);
}
});
} on PlatformException catch (e) {
if (e.code == auth_error.notAvailable) {
IPrint.debug("not avaliable");
} else if (e.code == auth_error.notEnrolled) {
IPrint.debug("not enrolled");
} else if (e.code == auth_error.lockedOut ||
e.code == auth_error.permanentlyLockedOut) {
IPrint.debug("locked out");
} else {
IPrint.debug("other reason:$e");
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
right: false,
child: WillPopScope(
onWillPop: () {
return Future(() => !widget.isModal);
},
child: Container(
margin: const EdgeInsets.symmetric(vertical: 100),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
_notifier.gestureText,
style: Theme.of(context).textTheme.titleMedium,
),
const SizedBox(height: 30),
Expanded(
child: GestureUnlockView(
key: _gestureUnlockView,
size: MediaQuery.of(context).size.width,
padding: 60,
roundSpace: 40,
defaultColor: Colors.grey.withOpacity(0.5),
selectedColor: Theme.of(context).primaryColor,
failedColor: Colors.redAccent,
disableColor: Colors.grey,
solidRadiusRatio: 0.3,
lineWidth: 2,
touchRadiusRatio: 0.3,
onCompleted: _gestureComplete,
),
),
Visibility(
visible: _isUseBiometric,
child: GestureDetector(
onTap: () {
auth();
},
child: Text(
"指纹识别",
style: Theme.of(context).textTheme.titleSmall,
),
),
),
],
),
),
),
),
);
}
void _gestureComplete(List<int> selected, UnlockStatus status) async {
switch (_notifier.status) {
case GestureStatus.verify:
case GestureStatus.verifyFailed:
String password = GestureUnlockView.selectedToString(selected);
if (_password == password) {
if (widget.onSuccess != null) widget.onSuccess!();
Navigator.pop(context);
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.normal);
} else {
setState(() {
_notifier.setStatus(
status: GestureStatus.verifyFailed,
gestureText: "密码错误, 请重新绘制",
);
});
_gestureUnlockView.currentState?.updateStatus(UnlockStatus.failed);
}
break;
case GestureStatus.verifyFailedCountOverflow:
case GestureStatus.create:
case GestureStatus.createFailed:
break;
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Content/article_detail_screen.dart | import 'dart:io';
import 'package:readar/Providers/rss_provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:tuple/tuple.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../Models/feed.dart';
import '../../Models/feed_setting.dart';
import '../../Models/rss_item.dart';
import '../../Providers/provider_manager.dart';
import '../../Utils/store.dart';
import '../../Widgets/Item/toolbar.dart';
import '../../generated/l10n.dart';
class ArticleDetailScreen extends StatefulWidget {
static final GlobalKey<ArticleDetailScreenState> state = GlobalKey();
ArticleDetailScreen() : super(key: state);
static const String routeName = "/article/detail";
@override
ArticleDetailScreenState createState() => ArticleDetailScreenState();
}
enum ArticleLoadState { loading, success, failure }
class ArticleDetailScreenState extends State<ArticleDetailScreen> {
late WebViewController _controller;
int requestId = 0;
ArticleLoadState loaded = ArticleLoadState.loading;
bool navigated = false;
CrawlType? _target;
late String iid;
late bool isSourceFeed;
void loadNewItem(String id, {bool? isSource}) {
if (!ProviderManager.rssProvider.currentRssServiceManager
.getItem(id)
.hasRead) {
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(id, read: true);
}
setState(() {
iid = id;
loaded = ArticleLoadState.loading;
navigated = false;
_target = null;
if (isSource != null) isSourceFeed = isSource;
});
}
Future<NavigationDecision> _onNavigate(NavigationRequest request) async {
if (navigated && request.isForMainFrame) {
//TODO 是否内置浏览器
const internal = true;
await launch(request.url,
forceSafariVC: internal, forceWebView: internal);
return NavigationDecision.prevent;
} else {
return NavigationDecision.navigate;
}
}
void _loadHtml(RssItem item, Feed source, {loadFull = false}) async {
var localUrl =
"http://${ProviderManager.address}:${ProviderManager.port}/article/article.html";
var currId = requestId;
String a;
if (loadFull) {
try {
var uri = Uri.parse(item.url);
var html = (await http.get(uri)).body;
a = Uri.encodeComponent(html);
} catch (exp) {
if (mounted && currId == requestId) {
setState(() {
loaded = ArticleLoadState.failure;
});
}
return;
}
} else {
a = Uri.encodeComponent(item.content);
}
if (!mounted || currId != requestId) return;
var h =
'<p id="source">${source.name}${(item.creator != null && item.creator!.isNotEmpty) ? ' / ${item.creator}' : ''}</p>';
h += '<p id="title">${item.title}</p>';
h +=
'<p id="date">${DateFormat.yMd(Localizations.localeOf(context).toString()).add_Hm().format(item.date)}</p>';
h += '<article></article>';
h = Uri.encodeComponent(h);
var s = Store.getArticleFontSize();
localUrl += "?a=$a&h=$h&s=$s&u=${item.url}&m=${loadFull ? 1 : 0}";
if (Platform.isAndroid ||
ProviderManager.globalProvider.getBrightness() != null) {
var brightness = ProviderManager.currentBrightness(context);
localUrl += "&t=${brightness.index}";
}
_controller.loadUrl(localUrl);
}
void _onPageReady(_) async {
if (Platform.isAndroid ||
ProviderManager.globalProvider.getBrightness() != null) {
await Future.delayed(const Duration(milliseconds: 300));
}
setState(() {
loaded = ArticleLoadState.success;
});
if (_target == CrawlType.rss || _target == CrawlType.full) {
navigated = true;
}
}
void _onWebpageReady(_) {
if (loaded == ArticleLoadState.success) navigated = true;
}
void _setOpenTarget(Feed source, {CrawlType? target}) {
setState(() {
_target = target ?? (source.feedSetting?.crawlType ?? CrawlType.web);
});
}
void _loadOpenTarget(RssItem item, Feed source) {
setState(() {
requestId += 1;
loaded = ArticleLoadState.loading;
navigated = false;
});
switch (_target) {
case CrawlType.unspecified:
case CrawlType.rss:
_loadHtml(item, source);
break;
case CrawlType.full:
_loadHtml(item, source, loadFull: true);
break;
case CrawlType.web:
case CrawlType.external:
_controller.loadUrl(item.url);
break;
case null:
break;
}
}
@override
Widget build(BuildContext context) {
final Tuple2<String, bool> arguments =
ModalRoute.of(context)?.settings.arguments as Tuple2<String, bool>;
iid = arguments.item1;
isSourceFeed = arguments.item2;
final viewOptions = {
0: const Padding(
padding: EdgeInsets.symmetric(horizontal: 8),
child: Icon(
Icons.rss_feed,
semanticLabel: "RSS内容",
),
),
1: const Icon(
Icons.article_outlined,
semanticLabel: "加载全文",
),
2: const Icon(
Icons.language,
semanticLabel: "加载网页",
),
};
return Selector<RssProvider, Tuple2<RssItem, Feed>>(
selector: (context, rssProvider) {
var item = rssProvider.currentRssServiceManager.getItem(iid);
var source = rssProvider.currentRssServiceManager.getFeed(item.feedFid);
return Tuple2(item, source);
},
builder: (context, tuple, child) {
var item = tuple.item1;
var source = tuple.item2;
_target ??= source.feedSetting?.crawlType;
final body = SafeArea(
bottom: false,
child: IndexedStack(
index: loaded.index,
children: [
const Center(child: CupertinoActivityIndicator()),
WebView(
key: Key("a-$iid-${_target?.index}"),
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
_loadOpenTarget(item, source);
},
onPageStarted: _onPageReady,
onPageFinished: _onWebpageReady,
navigationDelegate: _onNavigate,
),
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"发生错误",
style: TextStyle(
color: CupertinoColors.label.resolveFrom(context)),
),
CupertinoButton(
child: const Text("重试"),
onPressed: () {
_loadOpenTarget(item, source);
},
),
],
),
)
],
),
);
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
backgroundColor: CupertinoColors.systemBackground,
middle: CupertinoSlidingSegmentedControl(
children: viewOptions,
onValueChanged: (v) {
_setOpenTarget(source, target: CrawlType.values[v ?? 0]);
},
groupValue: _target?.index,
),
),
child: Consumer<RssProvider>(
child: body,
builder: (context, feedContentProvider, child) {
final feed = isSourceFeed
? feedContentProvider.currentRssItemList
: feedContentProvider.currentRssItemList;
var idx = feed.iids.indexOf(iid);
return CupertinoToolbar(
items: [
CupertinoToolbarItem(
icon: item.hasRead
? Icons.check_circle_outline_rounded
: Icons.circle_outlined,
semanticLabel: item.hasRead ? "标为未读" : "标为已读",
onPressed: () {
HapticFeedback.mediumImpact();
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(item.iid, read: !item.hasRead);
},
),
CupertinoToolbarItem(
icon: item.starred
? Icons.star_rounded
: Icons.star_outline_rounded,
semanticLabel: item.starred ? S.of(context).star : "取消星标",
onPressed: () {
HapticFeedback.mediumImpact();
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(item.iid, starred: !item.starred);
},
),
CupertinoToolbarItem(
icon: Icons.share,
semanticLabel: "分享",
onPressed: () {
final media = MediaQuery.of(context);
Share.share(item.url,
sharePositionOrigin: Rect.fromLTWH(
media.size.width -
MediaQuery.of(context).size.width / 2,
media.size.height - media.padding.bottom - 54,
0,
0));
},
),
CupertinoToolbarItem(
icon: Icons.keyboard_arrow_up_rounded,
semanticLabel: "上一个",
onPressed: idx <= 0
? () {}
: () {
loadNewItem(feed.iids[idx - 1]);
},
),
CupertinoToolbarItem(
icon: Icons.keyboard_arrow_down_rounded,
semanticLabel: "下一个",
onPressed: (idx == -1 ||
(idx == feed.iids.length - 1 && feed.allLoaded))
? () {}
: () async {
if (idx == feed.iids.length - 1) {
await feed.loadMore();
}
idx = feed.iids.indexOf(iid);
if (idx != feed.iids.length - 1) {
loadNewItem(feed.iids[idx + 1]);
}
},
),
],
body: child ?? Container(),
);
},
),
);
},
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/feed_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class FeedScreen extends StatefulWidget {
const FeedScreen({super.key});
static const String routeName = "/nav/subscription";
@override
State<FeedScreen> createState() => _FeedScreenState();
}
class _FeedScreenState extends State<FeedScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.add_link_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/library_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class LibraryScreen extends StatefulWidget {
const LibraryScreen({super.key});
static const String routeName = "/nav/library";
@override
State<LibraryScreen> createState() => _LibraryScreenState();
}
class _LibraryScreenState extends State<LibraryScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/explore_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class ExploreScreen extends StatefulWidget {
const ExploreScreen({super.key});
static const String routeName = "/nav/explore";
@override
State<ExploreScreen> createState() => _ExploreScreenState();
}
class _ExploreScreenState extends State<ExploreScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.done_all_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/article_screen.dart | import 'dart:io';
import 'package:readar/Models/rss_service.dart';
import 'package:readar/Providers/global_provider.dart';
import 'package:readar/Providers/rss_provider.dart';
import 'package:readar/Resources/gaps.dart';
import 'package:readar/Widgets/Item/item_builder.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';
import '../../Models/feed.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Custom/no_shadow_scroll_behavior.dart';
import '../../Widgets/Item/article_item.dart';
import '../../Widgets/Popup/dropdown_menu.dart';
import '../../Widgets/Popup/ipopup.dart';
class ArticleScreen extends StatefulWidget {
const ArticleScreen({super.key});
static const String routeName = "/nav/article";
@override
State<ArticleScreen> createState() => _ArticleScreenState();
}
class _ArticleScreenState extends State<ArticleScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
DateTime? _lastLoadedMoreTime;
late RefreshController _refreshController;
late PopController _dropdownController;
late final AnimationController _dropdownAnimationController;
late RssService? _currentRssService;
List<Feed> _currentFeedList = [];
final GlobalKey _appbarKey = GlobalKey();
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
_refreshController = RefreshController(initialRefresh: false);
_dropdownAnimationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
value: 0,
lowerBound: 0,
upperBound: 0.5,
);
_dropdownController = PopController();
refreshCurrentRssService(
ProviderManager.rssProvider.currentRssServiceManager.rssService);
}
@override
bool get wantKeepAlive => true;
void refreshCurrentRssService(RssService? value) {
setState(() {
_currentRssService = value;
_currentFeedList = ProviderManager.rssProvider
.getRssServiceManager(_currentRssService)
.getFeeds();
});
}
void _onRefresh() async {
await Future.delayed(const Duration(milliseconds: 1000));
_refreshController.refreshCompleted();
}
void _onLoading() async {
var feed = ProviderManager.rssProvider.currentRssItemList;
if (feed.loading) {
return;
} else if (feed.allLoaded) {
_refreshController.loadNoData();
} else if ((_lastLoadedMoreTime == null ||
DateTime.now().difference(_lastLoadedMoreTime!).inSeconds > 1)) {
_lastLoadedMoreTime = DateTime.now();
feed.loadMore().then((value) {
_refreshController.loadComplete();
});
}
}
@override
Widget build(BuildContext context) {
super.build(context);
return GestureDetector(
behavior: HitTestBehavior.opaque,
child: Scaffold(
appBar: _buildAppBar(),
body: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: Consumer2<GlobalProvider, RssProvider>(
builder: (context, globalProvider, rssProvider, child) =>
SmartRefresher(
enablePullDown: true,
enablePullUp: true,
header: MaterialClassicHeader(
backgroundColor: Theme.of(context).canvasColor,
color: Theme.of(context).primaryColor,
),
controller: _refreshController,
onRefresh: _onRefresh,
onLoading: _onLoading,
child: _buildRssItemList(rssProvider),
),
),
),
),
);
}
Widget _buildFeedServceNull() {
return Container(
alignment: Alignment.center,
child: Text("暂无订阅源,请从本地导入或添加RSS服务",
style: Theme.of(context).textTheme.titleLarge),
);
}
Widget _buildFeedServiceList(List<RssService> rssServices) {
return SizedBox(
width: 100,
child: ListView.builder(
itemCount: rssServices.length,
padding: EdgeInsets.zero,
itemBuilder: (content, index) {
return Material(
child: Ink(
decoration: BoxDecoration(color: Theme.of(context).canvasColor),
child: InkWell(
onTap: () {
refreshCurrentRssService(rssServices[index]);
},
child: Container(
padding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: Text(
rssServices[index].name,
style: Theme.of(context).textTheme.bodyMedium,
),
),
),
),
);
},
),
);
}
Widget _buildFeedList() {
return Expanded(
child: ListView.builder(
itemCount: _currentFeedList.length,
padding: EdgeInsets.zero,
itemBuilder: (context, index) {
return Material(
child: Ink(
decoration: BoxDecoration(color: Theme.of(context).canvasColor),
child: InkWell(
onTap: () {
ProviderManager.rssProvider
.loadRssItemListByFid(_currentFeedList[index].fid);
IPopup.pop(context);
},
child: Container(
padding:
const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
child: Text(
_currentFeedList[index].name,
style: Theme.of(context).textTheme.titleMedium,
),
),
),
),
);
},
),
);
}
Widget _buildRssItemList(RssProvider rssProvider) {
return ListView.builder(
itemCount: rssProvider.currentRssItemList.iids.length,
itemBuilder: (content, index) {
var item = ProviderManager.rssProvider.currentRssServiceManager
.getItem(rssProvider.currentRssItemList.iids[index]);
var tuple = Tuple2(
item,
ProviderManager.rssProvider.currentRssServiceManager
.getFeed(item.feedFid));
return ArticleItem(tuple.item1, tuple.item2, (_) {},
topMargin: index == 0);
},
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
key: _appbarKey,
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
title: GestureDetector(
onTap: () {
_showDropdownMenu();
},
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.only(left: 6),
child: Text(
"知乎热榜",
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 16,
letterSpacing: 0.1,
color: Theme.of(context).textTheme.titleMedium!.color,
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text("Feedbin", style: Theme.of(context).textTheme.labelSmall),
RotationTransition(
turns: CurvedAnimation(
parent: _dropdownAnimationController,
curve: Curves.linear),
child: Icon(Icons.keyboard_arrow_down_rounded,
size: 15,
color: Theme.of(context).textTheme.labelSmall!.color),
),
],
)
],
),
),
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.done_all_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
_showDropdownMenu() {
double height = MediaQuery.of(context).padding.top +
(_appbarKey.currentWidget as PreferredSizeWidget).preferredSize.height;
IPopup.show(
context,
DropDownMenu(
padding: EdgeInsets.only(top: height),
animationController: _dropdownAnimationController,
controller: _dropdownController,
child: GestureDetector(
onTap: () {},
child: Container(
color: Theme.of(context).canvasColor,
margin: EdgeInsets.only(top: height + 314.5),
height: MediaQuery.of(context).size.height * 0.6,
child: Selector<RssProvider, List<RssService>>(
selector: (context, rssProvider) => rssProvider.rssServices,
builder: (context, rssServices, _) => rssServices.isNotEmpty
? Row(
mainAxisSize: MainAxisSize.min,
children: [
_buildFeedServiceList(rssServices),
MyGaps.verticleDivider(context),
_buildFeedList(),
],
)
: _buildFeedServceNull(),
),
),
),
),
offsetLT: Offset(0, height),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/tts_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class TTSScreen extends StatefulWidget {
const TTSScreen({super.key});
static const String routeName = "/nav/tts";
@override
State<TTSScreen> createState() => _TTSScreenState();
}
class _TTSScreenState extends State<TTSScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/title_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class TitleScreen extends StatefulWidget {
const TitleScreen(this.title, {super.key});
final String title;
static const String routeName = "/nav/title";
@override
State<TitleScreen> createState() => _TitleScreenState();
}
class _TitleScreenState extends State<TitleScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
title: Text(widget.title, style: Theme.of(context).textTheme.titleLarge),
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/read_later_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class ReadLaterScreen extends StatefulWidget {
const ReadLaterScreen({super.key});
static const String routeName = "/nav/readLater";
@override
State<ReadLaterScreen> createState() => _ReadLaterScreenState();
}
class _ReadLaterScreenState extends State<ReadLaterScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Navigation/star_screen.dart | import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../Providers/provider_manager.dart';
import '../../Widgets/Item/item_builder.dart';
class StarScreen extends StatefulWidget {
const StarScreen({super.key});
static const String routeName = "/nav/star";
@override
State<StarScreen> createState() => _StarScreenState();
}
class _StarScreenState extends State<StarScreen>
with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
void initState() {
if (Platform.isAndroid) {
SystemUiOverlayStyle systemUiOverlayStyle = const SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
statusBarIconBrightness: Brightness.dark);
SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}
super.initState();
}
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
appBar: _buildAppBar(),
body: Container(),
);
}
bool _isNavigationBarEntry() {
String? name = ModalRoute.of(context)!.settings.name;
Object? arguments = ModalRoute.of(context)!.settings.arguments;
if (name != null && arguments != null && name == "isNavigationBarEntry") {
return arguments as bool;
} else {
return true;
}
}
PreferredSizeWidget _buildAppBar() {
return ItemBuilder.buildAppBar(
context: context,
leading: _isNavigationBarEntry()
? Icons.menu_rounded
: Icons.arrow_back_rounded,
onLeadingTap: () {
if (_isNavigationBarEntry()) {
ProviderManager.globalProvider.homeScaffoldKey.currentState
?.openDrawer();
ProviderManager.globalProvider.isDrawerOpen = true;
} else {
Navigator.of(context).pop();
}
},
actions: [
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.search_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
ItemBuilder.buildIconButton(
context: context,
icon: Icon(Icons.filter_list_rounded,
color: Theme.of(context).iconTheme.color),
onTap: () {}),
const SizedBox(width: 5),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/experiment_setting_screen.dart | import 'package:app_settings/app_settings.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import 'package:flutter_windowmanager/flutter_windowmanager.dart';
import 'package:local_auth/local_auth.dart';
import 'package:provider/provider.dart';
import '../../Providers/global_provider.dart';
import '../../Providers/provider_manager.dart';
import '../../Utils/hive_util.dart';
import '../../Utils/itoast.dart';
import '../../Widgets/BottomSheet/bottom_sheet_builder.dart';
import '../../Widgets/BottomSheet/list_bottom_sheet.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
import '../Lock/pin_change_screen.dart';
import '../Lock/pin_verify_screen.dart';
class ExperimentSettingScreen extends StatefulWidget {
const ExperimentSettingScreen({super.key});
static const String routeName = "/setting/experiment";
@override
State<ExperimentSettingScreen> createState() =>
_ExperimentSettingScreenState();
}
class _ExperimentSettingScreenState extends State<ExperimentSettingScreen>
with TickerProviderStateMixin {
bool _enableGuesturePasswd =
HiveUtil.getBool(key: HiveUtil.enableGuesturePasswdKey);
bool _hasGuesturePasswd =
HiveUtil.getString(key: HiveUtil.guesturePasswdKey) != null &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey)!.isNotEmpty;
bool _autoLock = HiveUtil.getBool(key: HiveUtil.autoLockKey);
bool _enableSafeMode =
HiveUtil.getBool(key: HiveUtil.enableSafeModeKey, defaultValue: false);
bool _enableBiometric = HiveUtil.getBool(key: HiveUtil.enableBiometricKey);
bool _biometricAvailable = false;
@override
void initState() {
super.initState();
initBiometricAuthentication();
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.experimentSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.ttsSetting),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.ttsEnable,
value: true,
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.ttsEngine,
tip: "默认引擎",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.ttsSpeed,
tip: "1.0x",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.ttsSystemSetting,
onTap: () {
AppSettings.openAppSettings(
type: AppSettingsType.tts, asAnotherTask: true);
},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.ttsSpot,
value: true,
description: S.current.ttsSpotTip,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.ttsAutoHaveRead,
value: true,
description: S.current.ttsAutoHaveReadTip,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.ttsWakeLock,
value: true,
description: S.current.ttsWakeLockTip,
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "AI摘要"),
ItemBuilder.buildEntryItem(
context: context,
title: "第三方AI服务管理",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "内容发送模板",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "内容发送字数上限",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "聊天室",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "翻译"),
ItemBuilder.buildEntryItem(
context: context,
title: "第三方翻译服务管理",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "源语言",
description: "当文章为何种语言时自动翻译",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "目标语言",
description: "将文章自动翻译为目标语言",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.privacySetting),
ItemBuilder.buildRadioItem(
context: context,
value: _enableGuesturePasswd,
title: "启用手势密码",
onTap: onEnablePinTapped,
),
Visibility(
visible: _enableGuesturePasswd,
child: ItemBuilder.buildEntryItem(
context: context,
title: _hasGuesturePasswd ? "更改手势密码" : "设置手势密码",
description: _hasGuesturePasswd ? "" : "设置手势密码后才能使用锁定功能",
onTap: onChangePinTapped,
),
),
Visibility(
visible: _enableGuesturePasswd &&
_hasGuesturePasswd &&
_biometricAvailable,
child: ItemBuilder.buildRadioItem(
context: context,
value: _enableBiometric,
title: "生物识别",
onTap: onBiometricTapped,
),
),
Visibility(
visible: _enableGuesturePasswd && _hasGuesturePasswd,
child: ItemBuilder.buildRadioItem(
context: context,
value: _autoLock,
title: "处于后台自动锁定",
onTap: onEnableAutoLockTapped,
),
),
Visibility(
visible:
_enableGuesturePasswd && _hasGuesturePasswd && _autoLock,
child: Selector<GlobalProvider, int>(
selector: (context, globalProvider) =>
globalProvider.autoLockTime,
builder: (context, autoLockTime, child) =>
ItemBuilder.buildEntryItem(
context: context,
title: "自动锁定时机",
tip: GlobalProvider.getAutoLockOptionLabel(autoLockTime),
onTap: () {
BottomSheetBuilder.showListBottomSheet(
context,
(context) => TileList.fromOptions(
GlobalProvider.getAutoLockOptions(),
autoLockTime,
(item2) {
ProviderManager.globalProvider.autoLockTime =
item2;
Navigator.pop(context);
},
context: context,
title: "选择自动锁定时机",
onCloseTap: () => Navigator.pop(context),
),
);
},
),
),
),
ItemBuilder.buildRadioItem(
context: context,
value: _enableSafeMode,
title: "安全模式",
bottomRadius: true,
description: "当软件进入最近任务列表页面,隐藏页面内容;同时禁用应用内截图",
onTap: onSafeModeTapped,
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
initBiometricAuthentication() async {
LocalAuthentication localAuth = LocalAuthentication();
bool available = await localAuth.canCheckBiometrics;
setState(() {
_biometricAvailable = available;
});
}
onEnablePinTapped() {
setState(() {
if (_enableGuesturePasswd) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PinVerifyScreen(
onSuccess: () {
IToast.showTop(context, text: "手势密码关闭成功");
setState(() {
_enableGuesturePasswd = !_enableGuesturePasswd;
HiveUtil.put(
key: HiveUtil.enableGuesturePasswdKey,
value: _enableGuesturePasswd);
_hasGuesturePasswd =
HiveUtil.getString(key: HiveUtil.guesturePasswdKey) !=
null &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey)!
.isNotEmpty;
});
},
isModal: false,
),
),
);
} else {
setState(() {
_enableGuesturePasswd = !_enableGuesturePasswd;
HiveUtil.put(
key: HiveUtil.enableGuesturePasswdKey,
value: _enableGuesturePasswd);
_hasGuesturePasswd =
HiveUtil.getString(key: HiveUtil.guesturePasswdKey) != null &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey)!
.isNotEmpty;
});
}
});
}
onBiometricTapped() {
if (!_enableBiometric) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PinVerifyScreen(
onSuccess: () {
IToast.showTop(context, text: "生物识别开启成功");
setState(() {
_enableBiometric = !_enableBiometric;
HiveUtil.put(
key: HiveUtil.enableBiometricKey, value: _enableBiometric);
});
},
isModal: false,
),
),
);
} else {
setState(() {
_enableBiometric = !_enableBiometric;
HiveUtil.put(key: HiveUtil.enableBiometricKey, value: _enableBiometric);
});
}
}
onChangePinTapped() {
setState(() {
Navigator.push(context,
MaterialPageRoute(builder: (context) => const PinChangeScreen()))
.then((value) {
setState(() {
_hasGuesturePasswd =
HiveUtil.getString(key: HiveUtil.guesturePasswdKey) != null &&
HiveUtil.getString(key: HiveUtil.guesturePasswdKey)!
.isNotEmpty;
});
});
});
}
onEnableAutoLockTapped() {
setState(() {
_autoLock = !_autoLock;
HiveUtil.put(key: HiveUtil.autoLockKey, value: _autoLock);
});
}
onSafeModeTapped() {
setState(() {
_enableSafeMode = !_enableSafeMode;
if (_enableSafeMode) {
FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE);
} else {
FlutterWindowManager.clearFlags(FlutterWindowManager.FLAG_SECURE);
}
HiveUtil.put(key: HiveUtil.enableSafeModeKey, value: _enableSafeMode);
});
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/entry_setting_screen.dart | import 'package:readar/Models/nav_entry.dart';
import 'package:readar/Providers/global_provider.dart';
import 'package:readar/Providers/provider_manager.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../Widgets/Custom/no_shadow_scroll_behavior.dart';
import '../../Widgets/Draggable/drag_and_drop_lists.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class EntrySettingScreen extends StatefulWidget {
const EntrySettingScreen({super.key});
static const String routeName = "/setting/entry";
@override
State<EntrySettingScreen> createState() => _EntrySettingScreenState();
}
class _EntrySettingScreenState extends State<EntrySettingScreen>
with TickerProviderStateMixin {
List<DragAndDropList> _contents = [];
bool _allShown = false;
bool _allHidden = false;
final ScrollController _scrollController = ScrollController();
@override
initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
initList();
updateNavBar();
});
}
@override
void didChangeDependencies() {
initList();
updateNavBar();
super.didChangeDependencies();
}
void initList() {
List<NavEntry> shownEntries = NavEntry.getShownEntries();
List<NavEntry> hiddenEntries = NavEntry.getHiddenEntries();
_contents = <DragAndDropList>[
DragAndDropList(
canDrag: false,
header: ItemBuilder.buildCaptionItem(
context: context,
title: _allHidden
? S.current.allEntriesHiddenTip
: S.current.shownEntries),
lastTarget: ItemBuilder.buildCaptionItem(
context: context,
title: S.current.dragTip,
topRadius: false,
bottomRadius: true),
contentsWhenEmpty: Container(),
children: List.generate(
shownEntries.length,
(index) => DragAndDropItem(
child: ItemBuilder.buildEntryItem(
context: context,
title: NavEntry.getLabel(shownEntries[index].id),
showTrailing: false,
),
data: shownEntries[index],
),
),
),
DragAndDropList(
canDrag: false,
header: ItemBuilder.buildCaptionItem(
context: context,
title: _allShown
? S.current.allEntriesShownTip
: S.current.hiddenEntries(S.current.library)),
lastTarget: ItemBuilder.buildCaptionItem(
context: context,
title: S.current.dragTip,
topRadius: false,
bottomRadius: true),
contentsWhenEmpty: Container(),
children: List.generate(
hiddenEntries.length,
(index) => DragAndDropItem(
child: ItemBuilder.buildEntryItem(
context: context,
title: NavEntry.getLabel(hiddenEntries[index].id),
showTrailing: false,
),
data: hiddenEntries[index],
),
),
),
];
}
void updateNavBar() {
_allShown = _contents[1].children.isEmpty;
_allHidden = _contents[0].children.isEmpty;
_contents[0].header = ItemBuilder.buildCaptionItem(
context: context,
title: _allHidden
? S.current.allEntriesHiddenTip
: S.current.shownEntries);
_contents[1].header = ItemBuilder.buildCaptionItem(
context: context,
title: _allShown
? S.current.allEntriesShownTip
: S.current.hiddenEntries(S.current.library));
}
void persist() {
List<NavEntry> navs = [];
int cur = 0;
for (DragAndDropItem item in _contents[0].children) {
NavEntry data = item.data;
data.visible = true;
data.index = cur;
cur += 1;
navs.add(data);
}
for (DragAndDropItem item in _contents[1].children) {
NavEntry data = item.data;
data.visible = false;
data.index = cur;
cur += 1;
navs.add(data);
}
ProviderManager.globalProvider.navEntries = navs;
}
@override
Widget build(BuildContext context) {
return Consumer<GlobalProvider>(builder: (context, globalProvider, child) {
return Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.sideBarEntriesSetting,
context: context,
),
body: Container(
margin: const EdgeInsets.only(left: 10, right: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: CustomScrollView(
slivers: [
const SliverToBoxAdapter(
child: SizedBox(height: 10),
),
_contents.isNotEmpty
? DragAndDropLists(
children: _contents,
onItemReorder: _onItemReorder,
listPadding: const EdgeInsets.only(bottom: 10),
onListReorder: (_, __) {},
lastItemTargetHeight: 0,
lastListTargetSize: 60,
sliverList: true,
scrollController: _scrollController,
itemDragOnLongPress: false,
itemGhostOpacity: 0.3,
itemOpacityWhileDragging: 0.7,
itemDragHandle: DragHandle(
child: Container(
margin: const EdgeInsets.only(right: 8),
child: ItemBuilder.buildIconButton(
context: context,
icon: Icon(
Icons.dehaze_rounded,
size: 20,
color: Theme.of(context)
.textTheme
.titleSmall
?.color,
),
onTap: () {}),
)),
)
: SliverToBoxAdapter(child: Container()),
],
),
),
),
);
});
}
_onItemReorder(
int oldItemIndex, int oldListIndex, int newItemIndex, int newListIndex) {
setState(() {
var movedItem = _contents[oldListIndex].children.removeAt(oldItemIndex);
_contents[newListIndex].children.insert(newItemIndex, movedItem);
});
persist();
updateNavBar();
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/about_setting_screen.dart | import 'package:readar/Utils/uri_util.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class AboutSettingScreen extends StatefulWidget {
const AboutSettingScreen({super.key});
static const String routeName = "/setting/about";
@override
State<AboutSettingScreen> createState() => _AboutSettingScreenState();
}
class _AboutSettingScreenState extends State<AboutSettingScreen>
with TickerProviderStateMixin {
int count = 0;
late String appName = "";
@override
void initState() {
super.initState();
getAppInfo();
}
void getAppInfo() {
PackageInfo.fromPlatform().then((PackageInfo packageInfo) {
setState(() {
appName = packageInfo.appName;
});
});
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
leading: Icons.close_rounded, context: context),
body: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
children: [
const SizedBox(height: 20),
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.asset(
'assets/logo.png',
height: 50,
width: 50,
fit: BoxFit.fitHeight,
),
),
Container(
margin: const EdgeInsets.only(top: 8),
alignment: Alignment.center,
child: Text(
appName,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w900,
),
),
),
Container(
margin: const EdgeInsets.all(10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.help,
showLeading: true,
topRadius: true,
padding: 15,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com/help");
},
leading: Icons.help_outline_rounded,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.privacyPolicy,
showLeading: true,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com/privacyPolicy");
},
bottomRadius: true,
leading: Icons.group_outlined,
),
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.contributor,
topRadius: true,
showLeading: true,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com/contributor");
},
leading: Icons.supervised_user_circle_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.changeLog,
showLeading: true,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com/changeLog");
},
leading: Icons.merge_type_outlined,
),
// ItemBuilder.buildEntryItem(
// context: context,
// title: S.current.participateInTranslation,
// onTap: () {},
// showLeading: true,
// leading: Icons.translate_rounded,
// ),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.bugReport,
onTap: () {
UriUtil.launchUrlUri(
"https://github.com/Robert-Stackflow/Readar/issues");
},
showLeading: true,
leading: Icons.bug_report_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.license,
showLeading: true,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com/license");
},
leading: Icons.local_library_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.githubRepo,
onTap: () {
UriUtil.launchUrlUri(
"https://github.com/Robert-Stackflow/Readar");
},
showLeading: true,
bottomRadius: true,
leading: Icons.commit_rounded,
),
const SizedBox(height: 10),
// ItemBuilder.buildEntryItem(
// context: context,
// title: S.current.rate,
// showLeading: true,
// onTap: () {},
// leading: Icons.rate_review_outlined,
// ),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.contact,
topRadius: true,
onTap: () {
UriUtil.launchEmailUri(context, "[email protected]",
subject: "反馈");
},
showLeading: true,
leading: Icons.contact_support_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.officialWebsite,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com");
},
showLeading: true,
leading: Icons.language_rounded,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.telegramGroup,
onTap: () {
UriUtil.launchUrlUri("https://t.me/Readar");
},
bottomRadius: true,
showLeading: true,
leading: Icons.telegram_outlined,
),
const SizedBox(height: 10)
],
),
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/extension_setting_screen.dart | import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class ExtensionSettingScreen extends StatefulWidget {
const ExtensionSettingScreen({super.key});
static const String routeName = "/setting/extension";
@override
State<ExtensionSettingScreen> createState() => _ExtensionSettingScreenState();
}
class _ExtensionSettingScreenState extends State<ExtensionSettingScreen>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.extensionSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "下列插件可直接保存文章"),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Pocket",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Evernote",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Instapaper",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "OneNote",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Notion",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "PinBoard",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "印象笔记",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "为知笔记",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "专注笔记",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "有道云笔记",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Joplin",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "flomo",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: "建议新的插件",
description: "向我们建议你希望支持的笔记服务插件",
topRadius: true,
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/operation_setting_screen.dart | import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class OperationSettingScreen extends StatefulWidget {
const OperationSettingScreen({super.key});
static const String routeName = "/setting/operation";
@override
State<OperationSettingScreen> createState() => _OperationSettingScreenState();
}
class _OperationSettingScreenState extends State<OperationSettingScreen>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.operationSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "文章列表快捷操作"),
ItemBuilder.buildEntryItem(
context: context,
title: "向左短滑动",
tip: "标记为星标",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "向左长滑动",
tip: "分享文章",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "向右短滑动",
tip: "标记为已读",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "向右长滑动",
tip: "加入稍后读",
onTap: () {},
bottomRadius: true,
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "文章详情页快捷操作"),
ItemBuilder.buildEntryItem(
context: context,
title: "双击页面",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "触顶滑动",
description: "仅在视图选项为非上下滑动式时生效",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "触底滑动",
description: "仅在视图选项为非上下滑动式时生效",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "音量键",
tip: "切换文章",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "其他选项"),
ItemBuilder.buildRadioItem(
context: context,
title: "隐藏空的订阅源",
value: false,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: "仅在WiFi下加载图片",
description: "图片将以占位符显示,你可以点击以加载",
value: false,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: "标记为已读前确认",
bottomRadius: true,
value: false,
onTap: () {},
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/general_setting_screen.dart | import 'package:readar/Screens/Setting/entry_setting_screen.dart';
import 'package:readar/Screens/Setting/select_theme_screen.dart';
import 'package:readar/Utils/cache_util.dart';
import 'package:readar/Utils/itoast.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:tuple/tuple.dart';
import '../../Providers/global_provider.dart';
import '../../Providers/provider_manager.dart';
import '../../Utils/locale_util.dart';
import '../../Widgets/BottomSheet/bottom_sheet_builder.dart';
import '../../Widgets/BottomSheet/list_bottom_sheet.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class GeneralSettingScreen extends StatefulWidget {
const GeneralSettingScreen({super.key});
static const String routeName = "/setting/general";
@override
State<GeneralSettingScreen> createState() => _GeneralSettingScreenState();
}
class _GeneralSettingScreenState extends State<GeneralSettingScreen>
with TickerProviderStateMixin {
String _cacheSize = "";
List<Tuple2<String, Locale?>> _supportedLocaleTuples = [];
@override
void initState() {
super.initState();
filterLocale();
getCacheSize();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
}
void getCacheSize() {
CacheUtil.loadCache().then((value) {
setState(() {
_cacheSize = value;
});
});
}
void filterLocale() {
_supportedLocaleTuples = [];
List<Locale> locales = S.delegate.supportedLocales;
_supportedLocaleTuples.add(Tuple2(S.current.followSystem, null));
for (Locale locale in locales) {
dynamic tuple = LocaleUtil.getTuple(locale);
if (tuple != null) {
_supportedLocaleTuples.add(tuple);
}
}
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.generalSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
const SizedBox(height: 10),
Selector<GlobalProvider, Locale?>(
selector: (context, globalProvider) => globalProvider.locale,
builder: (context, locale, child) =>
ItemBuilder.buildEntryItem(
context: context,
title: S.current.language,
tip: LocaleUtil.getLabel(locale)!,
topRadius: true,
bottomRadius: true,
onTap: () {
filterLocale();
BottomSheetBuilder.showListBottomSheet(
context,
(context) => TileList.fromOptions(
_supportedLocaleTuples,
locale,
(item2) {
ProviderManager.globalProvider.locale = item2;
Navigator.pop(context);
},
context: context,
title: S.current.chooseLanguage,
onCloseTap: () => Navigator.pop(context),
),
);
},
),
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.themeSetting),
Selector<GlobalProvider, ActiveThemeMode>(
selector: (context, globalProvider) =>
globalProvider.themeMode,
builder: (context, themeMode, child) =>
ItemBuilder.buildEntryItem(
context: context,
title: S.current.themeMode,
tip: GlobalProvider.getThemeModeLabel(themeMode),
onTap: () {
BottomSheetBuilder.showListBottomSheet(
context,
(context) => TileList.fromOptions(
GlobalProvider.getSupportedThemeMode(),
themeMode,
(item2) {
ProviderManager.globalProvider.themeMode = item2;
Navigator.pop(context);
},
context: context,
title: S.current.chooseThemeMode,
onCloseTap: () => Navigator.pop(context),
),
);
},
),
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.selectTheme,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => const SelectThemeScreen()));
},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.sideBarEntriesSetting,
bottomRadius: true,
onTap: () {
setState(() {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const EntrySettingScreen()));
});
},
),
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.checkUpdates,
topRadius: true,
bottomRadius: true,
description: "${S.current.checkUpdatesTip}2023-04-15",
tip: "1.0.0",
onTap: () {
IToast.showTop(context,
text: S.current.checkUpdatesAlreadyLatest);
},
),
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.clearCache,
topRadius: true,
bottomRadius: true,
tip: _cacheSize,
onTap: () {
getTemporaryDirectory().then((tempDir) {
CacheUtil.delDir(tempDir).then((value) {
CacheUtil.loadCache().then((value) {
setState(() {
_cacheSize = value;
IToast.showTop(context,
text: S.current.clearCacheSuccess);
});
});
});
});
},
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/select_theme_screen.dart | import 'package:readar/Providers/provider_manager.dart';
import 'package:readar/Resources/theme_color_data.dart';
import 'package:readar/Utils/hive_util.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class SelectThemeScreen extends StatefulWidget {
const SelectThemeScreen({super.key});
static const String routeName = "/setting/theme";
@override
State<SelectThemeScreen> createState() => _SelectThemeScreenState();
}
class _SelectThemeScreenState extends State<SelectThemeScreen>
with TickerProviderStateMixin {
int _selectedLightIndex = HiveUtil.getLightThemeIndex();
int _selectedDarkIndex = HiveUtil.getDarkThemeIndex();
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.selectTheme, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.lightTheme),
ItemBuilder.buildContainerItem(
context: context,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: IntrinsicHeight(
child: Row(
children: _buildLightThemeList(),
),
),
),
),
bottomRadius: true,
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.darkTheme),
ItemBuilder.buildContainerItem(
context: context,
child: Container(
margin: const EdgeInsets.symmetric(vertical: 10),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: IntrinsicHeight(
child: Row(
children: _buildDarkThemeList(),
),
),
),
),
bottomRadius: true,
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
List<Widget> _buildLightThemeList() {
var list = List<Widget>.generate(
ThemeColorData.defaultLightThemes.length,
(index) => ItemBuilder.buildThemeItem(
index: index,
groupIndex: _selectedLightIndex,
themeColorData: ThemeColorData.defaultLightThemes[index],
context: context,
onChanged: (index) {
setState(() {
_selectedLightIndex = index ?? 0;
ProviderManager.globalProvider.setLightTheme(index ?? 0);
});
}),
);
// list.add(ItemBuilder.buildEmptyThemeItem(context: context, onTap: null));
return list;
}
List<Widget> _buildDarkThemeList() {
var list = List<Widget>.generate(
ThemeColorData.defaultDarkThemes.length,
(index) => ItemBuilder.buildThemeItem(
index: index,
groupIndex: _selectedDarkIndex,
themeColorData: ThemeColorData.defaultDarkThemes[index],
context: context,
onChanged: (index) {
setState(() {
_selectedDarkIndex = index ?? 0;
ProviderManager.globalProvider.setDarkTheme(index ?? 0);
});
}),
);
// list.add(ItemBuilder.buildEmptyThemeItem(context: context, onTap: null));
return list;
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/service_setting_screen.dart | import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
class ServiceSettingScreen extends StatefulWidget {
const ServiceSettingScreen({super.key});
static const String routeName = "/setting/service";
@override
State<ServiceSettingScreen> createState() => _ServiceSettingScreenState();
}
class _ServiceSettingScreenState extends State<ServiceSettingScreen>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.serviceSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "第三方RSS服务"),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Inoreader",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "FeedHQ",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Feedbin",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Feed Wrangler",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "The Old Reader",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "BazQux Reader",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "NewsBlur",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "自建RSS服务"),
ItemBuilder.buildEntryItem(
context: context,
title: "Fever API",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "FreshRSS API",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "Google Reader API",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "Miniflux",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "Nextcloud News API",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: "建议新的RSS服务",
description: "向我们建议你希望支持的RSS服务",
topRadius: true,
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/backup_service_setting_screen.dart | import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/material.dart';
import '../../Utils/uri_util.dart';
import '../../Widgets/Item/item_builder.dart';
class BackupServiceSettingScreen extends StatefulWidget {
const BackupServiceSettingScreen({super.key});
static const String routeName = "/setting/backup/service";
@override
State<BackupServiceSettingScreen> createState() =>
_BackupServiceSettingScreenState();
}
class _BackupServiceSettingScreenState extends State<BackupServiceSettingScreen>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar:
ItemBuilder.buildSimpleAppBar(title: "选择备份服务", context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
children: [
const SizedBox(height: 10),
ItemBuilder.buildEntryItem(
context: context,
title: "云端备份服务使用指南",
topRadius: true,
bottomRadius: true,
leading: Icons.info,
showLeading: true,
showTrailing: false,
onTap: () {
UriUtil.launchUrlUri(
"https://rssreader.cloudchewie.com/help/cloudBackup");
},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context,
title:
"以下服务可用于备份软件配置、订阅源、星标、稍后再读、阅读历史、集锦等内容,其中星标、稍后再读、阅读历史不会备份文章正文;当你设置云盘备份服务后,也可以选择将文章以PDF/EPUB/MOBI格式导出到云盘"),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Dropbox",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "Google Drive",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "OneDrive",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
value: false,
title: "坚果云",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "其他WebDAV服务",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/backup_setting_screen.dart | import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
import 'backup_service_setting_screen.dart';
class BackupSettingScreen extends StatefulWidget {
const BackupSettingScreen({super.key});
static const String routeName = "/setting/backup";
@override
State<BackupSettingScreen> createState() => _BackupSettingScreenState();
}
class _BackupSettingScreenState extends State<BackupSettingScreen>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.backupSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
children: [
// const SizedBox(height: 10),
// ItemBuilder.buildCaptionItem(
// context: context,
// leading: Icons.info_outline_rounded,
// showLeading: true,
// title: "备份内容包括:软件配置、订阅源、星标、稍后再读、阅读历史、集锦",
// bottomRadius: true,
// ),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "云端备份设置"),
ItemBuilder.buildRadioItem(
context: context,
title: "启用云端备份",
value: true,
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "选择备份服务",
description: "已选择:Dropbox",
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const BackupServiceSettingScreen()));
},
),
ItemBuilder.buildEntryItem(
context: context,
title: "立即备份到云端",
description: "上次备份时间:2023-11-11 20:10:09",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "从云端拉取备份",
description: "上次拉取时间:2023-11-11 20:10:09",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "云端自动备份设置"),
ItemBuilder.buildRadioItem(
context: context,
title: "启用自动备份",
value: true,
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "自动备份时机",
description: "已选择:软件配置更改后、订阅源更改后、插件设置更改后",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "备份份数阈值",
tip: "20份",
description: "已有备份份数超过该阈值后,新备份将自动覆盖旧备份;当设置为1份时,即表示仅保留最新备份",
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "本地备份"),
ItemBuilder.buildEntryItem(
context: context,
title: "设置备份路径",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "备份到本地",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: "从本地导入备份",
bottomRadius: true,
onTap: () {},
),
// ItemBuilder.buildEntryItem(
// context: context,
// title: "导出订阅源为OPML文件",
// onTap: () {},
// ),
// ItemBuilder.buildEntryItem(
// context: context,
// title: "从OPML文件导入订阅源",
// bottomRadius: true,
// onTap: () {},
// ),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "其他选项"),
ItemBuilder.buildEntryItem(
context: context,
title: "设置备份密码",
description:
"本地密码用来对备份中的敏感信息(如服务的密码)加密和解密,如需在不同设备间同步,本地密码需一致",
onTap: () {},
showTrailing: false,
),
ItemBuilder.buildEntryItem(
context: context,
title: "恢复忽略列表",
description: "当从本地或云端恢复备份时不恢复的内容",
onTap: () {},
showTrailing: false,
bottomRadius: true,
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/global_setting_screen.dart | import 'package:readar/Providers/global_provider.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:readar/Widgets/Item/item_builder.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../generated/l10n.dart';
class GlobalSettingScreen extends StatefulWidget {
const GlobalSettingScreen({super.key});
static const String routeName = "/setting/global";
@override
State<GlobalSettingScreen> createState() => _GlobalSettingScreenState();
}
class _GlobalSettingScreenState extends State<GlobalSettingScreen>
with TickerProviderStateMixin {
@override
initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer<GlobalProvider>(builder: (context, globalProvider, child) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.globalSetting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
padding: EdgeInsets.zero,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context,
bottomRadius: true,
title: "以下为针对所有订阅源的全局设置。你可以通过修改某个具体订阅源的局部设置,来覆盖全局设置",
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "拉取文章"),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.pullStrategy,
tip: "仅在充电且使用WiFi时",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.cacheImageWhenPull,
tip: "仅在充电且使用WiFi时",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.cacheWebPageWhenPull,
tip: "仅在充电且使用WiFi时",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.cacheWebPageWhenReading,
tip: "仅在充电且使用WiFi时",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.removeDuplicateArticles,
value: true,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.pullWhenStartUp,
value: true,
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(context: context, title: "文章列表"),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.articleListLayoutType,
tip: "卡片",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.autoReadWhenScrolling,
value: true,
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "文章详情页布局"),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.articleDetailLayoutType,
tip: "左右滑动",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.articleDetailHeaderImageViewType,
tip: "全文图片轮播",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.articleDetailVideoViewType,
tip: "截取图片",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.articleDetailShowRelatedArticles,
value: true,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: S.current.articleDetailShowImageAlt,
value: true,
bottomRadius: true,
onTap: () {},
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: "文章详情页功能"),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.crawlType,
tip: "抓取全文",
onTap: () {},
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.mobilizerType,
tip: "Feedbin Parser",
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: "启用自动翻译",
value: true,
onTap: () {},
),
ItemBuilder.buildRadioItem(
context: context,
title: "启用AI摘要",
value: true,
onTap: () {},
bottomRadius: true,
),
const SizedBox(height: 10),
],
),
),
),
),
);
});
}
}
| 0 |
mirrored_repositories/Readar/lib/Screens | mirrored_repositories/Readar/lib/Screens/Setting/setting_screen.dart | import 'package:readar/Screens/Setting/service_setting_screen.dart';
import 'package:readar/Widgets/Custom/no_shadow_scroll_behavior.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../Utils/uri_util.dart';
import '../../Widgets/Item/item_builder.dart';
import '../../generated/l10n.dart';
import 'about_setting_screen.dart';
import 'backup_setting_screen.dart';
import 'experiment_setting_screen.dart';
import 'extension_setting_screen.dart';
import 'general_setting_screen.dart';
import 'global_setting_screen.dart';
import 'operation_setting_screen.dart';
class SettingScreen extends StatefulWidget {
const SettingScreen({super.key});
static const String routeName = "/setting";
@override
State<SettingScreen> createState() => _SettingScreenState();
}
class _SettingScreenState extends State<SettingScreen>
with TickerProviderStateMixin {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.transparent,
child: Scaffold(
appBar: ItemBuilder.buildSimpleAppBar(
title: S.current.setting, context: context),
body: Container(
margin: const EdgeInsets.symmetric(horizontal: 10),
child: ScrollConfiguration(
behavior: NoShadowScrollBehavior(),
child: ListView(
physics: const BouncingScrollPhysics(),
shrinkWrap: true,
children: [
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.basicSetting),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.generalSetting,
showLeading: true,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const GeneralSettingScreen()));
},
leading: Icons.settings_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
showLeading: true,
title: S.current.globalSetting,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => const GlobalSettingScreen()));
},
leading: Icons.settings_applications_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.operationSetting,
showLeading: true,
bottomRadius: true,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const OperationSettingScreen()));
},
leading: Icons.touch_app_outlined,
),
const SizedBox(height: 10),
ItemBuilder.buildCaptionItem(
context: context, title: S.current.advancedSetting),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.serviceSetting,
showLeading: true,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const ServiceSettingScreen()));
},
leading: Icons.business_center_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.backupSetting,
showLeading: true,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => const BackupSettingScreen()));
},
leading: Icons.backup_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
title: S.current.extensionSetting,
showLeading: true,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const ExtensionSettingScreen()));
},
leading: Icons.extension_outlined,
),
ItemBuilder.buildEntryItem(
context: context,
showLeading: true,
title: S.current.experimentSetting,
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) =>
const ExperimentSettingScreen()));
},
bottomRadius: true,
leading: Icons.outlined_flag_rounded,
),
const SizedBox(height: 10),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Animation/animated_slide.dart | import 'package:flutter/material.dart';
class AnimatedSlide extends AnimatedWidget {
const AnimatedSlide({
super.key,
required this.child,
required this.animation,
}) : super(listenable: animation);
final Animation<double> animation;
final Widget child;
@override
Widget build(BuildContext context) {
final slideWidth = MediaQuery.of(context).size.width * 0.3;
return Transform.translate(
offset: Offset(slideWidth * (1 - animation.value), 0),
child: child,
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Animation/animated_fade.dart | import 'package:flutter/material.dart';
class AnimatedFade extends AnimatedWidget {
const AnimatedFade({
super.key,
required this.child,
required this.animation,
}) : super(listenable: animation);
final Animation<double> animation;
final Widget child;
@override
Widget build(BuildContext context) {
final opacity = animation.value;
return IgnorePointer(
ignoring: opacity < 1,
child: Opacity(
opacity: opacity,
child: child,
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Animation/animated_overlay.dart | import 'package:flutter/material.dart';
class AnimatedOverlay extends AnimatedWidget {
final Color color;
final Widget? child;
final void Function()? onPress;
const AnimatedOverlay({
super.key,
required Animation animation,
required this.color,
this.child,
this.onPress,
}) : super(listenable: animation);
Animation<double> get animation => listenable as Animation<double>;
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
children: [
IgnorePointer(
ignoring: animation.value == 0,
child: InkWell(
onTap: onPress,
child: Container(
color: color.withOpacity(animation.value * 0.5),
),
),
),
if (child != null) child!,
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Wave/wave_widget.dart | import 'dart:async';
import 'dart:math';
import 'package:flutter/widgets.dart';
import 'config.dart';
import 'wave_controller.dart';
class WaveWidget extends StatefulWidget {
final Config config;
final Size size;
final double waveAmplitude;
final double wavePhase;
final double waveFrequency;
final double heightPercentage;
final int? duration;
final Color? backgroundColor;
final DecorationImage? backgroundImage;
final bool isLoop;
final WaveController controller;
const WaveWidget({
super.key,
required this.config,
required this.size,
this.waveAmplitude = 20.0,
this.wavePhase = 10.0,
this.waveFrequency = 1.6,
this.heightPercentage = 0.2,
this.duration = 6000,
this.backgroundColor,
this.backgroundImage,
this.isLoop = true,
required this.controller,
});
@override
State<StatefulWidget> createState() => _WaveWidgetState();
}
class _WaveWidgetState extends State<WaveWidget> with TickerProviderStateMixin {
late List<AnimationController> _waveControllers;
late List<Animation<double>> _wavePhaseValues;
final List<double> _waveAmplitudes = [];
Map<Animation<double>, AnimationController>? valueList;
Timer? _endAnimationTimer;
_initAnimations() {
if (widget.config.colorMode == ColorMode.custom) {
_waveControllers =
(widget.config as CustomConfig).durations!.map((duration) {
_waveAmplitudes.add(widget.waveAmplitude + 10);
return AnimationController(
vsync: this, duration: Duration(milliseconds: duration));
}).toList();
_wavePhaseValues = _waveControllers.map((controller) {
CurvedAnimation curve =
CurvedAnimation(parent: controller, curve: Curves.easeInOut);
Animation<double> value = Tween(
begin: widget.wavePhase,
end: 360 + widget.wavePhase,
).animate(
curve,
);
value.addStatusListener((status) {
switch (status) {
case AnimationStatus.completed:
controller.reverse();
break;
case AnimationStatus.dismissed:
controller.forward();
break;
default:
break;
}
});
controller.forward();
return value;
}).toList();
// If isLoop is false, stop the animation after the specified duration.
if (!widget.isLoop) {
_endAnimationTimer =
Timer(Duration(milliseconds: widget.duration!), () {
for (AnimationController waveController in _waveControllers) {
waveController.stop();
}
});
}
}
widget.controller.addListener(() {
if (widget.controller.isPlaying) {
for (AnimationController animationController in _waveControllers) {
animationController.forward();
}
} else {
for (AnimationController animationController in _waveControllers) {
animationController.stop();
}
}
});
for (AnimationController animationController in _waveControllers) {
animationController.stop();
}
}
_buildPaints() {
List<Widget> paints = [];
if (widget.config.colorMode == ColorMode.custom) {
List<Color>? colors = (widget.config as CustomConfig).colors;
List<List<Color>>? gradients = (widget.config as CustomConfig).gradients;
Alignment? begin = (widget.config as CustomConfig).gradientBegin;
Alignment? end = (widget.config as CustomConfig).gradientEnd;
for (int i = 0; i < _wavePhaseValues.length; i++) {
paints.add(
CustomPaint(
painter: _CustomWavePainter(
color: colors == null ? null : colors[i],
gradient: gradients == null ? null : gradients[i],
gradientBegin: begin,
gradientEnd: end,
heightPercentage:
(widget.config as CustomConfig).heightPercentages![i],
repaint: _waveControllers[i],
waveFrequency: widget.waveFrequency,
wavePhaseValue: _wavePhaseValues[i],
waveAmplitude: _waveAmplitudes[i],
blur: (widget.config as CustomConfig).blur,
),
size: widget.size,
),
);
}
}
return paints;
}
_disposeAnimations() {
for (var controller in _waveControllers) {
controller.dispose();
}
}
@override
void initState() {
super.initState();
_initAnimations();
}
@override
void dispose() {
_disposeAnimations();
_endAnimationTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: widget.backgroundColor,
image: widget.backgroundImage,
),
child: Stack(
children: _buildPaints(),
),
);
}
}
/// Meta data of layer
class Layer {
final Color? color;
final List<Color>? gradient;
final MaskFilter? blur;
final Path? path;
final double? amplitude;
final double? phase;
Layer({
this.color,
this.gradient,
this.blur,
this.path,
this.amplitude,
this.phase,
});
}
class _CustomWavePainter extends CustomPainter {
final ColorMode? colorMode;
final Color? color;
final List<Color>? gradient;
final Alignment? gradientBegin;
final Alignment? gradientEnd;
final MaskFilter? blur;
double? waveAmplitude;
Animation<double>? wavePhaseValue;
double? waveFrequency;
double? heightPercentage;
double _tempA = 0.0;
double _tempB = 0.0;
double viewWidth = 0.0;
final Paint _paint = Paint();
_CustomWavePainter({
// ignore: unused_element
this.colorMode,
this.color,
this.gradient,
this.gradientBegin,
this.gradientEnd,
this.blur,
this.heightPercentage,
this.waveFrequency,
this.wavePhaseValue,
this.waveAmplitude,
super.repaint,
});
_setPaths(double viewCenterY, Size size, Canvas canvas) {
Layer layer = Layer(
path: Path(),
color: color,
gradient: gradient,
blur: blur,
amplitude: (-1.6 + 0.8) * waveAmplitude!,
phase: wavePhaseValue!.value * 2 + 30,
);
layer.path!.reset();
layer.path!.moveTo(
0.0,
viewCenterY +
layer.amplitude! * _getSinY(layer.phase!, waveFrequency!, -1));
for (int i = 1; i < size.width + 1; i++) {
layer.path!.lineTo(
i.toDouble(),
viewCenterY +
layer.amplitude! * _getSinY(layer.phase!, waveFrequency!, i));
}
layer.path!.lineTo(size.width, size.height);
layer.path!.lineTo(0.0, size.height);
layer.path!.close();
if (layer.color != null) {
_paint.color = layer.color!;
}
if (layer.gradient != null) {
var rect = Offset.zero &
Size(size.width, size.height - viewCenterY * heightPercentage!);
_paint.shader = LinearGradient(
begin: gradientBegin == null
? Alignment.bottomCenter
: gradientBegin!,
end: gradientEnd == null ? Alignment.topCenter : gradientEnd!,
colors: layer.gradient!)
.createShader(rect);
}
if (layer.blur != null) {
_paint.maskFilter = layer.blur;
}
_paint.style = PaintingStyle.fill;
canvas.drawPath(layer.path!, _paint);
}
@override
void paint(Canvas canvas, Size size) {
double viewCenterY = size.height * (heightPercentage! + 0.1);
viewWidth = size.width;
_setPaths(viewCenterY, size, canvas);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return false;
}
double _getSinY(
double startradius, double waveFrequency, int currentposition) {
if (_tempA == 0) {
_tempA = pi / viewWidth;
}
if (_tempB == 0) {
_tempB = 2 * pi / 360.0;
}
return (sin(
_tempA * waveFrequency * (currentposition + 1) + startradius * _tempB));
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Wave/wave_controller.dart | import 'package:flutter/cupertino.dart';
class WaveController extends ChangeNotifier {
bool isPlaying = false;
void pause() {
isPlaying = false;
notifyListeners();
}
void start() {
isPlaying = true;
notifyListeners();
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Wave/config.dart | import 'package:flutter/widgets.dart';
enum ColorMode {
/// Waves with *single* **color** but different **alpha** and **amplitude**.
single,
/// Waves using *random* **color**, **alpha** and **amplitude**.
random,
/// Waves' colors must be set, and [colors]'s length must equal with [layers]
custom,
}
abstract class Config {
final ColorMode? colorMode;
Config({this.colorMode});
static void throwNullError(String colorModeStr, String configStr) {
throw FlutterError(
'When using `ColorMode.$colorModeStr`, `$configStr` must be set.');
}
}
class CustomConfig extends Config {
final List<Color>? colors;
final List<List<Color>>? gradients;
final Alignment? gradientBegin;
final Alignment? gradientEnd;
final List<int>? durations;
final List<double>? heightPercentages;
final MaskFilter? blur;
CustomConfig({
this.colors,
this.gradients,
this.gradientBegin,
this.gradientEnd,
required this.durations,
required this.heightPercentages,
this.blur,
}) : assert(() {
if (colors == null && gradients == null) {
Config.throwNullError('custom', 'colors` or `gradients');
}
return true;
}()),
assert(() {
if (gradients == null &&
(gradientBegin != null || gradientEnd != null)) {
throw FlutterError(
'You set a gradient direction but forgot setting `gradients`.');
}
return true;
}()),
assert(() {
if (durations == null) {
Config.throwNullError('custom', 'durations');
}
return true;
}()),
assert(() {
if (heightPercentages == null) {
Config.throwNullError('custom', 'heightPercentages');
}
return true;
}()),
assert(() {
if (colors != null &&
durations != null &&
heightPercentages != null) {
if (colors.length != durations.length ||
colors.length != heightPercentages.length) {
throw FlutterError(
'Length of `colors`, `durations` and `heightPercentages` must be equal.');
}
}
return true;
}()),
assert(colors == null || gradients == null,
'Cannot provide both colors and gradients.'),
super(colorMode: ColorMode.custom);
}
class RandomConfig extends Config {
RandomConfig() : super(colorMode: ColorMode.random);
}
class SingleConfig extends Config {
SingleConfig() : super(colorMode: ColorMode.single);
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Wave/wave_container.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vector_math/vector_math.dart' as vector;
class WaveContainer extends StatelessWidget {
final double height;
final double width;
final int xOffset;
final int yOffset;
final Color color;
final EdgeInsetsGeometry margin;
final Duration duration;
const WaveContainer({
super.key,
required this.height,
required this.width,
required this.xOffset,
required this.yOffset,
required this.color,
required this.duration,
required this.margin,
});
@override
Widget build(BuildContext context) {
Size size = Size(MediaQuery.of(context).size.width, 200.0);
return Wave(
height: height,
width: width,
size: size,
yOffset: yOffset,
xOffset: xOffset,
color: color,
margin: margin,
duration: duration,
);
}
}
class Wave extends StatefulWidget {
final double height;
final double width;
final Size size;
final int xOffset;
final int yOffset;
final Color color;
final EdgeInsetsGeometry margin;
final Duration duration;
const Wave({
super.key,
required this.height,
required this.width,
required this.size,
required this.xOffset,
required this.yOffset,
required this.color,
required this.margin,
required this.duration,
});
@override
WaveState createState() => WaveState();
}
class WaveState extends State<Wave> with TickerProviderStateMixin {
late AnimationController animationController;
List<Offset> animList1 = [];
@override
void initState() {
super.initState();
animationController = AnimationController(
vsync: this,
duration: widget.duration,
);
animationController.addListener(() {
animList1.clear();
for (int i = -2 - widget.xOffset;
i <= widget.size.width.toInt() + 2;
i++) {
final dx = i.toDouble() + widget.xOffset;
final dy = sin((animationController.value * 360 - i) %
360 *
vector.degrees2Radians) *
20 +
50 +
widget.yOffset;
animList1.add(Offset(dx, dy));
}
});
animationController.repeat();
}
@override
void dispose() {
animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
margin: widget.margin,
child: AnimatedBuilder(
animation: CurvedAnimation(
parent: animationController,
curve: Curves.easeInOut,
),
builder: (context, child) => ClipPath(
clipper: WaveClipper(
animationController.value,
animList1,
),
child: Container(
height: widget.height,
color: widget.color,
),
),
),
);
}
}
class WaveClipper extends CustomClipper<Path> {
final double animation;
List<Offset> waveList1 = [];
WaveClipper(this.animation, this.waveList1);
@override
Path getClip(Size size) {
Path path = Path();
path.addPolygon(waveList1, false);
path.lineTo(size.width, size.height);
path.lineTo(0.0, size.height);
path.close();
return path;
}
@override
bool shouldReclip(WaveClipper oldClipper) =>
animation != oldClipper.animation;
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Layout/circular_layout.dart | import 'dart:math';
import 'package:flutter/material.dart';
class CircularLayout extends StatelessWidget {
final List<Widget> children;
/// Initial angle
final double initAngle;
/// Arrangement direction
final bool reverse;
/// Scale the distance from the center of the subcomponent's circle to the center of the container's circle
final double radiusRatio;
/// The angle size of the container, 1 represents a circle
final double angleRatio;
/// Custom coordinates
final Offset center;
/// A Layout that makes sub-components present a circular layout
///
/// * [reverse] Used to control the arrangement direction of sub-components. False means clockwise arrangement. True means counterclockwise arrangement.
///
/// * [initAngle] Used to set the position of the first sub-component between 0 ~ 360
///
/// * [radiusRatio] Used to adjust the distance between the center of the subcomponent and the center of the container.
///
const CircularLayout({
super.key,
required this.children,
this.reverse = false,
this.radiusRatio = 1.0,
this.initAngle = 0,
this.angleRatio = 1.0,
this.center = const Offset(0, 0),
}) : assert(0.0 <= radiusRatio && radiusRatio <= 1.0),
assert(0.0 < angleRatio && angleRatio <= 1.0),
assert(0 <= initAngle && initAngle <= 360);
@override
Widget build(BuildContext context) {
return CustomMultiChildLayout(
delegate: _RingDelegate(
count: children.length,
initAngle: initAngle,
reverse: reverse,
center: center,
radiusRatio: radiusRatio,
angleRatio: angleRatio),
children: [
for (int i = 0; i < children.length; i++)
LayoutId(id: i, child: children[i])
],
);
}
}
class _RingDelegate extends MultiChildLayoutDelegate {
final double initAngle;
final bool reverse;
final int count;
final double radiusRatio;
final double angleRatio;
final Offset center;
_RingDelegate({
required this.initAngle,
required this.reverse,
required this.count,
required this.center,
required this.radiusRatio,
required this.angleRatio,
});
@override
void performLayout(Size size) {
/// Center point coordinates
Offset centralPoint = Offset(size.width / 2, size.height / 2 + 43);
// Offset centralPoint = center;
/// Container radius reference value
double fatherRadius = min(size.width, size.height) / 2;
double childRadius = _getChildRadius(fatherRadius, 360 / count);
Size constraintsSize = Size(childRadius * 2, childRadius * 2);
/// Traverse the children to get the space they need, and get the width of the widest child and the height of the tallest child.
/// Used to calculate an available radius r
/// r = radius given by the parent container - the "radius" of the largest child component
List<Size> sizeCache = [];
double largersRadius = 0;
for (int i = 0; i < count; i++) {
if (!hasChild(i)) break;
Size childSize = layoutChild(i, BoxConstraints.loose(constraintsSize));
sizeCache.add(Size.copy(childSize));
double radius = max(childSize.width, childSize.height) / 2;
largersRadius = radius > largersRadius ? radius : largersRadius;
}
fatherRadius -= largersRadius;
/// Place components
for (int i = 0; i < count; i++) {
if (!hasChild(i)) break;
Offset offset = _getChildCenterOffset(
centerPoint: centralPoint,
radius: fatherRadius * radiusRatio,
which: i,
count: count,
initAngle: initAngle,
angleRatio: angleRatio,
direction: reverse ? -1 : 1);
// Since the drawing direction is lt-rb, in order to avoid drawing beyond the boundaries of the parent container, the "radius" of the child control itself needs to be removed.
double cr = max(sizeCache[i].width, sizeCache[i].height) / 2;
offset -= Offset(cr, cr);
positionChild(i, offset);
}
}
@override
bool shouldRelayout(covariant MultiChildLayoutDelegate oldDelegate) => true;
}
/// Get the offset of the center point of the subcomponent in the container
///
/// * [centerPoint] container center point
///
/// * [radius] container radius
///
/// * [which] which child
///
/// * [count] Total number of sub-components
///
/// * [initAngle] is used to determine the starting position, the recommended value range is 0-360
///
/// * [direction] is used to determine the arrangement direction: 1 clockwise, -1 counterclockwise
///
Offset _getChildCenterOffset({
required Offset centerPoint,
required double radius,
required int which,
required int count,
required double initAngle,
required int direction,
required double angleRatio,
}) {
/// Circle center coordinates (a, b)
/// Radius: r
/// Radian: radian (π / 180 * angle)
///
/// Find any point on the circle to be (x, y)
/// but
/// x = a + r * cos(radian)
/// y = b + r * sin(radian)
double radian = angleRatio == 1.0
? _radian(360 / count)
: _radian(360 * angleRatio / (count - 1));
double radianOffset =
_radian(360 * ((0.75 - angleRatio / 2)) + initAngle * direction);
double x = centerPoint.dx + radius * cos(radian * which + radianOffset);
double y = centerPoint.dy + radius * sin(radian * which + radianOffset);
if (count == 3 && which == 1) {
y += 20;
}
if (count == 5) {
switch (which) {
case 0:
x -= 10;
y -= 5;
break;
case 1:
case 2:
case 3:
break;
case 4:
x += 10;
y -= 5;
break;
}
}
return Offset(x, y);
}
/// Get the child radius. Calculated based on the formula of the largest circle within the sector radius
double _getChildRadius(double r, double a) {
/// It is greater than 180 because only one child is placed, and because the formula cannot calculate the obtuse angle, just return the radius of the container.
if (a > 180) return r;
/// The radius of the sector is R, the central angle is A, and the radius of the inscribed circle is r.
/// SIN(A/2)=r/(R-r)
/// r=(R-r)*SIN(A/2)
/// r=R*SIN(A/2)-r*SIN(A/2)
/// r+r*SIN(A/2)=R*SIN(A/2)
/// r=(R*SIN(A/2))/(1+SIN(A/2))
return (r * sin(_radian(a / 2))) / (1 + sin(_radian(a / 2)));
}
/// Convert angle to radian
double _radian(double angle) {
return pi / 180 * angle;
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Layout/marquee_layout.dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
class MarqueeWidget extends StatefulWidget {
/// Number of subviews
final int count;
/// Subview builder
final IndexedWidgetBuilder itemBuilder;
/// Carousel time interval
final int loopSeconds;
final bool autoPlay;
final PageController controller;
const MarqueeWidget({
super.key,
required this.count,
required this.itemBuilder,
this.loopSeconds = 5,
this.autoPlay = false,
required this.controller,
});
@override
MarqueeWidgetState createState() => MarqueeWidgetState();
void switchTo(int index) {}
}
class MarqueeWidgetState extends State<MarqueeWidget> {
late PageController _controller;
late Timer _timer;
@override
void initState() {
super.initState();
_controller = widget.controller;
_timer = Timer.periodic(Duration(seconds: widget.loopSeconds), (timer) {
if (widget.autoPlay) {
if (_controller.page != null) {
if (_controller.page!.round() >= widget.count) {
_controller.jumpToPage(0);
}
_controller.nextPage(
duration: const Duration(milliseconds: 300),
curve: Curves.linear);
}
}
});
}
@override
Widget build(BuildContext context) {
return PageView.builder(
physics: const NeverScrollableScrollPhysics(),
scrollDirection: Axis.vertical,
controller: _controller,
itemBuilder: (buildContext, index) {
if (index < widget.count) {
return widget.itemBuilder(buildContext, index);
} else {
return widget.itemBuilder(buildContext, 0);
}
},
itemCount: widget.count + 1,
);
}
@override
void dispose() {
super.dispose();
_timer.cancel();
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Layout/info_item_layout.dart | import 'package:flutter/material.dart';
const Duration _kExpand = Duration(milliseconds: 200);
class InfoItemLayout extends StatefulWidget {
const InfoItemLayout({
super.key,
this.backgroundColor = Colors.transparent,
required this.onExpansionChanged,
this.children = const <Widget>[],
this.title,
this.content,
required this.isExpanded,
});
final ValueChanged<bool> onExpansionChanged;
final List<Widget> children;
final Color backgroundColor;
final bool isExpanded;
final String? title;
final String? content;
@override
InfoItemLayoutState createState() => InfoItemLayoutState();
}
class InfoItemLayoutState extends State<InfoItemLayout>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late bool _isExpanded;
@override
void initState() {
super.initState();
_controller = AnimationController(duration: _kExpand, vsync: this);
_isExpanded = widget.isExpanded;
if (_isExpanded) _controller.value = 1.0;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _handleTap(String tag, bool newValue) {
setState(() {
_isExpanded = newValue;
if (_isExpanded) {
_controller.forward();
} else {
_controller.reverse().then<void>((void value) {
if (!mounted) return;
});
}
PageStorage.of(context).writeState(context, _isExpanded);
});
widget.onExpansionChanged(_isExpanded);
}
Widget _buildChildren(BuildContext context, Widget? child) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
decoration: BoxDecoration(
color: widget.backgroundColor,
borderRadius: BorderRadius.circular(8),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
InkWell(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: () {
_handleTap("dd", !_isExpanded);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
widget.title ?? "",
style: Theme.of(context).textTheme.titleMedium,
),
),
Transform.rotate(
angle: _controller.value * 1.55,
child: const Icon(
Icons.keyboard_arrow_right,
size: 20,
color: Colors.grey,
),
),
],
),
),
Container(
child: child,
),
],
),
);
}
Widget _content() {
return Container(
alignment: Alignment.topLeft,
margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
child: SelectableText(
widget.content ?? "",
style: Theme.of(context).textTheme.titleSmall,
),
);
}
@override
Widget build(BuildContext context) {
_handleTap("tag", _isExpanded);
final bool closed = !_isExpanded;
return AnimatedBuilder(
animation: _controller.view,
builder: _buildChildren,
child: closed ? null : Column(children: [_content()]),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Layout/expansion_layout.dart | import 'package:flutter/material.dart';
const Duration _kExpand = Duration(milliseconds: 200);
class ExpansionLayout extends StatefulWidget {
const ExpansionLayout({
super.key,
required this.backgroundColor,
required this.onExpansionChanged,
this.children = const <Widget>[],
this.title,
required this.isExpanded,
});
final ValueChanged<bool> onExpansionChanged;
final List<Widget> children;
final Color backgroundColor;
final bool isExpanded;
final String? title;
@override
ExpansionLayoutState createState() => ExpansionLayoutState();
}
class ExpansionLayoutState extends State<ExpansionLayout>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late bool _isExpanded;
@override
void initState() {
super.initState();
_controller = AnimationController(duration: _kExpand, vsync: this);
_isExpanded = widget.isExpanded;
if (_isExpanded) _controller.value = 1.0;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void _handleTap(String tag, bool newValue) {
setState(() {
_isExpanded = newValue;
if (_isExpanded) {
_controller.forward();
} else {
_controller.reverse().then<void>((void value) {
if (!mounted) return;
});
}
PageStorage.of(context).writeState(context, _isExpanded);
});
widget.onExpansionChanged(_isExpanded);
}
Widget _buildChildren(BuildContext context, Widget? child) {
return Container(
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: Theme.of(context).canvasColor,
borderRadius: BorderRadius.circular(8),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
InkWell(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: () {
_handleTap("dd", !_isExpanded);
},
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
widget.title ?? "",
style: Theme.of(context).textTheme.titleMedium,
),
),
Transform.rotate(
angle: _controller.value * 1.55,
child: const Icon(
Icons.keyboard_arrow_right,
size: 20,
color: Colors.grey,
),
),
],
),
),
Container(
child: child,
),
],
),
);
}
@override
Widget build(BuildContext context) {
_handleTap("tag", _isExpanded);
final bool closed = !_isExpanded;
return AnimatedBuilder(
animation: _controller.view,
builder: _buildChildren,
child: closed ? null : Column(children: widget.children),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Unlock/gesture_unlock_view.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'unlock_line_painter.dart';
import 'unlock_point.dart';
import 'unlock_point_painter.dart';
enum UnlockType { solid, hollow }
enum UnlockStatus { normal, success, failed, disable }
class GestureUnlockView extends StatefulWidget {
final double size;
final UnlockType type;
final double padding;
final double roundSpace;
final double roundSpaceRatio;
final Color defaultColor;
final Color selectedColor;
final Color failedColor;
final Color disableColor;
final double lineWidth;
final double solidRadiusRatio;
final double touchRadiusRatio;
final int delayTime;
final Function(List<int>, UnlockStatus) onCompleted;
const GestureUnlockView({
super.key,
required this.size,
this.type = UnlockType.solid,
this.padding = 10,
required this.roundSpace,
this.roundSpaceRatio = 0.6,
this.defaultColor = Colors.grey,
this.selectedColor = Colors.blue,
this.failedColor = Colors.red,
this.disableColor = Colors.grey,
this.lineWidth = 2,
this.solidRadiusRatio = 0.4,
this.touchRadiusRatio = 0.6,
this.delayTime = 500,
required this.onCompleted,
});
@override
State<StatefulWidget> createState() => GestureState();
static String selectedToString(List<int> rounds) {
var sb = StringBuffer();
for (int i = 0; i < rounds.length; i++) {
sb.write(rounds[i] + 1);
}
return sb.toString();
}
}
class GestureState extends State<GestureUnlockView> {
UnlockStatus _status = UnlockStatus.normal;
final List<UnlockPoint> points =
List.filled(9, UnlockPoint(x: 0, y: 0, position: 0));
final List<UnlockPoint> pathPoints = [];
late UnlockPoint curPoint = UnlockPoint(x: 0, y: 0, position: 0);
late double _radius;
late double _solidRadius;
late double _touchRadius;
late Timer _timer = Timer(Duration(milliseconds: widget.delayTime), () {
updateStatus(UnlockStatus.normal);
});
@override
void initState() {
super.initState();
_init();
}
@override
void deactivate() {
super.deactivate();
if (_timer.isActive == true) {
_timer.cancel();
}
}
void _init() {
var width = widget.size;
var roundSpace = widget.roundSpace;
if (roundSpace != null) {
_radius = (width - widget.padding * 2 - roundSpace * 2) / 3 / 2;
} else {
_radius =
(width - widget.padding * 2) / (3 + widget.roundSpaceRatio * 2) / 2;
roundSpace = _radius * 2 * widget.roundSpaceRatio;
}
_solidRadius = _radius * widget.solidRadiusRatio;
_touchRadius = _radius * widget.touchRadiusRatio;
for (int i = 0; i < points.length; i++) {
var row = i ~/ 3;
var column = i % 3;
var dx = widget.padding + column * (_radius * 2 + roundSpace) + _radius;
var dy = widget.padding + row * (_radius * 2 + roundSpace) + _radius;
points[i] = UnlockPoint(x: dx, y: dy, position: i);
}
}
@override
Widget build(BuildContext context) {
var enableTouch = _status == UnlockStatus.normal;
return Stack(
children: <Widget>[
CustomPaint(
size: Size(widget.size, widget.size),
painter: UnlockPointPainter(
type: widget.type,
points: points,
radius: _radius,
solidRadius: _solidRadius,
lineWidth: widget.lineWidth,
defaultColor: widget.defaultColor,
selectedColor: widget.selectedColor,
failedColor: widget.failedColor,
disableColor: widget.disableColor),
),
GestureDetector(
onPanDown: enableTouch ? _onPanDown : null,
onPanUpdate: enableTouch
? (DragUpdateDetails e) => _onPanUpdate(e, context)
: null,
onPanEnd:
enableTouch ? (DragEndDetails e) => _onPanEnd(e, context) : null,
child: CustomPaint(
size: Size(widget.size, widget.size),
painter: UnlockLinePainter(
pathPoints: pathPoints,
status: _status,
selectColor: widget.selectedColor,
failedColor: widget.failedColor,
lineWidth: widget.lineWidth,
curPoint: curPoint),
),
)
],
);
}
void updateStatus(UnlockStatus status) {
_status = status;
switch (status) {
case UnlockStatus.normal:
case UnlockStatus.disable:
_updateRoundStatus(status);
_clearAllData();
break;
case UnlockStatus.failed:
for (UnlockPoint round in points) {
if (round.status == UnlockStatus.success) {
round.status = UnlockStatus.failed;
}
}
_timer = Timer(Duration(milliseconds: widget.delayTime), () {
updateStatus(UnlockStatus.normal);
});
break;
case UnlockStatus.success:
_timer = Timer(Duration(milliseconds: widget.delayTime), () {
updateStatus(UnlockStatus.normal);
});
break;
}
setState(() {});
}
void _updateRoundStatus(UnlockStatus status) {
for (UnlockPoint round in points) {
round.status = status;
}
}
void _onPanDown(DragDownDetails e) {
_clearAllData();
// if (this.onPanDown != null) this.onPanDown();
}
void _onPanUpdate(DragUpdateDetails e, BuildContext context) {
RenderBox box = context.findRenderObject() as RenderBox;
if (box == null) return;
Offset offset = box.globalToLocal(e.globalPosition);
_slideDealt(offset);
setState(() {
curPoint = UnlockPoint(x: offset.dx, y: offset.dy, position: -1);
});
}
void _onPanEnd(DragEndDetails e, BuildContext context) {
if (pathPoints.isNotEmpty) {
setState(() {
curPoint = pathPoints[pathPoints.length - 1];
});
List<int> items = pathPoints.map((item) => item.position).toList();
widget.onCompleted(items, _status);
// if (this.immediatelyClear) this._clearAllData(); //clear data
}
}
///滑动处理
void _slideDealt(Offset offSet) {
// print("offset =$offSet");
int xPosition = -1;
int yPosition = -1;
for (int i = 0; i < 3; i++) {
if (xPosition == -1 &&
points[i].x + _radius + _touchRadius >= offSet.dx &&
offSet.dx >= points[i].x - _radius - _touchRadius) {
xPosition = i;
}
if (yPosition == -1 &&
points[i * 3].y + _radius + _touchRadius >= offSet.dy &&
offSet.dy >= points[i * 3].y - _radius - _touchRadius) {
yPosition = i;
}
}
if (xPosition == -1 || yPosition == -1) return;
int position = yPosition * 3 + xPosition;
if (points[position].status != UnlockStatus.success) {
points[position].status = UnlockStatus.success;
pathPoints.add(points[position]);
}
// for (int i = 0; i < points.length; i++) {
// var round = points[i];
// if (round.status == UnlockStatus.normal &&
// round.contains(offSet, _touchRadius)) {
// round.status = UnlockStatus.success;
// pathPoints.add(round);
// break;
// }
// }
}
_clearAllData() {
for (int i = 0; i < 9; i++) {
points[i].status = UnlockStatus.normal;
}
pathPoints.clear();
setState(() {});
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Unlock/gesture_unlock_indicator.dart | import 'package:readar/Widgets/Unlock/unlock_point.dart';
import 'package:flutter/material.dart';
import 'gesture_unlock_view.dart';
class GestureUnlockIndicator extends StatefulWidget {
///控件大小
final double size;
///圆之间的间距
final double roundSpace;
///圆之间的间距比例(以圆直径作为基准),[roundSpace]设置时无效
final double roundSpaceRatio;
///线宽度
final double strokeWidth;
///默认颜色
final Color defaultColor;
///选中颜色
final Color selectedColor;
final GestureUnlockIndicatorState _state = GestureUnlockIndicatorState();
GestureUnlockIndicator(
{super.key,
required this.size,
required this.roundSpace,
this.roundSpaceRatio = 0.5,
this.strokeWidth = 1,
this.defaultColor = Colors.grey,
this.selectedColor = Colors.blue});
void setSelectPoint(List<int> selected) {
_state.setSelectPoint(selected);
}
@override
GestureUnlockIndicatorState createState() {
return _state;
}
}
class GestureUnlockIndicatorState extends State<GestureUnlockIndicator> {
final List<UnlockPoint> _rounds =
List.filled(9, UnlockPoint(x: 0, y: 0, position: 0));
late double _radius;
@override
void initState() {
super.initState();
_init();
}
@override
Widget build(BuildContext context) {
return CustomPaint(
size: Size(widget.size, widget.size),
painter: LockPatternIndicatorPainter(
_rounds,
_radius,
widget.strokeWidth,
widget.defaultColor,
widget.selectedColor,
));
}
void setSelectPoint(List<int> selected) {
for (int i = 0; i < _rounds.length; i++) {
_rounds[i].status =
selected.contains(i) ? UnlockStatus.success : UnlockStatus.normal;
}
}
void _init() {
var width = widget.size;
var roundSpace = widget.roundSpace;
if (roundSpace != null) {
_radius = (width - roundSpace * 2) / 3 / 2;
} else {
_radius = width / (3 + widget.roundSpaceRatio * 2) / 2;
roundSpace = _radius * 2 * widget.roundSpaceRatio;
}
for (int i = 0; i < _rounds.length; i++) {
var row = i ~/ 3;
var column = i % 3;
var dx = column * (_radius * 2 + roundSpace) + _radius;
var dy = row * (_radius * 2 + roundSpace) + _radius;
_rounds[i] = UnlockPoint(x: dx, y: dy, position: i);
}
setState(() {});
}
}
class LockPatternIndicatorPainter extends CustomPainter {
final List<UnlockPoint> _rounds;
final double _radius;
final double _strokeWidth;
final Color _defaultColor;
final Color _selectedColor;
LockPatternIndicatorPainter(this._rounds, this._radius, this._strokeWidth,
this._defaultColor, this._selectedColor);
@override
void paint(Canvas canvas, Size size) {
if (_radius == null) return;
var paint = Paint();
paint.strokeWidth = _strokeWidth;
for (var round in _rounds) {
switch (round.status) {
case UnlockStatus.normal:
paint.style = PaintingStyle.fill;
paint.color = _defaultColor;
canvas.drawCircle(round.toOffset(), _radius, paint);
break;
case UnlockStatus.success:
paint.style = PaintingStyle.fill;
paint.color = _selectedColor;
canvas.drawCircle(round.toOffset(), _radius, paint);
break;
default:
break;
}
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Unlock/unlock_point.dart | import 'dart:math';
import 'package:flutter/material.dart';
import 'gesture_unlock_view.dart';
class UnlockPoint {
double x;
double y;
bool isSelect = false;
UnlockStatus status = UnlockStatus.normal;
int position;
UnlockPoint({required this.x, required this.y, required this.position});
Offset toOffset() {
return Offset(x, y);
}
bool contains(Offset offset, radius) {
return sqrt(pow(offset.dx - x, 2) + pow(offset.dy - y, 2)) < radius;
}
@override
String toString() {
return "($x,$y)";
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Unlock/unlock_line_painter.dart | import 'package:readar/Widgets/Unlock/unlock_point.dart';
import 'package:flutter/material.dart';
import 'gesture_unlock_view.dart';
class UnlockLinePainter extends CustomPainter {
final List<UnlockPoint> pathPoints;
final Color selectColor;
final Color failedColor;
final UnlockStatus status;
final double lineWidth;
final UnlockPoint curPoint;
UnlockLinePainter(
{required this.pathPoints,
required this.status,
required this.selectColor,
required this.failedColor,
required this.lineWidth,
required this.curPoint});
@override
void paint(Canvas canvas, Size size) {
int length = pathPoints.length;
if (length < 1) return;
final linePaint = Paint()
..isAntiAlias = true
..color = status == UnlockStatus.failed ? failedColor : selectColor
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeWidth = lineWidth;
for (int i = 0; i < length - 1; i++) {
canvas.drawLine(Offset(pathPoints[i].x, pathPoints[i].y),
Offset(pathPoints[i + 1].x, pathPoints[i + 1].y), linePaint);
}
double endX = curPoint.x;
double endY = curPoint.y;
if (endX < 0) {
endX = 0;
} else if (endX > size.width) {
endX = size.width;
}
if (endY < 0) {
endY = 0;
} else if (endY > size.height) {
endY = size.height;
}
canvas.drawLine(Offset(pathPoints[length - 1].x, pathPoints[length - 1].y),
Offset(endX, endY), linePaint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Unlock/unlock_point_painter.dart | import 'package:flutter/material.dart';
import 'gesture_unlock_view.dart';
import 'unlock_point.dart';
class UnlockPointPainter extends CustomPainter {
final UnlockType type;
final List<UnlockPoint> points;
final double radius;
final double solidRadius;
final double lineWidth;
final Color defaultColor;
final Color selectedColor;
final Color failedColor;
final Color disableColor;
UnlockPointPainter(
{required this.type,
required this.points,
required this.radius,
required this.solidRadius,
required this.lineWidth,
required this.defaultColor,
required this.selectedColor,
required this.failedColor,
required this.disableColor});
@override
void paint(Canvas canvas, Size size) {
var paint = Paint();
if (type == UnlockType.solid) {
///画圆
_paintPoint(canvas, paint);
} else {
_paintPointWithHollow(canvas, paint);
}
}
void _paintPointWithHollow(Canvas canvas, Paint paint) {
paint.strokeWidth = lineWidth;
for (UnlockPoint point in points) {
switch (point.status) {
case UnlockStatus.normal:
{
paint.color = defaultColor;
paint.style = PaintingStyle.stroke;
canvas.drawCircle(point.toOffset(), radius, paint);
break;
}
case UnlockStatus.success:
{
paint.style = PaintingStyle.fill;
paint.color = selectedColor;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
paint.style = PaintingStyle.stroke;
canvas.drawCircle(point.toOffset(), radius, paint);
break;
}
case UnlockStatus.failed:
{
paint.style = PaintingStyle.fill;
paint.color = failedColor;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
paint.style = PaintingStyle.stroke;
canvas.drawCircle(point.toOffset(), radius, paint);
break;
}
case UnlockStatus.disable:
{
paint.color = disableColor;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
break;
}
}
}
}
void _paintPoint(Canvas canvas, Paint paint) {
for (UnlockPoint point in points) {
switch (point.status) {
case UnlockStatus.normal:
{
paint.color = defaultColor;
paint.style = PaintingStyle.fill;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
break;
}
case UnlockStatus.success:
{
paint.color = selectedColor;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
paint.color = selectedColor.withAlpha(14);
canvas.drawCircle(point.toOffset(), radius, paint);
break;
}
case UnlockStatus.failed:
{
paint.color = failedColor;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
paint.color = failedColor.withAlpha(14);
canvas.drawCircle(point.toOffset(), radius, paint);
break;
}
case UnlockStatus.disable:
{
paint.color = disableColor;
canvas.drawCircle(point.toOffset(), solidRadius, paint);
break;
}
}
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) => true;
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Unlock/gesture_notifier.dart | enum GestureStatus {
create,
createFailed,
verify,
verifyFailed,
verifyFailedCountOverflow
}
class GestureNotifier {
GestureNotifier({
required this.status,
required this.gestureText,
});
GestureStatus status;
String gestureText;
void setStatus({required GestureStatus status, required String gestureText}) {
this.status = status;
this.gestureText = gestureText;
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/dismissible_background.dart | import 'package:flutter/cupertino.dart';
class DismissibleBackground extends StatelessWidget {
final IconData icon;
final bool isToRight;
const DismissibleBackground(this.icon, this.isToRight, {super.key});
@override
Widget build(BuildContext context) => Container(
color: CupertinoColors.systemGrey5.resolveFrom(context),
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment:
isToRight ? CrossAxisAlignment.start : CrossAxisAlignment.end,
children: [
Icon(
icon,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
)
],
),
);
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/time_text.dart | import 'dart:async';
import 'package:flutter/cupertino.dart';
class TimeText extends StatefulWidget {
final DateTime date;
final TextStyle style;
const TimeText(this.date, {required this.style, super.key});
@override
TimeTextState createState() => TimeTextState();
}
class TimeTextState extends State<TimeText> {
Timer? _timer;
Duration? _duration;
int diffMinutes() {
final now = DateTime.now();
return now.difference(widget.date).inMinutes;
}
@override
void initState() {
super.initState();
updateTimer();
}
void updateTimer() {
final diff = diffMinutes();
Duration duration;
if (diff < 60) {
duration = const Duration(minutes: 1);
} else if (diff < 60 * 24) {
duration = Duration(minutes: 60 - diff % 60);
} else {
duration = Duration(minutes: (60 * 24) - diff % (60 * 24));
}
if (_duration == null || duration.compareTo(_duration!) != 0) {
_duration = duration;
var timer = _timer;
if (timer != null) timer.cancel();
timer = Timer.periodic(duration, (_) {
if (mounted) setState(() {});
updateTimer();
});
}
}
@override
void dispose() {
final timer = _timer;
if (timer != null) timer.cancel();
super.dispose();
}
@override
void didUpdateWidget(covariant TimeText oldWidget) {
if (oldWidget.date.compareTo(widget.date) != 0) updateTimer();
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
final diff = diffMinutes();
String label;
if (diff < 60) {
label = "${diff}m";
} else if (diff < 60 * 24) {
label = "${diff ~/ 60}h";
} else {
label = "${diff ~/ (60 * 24)}d";
}
return Text(label, style: widget.style);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/favicon.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import '../../Models/feed.dart';
class Favicon extends StatelessWidget {
final Feed source;
final double size;
const Favicon(this.source, {this.size = 16, super.key});
@override
Widget build(BuildContext context) {
final textStyle = TextStyle(
fontSize: size - 5,
color: CupertinoColors.systemGrey6,
);
if (source.iconUrl != null && source.iconUrl!.isNotEmpty) {
return CachedNetworkImage(
imageUrl: source.iconUrl ?? "",
width: size,
height: size,
);
} else {
return Container(
width: size,
height: size,
color: CupertinoColors.systemGrey.resolveFrom(context),
child: Center(
child: Text(
source.name.isNotEmpty ? source.name[0] : "?",
style: textStyle,
),
),
);
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/toolbar.dart | /*
* cupertino_toolbar
* Copyright (c) 2019 Christian Mengler. All rights reserved.
* See LICENSE for distribution and usage details.
*/
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Display a persistent bottom iOS styled toolbar for Cupertino theme
///
class CupertinoToolbar extends StatelessWidget {
/// Creates a persistent bottom iOS styled toolbar for Cupertino
/// themed app,
///
/// Typically used as the [child] attribute of a [CupertinoPageScaffold].
///
/// {@tool sample}
///
/// A sample code implementing a typical iOS page with bottom toolbar.
///
/// ```dart
/// CupertinoPageScaffold(
/// navigationBar: CupertinoNavigationBar(
/// middle: Text('Cupertino Toolbar')
/// ),
/// child: CupertinoToolbar(
/// items: <CupertinoToolbarItem>[
/// CupertinoToolbarItem(
/// icon: CupertinoIcons.delete,
/// onPressed: () {}
/// ),
/// CupertinoToolbarItem(
/// icon: CupertinoIcons.settings,
/// onPressed: () {}
/// )
/// ],
/// body: Center(
/// child: Text('Hello World')
/// )
/// )
/// )
/// ```
/// {@end-tool}
///
const CupertinoToolbar({super.key, required this.items, required this.body});
/// The interactive items laid out within the toolbar where each item has an icon.
final List<CupertinoToolbarItem> items;
/// The body displayed above the toolbar.
final Widget body;
@override
Widget build(BuildContext context) {
return Column(children: <Widget>[
Expanded(child: body),
Container(
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Theme.of(context).dividerColor, width: 0.0))),
child: SafeArea(
top: false,
child: SizedBox(
height: 44.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: _createButtons()))))
]);
}
List<Widget> _createButtons() {
final List<Widget> children = <Widget>[];
for (int i = 0; i < items.length; i += 1) {
children.add(CupertinoButton(
padding: EdgeInsets.zero,
child: Icon(
items[i].icon,
// color: CupertinoColors.systemBlue,
semanticLabel: items[i].semanticLabel,
),
onPressed: items[i].onPressed));
}
return children;
}
}
/// An interactive button within iOS themed [CupertinoToolbar]
class CupertinoToolbarItem {
/// Creates an item that is used with [CupertinoToolbar.items].
///
/// The argument [icon] should not be null.
const CupertinoToolbarItem(
{required this.icon,
required this.onPressed,
required this.semanticLabel});
/// The icon of the item.
///
/// This attribute must not be null.
final IconData icon;
/// The callback that is called when the item is tapped.
///
/// This attribute must not be null.
final VoidCallback onPressed;
/// Semantic label for the icon.
///
/// Announced in accessibility modes (e.g TalkBack/VoiceOver).
/// This label does not show in the UI.
final String semanticLabel;
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/item_builder.dart | import 'package:readar/Resources/gaps.dart';
import 'package:readar/Resources/theme_color_data.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../Scaffold/my_appbar.dart';
class ItemBuilder {
static PreferredSizeWidget buildSimpleAppBar({
String title = "",
Key? key,
IconData leading = Icons.arrow_back_rounded,
List<Widget>? actions,
required BuildContext context,
}) {
return MyAppBar(
key: key,
leading: Container(
margin: const EdgeInsets.only(left: 8),
child: buildIconButton(
context: context,
icon: Icon(leading, color: Theme.of(context).iconTheme.color),
onTap: () {
Navigator.pop(context);
},
),
),
title: title.isNotEmpty
? Container(
margin: const EdgeInsets.only(left: 5),
child:
Text(title, style: Theme.of(context).textTheme.titleMedium),
)
: Container(),
actions: actions,
);
}
static PreferredSizeWidget buildAppBar({
Widget? title,
Key? key,
IconData leading = Icons.arrow_back_rounded,
Function()? onLeadingTap,
List<Widget>? actions,
required BuildContext context,
}) {
return MyAppBar(
key: key,
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
elevation: 0,
scrolledUnderElevation: 0,
leading: Container(
margin: const EdgeInsets.only(left: 8),
child: buildIconButton(
context: context,
icon: Icon(leading, color: Theme.of(context).iconTheme.color),
onTap: onLeadingTap,
),
),
title: title,
actions: actions,
);
}
static Widget buildIconButton({
required BuildContext context,
required Icon icon,
required Function()? onTap,
}) {
return Material(
color: Colors.transparent,
shape: const CircleBorder(),
clipBehavior: Clip.hardEdge,
child: Ink(
child: InkWell(
onTap: onTap,
child: Container(
padding: const EdgeInsets.all(8),
child: icon,
),
),
),
);
}
static Widget buildRadioItem({
double radius = 10,
bool topRadius = false,
bool bottomRadius = false,
required bool value,
Color? titleColor,
bool showLeading = false,
IconData leading = Icons.check_box_outline_blank,
required String title,
String description = "",
Function()? onTap,
double trailingLeftMargin = 5,
double padding = 15,
required BuildContext context,
}) {
assert(padding > 5);
return Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: topRadius ? Radius.circular(radius) : const Radius.circular(0),
bottom:
bottomRadius ? Radius.circular(radius) : const Radius.circular(0),
),
),
child: Ink(
decoration: BoxDecoration(
color: Theme.of(context).canvasColor,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.vertical(
top: topRadius ? Radius.circular(radius) : const Radius.circular(0),
bottom: bottomRadius
? Radius.circular(radius)
: const Radius.circular(0),
),
border: ThemeColorData.isImmersive(context)
? Border.merge(
Border.symmetric(
vertical: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
),
),
Border(
top: topRadius
? BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
)
: BorderSide.none,
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
),
),
)
: const Border(),
),
child: InkWell(
borderRadius: BorderRadius.vertical(
top: topRadius
? Radius.circular(radius)
: const Radius.circular(0),
bottom: bottomRadius
? Radius.circular(radius)
: const Radius.circular(0)),
child: Column(
children: [
Container(
padding: EdgeInsets.symmetric(
vertical: description.isNotEmpty ? padding : padding - 5,
horizontal: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Visibility(
visible: showLeading,
child: Icon(leading, size: 20),
),
const SizedBox(width: 5),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: Theme.of(context).textTheme.titleMedium,
),
description.isNotEmpty
? Text(description,
style: Theme.of(context).textTheme.titleSmall)
: Container(),
],
),
),
SizedBox(width: trailingLeftMargin),
Transform.scale(
scale: 0.9,
child: Switch(
value: value,
onChanged: (_) {
HapticFeedback.lightImpact();
if (onTap != null) onTap();
},
),
),
],
),
),
ThemeColorData.isImmersive(context)
? MyGaps.empty
: Container(
height: 0,
margin: const EdgeInsets.symmetric(horizontal: 10),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
style: bottomRadius
? BorderStyle.none
: BorderStyle.solid,
),
),
),
),
],
),
),
),
);
}
static Widget buildEntryItem({
required BuildContext context,
double radius = 10,
bool topRadius = false,
bool bottomRadius = false,
bool showLeading = false,
bool showTrailing = true,
bool isCaption = false,
Color? backgroundColor,
IconData leading = Icons.home_filled,
required String title,
String tip = "",
String description = "",
Function()? onTap,
double padding = 18,
double trailingLeftMargin = 5,
bool dividerPadding = true,
IconData trailing = Icons.keyboard_arrow_right_rounded,
}) {
return Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
top: topRadius ? Radius.circular(radius) : const Radius.circular(0),
bottom:
bottomRadius ? Radius.circular(radius) : const Radius.circular(0),
),
),
child: Ink(
decoration: BoxDecoration(
color: backgroundColor ?? Theme.of(context).canvasColor,
shape: BoxShape.rectangle,
borderRadius: BorderRadius.vertical(
top: topRadius ? Radius.circular(radius) : const Radius.circular(0),
bottom: bottomRadius
? Radius.circular(radius)
: const Radius.circular(0),
),
border: ThemeColorData.isImmersive(context)
? Border.merge(
Border.symmetric(
vertical: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
),
),
Border(
top: topRadius
? BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
)
: BorderSide.none,
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
),
),
)
: const Border(),
),
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.vertical(
top: topRadius ? Radius.circular(radius) : const Radius.circular(0),
bottom: bottomRadius
? Radius.circular(radius)
: const Radius.circular(0),
),
child: Column(
children: [
Container(
padding:
EdgeInsets.symmetric(vertical: padding, horizontal: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Visibility(
visible: showLeading,
child: Icon(leading, size: 20),
),
showLeading
? const SizedBox(width: 10)
: const SizedBox(width: 5),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: isCaption
? Theme.of(context).textTheme.titleSmall
: Theme.of(context).textTheme.titleMedium,
),
description.isNotEmpty
? Text(description,
style: Theme.of(context).textTheme.titleSmall)
: Container(),
],
),
),
isCaption || tip.isEmpty
? MyGaps.empty
: const SizedBox(width: 50),
Text(
tip,
style: Theme.of(context).textTheme.titleSmall,
),
SizedBox(width: showTrailing ? trailingLeftMargin : 0),
Visibility(
visible: showTrailing,
child: Icon(
trailing,
size: 20,
color:
Theme.of(context).iconTheme.color?.withAlpha(127),
),
),
],
),
),
ThemeColorData.isImmersive(context)
? MyGaps.empty
: Container(
height: 0,
margin: EdgeInsets.symmetric(
horizontal: dividerPadding ? 10 : 0),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
style: bottomRadius
? BorderStyle.none
: BorderStyle.solid,
),
),
),
),
],
),
),
),
);
}
static Widget buildCaptionItem({
required BuildContext context,
double radius = 10,
bool topRadius = true,
bool bottomRadius = false,
bool showLeading = false,
bool showTrailing = true,
IconData leading = Icons.home_filled,
required String title,
IconData trailing = Icons.keyboard_arrow_right_rounded,
}) {
return buildEntryItem(
context: context,
title: title,
radius: radius,
topRadius: topRadius,
bottomRadius: bottomRadius,
showTrailing: false,
showLeading: showLeading,
onTap: null,
leading: leading,
trailing: trailing,
padding: 10,
isCaption: true,
dividerPadding: false,
);
}
static Widget buildContainerItem({
double radius = 10,
bool topRadius = false,
bool bottomRadius = false,
required Widget child,
required BuildContext context,
}) {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).canvasColor,
borderRadius: BorderRadius.vertical(
top: topRadius ? Radius.circular(radius) : const Radius.circular(0),
bottom:
bottomRadius ? Radius.circular(radius) : const Radius.circular(0),
),
border: ThemeColorData.isImmersive(context)
? Border.merge(
Border.symmetric(
vertical: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
),
),
Border(
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.5,
),
),
)
: const Border(),
),
child: Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.05,
style: bottomRadius ? BorderStyle.none : BorderStyle.solid,
),
top: BorderSide(
color: Theme.of(context).dividerColor,
width: 0.05,
style: topRadius ? BorderStyle.none : BorderStyle.solid,
),
),
),
child: child,
),
);
}
static Widget buildThemeItem({
required ThemeColorData themeColorData,
required int index,
required int groupIndex,
required BuildContext context,
required Function(int?)? onChanged,
}) {
return Container(
width: 107.3,
height: 166.4,
margin: EdgeInsets.only(left: index == 0 ? 10 : 0, right: 10),
child: Column(
children: [
Container(
padding:
const EdgeInsets.only(top: 10, bottom: 0, left: 8, right: 8),
decoration: BoxDecoration(
color: themeColorData.background,
borderRadius: const BorderRadius.all(Radius.circular(10)),
border: Border.all(
color: themeColorData.dividerColor,
style: BorderStyle.solid,
width: 0.6,
),
),
child: Column(
children: [
_buildCardRow(themeColorData),
const SizedBox(height: 5),
_buildCardRow(themeColorData),
const SizedBox(height: 15),
Radio(
value: index,
groupValue: groupIndex,
onChanged: onChanged,
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
fillColor: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.selected)) {
return themeColorData.primaryColor;
} else {
return themeColorData.textGrayColor;
}
}),
),
],
),
),
const SizedBox(height: 8),
Text(
themeColorData.name,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
);
}
static Widget buildEmptyThemeItem({
required BuildContext context,
required Function()? onTap,
}) {
return Container(
width: 107.3,
height: 166.4,
margin: const EdgeInsets.only(right: 10),
child: Column(
children: [
Container(
width: 107.3,
height: 141.7,
padding: const EdgeInsets.only(left: 8, right: 8),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(10)),
border: Border.all(
color: Theme.of(context).dividerColor,
style: BorderStyle.solid,
width: 0.6,
),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.add_rounded,
size: 30,
color: Theme.of(context).textTheme.titleSmall?.color,
),
const SizedBox(height: 6),
Text("新建主题", style: Theme.of(context).textTheme.titleSmall),
],
),
),
const SizedBox(height: 6),
Text(
"",
style: Theme.of(context).textTheme.bodySmall,
),
],
),
);
}
static Widget _buildCardRow(ThemeColorData themeColorData) {
return Container(
height: 35,
width: 90,
padding: const EdgeInsets.all(5),
decoration: BoxDecoration(
color: themeColorData.canvasBackground,
borderRadius: const BorderRadius.all(Radius.circular(5)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
height: 22,
width: 22,
decoration: BoxDecoration(
color: themeColorData.splashColor,
borderRadius: const BorderRadius.all(
Radius.circular(5),
),
),
),
const SizedBox(width: 5),
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
height: 5,
width: 45,
decoration: BoxDecoration(
color: themeColorData.textColor,
borderRadius: const BorderRadius.all(
Radius.circular(5),
),
),
),
const SizedBox(height: 5),
Container(
height: 5,
width: 35,
decoration: BoxDecoration(
color: themeColorData.textGrayColor,
borderRadius: const BorderRadius.all(
Radius.circular(5),
),
),
),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/radio_item.dart | import 'package:flutter/material.dart';
class RadioItem<T> extends StatelessWidget {
const RadioItem({
super.key,
required this.value,
required this.groupValue,
required this.onChanged,
this.toggleable = false,
this.activeColor,
this.title,
this.subtitle,
this.isThreeLine = false,
this.dense,
this.secondary,
this.selected = false,
this.autofocus = false,
this.contentPadding,
this.shape,
this.tileColor,
this.selectedTileColor,
this.visualDensity,
this.focusNode,
this.onFocusChange,
this.enableFeedback,
this.selectedColor,
});
final T value;
final T? groupValue;
final ValueChanged<T?>? onChanged;
final bool toggleable;
final Color? activeColor;
final Widget? title;
final Widget? subtitle;
final Widget? secondary;
final bool isThreeLine;
final bool? dense;
final bool selected;
final bool autofocus;
final EdgeInsetsGeometry? contentPadding;
bool get checked => value == groupValue;
final ShapeBorder? shape;
final Color? tileColor;
final Color? selectedTileColor;
final Color? selectedColor;
final VisualDensity? visualDensity;
final FocusNode? focusNode;
final ValueChanged<bool>? onFocusChange;
final bool? enableFeedback;
@override
Widget build(BuildContext context) {
return MergeSemantics(
child: ListTile(
style: ListTileStyle.list,
selectedColor: selectedColor,
title: title,
subtitle: subtitle,
isThreeLine: isThreeLine,
dense: dense,
enabled: onChanged != null,
shape: shape,
tileColor: tileColor,
selectedTileColor: selectedTileColor,
onTap: onChanged != null
? () {
if (toggleable && checked) {
onChanged!(null);
return;
}
if (!checked) {
onChanged!(value);
}
}
: null,
selected: selected,
autofocus: autofocus,
contentPadding: contentPadding,
visualDensity: visualDensity,
focusNode: focusNode,
onFocusChange: onFocusChange,
enableFeedback: enableFeedback,
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Item/article_item.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:readar/Utils/uri_util.dart';
import 'package:readar/Widgets/Item/time_text.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:tuple/tuple.dart';
import '../../Models/feed.dart';
import '../../Models/feed_setting.dart';
import '../../Models/rss_item.dart';
import '../../Providers/provider_manager.dart';
import '../../Providers/rss_provider.dart';
import '../../Screens/Content/article_detail_screen.dart';
import 'dismissible_background.dart';
import 'favicon.dart';
class ArticleItem extends StatefulWidget {
final RssItem item;
final Feed feed;
final Function openActionSheet;
final bool topMargin;
const ArticleItem(this.item, this.feed, this.openActionSheet,
{required this.topMargin, super.key});
@override
ArticleItemState createState() => ArticleItemState();
}
class ArticleItemState extends State<ArticleItem> {
bool pressed = false;
void _openArticle() {
Navigator.of(context, rootNavigator: true).popUntil((route) {
return route.isFirst;
});
if (!widget.item.hasRead) {
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(widget.item.iid, read: true);
}
if (widget.feed.feedSetting?.crawlType == CrawlType.external) {
UriUtil.launchUrlUri(widget.item.url);
} else {
var isSource = Navigator.of(context).canPop();
if (ArticleDetailScreen.state.currentWidget != null) {
ArticleDetailScreen.state.currentState!.loadNewItem(
widget.item.iid,
isSource: isSource,
);
} else {
Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => ArticleDetailScreen(),
settings: RouteSettings(
arguments: Tuple2(widget.item.iid, isSource))));
}
}
}
void _openActionSheet() {
HapticFeedback.mediumImpact();
widget.openActionSheet(widget.item);
}
Widget _imagePlaceholderBuilder(BuildContext context, String _) {
return Container(color: CupertinoColors.systemGrey5.resolveFrom(context));
}
static const _unreadIndicator = Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Icon(
Icons.circle_rounded,
size: 8,
color: Colors.amber,
),
);
static const _starredIndicator = Padding(
padding: EdgeInsets.symmetric(horizontal: 4),
child: Icon(
Icons.star_rounded,
size: 9,
color: CupertinoColors.activeBlue,
),
);
IconData? _getDismissIcon(ItemSwipeOption option) {
switch (option) {
case ItemSwipeOption.toggleRead:
return widget.item.hasRead
? Icons.radio_button_checked
: Icons.radio_button_unchecked;
case ItemSwipeOption.toggleStar:
return widget.item.starred
? Icons.star_outline_rounded
: Icons.star_rounded;
case ItemSwipeOption.share:
return Icons.share;
case ItemSwipeOption.openMenu:
return Icons.more_horiz_rounded;
case ItemSwipeOption.openExternal:
return Icons.open_in_browser_rounded;
}
}
void _performSwipeAction(ItemSwipeOption option) async {
switch (option) {
case ItemSwipeOption.toggleRead:
await Future.delayed(const Duration(milliseconds: 200));
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(widget.item.iid, read: !widget.item.hasRead);
break;
case ItemSwipeOption.toggleStar:
await Future.delayed(const Duration(milliseconds: 200));
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(widget.item.iid, starred: !widget.item.starred);
break;
case ItemSwipeOption.share:
break;
case ItemSwipeOption.openMenu:
widget.openActionSheet(widget.item);
break;
case ItemSwipeOption.openExternal:
if (!widget.item.hasRead) {
ProviderManager.rssProvider.currentRssServiceManager
.updateItem(widget.item.iid, read: true);
}
UriUtil.launchUrlUri(widget.item.url);
break;
}
}
Future<bool> _onDismiss(DismissDirection direction) async {
HapticFeedback.mediumImpact();
if (direction == DismissDirection.startToEnd) {
_performSwipeAction(ProviderManager.rssProvider.swipeR);
} else {
_performSwipeAction(ProviderManager.rssProvider.swipeL);
}
return false;
}
static const _dismissThresholds = {
DismissDirection.horizontal: 0.25,
};
@override
Widget build(BuildContext context) {
final _descStyle = TextStyle(
fontSize: 12,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
final titleStyle = TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: widget.item.hasRead
? CupertinoColors.secondaryLabel.resolveFrom(context)
: CupertinoColors.label.resolveFrom(context),
);
final snippetStyle = TextStyle(
fontSize: 16,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
final infoLine = Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Text(
widget.feed.name,
style: _descStyle,
overflow: TextOverflow.ellipsis,
)),
Row(children: [
if (!widget.item.hasRead) _unreadIndicator,
if (widget.item.starred) _starredIndicator,
TimeText(widget.item.date, style: _descStyle),
]),
],
),
);
final itemTexts = Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
widget.item.title,
style: titleStyle,
),
if (widget.item.snippet.isNotEmpty)
Text(
widget.item.snippet,
style: snippetStyle,
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
],
));
final body = GestureDetector(
onTapDown: (_) {
setState(() {
pressed = true;
});
},
onTapUp: (_) {
setState(() {
pressed = false;
});
},
onTapCancel: () {
setState(() {
pressed = false;
});
},
onLongPress: _openActionSheet,
onTap: _openArticle,
child: Container(
margin: EdgeInsets.only(
left: 10, right: 10, top: widget.topMargin ? 10 : 0, bottom: 5),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(10)),
color: pressed
? CupertinoColors.systemGrey4.resolveFrom(context)
: CupertinoColors.systemBackground.resolveFrom(context),
),
child: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(0, 20, 8, 0),
child: Favicon(widget.feed),
),
Expanded(
flex: 1,
child: Column(
children: [
infoLine,
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
itemTexts,
if (widget.item.thumb != null)
Padding(
padding: const EdgeInsets.only(left: 4),
child: ClipRRect(
borderRadius: BorderRadius.circular(4),
child: CachedNetworkImage(
imageUrl: widget.item.thumb ?? "",
width: 64,
height: 64,
fit: BoxFit.cover,
placeholder: _imagePlaceholderBuilder,
),
),
),
],
),
],
),
),
],
),
),
// Container(
// color: CupertinoColors.systemBackground.resolveFrom(context),
// padding: const EdgeInsets.only(left: 16),
// child: Divider(
// color: CupertinoColors.systemGrey4.resolveFrom(context),
// height: 1),
// ),
],
),
),
);
return Dismissible(
key: Key("D-${widget.item.iid}"),
background: DismissibleBackground(
_getDismissIcon(ProviderManager.rssProvider.swipeR) ?? Icons.add,
true,
),
secondaryBackground: DismissibleBackground(
_getDismissIcon(ProviderManager.rssProvider.swipeL) ?? Icons.add,
false,
),
dismissThresholds: _dismissThresholds,
confirmDismiss: _onDismiss,
child: body,
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Scaffold/my_drawer.dart | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/material.dart';
// Examples can assume:
// late BuildContext context;
// TODO(eseidel): Draw width should vary based on device size:
// https://material.io/design/components/navigation-drawer.html#specs
// Mobile:
// Width = Screen width − 56 dp
// Maximum width: 320dp
// Maximum width applies only when using a left nav. When using a right nav,
// the panel can cover the full width of the screen.
// Desktop/Tablet:
// Maximum width for a left nav is 400dp.
// The right nav can vary depending on content.
const double _kWidth = 304.0;
const double _kEdgeDragWidth = 20.0;
const double _kMinFlingVelocity = 365.0;
const Duration _kBaseSettleDuration = Duration(milliseconds: 246);
/// A Material Design panel that slides in horizontally from the edge of a
/// [Scaffold] to show navigation links in an application.
///
/// There is a Material 3 version of this component, [NavigationDrawer],
/// that's preferred for applications that are configured for Material 3
/// (see [ThemeData.useMaterial3]).
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=WRj86iHihgY}
///
/// Drawers are typically used with the [Scaffold.drawer] property. The child of
/// the drawer is usually a [ListView] whose first child is a [DrawerHeader]
/// that displays status information about the current user. The remaining
/// drawer children are often constructed with [ListTile]s, often concluding
/// with an [AboutListTile].
///
/// The [AppBar] automatically displays an appropriate [IconButton] to show the
/// [MyDrawer] when a [MyDrawer] is available in the [Scaffold]. The [Scaffold]
/// automatically handles the edge-swipe gesture to show the drawer.
///
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/drawer.mp4}
///
/// ## Updating to [NavigationDrawer]
///
/// There is a Material 3 version of this component, [NavigationDrawer],
/// that's preferred for applications that are configured for Material 3
/// (see [ThemeData.useMaterial3]). The [NavigationDrawer] widget's visual
/// are a little bit different, see the Material 3 spec at
/// <https://m3.material.io/components/navigation-drawer/overview> for
/// more details. While the [MyDrawer] widget can have only one child, the
/// [NavigationDrawer] widget can have list of widgets, which typically contains
/// [NavigationDrawerDestination] widgets and/or customized widgets like headlines
/// and dividers.
///
/// {@tool snippet}
/// This example shows how to create a [Scaffold] that contains an [AppBar] and
/// a [MyDrawer]. A user taps the "menu" icon in the [AppBar] to open the
/// [MyDrawer]. The [MyDrawer] displays four items: A header and three menu items.
/// The [MyDrawer] displays the four items using a [ListView], which allows the
/// user to scroll through the items if need be.
///
/// ```dart
/// Scaffold(
/// appBar: AppBar(
/// title: const Text('Drawer Demo'),
/// ),
/// drawer: Drawer(
/// child: ListView(
/// padding: EdgeInsets.zero,
/// children: const <Widget>[
/// DrawerHeader(
/// decoration: BoxDecoration(
/// color: Colors.blue,
/// ),
/// child: Text(
/// 'Drawer Header',
/// style: TextStyle(
/// color: Colors.white,
/// fontSize: 24,
/// ),
/// ),
/// ),
/// ListTile(
/// leading: Icon(Icons.message),
/// title: Text('Messages'),
/// ),
/// ListTile(
/// leading: Icon(Icons.account_circle),
/// title: Text('Profile'),
/// ),
/// ListTile(
/// leading: Icon(Icons.settings),
/// title: Text('Settings'),
/// ),
/// ],
/// ),
/// ),
/// )
/// ```
/// {@end-tool}
///
/// {@tool snippet}
/// This example shows how to migrate the above [MyDrawer] to a [NavigationDrawer].
///
/// See code in examples/api/lib/material/navigation_drawer/navigation_drawer.1.dart **
/// {@end-tool}
///
/// An open drawer may be closed with a swipe to close gesture, pressing the
/// escape key, by tapping the scrim, or by calling pop route function such as
/// [Navigator.pop]. For example a drawer item might close the drawer when tapped:
///
/// ```dart
/// ListTile(
/// leading: const Icon(Icons.change_history),
/// title: const Text('Change history'),
/// onTap: () {
/// // change app state...
/// Navigator.pop(context); // close the drawer
/// },
/// );
/// ```
///
/// See also:
///
/// * [Scaffold.drawer], where one specifies a [MyDrawer] so that it can be
/// shown.
/// * [Scaffold.of], to obtain the current [ScaffoldState], which manages the
/// display and animation of the drawer.
/// * [ScaffoldState.openDrawer], which displays its [MyDrawer], if any.
/// * <https://material.io/design/components/navigation-drawer.html>
class MyDrawer extends StatelessWidget {
/// Creates a Material Design drawer.
///
/// Typically used in the [Scaffold.drawer] property.
///
/// The [elevation] must be non-negative.
const MyDrawer({
super.key,
this.backgroundColor,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.shape,
this.width,
this.child,
this.semanticLabel,
this.clipBehavior,
}) : assert(elevation == null || elevation >= 0.0);
/// Sets the color of the [Material] that holds all of the [MyDrawer]'s
/// contents.
///
/// If this is null, then [DrawerThemeData.backgroundColor] is used. If that
/// is also null, then it falls back to [Material]'s default.
final Color? backgroundColor;
/// The z-coordinate at which to place this drawer relative to its parent.
///
/// This controls the size of the shadow below the drawer.
///
/// If this is null, then [DrawerThemeData.elevation] is used. If that
/// is also null, then it defaults to 16.0.
final double? elevation;
/// The color used to paint a drop shadow under the drawer's [Material],
/// which reflects the drawer's [elevation].
///
/// If null and [ThemeData.useMaterial3] is true then no drop shadow will
/// be rendered.
///
/// If null and [ThemeData.useMaterial3] is false then it will default to
/// [ThemeData.shadowColor].
///
/// See also:
/// * [Material.shadowColor], which describes how the drop shadow is painted.
/// * [elevation], which affects how the drop shadow is painted.
/// * [surfaceTintColor], which can be used to indicate elevation through
/// tinting the background color.
final Color? shadowColor;
/// The color used as a surface tint overlay on the drawer's background color,
/// which reflects the drawer's [elevation].
///
/// If [ThemeData.useMaterial3] is false property has no effect.
///
/// If null and [ThemeData.useMaterial3] is true then [ThemeData]'s
/// [ColorScheme.surfaceTint] will be used.
///
/// To disable this feature, set [surfaceTintColor] to [Colors.transparent].
///
/// See also:
/// * [Material.surfaceTintColor], which describes how the surface tint will
/// be applied to the background color of the drawer.
/// * [elevation], which affects the opacity of the surface tint.
/// * [shadowColor], which can be used to indicate elevation through
/// a drop shadow.
final Color? surfaceTintColor;
/// The shape of the drawer.
///
/// Defines the drawer's [Material.shape].
///
/// If this is null, then [DrawerThemeData.shape] is used. If that
/// is also null, then it falls back to [Material]'s default.
final ShapeBorder? shape;
/// The width of the drawer.
///
/// If this is null, then [DrawerThemeData.width] is used. If that is also
/// null, then it falls back to the Material spec's default (304.0).
final double? width;
/// The widget below this widget in the tree.
///
/// Typically a [SliverList].
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// The semantic label of the drawer used by accessibility frameworks to
/// announce screen transitions when the drawer is opened and closed.
///
/// If this label is not provided, it will default to
/// [MaterialLocalizations.drawerLabel].
///
/// See also:
///
/// * [SemanticsConfiguration.namesRoute], for a description of how this
/// value is used.
final String? semanticLabel;
/// {@macro flutter.material.Material.clipBehavior}
///
/// The [clipBehavior] argument specifies how to clip the drawer's [shape].
///
/// If the drawer has a [shape], it defaults to [Clip.hardEdge]. Otherwise,
/// defaults to [Clip.none].
final Clip? clipBehavior;
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final DrawerThemeData drawerTheme = DrawerTheme.of(context);
String? label = semanticLabel;
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
label = semanticLabel ?? MaterialLocalizations.of(context).drawerLabel;
}
final bool useMaterial3 = Theme.of(context).useMaterial3;
final bool isDrawerStart =
MyDrawerController.maybeOf(context)?.alignment != DrawerAlignment.end;
final DrawerThemeData defaults =
useMaterial3 ? _DrawerDefaultsM3(context) : _DrawerDefaultsM2(context);
final ShapeBorder? effectiveShape = shape ??
(isDrawerStart
? (drawerTheme.shape ?? defaults.shape)
: (drawerTheme.endShape ?? defaults.endShape));
return Semantics(
scopesRoute: true,
namesRoute: true,
explicitChildNodes: true,
label: label,
child: ConstrainedBox(
constraints:
BoxConstraints.expand(width: width ?? drawerTheme.width ?? _kWidth),
child: Material(
color: backgroundColor ??
drawerTheme.backgroundColor ??
defaults.backgroundColor,
elevation: elevation ?? drawerTheme.elevation ?? defaults.elevation!,
shadowColor:
shadowColor ?? drawerTheme.shadowColor ?? defaults.shadowColor,
surfaceTintColor: surfaceTintColor ??
drawerTheme.surfaceTintColor ??
defaults.surfaceTintColor,
shape: effectiveShape,
clipBehavior: effectiveShape != null
? (clipBehavior ?? Clip.hardEdge)
: Clip.none,
child: child,
),
),
);
}
}
class _DrawerControllerScope extends InheritedWidget {
const _DrawerControllerScope({
required this.controller,
required super.child,
});
final MyDrawerController controller;
@override
bool updateShouldNotify(_DrawerControllerScope old) {
return controller != old.controller;
}
}
/// Provides interactive behavior for [MyDrawer] widgets.
///
/// Rarely used directly. Drawer controllers are typically created automatically
/// by [Scaffold] widgets.
///
/// The drawer controller provides the ability to open and close a drawer, either
/// via an animation or via user interaction. When closed, the drawer collapses
/// to a translucent gesture detector that can be used to listen for edge
/// swipes.
///
/// See also:
///
/// * [MyDrawer], a container with the default width of a drawer.
/// * [Scaffold.drawer], the [Scaffold] slot for showing a drawer.
class MyDrawerController extends StatefulWidget {
/// Creates a controller for a [MyDrawer].
///
/// Rarely used directly.
///
/// The [child] argument must not be null and is typically a [MyDrawer].
const MyDrawerController({
GlobalKey? key,
required this.child,
required this.alignment,
this.isDrawerOpen = false,
this.drawerCallback,
this.dragStartBehavior = DragStartBehavior.start,
this.scrimColor,
this.edgeDragWidth,
this.customAnimationController,
this.enableOpenDragGesture = true,
}) : super(key: key);
/// The widget below this widget in the tree.
///
/// Typically a [MyDrawer].
final Widget child;
final AnimationController? customAnimationController;
/// The alignment of the [MyDrawer].
///
/// This controls the direction in which the user should swipe to open and
/// close the drawer.
final DrawerAlignment alignment;
/// Optional callback that is called when a [MyDrawer] is opened or closed.
final DrawerCallback? drawerCallback;
/// {@template flutter.material.DrawerController.dragStartBehavior}
/// Determines the way that drag start behavior is handled.
///
/// If set to [DragStartBehavior.start], the drag behavior used for opening
/// and closing a drawer will begin at the position where the drag gesture won
/// the arena. If set to [DragStartBehavior.down] it will begin at the position
/// where a down event is first detected.
///
/// In general, setting this to [DragStartBehavior.start] will make drag
/// animation smoother and setting it to [DragStartBehavior.down] will make
/// drag behavior feel slightly more reactive.
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// See also:
///
/// * [DragGestureRecognizer.dragStartBehavior], which gives an example for
/// the different behaviors.
///
/// {@endtemplate}
final DragStartBehavior dragStartBehavior;
/// The color to use for the scrim that obscures the underlying content while
/// a drawer is open.
///
/// If this is null, then [DrawerThemeData.scrimColor] is used. If that
/// is also null, then it defaults to [Colors.black54].
final Color? scrimColor;
/// Determines if the [MyDrawer] can be opened with a drag gesture.
///
/// By default, the drag gesture is enabled.
final bool enableOpenDragGesture;
/// The width of the area within which a horizontal swipe will open the
/// drawer.
///
/// By default, the value used is 20.0 added to the padding edge of
/// `MediaQuery.paddingOf(context)` that corresponds to [alignment].
/// This ensures that the drag area for notched devices is not obscured. For
/// example, if [alignment] is set to [DrawerAlignment.start] and
/// `TextDirection.of(context)` is set to [TextDirection.ltr],
/// 20.0 will be added to `MediaQuery.paddingOf(context).left`.
final double? edgeDragWidth;
/// Whether or not the drawer is opened or closed.
///
/// This parameter is primarily used by the state restoration framework
/// to restore the drawer's animation controller to the open or closed state
/// depending on what was last saved to the target platform before the
/// application was killed.
final bool isDrawerOpen;
/// The closest instance of [MyDrawerController] that encloses the given
/// context, or null if none is found.
///
/// {@tool snippet} Typical usage is as follows:
///
/// ```dart
/// DrawerController? controller = DrawerController.maybeOf(context);
/// ```
/// {@end-tool}
///
/// Calling this method will create a dependency on the closest
/// [MyDrawerController] in the [context], if there is one.
///
/// See also:
///
/// * [MyDrawerController.of], which is similar to this method, but asserts
/// if no [MyDrawerController] ancestor is found.
static MyDrawerController? maybeOf(BuildContext context) {
return context
.dependOnInheritedWidgetOfExactType<_DrawerControllerScope>()
?.controller;
}
/// The closest instance of [MyDrawerController] that encloses the given
/// context.
///
/// If no instance is found, this method will assert in debug mode and throw
/// an exception in release mode.
///
/// Calling this method will create a dependency on the closest
/// [MyDrawerController] in the [context].
///
/// {@tool snippet} Typical usage is as follows:
///
/// ```dart
/// DrawerController controller = DrawerController.of(context);
/// ```
/// {@end-tool}
static MyDrawerController of(BuildContext context) {
final MyDrawerController? controller = maybeOf(context);
assert(() {
if (controller == null) {
throw FlutterError(
'DrawerController.of() was called with a context that does not '
'contain a DrawerController widget.\n'
'No DrawerController widget ancestor could be found starting from '
'the context that was passed to DrawerController.of(). This can '
'happen because you are using a widget that looks for a DrawerController '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return controller!;
}
@override
MyDrawerControllerState createState() => MyDrawerControllerState();
}
/// State for a [MyDrawerController].
///
/// Typically used by a [Scaffold] to [open] and [close] the drawer.
class MyDrawerControllerState extends State<MyDrawerController>
with SingleTickerProviderStateMixin {
@override
void initState() {
super.initState();
if (widget.customAnimationController != null) {
_controller = widget.customAnimationController!;
} else {
_controller = AnimationController(
value: widget.isDrawerOpen ? 1.0 : 0.0,
duration: _kBaseSettleDuration,
vsync: this,
);
}
_controller
..addListener(_animationChanged)
..addStatusListener(_animationStatusChanged);
}
@override
void dispose() {
_historyEntry?.remove();
_controller.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_scrimColorTween = _buildScrimColorTween();
}
@override
void didUpdateWidget(MyDrawerController oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.scrimColor != oldWidget.scrimColor) {
_scrimColorTween = _buildScrimColorTween();
}
if (widget.isDrawerOpen != oldWidget.isDrawerOpen) {
switch (_controller.status) {
case AnimationStatus.completed:
case AnimationStatus.dismissed:
_controller.value = widget.isDrawerOpen ? 1.0 : 0.0;
case AnimationStatus.forward:
case AnimationStatus.reverse:
break;
}
}
}
void _animationChanged() {
setState(() {
// The animation controller's state is our build state, and it changed already.
});
}
LocalHistoryEntry? _historyEntry;
final FocusScopeNode _focusScopeNode = FocusScopeNode();
void _ensureHistoryEntry() {
if (_historyEntry == null) {
final ModalRoute<dynamic>? route = ModalRoute.of(context);
if (route != null) {
_historyEntry = LocalHistoryEntry(
onRemove: _handleHistoryEntryRemoved,
impliesAppBarDismissal: false);
route.addLocalHistoryEntry(_historyEntry!);
FocusScope.of(context).setFirstFocus(_focusScopeNode);
}
}
}
void _animationStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.forward:
_ensureHistoryEntry();
case AnimationStatus.reverse:
_historyEntry?.remove();
_historyEntry = null;
case AnimationStatus.dismissed:
break;
case AnimationStatus.completed:
break;
}
}
void _handleHistoryEntryRemoved() {
_historyEntry = null;
close();
}
late AnimationController _controller;
void _handleDragDown(DragDownDetails details) {
_controller.stop();
_ensureHistoryEntry();
}
void _handleDragCancel() {
if (_controller.isDismissed || _controller.isAnimating) {
return;
}
if (_controller.value < 0.5) {
close();
} else {
open();
}
}
final GlobalKey _drawerKey = GlobalKey();
double get _width {
final RenderBox? box =
_drawerKey.currentContext?.findRenderObject() as RenderBox?;
if (box != null) {
return box.size.width;
}
return _kWidth; // drawer not being shown currently
}
bool _previouslyOpened = false;
void _move(DragUpdateDetails details) {
double delta = details.primaryDelta! / _width;
switch (widget.alignment) {
case DrawerAlignment.start:
break;
case DrawerAlignment.end:
delta = -delta;
}
switch (Directionality.of(context)) {
case TextDirection.rtl:
_controller.value -= delta;
case TextDirection.ltr:
_controller.value += delta;
}
final bool opened = _controller.value > 0.5;
if (opened != _previouslyOpened && widget.drawerCallback != null) {
widget.drawerCallback!(opened);
}
_previouslyOpened = opened;
}
void _settle(DragEndDetails details) {
if (_controller.isDismissed) {
return;
}
if (details.velocity.pixelsPerSecond.dx.abs() >= _kMinFlingVelocity) {
double visualVelocity = details.velocity.pixelsPerSecond.dx / _width;
switch (widget.alignment) {
case DrawerAlignment.start:
break;
case DrawerAlignment.end:
visualVelocity = -visualVelocity;
}
switch (Directionality.of(context)) {
case TextDirection.rtl:
_controller.fling(velocity: -visualVelocity);
widget.drawerCallback?.call(visualVelocity < 0.0);
case TextDirection.ltr:
_controller.fling(velocity: visualVelocity);
widget.drawerCallback?.call(visualVelocity > 0.0);
}
} else if (_controller.value < 0.5) {
close();
} else {
open();
}
}
/// Starts an animation to open the drawer.
///
/// Typically called by [ScaffoldState.openDrawer].
void open() {
_controller.fling();
widget.drawerCallback?.call(true);
}
/// Starts an animation to close the drawer.
void close() {
_controller.fling(velocity: -1.0);
widget.drawerCallback?.call(false);
}
late ColorTween _scrimColorTween;
final GlobalKey _gestureDetectorKey = GlobalKey();
ColorTween _buildScrimColorTween() {
return ColorTween(
begin: Colors.transparent,
end: widget.scrimColor ??
DrawerTheme.of(context).scrimColor ??
Colors.black54,
);
}
AlignmentDirectional get _drawerOuterAlignment {
switch (widget.alignment) {
case DrawerAlignment.start:
return AlignmentDirectional.centerStart;
case DrawerAlignment.end:
return AlignmentDirectional.centerEnd;
}
}
AlignmentDirectional get _drawerInnerAlignment {
switch (widget.alignment) {
case DrawerAlignment.start:
return AlignmentDirectional.centerEnd;
case DrawerAlignment.end:
return AlignmentDirectional.centerStart;
}
}
Widget _buildDrawer(BuildContext context) {
final bool drawerIsStart = widget.alignment == DrawerAlignment.start;
final TextDirection textDirection = Directionality.of(context);
final bool isDesktop;
switch (Theme.of(context).platform) {
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
isDesktop = false;
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
isDesktop = true;
}
double? dragAreaWidth = widget.edgeDragWidth;
if (widget.edgeDragWidth == null) {
final EdgeInsets padding = MediaQuery.paddingOf(context);
switch (textDirection) {
case TextDirection.ltr:
dragAreaWidth =
_kEdgeDragWidth + (drawerIsStart ? padding.left : padding.right);
case TextDirection.rtl:
dragAreaWidth =
_kEdgeDragWidth + (drawerIsStart ? padding.right : padding.left);
}
}
if (_controller.status == AnimationStatus.dismissed) {
if (widget.enableOpenDragGesture && !isDesktop) {
return Align(
alignment: _drawerOuterAlignment,
child: GestureDetector(
key: _gestureDetectorKey,
onHorizontalDragUpdate: _move,
onHorizontalDragEnd: _settle,
behavior: HitTestBehavior.deferToChild,
excludeFromSemantics: true,
dragStartBehavior: widget.dragStartBehavior,
child: Container(width: dragAreaWidth),
),
);
} else {
return const SizedBox.shrink();
}
} else {
final bool platformHasBackButton;
switch (Theme.of(context).platform) {
case TargetPlatform.android:
platformHasBackButton = true;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
platformHasBackButton = false;
}
final Widget child = _DrawerControllerScope(
controller: widget,
child: RepaintBoundary(
child: Stack(
children: <Widget>[
BlockSemantics(
child: ExcludeSemantics(
// On Android, the back button is used to dismiss a modal.
excluding: platformHasBackButton,
child: GestureDetector(
onTap: close,
child: Semantics(
label: MaterialLocalizations.of(context)
.modalBarrierDismissLabel,
child: Container(
// The drawer's "scrim"
color: _scrimColorTween.evaluate(_controller),
),
),
),
),
),
Align(
alignment: _drawerOuterAlignment,
child: Align(
alignment: _drawerInnerAlignment,
widthFactor: _controller.value,
child: RepaintBoundary(
child: FocusScope(
key: _drawerKey,
node: _focusScopeNode,
child: widget.child,
),
),
),
),
],
),
),
);
if (isDesktop) {
return child;
}
return GestureDetector(
key: _gestureDetectorKey,
onHorizontalDragDown: _handleDragDown,
onHorizontalDragUpdate: _move,
onHorizontalDragEnd: _settle,
onHorizontalDragCancel: _handleDragCancel,
excludeFromSemantics: true,
dragStartBehavior: widget.dragStartBehavior,
child: child,
);
}
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
return ListTileTheme.merge(
style: ListTileStyle.drawer,
child: _buildDrawer(context),
);
}
}
class _DrawerDefaultsM2 extends DrawerThemeData {
const _DrawerDefaultsM2(this.context) : super(elevation: 16.0);
final BuildContext context;
@override
Color? get shadowColor => Theme.of(context).shadowColor;
}
// BEGIN GENERATED TOKEN PROPERTIES - Drawer
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _DrawerDefaultsM3 extends DrawerThemeData {
_DrawerDefaultsM3(this.context) : super(elevation: 1.0);
final BuildContext context;
late final TextDirection direction = Directionality.of(context);
@override
Color? get backgroundColor => Theme.of(context).colorScheme.surface;
@override
Color? get surfaceTintColor => Theme.of(context).colorScheme.surfaceTint;
@override
Color? get shadowColor => Colors.transparent;
// There isn't currently a token for this value, but it is shown in the spec,
// so hard coding here for now.
@override
ShapeBorder? get shape => RoundedRectangleBorder(
borderRadius: const BorderRadiusDirectional.horizontal(
end: Radius.circular(16.0),
).resolve(direction),
);
// There isn't currently a token for this value, but it is shown in the spec,
// so hard coding here for now.
@override
ShapeBorder? get endShape => RoundedRectangleBorder(
borderRadius: const BorderRadiusDirectional.horizontal(
start: Radius.circular(16.0),
).resolve(direction),
);
}
// END GENERATED TOKEN PROPERTIES - Drawer
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Scaffold/my_scaffold.dart | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:math' as math;
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/material.dart';
import 'my_drawer.dart';
// Examples can assume:
// late TabController tabController;
// void setState(VoidCallback fn) { }
// late String appBarTitle;
// late int tabCount;
// late TickerProvider tickerProvider;
const FloatingActionButtonLocation _kDefaultFloatingActionButtonLocation =
FloatingActionButtonLocation.endFloat;
const FloatingActionButtonAnimator _kDefaultFloatingActionButtonAnimator =
FloatingActionButtonAnimator.scaling;
const Curve _standardBottomSheetCurve = standardEasing;
// When the top of the BottomSheet crosses this threshold, it will start to
// shrink the FAB and show a scrim.
const double _kBottomSheetDominatesPercentage = 0.3;
const double _kMinBottomSheetScrimOpacity = 0.1;
const double _kMaxBottomSheetScrimOpacity = 0.6;
enum _ScaffoldSlot {
body,
appBar,
bodyScrim,
bottomSheet,
snackBar,
materialBanner,
persistentFooter,
bottomNavigationBar,
floatingActionButton,
drawer,
endDrawer,
statusBar,
}
/// Manages [SnackBar]s and [MaterialBanner]s for descendant [MyScaffold]s.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=lytQi-slT5Y}
///
/// This class provides APIs for showing snack bars and material banners at the
/// bottom and top of the screen, respectively.
///
/// To display one of these notifications, obtain the [ScaffoldMessengerState]
/// for the current [BuildContext] via [ScaffoldMessenger.of] and use the
/// [ScaffoldMessengerState.showSnackBar] or the
/// [ScaffoldMessengerState.showMaterialBanner] functions.
///
/// When the [ScaffoldMessenger] has nested [MyScaffold] descendants, the
/// ScaffoldMessenger will only present the notification to the root Scaffold of
/// the subtree of Scaffolds. In order to show notifications for the inner, nested
/// Scaffolds, set a new scope by instantiating a new ScaffoldMessenger in
/// between the levels of nesting.
///
/// {@tool dartpad}
/// Here is an example of showing a [SnackBar] when the user presses a button.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.0.dart **
/// {@end-tool}
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=lytQi-slT5Y}
///
/// See also:
///
/// * [SnackBar], which is a temporary notification typically shown near the
/// bottom of the app using the [ScaffoldMessengerState.showSnackBar] method.
/// * [MaterialBanner], which is a temporary notification typically shown at the
/// top of the app using the [ScaffoldMessengerState.showMaterialBanner] method.
/// * [debugCheckHasScaffoldMessenger], which asserts that the given context
/// has a [ScaffoldMessenger] ancestor.
/// * Cookbook: [Display a SnackBar](https://flutter.dev/docs/cookbook/design/snackbars)
class ScaffoldMessenger extends StatefulWidget {
/// Creates a widget that manages [SnackBar]s for [MyScaffold] descendants.
const ScaffoldMessenger({
super.key,
required this.child,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// {@tool dartpad}
/// Typical usage of the [ScaffoldMessenger.of] function is to call it in
/// response to a user gesture or an application state change.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.of.0.dart **
/// {@end-tool}
///
/// A less elegant but more expedient solution is to assign a [GlobalKey] to the
/// [ScaffoldMessenger], then use the `key.currentState` property to obtain the
/// [ScaffoldMessengerState] rather than using the [ScaffoldMessenger.of]
/// function. The [MaterialApp.scaffoldMessengerKey] refers to the root
/// ScaffoldMessenger that is provided by default.
///
/// {@tool dartpad}
/// Sometimes [SnackBar]s are produced by code that doesn't have ready access
/// to a valid [BuildContext]. One such example of this is when you show a
/// SnackBar from a method outside of the `build` function. In these
/// cases, you can assign a [GlobalKey] to the [ScaffoldMessenger]. This
/// example shows a key being used to obtain the [ScaffoldMessengerState]
/// provided by the [MaterialApp].
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger.of.1.dart **
/// {@end-tool}
///
/// If there is no [ScaffoldMessenger] in scope, then this will assert in
/// debug mode, and throw an exception in release mode.
///
/// See also:
///
/// * [maybeOf], which is a similar function but will return null instead of
/// throwing if there is no [ScaffoldMessenger] ancestor.
/// * [debugCheckHasScaffoldMessenger], which asserts that the given context
/// has a [ScaffoldMessenger] ancestor.
static ScaffoldMessengerState of(BuildContext context) {
assert(debugCheckHasScaffoldMessenger(context));
final _ScaffoldMessengerScope scope =
context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>()!;
return scope._scaffoldMessengerState;
}
/// The state from the closest instance of this class that encloses the given
/// context, if any.
///
/// Will return null if a [ScaffoldMessenger] is not found in the given context.
///
/// See also:
///
/// * [of], which is a similar function, except that it will throw an
/// exception if a [ScaffoldMessenger] is not found in the given context.
static ScaffoldMessengerState? maybeOf(BuildContext context) {
final _ScaffoldMessengerScope? scope =
context.dependOnInheritedWidgetOfExactType<_ScaffoldMessengerScope>();
return scope?._scaffoldMessengerState;
}
@override
ScaffoldMessengerState createState() => ScaffoldMessengerState();
}
/// State for a [ScaffoldMessenger].
///
/// A [ScaffoldMessengerState] object can be used to [showSnackBar] or
/// [showMaterialBanner] for every registered [MyScaffold] that is a descendant of
/// the associated [ScaffoldMessenger]. Scaffolds will register to receive
/// [SnackBar]s and [MaterialBanner]s from their closest ScaffoldMessenger
/// ancestor.
///
/// Typically obtained via [ScaffoldMessenger.of].
class ScaffoldMessengerState extends State<ScaffoldMessenger>
with TickerProviderStateMixin {
final LinkedHashSet<MyScaffoldState> _scaffolds =
LinkedHashSet<MyScaffoldState>();
final Queue<
ScaffoldFeatureController<MaterialBanner,
MaterialBannerClosedReason>> _materialBanners = Queue<
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>>();
AnimationController? _materialBannerController;
final Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>
_snackBars =
Queue<ScaffoldFeatureController<SnackBar, SnackBarClosedReason>>();
AnimationController? _snackBarController;
Timer? _snackBarTimer;
bool? _accessibleNavigation;
@override
void didChangeDependencies() {
final bool accessibleNavigation =
MediaQuery.accessibleNavigationOf(context);
// If we transition from accessible navigation to non-accessible navigation
// and there is a SnackBar that would have timed out that has already
// completed its timer, dismiss that SnackBar. If the timer hasn't finished
// yet, let it timeout as normal.
if ((_accessibleNavigation ?? false) &&
!accessibleNavigation &&
_snackBarTimer != null &&
!_snackBarTimer!.isActive) {
hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
}
_accessibleNavigation = accessibleNavigation;
super.didChangeDependencies();
}
void _register(MyScaffoldState scaffold) {
_scaffolds.add(scaffold);
if (_isRoot(scaffold)) {
if (_snackBars.isNotEmpty) {
scaffold._updateSnackBar();
}
if (_materialBanners.isNotEmpty) {
scaffold._updateMaterialBanner();
}
}
}
void _unregister(MyScaffoldState scaffold) {
final bool removed = _scaffolds.remove(scaffold);
// ScaffoldStates should only be removed once.
assert(removed);
}
void _updateScaffolds() {
for (final MyScaffoldState scaffold in _scaffolds) {
if (_isRoot(scaffold)) {
scaffold._updateSnackBar();
scaffold._updateMaterialBanner();
}
}
}
// Nested Scaffolds are handled by the ScaffoldMessenger by only presenting a
// MaterialBanner or SnackBar in the root Scaffold of the nested set.
bool _isRoot(MyScaffoldState scaffold) {
final MyScaffoldState? parent =
scaffold.context.findAncestorStateOfType<MyScaffoldState>();
return parent == null || !_scaffolds.contains(parent);
}
// SNACKBAR API
/// Shows a [SnackBar] across all registered [MyScaffold]s. Scaffolds register
/// to receive snack bars from their closest [ScaffoldMessenger] ancestor.
/// If there are several registered scaffolds the snack bar is shown
/// simultaneously on all of them.
///
/// A scaffold can show at most one snack bar at a time. If this function is
/// called while another snack bar is already visible, the given snack bar
/// will be added to a queue and displayed after the earlier snack bars have
/// closed.
///
/// To control how long a [SnackBar] remains visible, use [SnackBar.duration].
///
/// To remove the [SnackBar] with an exit animation, use [hideCurrentSnackBar]
/// or call [ScaffoldFeatureController.close] on the returned
/// [ScaffoldFeatureController]. To remove a [SnackBar] suddenly (without an
/// animation), use [removeCurrentSnackBar].
///
/// See [ScaffoldMessenger.of] for information about how to obtain the
/// [ScaffoldMessengerState].
///
/// {@tool dartpad}
/// Here is an example of showing a [SnackBar] when the user presses a button.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.0.dart **
/// {@end-tool}
///
/// ## Relative positioning of floating SnackBars
///
/// A [SnackBar] with [SnackBar.behavior] set to [SnackBarBehavior.floating] is
/// positioned above the widgets provided to [MyScaffold.floatingActionButton],
/// [MyScaffold.persistentFooterButtons], and [MyScaffold.bottomNavigationBar].
/// If some or all of these widgets take up enough space such that the SnackBar
/// would not be visible when positioned above them, an error will be thrown.
/// In this case, consider constraining the size of these widgets to allow room for
/// the SnackBar to be visible.
///
/// {@tool dartpad}
/// Here is an example showing that a floating [SnackBar] appears above [MyScaffold.floatingActionButton].
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_snack_bar.1.dart **
/// {@end-tool}
///
ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSnackBar(
SnackBar snackBar) {
assert(
_scaffolds.isNotEmpty,
'ScaffoldMessenger.showSnackBar was called, but there are currently no '
'descendant Scaffolds to present to.',
);
_snackBarController ??= SnackBar.createAnimationController(vsync: this)
..addStatusListener(_handleSnackBarStatusChanged);
if (_snackBars.isEmpty) {
assert(_snackBarController!.isDismissed);
_snackBarController!.forward();
}
late ScaffoldFeatureController<SnackBar, SnackBarClosedReason> controller;
controller = ScaffoldFeatureController<SnackBar, SnackBarClosedReason>._(
// We provide a fallback key so that if back-to-back snackbars happen to
// match in structure, material ink splashes and highlights don't survive
// from one to the next.
snackBar.withAnimation(_snackBarController!, fallbackKey: UniqueKey()),
Completer<SnackBarClosedReason>(),
() {
assert(_snackBars.first == controller);
hideCurrentSnackBar();
},
null, // SnackBar doesn't use a builder function so setState() wouldn't rebuild it
);
try {
setState(() {
_snackBars.addLast(controller);
});
_updateScaffolds();
} catch (exception) {
assert(() {
if (exception is FlutterError) {
final String summary = exception.diagnostics.first.toDescription();
if (summary ==
'setState() or markNeedsBuild() called during build.') {
final List<DiagnosticsNode> information = <DiagnosticsNode>[
ErrorSummary(
'The showSnackBar() method cannot be called during build.'),
ErrorDescription(
'The showSnackBar() method was called during build, which is '
'prohibited as showing snack bars requires updating state. Updating '
'state is not possible during build.',
),
ErrorHint(
'Instead of calling showSnackBar() during build, call it directly '
'in your on tap (and related) callbacks. If you need to immediately '
'show a snack bar, make the call in initState() or '
'didChangeDependencies() instead. Otherwise, you can also schedule a '
'post-frame callback using SchedulerBinding.addPostFrameCallback to '
'show the snack bar after the current frame.',
),
context.describeOwnershipChain(
'The ownership chain for the particular ScaffoldMessenger is',
),
];
throw FlutterError.fromParts(information);
}
}
return true;
}());
rethrow;
}
return controller;
}
void _handleSnackBarStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.dismissed:
assert(_snackBars.isNotEmpty);
setState(() {
_snackBars.removeFirst();
});
_updateScaffolds();
if (_snackBars.isNotEmpty) {
_snackBarController!.forward();
}
case AnimationStatus.completed:
setState(() {
assert(_snackBarTimer == null);
// build will create a new timer if necessary to dismiss the snackBar.
});
_updateScaffolds();
case AnimationStatus.forward:
break;
case AnimationStatus.reverse:
break;
}
}
/// Removes the current [SnackBar] (if any) immediately from registered
/// [MyScaffold]s.
///
/// The removed snack bar does not run its normal exit animation. If there are
/// any queued snack bars, they begin their entrance animation immediately.
void removeCurrentSnackBar(
{SnackBarClosedReason reason = SnackBarClosedReason.remove}) {
if (_snackBars.isEmpty) {
return;
}
final Completer<SnackBarClosedReason> completer =
_snackBars.first._completer;
if (!completer.isCompleted) {
completer.complete(reason);
}
_snackBarTimer?.cancel();
_snackBarTimer = null;
// This will trigger the animation's status callback.
_snackBarController!.value = 0.0;
}
/// Removes the current [SnackBar] by running its normal exit animation.
///
/// The closed completer is called after the animation is complete.
void hideCurrentSnackBar(
{SnackBarClosedReason reason = SnackBarClosedReason.hide}) {
if (_snackBars.isEmpty ||
_snackBarController!.status == AnimationStatus.dismissed) {
return;
}
final Completer<SnackBarClosedReason> completer =
_snackBars.first._completer;
if (_accessibleNavigation!) {
_snackBarController!.value = 0.0;
completer.complete(reason);
} else {
_snackBarController!.reverse().then<void>((void value) {
assert(mounted);
if (!completer.isCompleted) {
completer.complete(reason);
}
});
}
_snackBarTimer?.cancel();
_snackBarTimer = null;
}
/// Removes all the snackBars currently in queue by clearing the queue
/// and running normal exit animation on the current snackBar.
void clearSnackBars() {
if (_snackBars.isEmpty ||
_snackBarController!.status == AnimationStatus.dismissed) {
return;
}
final ScaffoldFeatureController<SnackBar, SnackBarClosedReason>
currentSnackbar = _snackBars.first;
_snackBars.clear();
_snackBars.add(currentSnackbar);
hideCurrentSnackBar();
}
// MATERIAL BANNER API
/// Shows a [MaterialBanner] across all registered [MyScaffold]s. Scaffolds register
/// to receive material banners from their closest [ScaffoldMessenger] ancestor.
/// If there are several registered scaffolds the material banner is shown
/// simultaneously on all of them.
///
/// A scaffold can show at most one material banner at a time. If this function is
/// called while another material banner is already visible, the given material banner
/// will be added to a queue and displayed after the earlier material banners have
/// closed.
///
/// To remove the [MaterialBanner] with an exit animation, use [hideCurrentMaterialBanner]
/// or call [ScaffoldFeatureController.close] on the returned
/// [ScaffoldFeatureController]. To remove a [MaterialBanner] suddenly (without an
/// animation), use [removeCurrentMaterialBanner].
///
/// See [ScaffoldMessenger.of] for information about how to obtain the
/// [ScaffoldMessengerState].
///
/// {@tool dartpad}
/// Here is an example of showing a [MaterialBanner] when the user presses a button.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_messenger_state.show_material_banner.0.dart **
/// {@end-tool}
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>
showMaterialBanner(MaterialBanner materialBanner) {
assert(
_scaffolds.isNotEmpty,
'ScaffoldMessenger.showMaterialBanner was called, but there are currently no '
'descendant Scaffolds to present to.',
);
_materialBannerController ??=
MaterialBanner.createAnimationController(vsync: this)
..addStatusListener(_handleMaterialBannerStatusChanged);
if (_materialBanners.isEmpty) {
assert(_materialBannerController!.isDismissed);
_materialBannerController!.forward();
}
late ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>
controller;
controller =
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>._(
// We provide a fallback key so that if back-to-back material banners happen to
// match in structure, material ink splashes and highlights don't survive
// from one to the next.
materialBanner.withAnimation(_materialBannerController!,
fallbackKey: UniqueKey()),
Completer<MaterialBannerClosedReason>(),
() {
assert(_materialBanners.first == controller);
hideCurrentMaterialBanner();
},
null, // MaterialBanner doesn't use a builder function so setState() wouldn't rebuild it
);
setState(() {
_materialBanners.addLast(controller);
});
_updateScaffolds();
return controller;
}
void _handleMaterialBannerStatusChanged(AnimationStatus status) {
switch (status) {
case AnimationStatus.dismissed:
assert(_materialBanners.isNotEmpty);
setState(() {
_materialBanners.removeFirst();
});
_updateScaffolds();
if (_materialBanners.isNotEmpty) {
_materialBannerController!.forward();
}
case AnimationStatus.completed:
_updateScaffolds();
case AnimationStatus.forward:
break;
case AnimationStatus.reverse:
break;
}
}
/// Removes the current [MaterialBanner] (if any) immediately from registered
/// [MyScaffold]s.
///
/// The removed material banner does not run its normal exit animation. If there are
/// any queued material banners, they begin their entrance animation immediately.
void removeCurrentMaterialBanner(
{MaterialBannerClosedReason reason = MaterialBannerClosedReason.remove}) {
if (_materialBanners.isEmpty) {
return;
}
final Completer<MaterialBannerClosedReason> completer =
_materialBanners.first._completer;
if (!completer.isCompleted) {
completer.complete(reason);
}
// This will trigger the animation's status callback.
_materialBannerController!.value = 0.0;
}
/// Removes the current [MaterialBanner] by running its normal exit animation.
///
/// The closed completer is called after the animation is complete.
void hideCurrentMaterialBanner(
{MaterialBannerClosedReason reason = MaterialBannerClosedReason.hide}) {
if (_materialBanners.isEmpty ||
_materialBannerController!.status == AnimationStatus.dismissed) {
return;
}
final Completer<MaterialBannerClosedReason> completer =
_materialBanners.first._completer;
if (_accessibleNavigation!) {
_materialBannerController!.value = 0.0;
completer.complete(reason);
} else {
_materialBannerController!.reverse().then<void>((void value) {
assert(mounted);
if (!completer.isCompleted) {
completer.complete(reason);
}
});
}
}
/// Removes all the [MaterialBanner]s currently in queue by clearing the queue
/// and running normal exit animation on the current [MaterialBanner].
void clearMaterialBanners() {
if (_materialBanners.isEmpty ||
_materialBannerController!.status == AnimationStatus.dismissed) {
return;
}
final ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>
currentMaterialBanner = _materialBanners.first;
_materialBanners.clear();
_materialBanners.add(currentMaterialBanner);
hideCurrentMaterialBanner();
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
_accessibleNavigation = MediaQuery.accessibleNavigationOf(context);
if (_snackBars.isNotEmpty) {
final ModalRoute<dynamic>? route = ModalRoute.of(context);
if (route == null || route.isCurrent) {
if (_snackBarController!.isCompleted && _snackBarTimer == null) {
final SnackBar snackBar = _snackBars.first._widget;
_snackBarTimer = Timer(snackBar.duration, () {
assert(
_snackBarController!.status == AnimationStatus.forward ||
_snackBarController!.status == AnimationStatus.completed,
);
// Look up MediaQuery again in case the setting changed.
if (snackBar.action != null &&
MediaQuery.accessibleNavigationOf(context)) {
return;
}
hideCurrentSnackBar(reason: SnackBarClosedReason.timeout);
});
}
}
}
return _ScaffoldMessengerScope(
scaffoldMessengerState: this,
child: widget.child,
);
}
@override
void dispose() {
_snackBarController?.dispose();
_snackBarTimer?.cancel();
_snackBarTimer = null;
super.dispose();
}
}
class _ScaffoldMessengerScope extends InheritedWidget {
const _ScaffoldMessengerScope({
required super.child,
required ScaffoldMessengerState scaffoldMessengerState,
}) : _scaffoldMessengerState = scaffoldMessengerState;
final ScaffoldMessengerState _scaffoldMessengerState;
@override
bool updateShouldNotify(_ScaffoldMessengerScope old) =>
_scaffoldMessengerState != old._scaffoldMessengerState;
}
/// A snapshot of a transition between two [FloatingActionButtonLocation]s.
///
/// [MyScaffoldState] uses this to seamlessly change transition animations
/// when a running [FloatingActionButtonLocation] transition is interrupted by a new transition.
@immutable
class _TransitionSnapshotFabLocation extends FloatingActionButtonLocation {
const _TransitionSnapshotFabLocation(
this.begin, this.end, this.animator, this.progress);
final FloatingActionButtonLocation begin;
final FloatingActionButtonLocation end;
final FloatingActionButtonAnimator animator;
final double progress;
@override
Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
return animator.getOffset(
begin: begin.getOffset(scaffoldGeometry),
end: end.getOffset(scaffoldGeometry),
progress: progress,
);
}
@override
String toString() {
return '${objectRuntimeType(this, '_TransitionSnapshotFabLocation')}(begin: $begin, end: $end, progress: $progress)';
}
}
/// Geometry information for [MyScaffold] components after layout is finished.
///
/// To get a [ValueNotifier] for the scaffold geometry of a given
/// [BuildContext], use [MyScaffold.geometryOf].
///
/// The ScaffoldGeometry is only available during the paint phase, because
/// its value is computed during the animation and layout phases prior to painting.
///
/// For an example of using the [ScaffoldGeometry], see the [BottomAppBar],
/// which uses the [ScaffoldGeometry] to paint a notch around the
/// [FloatingActionButton].
///
/// For information about the [MyScaffold]'s geometry that is used while laying
/// out the [FloatingActionButton], see [ScaffoldPrelayoutGeometry].
@immutable
class ScaffoldGeometry {
/// Create an object that describes the geometry of a [MyScaffold].
const ScaffoldGeometry({
this.bottomNavigationBarTop,
this.floatingActionButtonArea,
});
/// The distance from the [MyScaffold]'s top edge to the top edge of the
/// rectangle in which the [MyScaffold.bottomNavigationBar] bar is laid out.
///
/// Null if [MyScaffold.bottomNavigationBar] is null.
final double? bottomNavigationBarTop;
/// The [MyScaffold.floatingActionButton]'s bounding rectangle.
///
/// This is null when there is no floating action button showing.
final Rect? floatingActionButtonArea;
ScaffoldGeometry _scaleFloatingActionButton(double scaleFactor) {
if (scaleFactor == 1.0) {
return this;
}
if (scaleFactor == 0.0) {
return ScaffoldGeometry(
bottomNavigationBarTop: bottomNavigationBarTop,
);
}
final Rect scaledButton = Rect.lerp(
floatingActionButtonArea!.center & Size.zero,
floatingActionButtonArea,
scaleFactor,
)!;
return copyWith(floatingActionButtonArea: scaledButton);
}
/// Creates a copy of this [ScaffoldGeometry] but with the given fields replaced with
/// the new values.
ScaffoldGeometry copyWith({
double? bottomNavigationBarTop,
Rect? floatingActionButtonArea,
}) {
return ScaffoldGeometry(
bottomNavigationBarTop:
bottomNavigationBarTop ?? this.bottomNavigationBarTop,
floatingActionButtonArea:
floatingActionButtonArea ?? this.floatingActionButtonArea,
);
}
}
class _ScaffoldGeometryNotifier extends ChangeNotifier
implements ValueListenable<ScaffoldGeometry> {
_ScaffoldGeometryNotifier(this.geometry, this.context);
final BuildContext context;
double? floatingActionButtonScale;
ScaffoldGeometry geometry;
@override
ScaffoldGeometry get value {
assert(() {
final RenderObject? renderObject = context.findRenderObject();
if (renderObject == null || !renderObject.owner!.debugDoingPaint) {
throw FlutterError(
'Scaffold.geometryOf() must only be accessed during the paint phase.\n'
'The ScaffoldGeometry is only available during the paint phase, because '
'its value is computed during the animation and layout phases prior to painting.',
);
}
return true;
}());
return geometry._scaleFloatingActionButton(floatingActionButtonScale!);
}
void _updateWith({
double? bottomNavigationBarTop,
Rect? floatingActionButtonArea,
double? floatingActionButtonScale,
}) {
this.floatingActionButtonScale =
floatingActionButtonScale ?? this.floatingActionButtonScale;
geometry = geometry.copyWith(
bottomNavigationBarTop: bottomNavigationBarTop,
floatingActionButtonArea: floatingActionButtonArea,
);
notifyListeners();
}
}
// Used to communicate the height of the Scaffold's bottomNavigationBar and
// persistentFooterButtons to the LayoutBuilder which builds the Scaffold's body.
//
// Scaffold expects a _BodyBoxConstraints to be passed to the _BodyBuilder
// widget's LayoutBuilder, see _ScaffoldLayout.performLayout(). The BoxConstraints
// methods that construct new BoxConstraints objects, like copyWith() have not
// been overridden here because we expect the _BodyBoxConstraintsObject to be
// passed along unmodified to the LayoutBuilder. If that changes in the future
// then _BodyBuilder will assert.
class _BodyBoxConstraints extends BoxConstraints {
const _BodyBoxConstraints({
super.maxWidth,
super.maxHeight,
required this.bottomWidgetsHeight,
required this.appBarHeight,
required this.materialBannerHeight,
}) : assert(bottomWidgetsHeight >= 0),
assert(appBarHeight >= 0),
assert(materialBannerHeight >= 0);
final double bottomWidgetsHeight;
final double appBarHeight;
final double materialBannerHeight;
// RenderObject.layout() will only short-circuit its call to its performLayout
// method if the new layout constraints are not == to the current constraints.
// If the height of the bottom widgets has changed, even though the constraints'
// min and max values have not, we still want performLayout to happen.
@override
bool operator ==(Object other) {
if (super != other) {
return false;
}
return other is _BodyBoxConstraints &&
other.materialBannerHeight == materialBannerHeight &&
other.bottomWidgetsHeight == bottomWidgetsHeight &&
other.appBarHeight == appBarHeight;
}
@override
int get hashCode => Object.hash(
super.hashCode, materialBannerHeight, bottomWidgetsHeight, appBarHeight);
}
// Used when Scaffold.extendBody is true to wrap the scaffold's body in a MediaQuery
// whose padding accounts for the height of the bottomNavigationBar and/or the
// persistentFooterButtons.
//
// The bottom widgets' height is passed along via the _BodyBoxConstraints parameter.
// The constraints parameter is constructed in_ScaffoldLayout.performLayout().
class _BodyBuilder extends StatelessWidget {
const _BodyBuilder({
required this.extendBody,
required this.extendBodyBehindAppBar,
required this.body,
});
final Widget body;
final bool extendBody;
final bool extendBodyBehindAppBar;
@override
Widget build(BuildContext context) {
if (!extendBody && !extendBodyBehindAppBar) {
return body;
}
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final _BodyBoxConstraints bodyConstraints =
constraints as _BodyBoxConstraints;
final MediaQueryData metrics = MediaQuery.of(context);
final double bottom = extendBody
? math.max(
metrics.padding.bottom, bodyConstraints.bottomWidgetsHeight)
: metrics.padding.bottom;
final double top = extendBodyBehindAppBar
? math.max(
metrics.padding.top,
bodyConstraints.appBarHeight +
bodyConstraints.materialBannerHeight)
: metrics.padding.top;
return MediaQuery(
data: metrics.copyWith(
padding: metrics.padding.copyWith(
top: top,
bottom: bottom,
),
),
child: body,
);
},
);
}
}
class _ScaffoldLayout extends MultiChildLayoutDelegate {
_ScaffoldLayout({
required this.minInsets,
required this.minViewPadding,
required this.textDirection,
required this.geometryNotifier,
// for floating action button
required this.previousFloatingActionButtonLocation,
required this.currentFloatingActionButtonLocation,
required this.floatingActionButtonMoveAnimationProgress,
required this.floatingActionButtonMotionAnimator,
required this.isSnackBarFloating,
required this.snackBarWidth,
required this.extendBody,
required this.extendBodyBehindAppBar,
required this.extendBodyBehindMaterialBanner,
});
final bool extendBody;
final bool extendBodyBehindAppBar;
final EdgeInsets minInsets;
final EdgeInsets minViewPadding;
final TextDirection textDirection;
final _ScaffoldGeometryNotifier geometryNotifier;
final FloatingActionButtonLocation previousFloatingActionButtonLocation;
final FloatingActionButtonLocation currentFloatingActionButtonLocation;
final double floatingActionButtonMoveAnimationProgress;
final FloatingActionButtonAnimator floatingActionButtonMotionAnimator;
final bool isSnackBarFloating;
final double? snackBarWidth;
final bool extendBodyBehindMaterialBanner;
@override
void performLayout(Size size) {
final BoxConstraints looseConstraints = BoxConstraints.loose(size);
// This part of the layout has the same effect as putting the app bar and
// body in a column and making the body flexible. What's different is that
// in this case the app bar appears _after_ the body in the stacking order,
// so the app bar's shadow is drawn on top of the body.
final BoxConstraints fullWidthConstraints =
looseConstraints.tighten(width: size.width);
final double bottom = size.height;
double contentTop = 0.0;
double bottomWidgetsHeight = 0.0;
double appBarHeight = 0.0;
if (hasChild(_ScaffoldSlot.appBar)) {
appBarHeight =
layoutChild(_ScaffoldSlot.appBar, fullWidthConstraints).height;
contentTop = extendBodyBehindAppBar ? 0.0 : appBarHeight;
positionChild(_ScaffoldSlot.appBar, Offset.zero);
}
double? bottomNavigationBarTop;
if (hasChild(_ScaffoldSlot.bottomNavigationBar)) {
final double bottomNavigationBarHeight =
layoutChild(_ScaffoldSlot.bottomNavigationBar, fullWidthConstraints)
.height;
bottomWidgetsHeight += bottomNavigationBarHeight;
bottomNavigationBarTop = math.max(0.0, bottom - bottomWidgetsHeight);
positionChild(_ScaffoldSlot.bottomNavigationBar,
Offset(0.0, bottomNavigationBarTop));
}
if (hasChild(_ScaffoldSlot.persistentFooter)) {
final BoxConstraints footerConstraints = BoxConstraints(
maxWidth: fullWidthConstraints.maxWidth,
maxHeight: math.max(0.0, bottom - bottomWidgetsHeight - contentTop),
);
final double persistentFooterHeight =
layoutChild(_ScaffoldSlot.persistentFooter, footerConstraints).height;
bottomWidgetsHeight += persistentFooterHeight;
positionChild(_ScaffoldSlot.persistentFooter,
Offset(0.0, math.max(0.0, bottom - bottomWidgetsHeight)));
}
Size materialBannerSize = Size.zero;
if (hasChild(_ScaffoldSlot.materialBanner)) {
materialBannerSize =
layoutChild(_ScaffoldSlot.materialBanner, fullWidthConstraints);
positionChild(_ScaffoldSlot.materialBanner, Offset(0.0, appBarHeight));
// Push content down only if elevation is 0.
if (!extendBodyBehindMaterialBanner) {
contentTop += materialBannerSize.height;
}
}
// Set the content bottom to account for the greater of the height of any
// bottom-anchored material widgets or of the keyboard or other
// bottom-anchored system UI.
final double contentBottom =
math.max(0.0, bottom - math.max(minInsets.bottom, bottomWidgetsHeight));
if (hasChild(_ScaffoldSlot.body)) {
double bodyMaxHeight = math.max(0.0, contentBottom - contentTop);
if (extendBody) {
bodyMaxHeight += bottomWidgetsHeight;
bodyMaxHeight = clampDouble(
bodyMaxHeight, 0.0, looseConstraints.maxHeight - contentTop);
assert(bodyMaxHeight <=
math.max(0.0, looseConstraints.maxHeight - contentTop));
}
final BoxConstraints bodyConstraints = _BodyBoxConstraints(
maxWidth: fullWidthConstraints.maxWidth,
maxHeight: bodyMaxHeight,
materialBannerHeight: materialBannerSize.height,
bottomWidgetsHeight: extendBody ? bottomWidgetsHeight : 0.0,
appBarHeight: appBarHeight,
);
layoutChild(_ScaffoldSlot.body, bodyConstraints);
positionChild(_ScaffoldSlot.body, Offset(0.0, contentTop));
}
// The BottomSheet and the SnackBar are anchored to the bottom of the parent,
// they're as wide as the parent and are given their intrinsic height. The
// only difference is that SnackBar appears on the top side of the
// BottomNavigationBar while the BottomSheet is stacked on top of it.
//
// If all three elements are present then either the center of the FAB straddles
// the top edge of the BottomSheet or the bottom of the FAB is
// kFloatingActionButtonMargin above the SnackBar, whichever puts the FAB
// the farthest above the bottom of the parent. If only the FAB is has a
// non-zero height then it's inset from the parent's right and bottom edges
// by kFloatingActionButtonMargin.
Size bottomSheetSize = Size.zero;
Size snackBarSize = Size.zero;
if (hasChild(_ScaffoldSlot.bodyScrim)) {
final BoxConstraints bottomSheetScrimConstraints = BoxConstraints(
maxWidth: fullWidthConstraints.maxWidth,
maxHeight: contentBottom,
);
layoutChild(_ScaffoldSlot.bodyScrim, bottomSheetScrimConstraints);
positionChild(_ScaffoldSlot.bodyScrim, Offset.zero);
}
// Set the size of the SnackBar early if the behavior is fixed so
// the FAB can be positioned correctly.
if (hasChild(_ScaffoldSlot.snackBar) && !isSnackBarFloating) {
snackBarSize = layoutChild(_ScaffoldSlot.snackBar, fullWidthConstraints);
}
if (hasChild(_ScaffoldSlot.bottomSheet)) {
final BoxConstraints bottomSheetConstraints = BoxConstraints(
maxWidth: fullWidthConstraints.maxWidth,
maxHeight: math.max(0.0, contentBottom - contentTop),
);
bottomSheetSize =
layoutChild(_ScaffoldSlot.bottomSheet, bottomSheetConstraints);
positionChild(
_ScaffoldSlot.bottomSheet,
Offset((size.width - bottomSheetSize.width) / 2.0,
contentBottom - bottomSheetSize.height));
}
late Rect floatingActionButtonRect;
if (hasChild(_ScaffoldSlot.floatingActionButton)) {
final Size fabSize =
layoutChild(_ScaffoldSlot.floatingActionButton, looseConstraints);
// To account for the FAB position being changed, we'll animate between
// the old and new positions.
final ScaffoldPrelayoutGeometry currentGeometry =
ScaffoldPrelayoutGeometry(
bottomSheetSize: bottomSheetSize,
contentBottom: contentBottom,
/// [appBarHeight] should be used instead of [contentTop] because
/// ScaffoldPrelayoutGeometry.contentTop must not be affected by [extendBodyBehindAppBar].
contentTop: appBarHeight,
floatingActionButtonSize: fabSize,
minInsets: minInsets,
scaffoldSize: size,
snackBarSize: snackBarSize,
materialBannerSize: materialBannerSize,
textDirection: textDirection,
minViewPadding: minViewPadding,
);
final Offset currentFabOffset =
currentFloatingActionButtonLocation.getOffset(currentGeometry);
final Offset previousFabOffset =
previousFloatingActionButtonLocation.getOffset(currentGeometry);
final Offset fabOffset = floatingActionButtonMotionAnimator.getOffset(
begin: previousFabOffset,
end: currentFabOffset,
progress: floatingActionButtonMoveAnimationProgress,
);
positionChild(_ScaffoldSlot.floatingActionButton, fabOffset);
floatingActionButtonRect = fabOffset & fabSize;
}
if (hasChild(_ScaffoldSlot.snackBar)) {
final bool hasCustomWidth =
snackBarWidth != null && snackBarWidth! < size.width;
if (snackBarSize == Size.zero) {
snackBarSize = layoutChild(
_ScaffoldSlot.snackBar,
hasCustomWidth ? looseConstraints : fullWidthConstraints,
);
}
final double snackBarYOffsetBase;
if (floatingActionButtonRect.size != Size.zero && isSnackBarFloating) {
snackBarYOffsetBase = floatingActionButtonRect.top;
} else {
// SnackBarBehavior.fixed applies a SafeArea automatically.
// SnackBarBehavior.floating does not since the positioning is affected
// if there is a FloatingActionButton (see condition above). If there is
// no FAB, make sure we account for safe space when the SnackBar is
// floating.
final double safeYOffsetBase = size.height - minViewPadding.bottom;
snackBarYOffsetBase = isSnackBarFloating
? math.min(contentBottom, safeYOffsetBase)
: contentBottom;
}
final double xOffset =
hasCustomWidth ? (size.width - snackBarWidth!) / 2 : 0.0;
positionChild(_ScaffoldSlot.snackBar,
Offset(xOffset, snackBarYOffsetBase - snackBarSize.height));
assert(() {
// Whether a floating SnackBar has been offset too high.
//
// To improve the developer experience, this assert is done after the call to positionChild.
// if we assert sooner the SnackBar is visible because its defaults position is (0,0) and
// it can cause confusion to the user as the error message states that the SnackBar is off screen.
if (isSnackBarFloating) {
final bool snackBarVisible =
(snackBarYOffsetBase - snackBarSize.height) >= 0;
if (!snackBarVisible) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Floating SnackBar presented off screen.'),
ErrorDescription(
'A SnackBar with behavior property set to SnackBarBehavior.floating is fully '
'or partially off screen because some or all the widgets provided to '
'Scaffold.floatingActionButton, Scaffold.persistentFooterButtons and '
'Scaffold.bottomNavigationBar take up too much vertical space.\n'),
ErrorHint(
'Consider constraining the size of these widgets to allow room for the SnackBar to be visible.',
),
]);
}
}
return true;
}());
}
if (hasChild(_ScaffoldSlot.statusBar)) {
layoutChild(_ScaffoldSlot.statusBar,
fullWidthConstraints.tighten(height: minInsets.top));
positionChild(_ScaffoldSlot.statusBar, Offset.zero);
}
if (hasChild(_ScaffoldSlot.drawer)) {
layoutChild(_ScaffoldSlot.drawer, BoxConstraints.tight(size));
positionChild(_ScaffoldSlot.drawer, Offset.zero);
}
if (hasChild(_ScaffoldSlot.endDrawer)) {
layoutChild(_ScaffoldSlot.endDrawer, BoxConstraints.tight(size));
positionChild(_ScaffoldSlot.endDrawer, Offset.zero);
}
geometryNotifier._updateWith(
bottomNavigationBarTop: bottomNavigationBarTop,
floatingActionButtonArea: floatingActionButtonRect,
);
}
@override
bool shouldRelayout(_ScaffoldLayout oldDelegate) {
return oldDelegate.minInsets != minInsets ||
oldDelegate.minViewPadding != minViewPadding ||
oldDelegate.textDirection != textDirection ||
oldDelegate.floatingActionButtonMoveAnimationProgress !=
floatingActionButtonMoveAnimationProgress ||
oldDelegate.previousFloatingActionButtonLocation !=
previousFloatingActionButtonLocation ||
oldDelegate.currentFloatingActionButtonLocation !=
currentFloatingActionButtonLocation ||
oldDelegate.extendBody != extendBody ||
oldDelegate.extendBodyBehindAppBar != extendBodyBehindAppBar;
}
}
/// Handler for scale and rotation animations in the [FloatingActionButton].
///
/// Currently, there are two types of [FloatingActionButton] animations:
///
/// * Entrance/Exit animations, which this widget triggers
/// when the [FloatingActionButton] is added, updated, or removed.
/// * Motion animations, which are triggered by the [MyScaffold]
/// when its [FloatingActionButtonLocation] is updated.
class _FloatingActionButtonTransition extends StatefulWidget {
const _FloatingActionButtonTransition({
required this.child,
required this.fabMoveAnimation,
required this.fabMotionAnimator,
required this.geometryNotifier,
required this.currentController,
});
final Widget? child;
final Animation<double> fabMoveAnimation;
final FloatingActionButtonAnimator fabMotionAnimator;
final _ScaffoldGeometryNotifier geometryNotifier;
/// Controls the current child widget.child as it exits.
final AnimationController currentController;
@override
_FloatingActionButtonTransitionState createState() =>
_FloatingActionButtonTransitionState();
}
class _FloatingActionButtonTransitionState
extends State<_FloatingActionButtonTransition>
with TickerProviderStateMixin {
// The animations applied to the Floating Action Button when it is entering or exiting.
// Controls the previous widget.child as it exits.
late AnimationController _previousController;
late Animation<double> _previousScaleAnimation;
late Animation<double> _previousRotationAnimation;
// The animations to run, considering the widget's fabMoveAnimation and the current/previous entrance/exit animations.
late Animation<double> _currentScaleAnimation;
late Animation<double> _extendedCurrentScaleAnimation;
late Animation<double> _currentRotationAnimation;
Widget? _previousChild;
@override
void initState() {
super.initState();
_previousController = AnimationController(
duration: kFloatingActionButtonSegue,
vsync: this,
)..addStatusListener(_handlePreviousAnimationStatusChanged);
_updateAnimations();
if (widget.child != null) {
// If we start out with a child, have the child appear fully visible instead
// of animating in.
widget.currentController.value = 1.0;
} else {
// If we start without a child we update the geometry object with a
// floating action button scale of 0, as it is not showing on the screen.
_updateGeometryScale(0.0);
}
}
@override
void dispose() {
_previousController.dispose();
super.dispose();
}
@override
void didUpdateWidget(_FloatingActionButtonTransition oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.fabMotionAnimator != widget.fabMotionAnimator ||
oldWidget.fabMoveAnimation != widget.fabMoveAnimation) {
// Get the right scale and rotation animations to use for this widget.
_updateAnimations();
}
final bool oldChildIsNull = oldWidget.child == null;
final bool newChildIsNull = widget.child == null;
if (oldChildIsNull == newChildIsNull &&
oldWidget.child?.key == widget.child?.key) {
return;
}
if (_previousController.status == AnimationStatus.dismissed) {
final double currentValue = widget.currentController.value;
if (currentValue == 0.0 || oldWidget.child == null) {
// The current child hasn't started its entrance animation yet. We can
// just skip directly to the new child's entrance.
_previousChild = null;
if (widget.child != null) {
widget.currentController.forward();
}
} else {
// Otherwise, we need to copy the state from the current controller to
// the previous controller and run an exit animation for the previous
// widget before running the entrance animation for the new child.
_previousChild = oldWidget.child;
_previousController
..value = currentValue
..reverse();
widget.currentController.value = 0.0;
}
}
}
static final Animatable<double> _entranceTurnTween = Tween<double>(
begin: 1.0 - kFloatingActionButtonTurnInterval,
end: 1.0,
).chain(CurveTween(curve: Curves.easeIn));
void _updateAnimations() {
// Get the animations for exit and entrance.
final CurvedAnimation previousExitScaleAnimation = CurvedAnimation(
parent: _previousController,
curve: Curves.easeIn,
);
final Animation<double> previousExitRotationAnimation =
Tween<double>(begin: 1.0, end: 1.0).animate(
CurvedAnimation(
parent: _previousController,
curve: Curves.easeIn,
),
);
final CurvedAnimation currentEntranceScaleAnimation = CurvedAnimation(
parent: widget.currentController,
curve: Curves.easeIn,
);
final Animation<double> currentEntranceRotationAnimation =
widget.currentController.drive(_entranceTurnTween);
// Get the animations for when the FAB is moving.
final Animation<double> moveScaleAnimation = widget.fabMotionAnimator
.getScaleAnimation(parent: widget.fabMoveAnimation);
final Animation<double> moveRotationAnimation = widget.fabMotionAnimator
.getRotationAnimation(parent: widget.fabMoveAnimation);
// Aggregate the animations.
_previousScaleAnimation =
AnimationMin<double>(moveScaleAnimation, previousExitScaleAnimation);
_currentScaleAnimation =
AnimationMin<double>(moveScaleAnimation, currentEntranceScaleAnimation);
_extendedCurrentScaleAnimation = _currentScaleAnimation
.drive(CurveTween(curve: const Interval(0.0, 0.1)));
_previousRotationAnimation = TrainHoppingAnimation(
previousExitRotationAnimation, moveRotationAnimation);
_currentRotationAnimation = TrainHoppingAnimation(
currentEntranceRotationAnimation, moveRotationAnimation);
_currentScaleAnimation.addListener(_onProgressChanged);
_previousScaleAnimation.addListener(_onProgressChanged);
}
void _handlePreviousAnimationStatusChanged(AnimationStatus status) {
setState(() {
if (widget.child != null && status == AnimationStatus.dismissed) {
assert(widget.currentController.status == AnimationStatus.dismissed);
widget.currentController.forward();
}
});
}
bool _isExtendedFloatingActionButton(Widget? widget) {
return widget is FloatingActionButton && widget.isExtended;
}
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.centerRight,
children: <Widget>[
if (_previousController.status != AnimationStatus.dismissed)
if (_isExtendedFloatingActionButton(_previousChild))
FadeTransition(
opacity: _previousScaleAnimation,
child: _previousChild,
)
else
ScaleTransition(
scale: _previousScaleAnimation,
child: RotationTransition(
turns: _previousRotationAnimation,
child: _previousChild,
),
),
if (_isExtendedFloatingActionButton(widget.child))
ScaleTransition(
scale: _extendedCurrentScaleAnimation,
child: FadeTransition(
opacity: _currentScaleAnimation,
child: widget.child,
),
)
else
ScaleTransition(
scale: _currentScaleAnimation,
child: RotationTransition(
turns: _currentRotationAnimation,
child: widget.child,
),
),
],
);
}
void _onProgressChanged() {
_updateGeometryScale(
math.max(_previousScaleAnimation.value, _currentScaleAnimation.value));
}
void _updateGeometryScale(double scale) {
widget.geometryNotifier._updateWith(
floatingActionButtonScale: scale,
);
}
}
/// Implements the basic Material Design visual layout structure.
///
/// This class provides APIs for showing drawers and bottom sheets.
///
/// To display a persistent bottom sheet, obtain the
/// [MyScaffoldState] for the current [BuildContext] via [MyScaffold.of] and use the
/// [MyScaffoldState.showBottomSheet] function.
///
/// {@tool dartpad}
/// This example shows a [MyScaffold] with a [body] and [FloatingActionButton].
/// The [body] is a [Text] placed in a [Center] in order to center the text
/// within the [MyScaffold]. The [FloatingActionButton] is connected to a
/// callback that increments a counter.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows a [MyScaffold] with a blueGrey [backgroundColor], [body]
/// and [FloatingActionButton]. The [body] is a [Text] placed in a [Center] in
/// order to center the text within the [MyScaffold]. The [FloatingActionButton]
/// is connected to a callback that increments a counter.
///
/// 
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.1.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows a [MyScaffold] with an [AppBar], a [BottomAppBar] and a
/// [FloatingActionButton]. The [body] is a [Text] placed in a [Center] in order
/// to center the text within the [MyScaffold]. The [FloatingActionButton] is
/// centered and docked within the [BottomAppBar] using
/// [FloatingActionButtonLocation.centerDocked]. The [FloatingActionButton] is
/// connected to a callback that increments a counter.
///
/// 
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.2.dart **
/// {@end-tool}
///
/// ## Scaffold layout, the keyboard, and display "notches"
///
/// The scaffold will expand to fill the available space. That usually
/// means that it will occupy its entire window or device screen. When
/// the device's keyboard appears the Scaffold's ancestor [MediaQuery]
/// widget's [MediaQueryData.viewInsets] changes and the Scaffold will
/// be rebuilt. By default the scaffold's [body] is resized to make
/// room for the keyboard. To prevent the resize set
/// [resizeToAvoidBottomInset] to false. In either case the focused
/// widget will be scrolled into view if it's within a scrollable
/// container.
///
/// The [MediaQueryData.padding] value defines areas that might
/// not be completely visible, like the display "notch" on the iPhone
/// X. The scaffold's [body] is not inset by this padding value
/// although an [appBar] or [bottomNavigationBar] will typically
/// cause the body to avoid the padding. The [SafeArea]
/// widget can be used within the scaffold's body to avoid areas
/// like display notches.
///
/// ## Floating action button with a draggable scrollable bottom sheet
///
/// If [MyScaffold.bottomSheet] is a [DraggableScrollableSheet],
/// [MyScaffold.floatingActionButton] is set, and the bottom sheet is dragged to
/// cover greater than 70% of the Scaffold's height, two things happen in parallel:
///
/// * Scaffold starts to show scrim (see [MyScaffoldState.showBodyScrim]), and
/// * [MyScaffold.floatingActionButton] is scaled down through an animation with a [Curves.easeIn], and
/// disappears when the bottom sheet covers the entire Scaffold.
///
/// And as soon as the bottom sheet is dragged down to cover less than 70% of the [MyScaffold], the scrim
/// disappears and [MyScaffold.floatingActionButton] animates back to its normal size.
///
/// ## Troubleshooting
///
/// ### Nested Scaffolds
///
/// The Scaffold is designed to be a top level container for
/// a [MaterialApp]. This means that adding a Scaffold
/// to each route on a Material app will provide the app with
/// Material's basic visual layout structure.
///
/// It is typically not necessary to nest Scaffolds. For example, in a
/// tabbed UI, where the [bottomNavigationBar] is a [TabBar]
/// and the body is a [TabBarView], you might be tempted to make each tab bar
/// view a scaffold with a differently titled AppBar. Rather, it would be
/// better to add a listener to the [TabController] that updates the
/// AppBar
///
/// {@tool snippet}
/// Add a listener to the app's tab controller so that the [AppBar] title of the
/// app's one and only scaffold is reset each time a new tab is selected.
///
/// ```dart
/// TabController(vsync: tickerProvider, length: tabCount)..addListener(() {
/// if (!tabController.indexIsChanging) {
/// setState(() {
/// // Rebuild the enclosing scaffold with a new AppBar title
/// appBarTitle = 'Tab ${tabController.index}';
/// });
/// }
/// })
/// ```
/// {@end-tool}
///
/// Although there are some use cases, like a presentation app that
/// shows embedded flutter content, where nested scaffolds are
/// appropriate, it's best to avoid nesting scaffolds.
///
/// See also:
///
/// * [AppBar], which is a horizontal bar typically shown at the top of an app
/// using the [appBar] property.
/// * [BottomAppBar], which is a horizontal bar typically shown at the bottom
/// of an app using the [bottomNavigationBar] property.
/// * [FloatingActionButton], which is a circular button typically shown in the
/// bottom right corner of the app using the [floatingActionButton] property.
/// * [Drawer], which is a vertical panel that is typically displayed to the
/// left of the body (and often hidden on phones) using the [drawer]
/// property.
/// * [BottomNavigationBar], which is a horizontal array of buttons typically
/// shown along the bottom of the app using the [bottomNavigationBar]
/// property.
/// * [BottomSheet], which is an overlay typically shown near the bottom of the
/// app. A bottom sheet can either be persistent, in which case it is shown
/// using the [MyScaffoldState.showBottomSheet] method, or modal, in which case
/// it is shown using the [showModalBottomSheet] function.
/// * [SnackBar], which is a lightweight message with an optional action which
/// briefly displays at the bottom of the screen. Use the
/// [ScaffoldMessengerState.showSnackBar] method to show snack bars.
/// * [MaterialBanner], which displays an important, succinct message, at the
/// top of the screen, below the app bar. Use the
/// [ScaffoldMessengerState.showMaterialBanner] method to show material banners.
/// * [MyScaffoldState], which is the state associated with this widget.
/// * <https://material.io/design/layout/responsive-layout-grid.html>
/// * Cookbook: [Add a Drawer to a screen](https://flutter.dev/docs/cookbook/design/drawer)
class MyScaffold extends StatefulWidget {
/// Creates a visual scaffold for Material Design widgets.
const MyScaffold({
super.key,
this.appBar,
this.body,
this.floatingActionButton,
this.floatingActionButtonLocation,
this.floatingActionButtonAnimator,
this.persistentFooterButtons,
this.persistentFooterAlignment = AlignmentDirectional.centerEnd,
this.drawer,
this.onDrawerChanged,
this.endDrawer,
this.onEndDrawerChanged,
this.bottomNavigationBar,
this.bottomSheet,
this.backgroundColor,
this.resizeToAvoidBottomInset,
this.primary = true,
this.drawerDragStartBehavior = DragStartBehavior.start,
this.extendBody = false,
this.extendBodyBehindAppBar = false,
this.drawerScrimColor,
this.drawerEdgeDragWidth,
this.drawerEnableOpenDragGesture = true,
this.endDrawerEnableOpenDragGesture = true,
this.restorationId,
this.customAnimationController,
});
/// If true, and [bottomNavigationBar] or [persistentFooterButtons]
/// is specified, then the [body] extends to the bottom of the Scaffold,
/// instead of only extending to the top of the [bottomNavigationBar]
/// or the [persistentFooterButtons].
///
/// If true, a [MediaQuery] widget whose bottom padding matches the height
/// of the [bottomNavigationBar] will be added above the scaffold's [body].
///
/// This property is often useful when the [bottomNavigationBar] has
/// a non-rectangular shape, like [CircularNotchedRectangle], which
/// adds a [FloatingActionButton] sized notch to the top edge of the bar.
/// In this case specifying `extendBody: true` ensures that scaffold's
/// body will be visible through the bottom navigation bar's notch.
///
/// See also:
///
/// * [extendBodyBehindAppBar], which extends the height of the body
/// to the top of the scaffold.
final bool extendBody;
/// If true, and an [appBar] is specified, then the height of the [body] is
/// extended to include the height of the app bar and the top of the body
/// is aligned with the top of the app bar.
///
/// This is useful if the app bar's [AppBar.backgroundColor] is not
/// completely opaque.
///
/// This property is false by default. It must not be null.
///
/// See also:
///
/// * [extendBody], which extends the height of the body to the bottom
/// of the scaffold.
final bool extendBodyBehindAppBar;
/// An app bar to display at the top of the scaffold.
final PreferredSizeWidget? appBar;
/// The primary content of the scaffold.
///
/// Displayed below the [appBar], above the bottom of the ambient
/// [MediaQuery]'s [MediaQueryData.viewInsets], and behind the
/// [floatingActionButton] and [drawer]. If [resizeToAvoidBottomInset] is
/// false then the body is not resized when the onscreen keyboard appears,
/// i.e. it is not inset by `viewInsets.bottom`.
///
/// The widget in the body of the scaffold is positioned at the top-left of
/// the available space between the app bar and the bottom of the scaffold. To
/// center this widget instead, consider putting it in a [Center] widget and
/// having that be the body. To expand this widget instead, consider
/// putting it in a [SizedBox.expand].
///
/// If you have a column of widgets that should normally fit on the screen,
/// but may overflow and would in such cases need to scroll, consider using a
/// [ListView] as the body of the scaffold. This is also a good choice for
/// the case where your body is a scrollable list.
final Widget? body;
/// A button displayed floating above [body], in the bottom right corner.
///
/// Typically a [FloatingActionButton].
final Widget? floatingActionButton;
/// Responsible for determining where the [floatingActionButton] should go.
///
/// If null, the [MyScaffoldState] will use the default location, [FloatingActionButtonLocation.endFloat].
final FloatingActionButtonLocation? floatingActionButtonLocation;
/// Animator to move the [floatingActionButton] to a new [floatingActionButtonLocation].
///
/// If null, the [MyScaffoldState] will use the default animator, [FloatingActionButtonAnimator.scaling].
final FloatingActionButtonAnimator? floatingActionButtonAnimator;
/// A set of buttons that are displayed at the bottom of the scaffold.
///
/// Typically this is a list of [TextButton] widgets. These buttons are
/// persistently visible, even if the [body] of the scaffold scrolls.
///
/// These widgets will be wrapped in an [OverflowBar].
///
/// The [persistentFooterButtons] are rendered above the
/// [bottomNavigationBar] but below the [body].
final List<Widget>? persistentFooterButtons;
/// The alignment of the [persistentFooterButtons] inside the [OverflowBar].
///
/// Defaults to [AlignmentDirectional.centerEnd].
final AlignmentDirectional persistentFooterAlignment;
/// A panel displayed to the side of the [body], often hidden on mobile
/// devices. Swipes in from either left-to-right ([TextDirection.ltr]) or
/// right-to-left ([TextDirection.rtl])
///
/// Typically a [Drawer].
///
/// To open the drawer, use the [MyScaffoldState.openDrawer] function.
///
/// To close the drawer, use either [MyScaffoldState.closeDrawer], [Navigator.pop]
/// or press the escape key on the keyboard.
///
/// {@tool dartpad}
/// To disable the drawer edge swipe on mobile, set the
/// [MyScaffold.drawerEnableOpenDragGesture] to false. Then, use
/// [MyScaffoldState.openDrawer] to open the drawer and [Navigator.pop] to close
/// it.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.drawer.0.dart **
/// {@end-tool}
final Widget? drawer;
/// Optional callback that is called when the [MyScaffold.drawer] is opened or closed.
final DrawerCallback? onDrawerChanged;
final AnimationController? customAnimationController;
/// A panel displayed to the side of the [body], often hidden on mobile
/// devices. Swipes in from right-to-left ([TextDirection.ltr]) or
/// left-to-right ([TextDirection.rtl])
///
/// Typically a [Drawer].
///
/// To open the drawer, use the [MyScaffoldState.openEndDrawer] function.
///
/// To close the drawer, use either [MyScaffoldState.closeEndDrawer], [Navigator.pop]
/// or press the escape key on the keyboard.
///
/// {@tool dartpad}
/// To disable the drawer edge swipe, set the
/// [MyScaffold.endDrawerEnableOpenDragGesture] to false. Then, use
/// [MyScaffoldState.openEndDrawer] to open the drawer and [Navigator.pop] to
/// close it.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.end_drawer.0.dart **
/// {@end-tool}
final Widget? endDrawer;
/// Optional callback that is called when the [MyScaffold.endDrawer] is opened or closed.
final DrawerCallback? onEndDrawerChanged;
/// The color to use for the scrim that obscures primary content while a drawer is open.
///
/// If this is null, then [DrawerThemeData.scrimColor] is used. If that
/// is also null, then it defaults to [Colors.black54].
final Color? drawerScrimColor;
/// The color of the [Material] widget that underlies the entire Scaffold.
///
/// The theme's [ThemeData.scaffoldBackgroundColor] by default.
final Color? backgroundColor;
/// A bottom navigation bar to display at the bottom of the scaffold.
///
/// Snack bars slide from underneath the bottom navigation bar while bottom
/// sheets are stacked on top.
///
/// The [bottomNavigationBar] is rendered below the [persistentFooterButtons]
/// and the [body].
final Widget? bottomNavigationBar;
/// The persistent bottom sheet to display.
///
/// A persistent bottom sheet shows information that supplements the primary
/// content of the app. A persistent bottom sheet remains visible even when
/// the user interacts with other parts of the app.
///
/// A closely related widget is a modal bottom sheet, which is an alternative
/// to a menu or a dialog and prevents the user from interacting with the rest
/// of the app. Modal bottom sheets can be created and displayed with the
/// [showModalBottomSheet] function.
///
/// Unlike the persistent bottom sheet displayed by [showBottomSheet]
/// this bottom sheet is not a [LocalHistoryEntry] and cannot be dismissed
/// with the scaffold appbar's back button.
///
/// If a persistent bottom sheet created with [showBottomSheet] is already
/// visible, it must be closed before building the Scaffold with a new
/// [bottomSheet].
///
/// The value of [bottomSheet] can be any widget at all. It's unlikely to
/// actually be a [BottomSheet], which is used by the implementations of
/// [showBottomSheet] and [showModalBottomSheet]. Typically it's a widget
/// that includes [Material].
///
/// See also:
///
/// * [showBottomSheet], which displays a bottom sheet as a route that can
/// be dismissed with the scaffold's back button.
/// * [showModalBottomSheet], which displays a modal bottom sheet.
/// * [BottomSheetThemeData], which can be used to customize the default
/// bottom sheet property values when using a [BottomSheet].
final Widget? bottomSheet;
/// If true the [body] and the scaffold's floating widgets should size
/// themselves to avoid the onscreen keyboard whose height is defined by the
/// ambient [MediaQuery]'s [MediaQueryData.viewInsets] `bottom` property.
///
/// For example, if there is an onscreen keyboard displayed above the
/// scaffold, the body can be resized to avoid overlapping the keyboard, which
/// prevents widgets inside the body from being obscured by the keyboard.
///
/// Defaults to true.
final bool? resizeToAvoidBottomInset;
/// Whether this scaffold is being displayed at the top of the screen.
///
/// If true then the height of the [appBar] will be extended by the height
/// of the screen's status bar, i.e. the top padding for [MediaQuery].
///
/// The default value of this property, like the default value of
/// [AppBar.primary], is true.
final bool primary;
/// {@macro flutter.material.DrawerController.dragStartBehavior}
final DragStartBehavior drawerDragStartBehavior;
/// The width of the area within which a horizontal swipe will open the
/// drawer.
///
/// By default, the value used is 20.0 added to the padding edge of
/// `MediaQuery.paddingOf(context)` that corresponds to the surrounding
/// [TextDirection]. This ensures that the drag area for notched devices is
/// not obscured. For example, if `TextDirection.of(context)` is set to
/// [TextDirection.ltr], 20.0 will be added to
/// `MediaQuery.paddingOf(context).left`.
final double? drawerEdgeDragWidth;
/// Determines if the [MyScaffold.drawer] can be opened with a drag
/// gesture on mobile.
///
/// On desktop platforms, the drawer is not draggable.
///
/// By default, the drag gesture is enabled on mobile.
final bool drawerEnableOpenDragGesture;
/// Determines if the [MyScaffold.endDrawer] can be opened with a
/// gesture on mobile.
///
/// On desktop platforms, the drawer is not draggable.
///
/// By default, the drag gesture is enabled on mobile.
final bool endDrawerEnableOpenDragGesture;
/// Restoration ID to save and restore the state of the [MyScaffold].
///
/// If it is non-null, the scaffold will persist and restore whether the
/// [drawer] and [endDrawer] was open or closed.
///
/// The state of this widget is persisted in a [RestorationBucket] claimed
/// from the surrounding [RestorationScope] using the provided restoration ID.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// Finds the [MyScaffoldState] from the closest instance of this class that
/// encloses the given context.
///
/// If no instance of this class encloses the given context, will cause an
/// assert in debug mode, and throw an exception in release mode.
///
/// This method can be expensive (it walks the element tree).
///
/// {@tool dartpad}
/// Typical usage of the [MyScaffold.of] function is to call it from within the
/// `build` method of a child of a [MyScaffold].
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.of.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// When the [MyScaffold] is actually created in the same `build` function, the
/// `context` argument to the `build` function can't be used to find the
/// [MyScaffold] (since it's "above" the widget being returned in the widget
/// tree). In such cases, the following technique with a [Builder] can be used
/// to provide a new scope with a [BuildContext] that is "under" the
/// [Scaffold]:
///
/// ** See code in examples/api/lib/material/scaffold/scaffold.of.1.dart **
/// {@end-tool}
///
/// A more efficient solution is to split your build function into several
/// widgets. This introduces a new context from which you can obtain the
/// [MyScaffold]. In this solution, you would have an outer widget that creates
/// the [MyScaffold] populated by instances of your new inner widgets, and then
/// in these inner widgets you would use [MyScaffold.of].
///
/// A less elegant but more expedient solution is assign a [GlobalKey] to the
/// [MyScaffold], then use the `key.currentState` property to obtain the
/// [MyScaffoldState] rather than using the [MyScaffold.of] function.
///
/// If there is no [MyScaffold] in scope, then this will throw an exception.
/// To return null if there is no [MyScaffold], use [maybeOf] instead.
static MyScaffoldState of(BuildContext context) {
final MyScaffoldState? result =
context.findAncestorStateOfType<MyScaffoldState>();
if (result != null) {
return result;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'Scaffold.of() called with a context that does not contain a Scaffold.',
),
ErrorDescription(
'No Scaffold ancestor could be found starting from the context that was passed to Scaffold.of(). '
'This usually happens when the context provided is from the same StatefulWidget as that '
'whose build function actually creates the Scaffold widget being sought.',
),
ErrorHint(
'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
'context that is "under" the Scaffold. For an example of this, please see the '
'documentation for Scaffold.of():\n'
' https://api.flutter.dev/flutter/material/Scaffold/of.html',
),
ErrorHint(
'A more efficient solution is to split your build function into several widgets. This '
'introduces a new context from which you can obtain the Scaffold. In this solution, '
'you would have an outer widget that creates the Scaffold populated by instances of '
'your new inner widgets, and then in these inner widgets you would use Scaffold.of().\n'
'A less elegant but more expedient solution is assign a GlobalKey to the Scaffold, '
'then use the key.currentState property to obtain the ScaffoldState rather than '
'using the Scaffold.of() function.',
),
context.describeElement('The context used was'),
]);
}
/// Finds the [MyScaffoldState] from the closest instance of this class that
/// encloses the given context.
///
/// If no instance of this class encloses the given context, will return null.
/// To throw an exception instead, use [of] instead of this function.
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [of], a similar function to this one that throws if no instance
/// encloses the given context. Also includes some sample code in its
/// documentation.
static MyScaffoldState? maybeOf(BuildContext context) {
return context.findAncestorStateOfType<MyScaffoldState>();
}
/// Returns a [ValueListenable] for the [ScaffoldGeometry] for the closest
/// [MyScaffold] ancestor of the given context.
///
/// The [ValueListenable.value] is only available at paint time.
///
/// Notifications are guaranteed to be sent before the first paint pass
/// with the new geometry, but there is no guarantee whether a build or
/// layout passes are going to happen between the notification and the next
/// paint pass.
///
/// The closest [MyScaffold] ancestor for the context might change, e.g when
/// an element is moved from one scaffold to another. For [StatefulWidget]s
/// using this listenable, a change of the [MyScaffold] ancestor will
/// trigger a [State.didChangeDependencies].
///
/// A typical pattern for listening to the scaffold geometry would be to
/// call [MyScaffold.geometryOf] in [State.didChangeDependencies], compare the
/// return value with the previous listenable, if it has changed, unregister
/// the listener, and register a listener to the new [ScaffoldGeometry]
/// listenable.
static ValueListenable<ScaffoldGeometry> geometryOf(BuildContext context) {
final _ScaffoldScope? scaffoldScope =
context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>();
if (scaffoldScope == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'Scaffold.geometryOf() called with a context that does not contain a Scaffold.',
),
ErrorDescription(
'This usually happens when the context provided is from the same StatefulWidget as that '
'whose build function actually creates the Scaffold widget being sought.',
),
ErrorHint(
'There are several ways to avoid this problem. The simplest is to use a Builder to get a '
'context that is "under" the Scaffold. For an example of this, please see the '
'documentation for Scaffold.of():\n'
' https://api.flutter.dev/flutter/material/Scaffold/of.html',
),
ErrorHint(
'A more efficient solution is to split your build function into several widgets. This '
'introduces a new context from which you can obtain the Scaffold. In this solution, '
'you would have an outer widget that creates the Scaffold populated by instances of '
'your new inner widgets, and then in these inner widgets you would use Scaffold.geometryOf().',
),
context.describeElement('The context used was'),
]);
}
return scaffoldScope.geometryNotifier;
}
/// Whether the Scaffold that most tightly encloses the given context has a
/// drawer.
///
/// If this is being used during a build (for example to decide whether to
/// show an "open drawer" button), set the `registerForUpdates` argument to
/// true. This will then set up an [InheritedWidget] relationship with the
/// [MyScaffold] so that the client widget gets rebuilt whenever the [hasDrawer]
/// value changes.
///
/// This method can be expensive (it walks the element tree).
///
/// See also:
///
/// * [MyScaffold.of], which provides access to the [MyScaffoldState] object as a
/// whole, from which you can show bottom sheets, and so forth.
static bool hasDrawer(BuildContext context,
{bool registerForUpdates = true}) {
if (registerForUpdates) {
final _ScaffoldScope? scaffold =
context.dependOnInheritedWidgetOfExactType<_ScaffoldScope>();
return scaffold?.hasDrawer ?? false;
} else {
final MyScaffoldState? scaffold =
context.findAncestorStateOfType<MyScaffoldState>();
return scaffold?.hasDrawer ?? false;
}
}
@override
MyScaffoldState createState() => MyScaffoldState();
}
/// State for a [MyScaffold].
///
/// Can display [BottomSheet]s. Retrieve a [MyScaffoldState] from the current
/// [BuildContext] using [MyScaffold.of].
class MyScaffoldState extends State<MyScaffold>
with TickerProviderStateMixin, RestorationMixin {
@override
String? get restorationId => widget.restorationId;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_drawerOpened, 'drawer_open');
registerForRestoration(_endDrawerOpened, 'end_drawer_open');
}
// DRAWER API
final GlobalKey<MyDrawerControllerState> _drawerKey =
GlobalKey<MyDrawerControllerState>();
final GlobalKey<MyDrawerControllerState> _endDrawerKey =
GlobalKey<MyDrawerControllerState>();
final GlobalKey _bodyKey = GlobalKey();
/// Whether this scaffold has a non-null [MyScaffold.appBar].
bool get hasAppBar => widget.appBar != null;
/// Whether this scaffold has a non-null [MyScaffold.drawer].
bool get hasDrawer => widget.drawer != null;
/// Whether this scaffold has a non-null [MyScaffold.endDrawer].
bool get hasEndDrawer => widget.endDrawer != null;
/// Whether this scaffold has a non-null [MyScaffold.floatingActionButton].
bool get hasFloatingActionButton => widget.floatingActionButton != null;
double? _appBarMaxHeight;
/// The max height the [MyScaffold.appBar] uses.
///
/// This is based on the appBar preferred height plus the top padding.
double? get appBarMaxHeight => _appBarMaxHeight;
final RestorableBool _drawerOpened = RestorableBool(false);
final RestorableBool _endDrawerOpened = RestorableBool(false);
/// Whether the [MyScaffold.drawer] is opened.
///
/// See also:
///
/// * [MyScaffoldState.openDrawer], which opens the [MyScaffold.drawer] of a
/// [MyScaffold].
bool get isDrawerOpen => _drawerOpened.value;
/// Whether the [MyScaffold.endDrawer] is opened.
///
/// See also:
///
/// * [MyScaffoldState.openEndDrawer], which opens the [MyScaffold.endDrawer] of
/// a [MyScaffold].
bool get isEndDrawerOpen => _endDrawerOpened.value;
void _drawerOpenedCallback(bool isOpened) {
if (_drawerOpened.value != isOpened && _drawerKey.currentState != null) {
setState(() {
_drawerOpened.value = isOpened;
});
widget.onDrawerChanged?.call(isOpened);
}
}
void _endDrawerOpenedCallback(bool isOpened) {
if (_endDrawerOpened.value != isOpened &&
_endDrawerKey.currentState != null) {
setState(() {
_endDrawerOpened.value = isOpened;
});
widget.onEndDrawerChanged?.call(isOpened);
}
}
/// Opens the [Drawer] (if any).
///
/// If the scaffold has a non-null [MyScaffold.drawer], this function will cause
/// the drawer to begin its entrance animation.
///
/// Normally this is not needed since the [MyScaffold] automatically shows an
/// appropriate [IconButton], and handles the edge-swipe gesture, to show the
/// drawer.
///
/// To close the drawer, use either [MyScaffoldState.closeEndDrawer] or
/// [Navigator.pop].
///
/// See [MyScaffold.of] for information about how to obtain the [MyScaffoldState].
void openDrawer() {
if (_endDrawerKey.currentState != null && _endDrawerOpened.value) {
_endDrawerKey.currentState!.close();
}
_drawerKey.currentState?.open();
}
/// Opens the end side [Drawer] (if any).
///
/// If the scaffold has a non-null [MyScaffold.endDrawer], this function will cause
/// the end side drawer to begin its entrance animation.
///
/// Normally this is not needed since the [MyScaffold] automatically shows an
/// appropriate [IconButton], and handles the edge-swipe gesture, to show the
/// drawer.
///
/// To close the drawer, use either [MyScaffoldState.closeEndDrawer] or
/// [Navigator.pop].
///
/// See [MyScaffold.of] for information about how to obtain the [MyScaffoldState].
void openEndDrawer() {
if (_drawerKey.currentState != null && _drawerOpened.value) {
_drawerKey.currentState!.close();
}
_endDrawerKey.currentState?.open();
}
// Used for both the snackbar and material banner APIs
ScaffoldMessengerState? _scaffoldMessenger;
// SNACKBAR API
ScaffoldFeatureController<SnackBar, SnackBarClosedReason>? _messengerSnackBar;
// This is used to update the _messengerSnackBar by the ScaffoldMessenger.
void _updateSnackBar() {
final ScaffoldFeatureController<SnackBar, SnackBarClosedReason>?
messengerSnackBar = _scaffoldMessenger!._snackBars.isNotEmpty
? _scaffoldMessenger!._snackBars.first
: null;
if (_messengerSnackBar != messengerSnackBar) {
setState(() {
_messengerSnackBar = messengerSnackBar;
});
}
}
// MATERIAL BANNER API
// The _messengerMaterialBanner represents the current MaterialBanner being managed by
// the ScaffoldMessenger, instead of the Scaffold.
ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>?
_messengerMaterialBanner;
// This is used to update the _messengerMaterialBanner by the ScaffoldMessenger.
void _updateMaterialBanner() {
final ScaffoldFeatureController<MaterialBanner, MaterialBannerClosedReason>?
messengerMaterialBanner =
_scaffoldMessenger!._materialBanners.isNotEmpty
? _scaffoldMessenger!._materialBanners.first
: null;
if (_messengerMaterialBanner != messengerMaterialBanner) {
setState(() {
_messengerMaterialBanner = messengerMaterialBanner;
});
}
}
// PERSISTENT BOTTOM SHEET API
// Contains bottom sheets that may still be animating out of view.
// Important if the app/user takes an action that could repeatedly show a
// bottom sheet.
final List<_StandardBottomSheet> _dismissedBottomSheets =
<_StandardBottomSheet>[];
PersistentBottomSheetController<dynamic>? _currentBottomSheet;
final GlobalKey _currentBottomSheetKey = GlobalKey();
LocalHistoryEntry? _persistentSheetHistoryEntry;
void _maybeBuildPersistentBottomSheet() {
if (widget.bottomSheet != null && _currentBottomSheet == null) {
// The new _currentBottomSheet is not a local history entry so a "back" button
// will not be added to the Scaffold's appbar and the bottom sheet will not
// support drag or swipe to dismiss.
final AnimationController animationController =
BottomSheet.createAnimationController(this)..value = 1.0;
bool persistentBottomSheetExtentChanged(
DraggableScrollableNotification notification) {
if (notification.extent - notification.initialExtent >
precisionErrorTolerance) {
if (_persistentSheetHistoryEntry == null) {
_persistentSheetHistoryEntry = LocalHistoryEntry(onRemove: () {
DraggableScrollableActuator.reset(notification.context);
showBodyScrim(false, 0.0);
_floatingActionButtonVisibilityValue = 1.0;
_persistentSheetHistoryEntry = null;
});
ModalRoute.of(context)!
.addLocalHistoryEntry(_persistentSheetHistoryEntry!);
}
} else if (_persistentSheetHistoryEntry != null) {
_persistentSheetHistoryEntry!.remove();
}
return false;
}
// Stop the animation and unmount the dismissed sheets from the tree immediately,
// otherwise may cause duplicate GlobalKey assertion if the sheet sub-tree contains
// GlobalKey widgets.
if (_dismissedBottomSheets.isNotEmpty) {
final List<_StandardBottomSheet> sheets = List<_StandardBottomSheet>.of(
_dismissedBottomSheets,
growable: false);
for (final _StandardBottomSheet sheet in sheets) {
sheet.animationController.reset();
}
assert(_dismissedBottomSheets.isEmpty);
}
_currentBottomSheet = _buildBottomSheet<void>(
(BuildContext context) {
return NotificationListener<DraggableScrollableNotification>(
onNotification: persistentBottomSheetExtentChanged,
child: DraggableScrollableActuator(
child: StatefulBuilder(
key: _currentBottomSheetKey,
builder: (BuildContext context, StateSetter setState) {
return widget.bottomSheet ?? const SizedBox.shrink();
},
),
),
);
},
isPersistent: true,
animationController: animationController,
);
}
}
void _closeCurrentBottomSheet() {
if (_currentBottomSheet != null) {
if (!_currentBottomSheet!._isLocalHistoryEntry) {
_currentBottomSheet!.close();
}
assert(() {
_currentBottomSheet?._completer.future.whenComplete(() {
assert(_currentBottomSheet == null);
});
return true;
}());
}
}
/// Closes [MyScaffold.drawer] if it is currently opened.
///
/// See [MyScaffold.of] for information about how to obtain the [MyScaffoldState].
void closeDrawer() {
if (hasDrawer && isDrawerOpen) {
_drawerKey.currentState!.close();
}
}
/// Closes [MyScaffold.endDrawer] if it is currently opened.
///
/// See [MyScaffold.of] for information about how to obtain the [MyScaffoldState].
void closeEndDrawer() {
if (hasEndDrawer && isEndDrawerOpen) {
_endDrawerKey.currentState!.close();
}
}
void _updatePersistentBottomSheet() {
_currentBottomSheetKey.currentState!.setState(() {});
}
PersistentBottomSheetController<T> _buildBottomSheet<T>(
WidgetBuilder builder, {
required bool isPersistent,
required AnimationController animationController,
Color? backgroundColor,
double? elevation,
ShapeBorder? shape,
Clip? clipBehavior,
BoxConstraints? constraints,
bool? enableDrag,
bool shouldDisposeAnimationController = true,
}) {
assert(() {
if (widget.bottomSheet != null &&
isPersistent &&
_currentBottomSheet != null) {
throw FlutterError(
'Scaffold.bottomSheet cannot be specified while a bottom sheet '
'displayed with showBottomSheet() is still visible.\n'
'Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet().',
);
}
return true;
}());
final Completer<T> completer = Completer<T>();
final GlobalKey<_StandardBottomSheetState> bottomSheetKey =
GlobalKey<_StandardBottomSheetState>();
late _StandardBottomSheet bottomSheet;
bool removedEntry = false;
bool doingDispose = false;
void removePersistentSheetHistoryEntryIfNeeded() {
assert(isPersistent);
if (_persistentSheetHistoryEntry != null) {
_persistentSheetHistoryEntry!.remove();
_persistentSheetHistoryEntry = null;
}
}
void removeCurrentBottomSheet() {
removedEntry = true;
if (_currentBottomSheet == null) {
return;
}
assert(_currentBottomSheet!._widget == bottomSheet);
assert(bottomSheetKey.currentState != null);
_showFloatingActionButton();
if (isPersistent) {
removePersistentSheetHistoryEntryIfNeeded();
}
bottomSheetKey.currentState!.close();
setState(() {
_showBodyScrim = false;
_bodyScrimColor = Colors.black.withOpacity(0.0);
_currentBottomSheet = null;
});
if (animationController.status != AnimationStatus.dismissed) {
_dismissedBottomSheets.add(bottomSheet);
}
completer.complete();
}
final LocalHistoryEntry? entry = isPersistent
? null
: LocalHistoryEntry(onRemove: () {
if (!removedEntry &&
_currentBottomSheet?._widget == bottomSheet &&
!doingDispose) {
removeCurrentBottomSheet();
}
});
void removeEntryIfNeeded() {
if (!isPersistent && !removedEntry) {
assert(entry != null);
entry!.remove();
removedEntry = true;
}
}
bottomSheet = _StandardBottomSheet(
key: bottomSheetKey,
animationController: animationController,
enableDrag: enableDrag ?? !isPersistent,
onClosing: () {
if (_currentBottomSheet == null) {
return;
}
assert(_currentBottomSheet!._widget == bottomSheet);
removeEntryIfNeeded();
},
onDismissed: () {
if (_dismissedBottomSheets.contains(bottomSheet)) {
setState(() {
_dismissedBottomSheets.remove(bottomSheet);
});
}
},
onDispose: () {
doingDispose = true;
removeEntryIfNeeded();
if (shouldDisposeAnimationController) {
animationController.dispose();
}
},
builder: builder,
isPersistent: isPersistent,
backgroundColor: backgroundColor,
elevation: elevation,
shape: shape,
clipBehavior: clipBehavior,
constraints: constraints,
);
if (!isPersistent) {
ModalRoute.of(context)!.addLocalHistoryEntry(entry!);
}
return PersistentBottomSheetController<T>._(
bottomSheet,
completer,
entry != null ? entry.remove : removeCurrentBottomSheet,
(VoidCallback fn) {
bottomSheetKey.currentState?.setState(fn);
},
!isPersistent,
);
}
/// Shows a Material Design bottom sheet in the nearest [MyScaffold]. To show
/// a persistent bottom sheet, use the [MyScaffold.bottomSheet].
///
/// Returns a controller that can be used to close and otherwise manipulate the
/// bottom sheet.
///
/// To rebuild the bottom sheet (e.g. if it is stateful), call
/// [PersistentBottomSheetController.setState] on the controller returned by
/// this method.
///
/// The new bottom sheet becomes a [LocalHistoryEntry] for the enclosing
/// [ModalRoute] and a back button is added to the app bar of the [MyScaffold]
/// that closes the bottom sheet.
///
/// The [transitionAnimationController] controls the bottom sheet's entrance and
/// exit animations. It's up to the owner of the controller to call
/// [AnimationController.dispose] when the controller is no longer needed.
///
/// To create a persistent bottom sheet that is not a [LocalHistoryEntry] and
/// does not add a back button to the enclosing Scaffold's app bar, use the
/// [MyScaffold.bottomSheet] constructor parameter.
///
/// A persistent bottom sheet shows information that supplements the primary
/// content of the app. A persistent bottom sheet remains visible even when
/// the user interacts with other parts of the app.
///
/// A closely related widget is a modal bottom sheet, which is an alternative
/// to a menu or a dialog and prevents the user from interacting with the rest
/// of the app. Modal bottom sheets can be created and displayed with the
/// [showModalBottomSheet] function.
///
/// {@tool dartpad}
/// This example demonstrates how to use [showBottomSheet] to display a
/// bottom sheet when a user taps a button. It also demonstrates how to
/// close a bottom sheet using the Navigator.
///
/// ** See code in examples/api/lib/material/scaffold/scaffold_state.show_bottom_sheet.0.dart **
/// {@end-tool}
/// See also:
///
/// * [BottomSheet], which becomes the parent of the widget returned by the
/// `builder`.
/// * [showBottomSheet], which calls this method given a [BuildContext].
/// * [showModalBottomSheet], which can be used to display a modal bottom
/// sheet.
/// * [MyScaffold.of], for information about how to obtain the [MyScaffoldState].
/// * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
/// * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
PersistentBottomSheetController<T> showBottomSheet<T>(
WidgetBuilder builder, {
Color? backgroundColor,
double? elevation,
ShapeBorder? shape,
Clip? clipBehavior,
BoxConstraints? constraints,
bool? enableDrag,
AnimationController? transitionAnimationController,
}) {
assert(() {
if (widget.bottomSheet != null) {
throw FlutterError(
'Scaffold.bottomSheet cannot be specified while a bottom sheet '
'displayed with showBottomSheet() is still visible.\n'
'Rebuild the Scaffold with a null bottomSheet before calling showBottomSheet().',
);
}
return true;
}());
assert(debugCheckHasMediaQuery(context));
_closeCurrentBottomSheet();
final AnimationController controller = (transitionAnimationController ??
BottomSheet.createAnimationController(this))
..forward();
setState(() {
_currentBottomSheet = _buildBottomSheet<T>(
builder,
isPersistent: false,
animationController: controller,
backgroundColor: backgroundColor,
elevation: elevation,
shape: shape,
clipBehavior: clipBehavior,
constraints: constraints,
enableDrag: enableDrag,
shouldDisposeAnimationController: transitionAnimationController == null,
);
});
return _currentBottomSheet! as PersistentBottomSheetController<T>;
}
// Floating Action Button API
late AnimationController _floatingActionButtonMoveController;
late FloatingActionButtonAnimator _floatingActionButtonAnimator;
FloatingActionButtonLocation? _previousFloatingActionButtonLocation;
FloatingActionButtonLocation? _floatingActionButtonLocation;
late AnimationController _floatingActionButtonVisibilityController;
/// Gets the current value of the visibility animation for the
/// [MyScaffold.floatingActionButton].
double get _floatingActionButtonVisibilityValue =>
_floatingActionButtonVisibilityController.value;
/// Sets the current value of the visibility animation for the
/// [MyScaffold.floatingActionButton]. This value must not be null.
set _floatingActionButtonVisibilityValue(double newValue) {
_floatingActionButtonVisibilityController.value = clampDouble(
newValue,
_floatingActionButtonVisibilityController.lowerBound,
_floatingActionButtonVisibilityController.upperBound,
);
}
/// Shows the [MyScaffold.floatingActionButton].
TickerFuture _showFloatingActionButton() {
return _floatingActionButtonVisibilityController.forward();
}
// Moves the Floating Action Button to the new Floating Action Button Location.
void _moveFloatingActionButton(
final FloatingActionButtonLocation newLocation) {
FloatingActionButtonLocation? previousLocation =
_floatingActionButtonLocation;
double restartAnimationFrom = 0.0;
// If the Floating Action Button is moving right now, we need to start from a snapshot of the current transition.
if (_floatingActionButtonMoveController.isAnimating) {
previousLocation = _TransitionSnapshotFabLocation(
_previousFloatingActionButtonLocation!,
_floatingActionButtonLocation!,
_floatingActionButtonAnimator,
_floatingActionButtonMoveController.value);
restartAnimationFrom = _floatingActionButtonAnimator
.getAnimationRestart(_floatingActionButtonMoveController.value);
}
setState(() {
_previousFloatingActionButtonLocation = previousLocation;
_floatingActionButtonLocation = newLocation;
});
// Animate the motion even when the fab is null so that if the exit animation is running,
// the old fab will start the motion transition while it exits instead of jumping to the
// new position.
_floatingActionButtonMoveController.forward(from: restartAnimationFrom);
}
// iOS FEATURES - status bar tap, back gesture
// On iOS, tapping the status bar scrolls the app's primary scrollable to the
// top. We implement this by looking up the primary scroll controller and
// scrolling it to the top when tapped.
void _handleStatusBarTap() {
final ScrollController? primaryScrollController =
PrimaryScrollController.maybeOf(context);
if (primaryScrollController != null && primaryScrollController.hasClients) {
primaryScrollController.animateTo(
0.0,
duration: const Duration(milliseconds: 1000),
curve: Curves.easeOutCirc,
);
}
}
// INTERNALS
late _ScaffoldGeometryNotifier _geometryNotifier;
bool get _resizeToAvoidBottomInset {
return widget.resizeToAvoidBottomInset ?? true;
}
@override
void initState() {
super.initState();
_geometryNotifier =
_ScaffoldGeometryNotifier(const ScaffoldGeometry(), context);
_floatingActionButtonLocation = widget.floatingActionButtonLocation ??
_kDefaultFloatingActionButtonLocation;
_floatingActionButtonAnimator = widget.floatingActionButtonAnimator ??
_kDefaultFloatingActionButtonAnimator;
_previousFloatingActionButtonLocation = _floatingActionButtonLocation;
_floatingActionButtonMoveController = AnimationController(
vsync: this,
value: 1.0,
duration: kFloatingActionButtonSegue * 2,
);
_floatingActionButtonVisibilityController = AnimationController(
duration: kFloatingActionButtonSegue,
vsync: this,
);
}
@override
void didUpdateWidget(MyScaffold oldWidget) {
super.didUpdateWidget(oldWidget);
// Update the Floating Action Button Animator, and then schedule the Floating Action Button for repositioning.
if (widget.floatingActionButtonAnimator !=
oldWidget.floatingActionButtonAnimator) {
_floatingActionButtonAnimator = widget.floatingActionButtonAnimator ??
_kDefaultFloatingActionButtonAnimator;
}
if (widget.floatingActionButtonLocation !=
oldWidget.floatingActionButtonLocation) {
_moveFloatingActionButton(widget.floatingActionButtonLocation ??
_kDefaultFloatingActionButtonLocation);
}
if (widget.bottomSheet != oldWidget.bottomSheet) {
assert(() {
if (widget.bottomSheet != null &&
(_currentBottomSheet?._isLocalHistoryEntry ?? false)) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary(
'Scaffold.bottomSheet cannot be specified while a bottom sheet displayed '
'with showBottomSheet() is still visible.',
),
ErrorHint(
'Use the PersistentBottomSheetController '
'returned by showBottomSheet() to close the old bottom sheet before creating '
'a Scaffold with a (non null) bottomSheet.',
),
]);
}
return true;
}());
if (widget.bottomSheet == null) {
_closeCurrentBottomSheet();
} else if (widget.bottomSheet != null && oldWidget.bottomSheet == null) {
_maybeBuildPersistentBottomSheet();
} else {
_updatePersistentBottomSheet();
}
}
}
@override
void didChangeDependencies() {
// Using maybeOf is valid here since both the Scaffold and ScaffoldMessenger
// are currently available for managing SnackBars.
final ScaffoldMessengerState? currentScaffoldMessenger =
ScaffoldMessenger.maybeOf(context);
// If our ScaffoldMessenger has changed, unregister with the old one first.
if (_scaffoldMessenger != null &&
(currentScaffoldMessenger == null ||
_scaffoldMessenger != currentScaffoldMessenger)) {
_scaffoldMessenger?._unregister(this);
}
// Register with the current ScaffoldMessenger, if there is one.
_scaffoldMessenger = currentScaffoldMessenger;
_scaffoldMessenger?._register(this);
_maybeBuildPersistentBottomSheet();
super.didChangeDependencies();
}
@override
void dispose() {
_geometryNotifier.dispose();
_floatingActionButtonMoveController.dispose();
_floatingActionButtonVisibilityController.dispose();
_scaffoldMessenger?._unregister(this);
_drawerOpened.dispose();
_endDrawerOpened.dispose();
super.dispose();
}
void _addIfNonNull(
List<LayoutId> children,
Widget? child,
Object childId, {
required bool removeLeftPadding,
required bool removeTopPadding,
required bool removeRightPadding,
required bool removeBottomPadding,
bool removeBottomInset = false,
bool maintainBottomViewPadding = false,
}) {
MediaQueryData data = MediaQuery.of(context).removePadding(
removeLeft: removeLeftPadding,
removeTop: removeTopPadding,
removeRight: removeRightPadding,
removeBottom: removeBottomPadding,
);
if (removeBottomInset) {
data = data.removeViewInsets(removeBottom: true);
}
if (maintainBottomViewPadding && data.viewInsets.bottom != 0.0) {
data = data.copyWith(
padding: data.padding.copyWith(bottom: data.viewPadding.bottom),
);
}
if (child != null) {
children.add(
LayoutId(
id: childId,
child: MediaQuery(data: data, child: child),
),
);
}
}
void _buildEndDrawer(List<LayoutId> children, TextDirection textDirection) {
if (widget.endDrawer != null) {
assert(hasEndDrawer);
_addIfNonNull(
children,
MyDrawerController(
key: _endDrawerKey,
alignment: DrawerAlignment.end,
drawerCallback: _endDrawerOpenedCallback,
dragStartBehavior: widget.drawerDragStartBehavior,
scrimColor: widget.drawerScrimColor,
edgeDragWidth: widget.drawerEdgeDragWidth,
enableOpenDragGesture: widget.endDrawerEnableOpenDragGesture,
isDrawerOpen: _endDrawerOpened.value,
customAnimationController: widget.customAnimationController,
child: widget.endDrawer!,
),
_ScaffoldSlot.endDrawer,
// remove the side padding from the side we're not touching
removeLeftPadding: textDirection == TextDirection.ltr,
removeTopPadding: false,
removeRightPadding: textDirection == TextDirection.rtl,
removeBottomPadding: false,
);
}
}
void _buildDrawer(List<LayoutId> children, TextDirection textDirection) {
if (widget.drawer != null) {
assert(hasDrawer);
_addIfNonNull(
children,
MyDrawerController(
key: _drawerKey,
alignment: DrawerAlignment.start,
drawerCallback: _drawerOpenedCallback,
dragStartBehavior: widget.drawerDragStartBehavior,
scrimColor: widget.drawerScrimColor,
edgeDragWidth: widget.drawerEdgeDragWidth,
enableOpenDragGesture: widget.drawerEnableOpenDragGesture,
isDrawerOpen: _drawerOpened.value,
customAnimationController: widget.customAnimationController,
child: widget.drawer!,
),
_ScaffoldSlot.drawer,
// remove the side padding from the side we're not touching
removeLeftPadding: textDirection == TextDirection.rtl,
removeTopPadding: false,
removeRightPadding: textDirection == TextDirection.ltr,
removeBottomPadding: false,
);
}
}
bool _showBodyScrim = false;
Color _bodyScrimColor = Colors.black;
/// Whether to show a [ModalBarrier] over the body of the scaffold.
///
/// The `value` parameter must not be null.
void showBodyScrim(bool value, double opacity) {
if (_showBodyScrim == value && _bodyScrimColor.opacity == opacity) {
return;
}
setState(() {
_showBodyScrim = value;
_bodyScrimColor = Colors.black.withOpacity(opacity);
});
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasDirectionality(context));
final ThemeData themeData = Theme.of(context);
final TextDirection textDirection = Directionality.of(context);
final List<LayoutId> children = <LayoutId>[];
_addIfNonNull(
children,
widget.body == null
? null
: _BodyBuilder(
extendBody: widget.extendBody,
extendBodyBehindAppBar: widget.extendBodyBehindAppBar,
body: KeyedSubtree(key: _bodyKey, child: widget.body!),
),
_ScaffoldSlot.body,
removeLeftPadding: false,
removeTopPadding: widget.appBar != null,
removeRightPadding: false,
removeBottomPadding: widget.bottomNavigationBar != null ||
widget.persistentFooterButtons != null,
removeBottomInset: _resizeToAvoidBottomInset,
);
if (_showBodyScrim) {
_addIfNonNull(
children,
ModalBarrier(
dismissible: false,
color: _bodyScrimColor,
),
_ScaffoldSlot.bodyScrim,
removeLeftPadding: true,
removeTopPadding: true,
removeRightPadding: true,
removeBottomPadding: true,
);
}
if (widget.appBar != null) {
final double topPadding =
widget.primary ? MediaQuery.paddingOf(context).top : 0.0;
_appBarMaxHeight =
AppBar.preferredHeightFor(context, widget.appBar!.preferredSize) +
topPadding;
assert(_appBarMaxHeight! >= 0.0 && _appBarMaxHeight!.isFinite);
_addIfNonNull(
children,
ConstrainedBox(
constraints: BoxConstraints(maxHeight: _appBarMaxHeight!),
child: FlexibleSpaceBar.createSettings(
currentExtent: _appBarMaxHeight!,
child: widget.appBar!,
),
),
_ScaffoldSlot.appBar,
removeLeftPadding: false,
removeTopPadding: false,
removeRightPadding: false,
removeBottomPadding: true,
);
}
bool isSnackBarFloating = false;
double? snackBarWidth;
if (_currentBottomSheet != null || _dismissedBottomSheets.isNotEmpty) {
final Widget stack = Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
..._dismissedBottomSheets,
if (_currentBottomSheet != null) _currentBottomSheet!._widget,
],
);
_addIfNonNull(
children,
stack,
_ScaffoldSlot.bottomSheet,
removeLeftPadding: false,
removeTopPadding: true,
removeRightPadding: false,
removeBottomPadding: _resizeToAvoidBottomInset,
);
}
// SnackBar set by ScaffoldMessenger
if (_messengerSnackBar != null) {
final SnackBarBehavior snackBarBehavior =
_messengerSnackBar?._widget.behavior ??
themeData.snackBarTheme.behavior ??
SnackBarBehavior.fixed;
isSnackBarFloating = snackBarBehavior == SnackBarBehavior.floating;
snackBarWidth =
_messengerSnackBar?._widget.width ?? themeData.snackBarTheme.width;
_addIfNonNull(
children,
_messengerSnackBar?._widget,
_ScaffoldSlot.snackBar,
removeLeftPadding: false,
removeTopPadding: true,
removeRightPadding: false,
removeBottomPadding: widget.bottomNavigationBar != null ||
widget.persistentFooterButtons != null,
maintainBottomViewPadding: !_resizeToAvoidBottomInset,
);
}
bool extendBodyBehindMaterialBanner = false;
// MaterialBanner set by ScaffoldMessenger
if (_messengerMaterialBanner != null) {
final MaterialBannerThemeData bannerTheme =
MaterialBannerTheme.of(context);
final double elevation = _messengerMaterialBanner?._widget.elevation ??
bannerTheme.elevation ??
0.0;
extendBodyBehindMaterialBanner = elevation != 0.0;
_addIfNonNull(
children,
_messengerMaterialBanner?._widget,
_ScaffoldSlot.materialBanner,
removeLeftPadding: false,
removeTopPadding: widget.appBar != null,
removeRightPadding: false,
removeBottomPadding: true,
maintainBottomViewPadding: !_resizeToAvoidBottomInset,
);
}
if (widget.persistentFooterButtons != null) {
_addIfNonNull(
children,
Container(
decoration: BoxDecoration(
border: Border(
top: Divider.createBorderSide(context, width: 1.0),
),
),
child: SafeArea(
top: false,
child: IntrinsicHeight(
child: Container(
alignment: widget.persistentFooterAlignment,
padding: const EdgeInsets.all(8),
child: OverflowBar(
spacing: 8,
overflowAlignment: OverflowBarAlignment.end,
children: widget.persistentFooterButtons!,
),
),
),
),
),
_ScaffoldSlot.persistentFooter,
removeLeftPadding: false,
removeTopPadding: true,
removeRightPadding: false,
removeBottomPadding: widget.bottomNavigationBar != null,
maintainBottomViewPadding: !_resizeToAvoidBottomInset,
);
}
if (widget.bottomNavigationBar != null) {
_addIfNonNull(
children,
widget.bottomNavigationBar,
_ScaffoldSlot.bottomNavigationBar,
removeLeftPadding: false,
removeTopPadding: true,
removeRightPadding: false,
removeBottomPadding: false,
maintainBottomViewPadding: !_resizeToAvoidBottomInset,
);
}
_addIfNonNull(
children,
_FloatingActionButtonTransition(
fabMoveAnimation: _floatingActionButtonMoveController,
fabMotionAnimator: _floatingActionButtonAnimator,
geometryNotifier: _geometryNotifier,
currentController: _floatingActionButtonVisibilityController,
child: widget.floatingActionButton,
),
_ScaffoldSlot.floatingActionButton,
removeLeftPadding: true,
removeTopPadding: true,
removeRightPadding: true,
removeBottomPadding: true,
);
switch (themeData.platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
_addIfNonNull(
children,
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _handleStatusBarTap,
// iOS accessibility automatically adds scroll-to-top to the clock in the status bar
excludeFromSemantics: true,
),
_ScaffoldSlot.statusBar,
removeLeftPadding: false,
removeTopPadding: true,
removeRightPadding: false,
removeBottomPadding: true,
);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
break;
}
if (_endDrawerOpened.value) {
_buildDrawer(children, textDirection);
_buildEndDrawer(children, textDirection);
} else {
_buildEndDrawer(children, textDirection);
_buildDrawer(children, textDirection);
}
// The minimum insets for contents of the Scaffold to keep visible.
final EdgeInsets minInsets = MediaQuery.paddingOf(context).copyWith(
bottom: _resizeToAvoidBottomInset
? MediaQuery.viewInsetsOf(context).bottom
: 0.0,
);
// The minimum viewPadding for interactive elements positioned by the
// Scaffold to keep within safe interactive areas.
final EdgeInsets minViewPadding =
MediaQuery.viewPaddingOf(context).copyWith(
bottom: _resizeToAvoidBottomInset &&
MediaQuery.viewInsetsOf(context).bottom != 0.0
? 0.0
: null,
);
// extendBody locked when keyboard is open
final bool extendBody = minInsets.bottom <= 0 && widget.extendBody;
return _ScaffoldScope(
hasDrawer: hasDrawer,
geometryNotifier: _geometryNotifier,
child: ScrollNotificationObserver(
child: Material(
color: widget.backgroundColor ?? themeData.scaffoldBackgroundColor,
child: AnimatedBuilder(
animation: _floatingActionButtonMoveController,
builder: (BuildContext context, Widget? child) {
return Actions(
actions: <Type, Action<Intent>>{
DismissIntent: _DismissDrawerAction(context),
},
child: CustomMultiChildLayout(
delegate: _ScaffoldLayout(
extendBody: extendBody,
extendBodyBehindAppBar: widget.extendBodyBehindAppBar,
minInsets: minInsets,
minViewPadding: minViewPadding,
currentFloatingActionButtonLocation:
_floatingActionButtonLocation!,
floatingActionButtonMoveAnimationProgress:
_floatingActionButtonMoveController.value,
floatingActionButtonMotionAnimator:
_floatingActionButtonAnimator,
geometryNotifier: _geometryNotifier,
previousFloatingActionButtonLocation:
_previousFloatingActionButtonLocation!,
textDirection: textDirection,
isSnackBarFloating: isSnackBarFloating,
extendBodyBehindMaterialBanner:
extendBodyBehindMaterialBanner,
snackBarWidth: snackBarWidth,
),
children: children,
),
);
}),
),
),
);
}
}
class _DismissDrawerAction extends DismissAction {
_DismissDrawerAction(this.context);
final BuildContext context;
@override
bool isEnabled(DismissIntent intent) {
return MyScaffold.of(context).isDrawerOpen ||
MyScaffold.of(context).isEndDrawerOpen;
}
@override
void invoke(DismissIntent intent) {
MyScaffold.of(context).closeDrawer();
MyScaffold.of(context).closeEndDrawer();
}
}
/// An interface for controlling a feature of a [MyScaffold].
///
/// Commonly obtained from [ScaffoldMessengerState.showSnackBar] or
/// [MyScaffoldState.showBottomSheet].
class ScaffoldFeatureController<T extends Widget, U> {
const ScaffoldFeatureController._(
this._widget, this._completer, this.close, this.setState);
final T _widget;
final Completer<U> _completer;
/// Completes when the feature controlled by this object is no longer visible.
Future<U> get closed => _completer.future;
/// Remove the feature (e.g., bottom sheet, snack bar, or material banner) from the scaffold.
final VoidCallback close;
/// Mark the feature (e.g., bottom sheet or snack bar) as needing to rebuild.
final StateSetter? setState;
}
// TODO(guidezpl): Look into making this public. A copy of this class is in
// bottom_sheet.dart, for now, https://github.com/flutter/flutter/issues/51627
/// A curve that progresses linearly until a specified [startingPoint], at which
/// point [curve] will begin. Unlike [Interval], [curve] will not start at zero,
/// but will use [startingPoint] as the Y position.
///
/// For example, if [startingPoint] is set to `0.5`, and [curve] is set to
/// [Curves.easeOut], then the bottom-left quarter of the curve will be a
/// straight line, and the top-right quarter will contain the entire contents of
/// [Curves.easeOut].
///
/// This is useful in situations where a widget must track the user's finger
/// (which requires a linear animation), and afterwards can be flung using a
/// curve specified with the [curve] argument, after the finger is released. In
/// such a case, the value of [startingPoint] would be the progress of the
/// animation at the time when the finger was released.
///
/// The [startingPoint] and [curve] arguments must not be null.
class _BottomSheetSuspendedCurve extends ParametricCurve<double> {
/// Creates a suspended curve.
const _BottomSheetSuspendedCurve(
this.startingPoint, {
this.curve = Curves.easeOutCubic,
});
/// The progress value at which [curve] should begin.
///
/// This defaults to [Curves.easeOutCubic].
final double startingPoint;
/// The curve to use when [startingPoint] is reached.
final Curve curve;
@override
double transform(double t) {
assert(t >= 0.0 && t <= 1.0);
assert(startingPoint >= 0.0 && startingPoint <= 1.0);
if (t < startingPoint) {
return t;
}
if (t == 1.0) {
return t;
}
final double curveProgress = (t - startingPoint) / (1 - startingPoint);
final double transformed = curve.transform(curveProgress);
return lerpDouble(startingPoint, 1, transformed)!;
}
@override
String toString() {
return '${describeIdentity(this)}($startingPoint, $curve)';
}
}
class _StandardBottomSheet extends StatefulWidget {
const _StandardBottomSheet({
super.key,
required this.animationController,
this.enableDrag = true,
required this.onClosing,
required this.onDismissed,
required this.builder,
this.isPersistent = false,
this.backgroundColor,
this.elevation,
this.shape,
this.clipBehavior,
this.constraints,
this.onDispose,
});
final AnimationController
animationController; // we control it, but it must be disposed by whoever created it.
final bool enableDrag;
final VoidCallback? onClosing;
final VoidCallback? onDismissed;
final VoidCallback? onDispose;
final WidgetBuilder builder;
final bool isPersistent;
final Color? backgroundColor;
final double? elevation;
final ShapeBorder? shape;
final Clip? clipBehavior;
final BoxConstraints? constraints;
@override
_StandardBottomSheetState createState() => _StandardBottomSheetState();
}
class _StandardBottomSheetState extends State<_StandardBottomSheet> {
ParametricCurve<double> animationCurve = _standardBottomSheetCurve;
@override
void initState() {
super.initState();
assert(
widget.animationController.status == AnimationStatus.forward ||
widget.animationController.status == AnimationStatus.completed,
);
widget.animationController.addStatusListener(_handleStatusChange);
}
@override
void dispose() {
widget.onDispose?.call();
super.dispose();
}
@override
void didUpdateWidget(_StandardBottomSheet oldWidget) {
super.didUpdateWidget(oldWidget);
assert(widget.animationController == oldWidget.animationController);
}
void close() {
widget.animationController.reverse();
widget.onClosing?.call();
}
void _handleDragStart(DragStartDetails details) {
// Allow the bottom sheet to track the user's finger accurately.
animationCurve = Curves.linear;
}
void _handleDragEnd(DragEndDetails details, {bool? isClosing}) {
// Allow the bottom sheet to animate smoothly from its current position.
animationCurve = _BottomSheetSuspendedCurve(
widget.animationController.value,
curve: _standardBottomSheetCurve,
);
}
void _handleStatusChange(AnimationStatus status) {
if (status == AnimationStatus.dismissed) {
widget.onDismissed?.call();
}
}
bool extentChanged(DraggableScrollableNotification notification) {
final double extentRemaining = 1.0 - notification.extent;
final MyScaffoldState scaffold = MyScaffold.of(context);
if (extentRemaining < _kBottomSheetDominatesPercentage) {
scaffold._floatingActionButtonVisibilityValue =
extentRemaining * _kBottomSheetDominatesPercentage * 10;
scaffold.showBodyScrim(
true,
math.max(
_kMinBottomSheetScrimOpacity,
_kMaxBottomSheetScrimOpacity -
scaffold._floatingActionButtonVisibilityValue,
));
} else {
scaffold._floatingActionButtonVisibilityValue = 1.0;
scaffold.showBodyScrim(false, 0.0);
}
// If the Scaffold.bottomSheet != null, we're a persistent bottom sheet.
if (notification.extent == notification.minExtent &&
scaffold.widget.bottomSheet == null &&
notification.shouldCloseOnMinExtent) {
close();
}
return false;
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: widget.animationController,
builder: (BuildContext context, Widget? child) {
return Align(
alignment: AlignmentDirectional.topStart,
heightFactor:
animationCurve.transform(widget.animationController.value),
child: child,
);
},
child: Semantics(
container: true,
onDismiss: !widget.isPersistent ? close : null,
child: NotificationListener<DraggableScrollableNotification>(
onNotification: extentChanged,
child: BottomSheet(
animationController: widget.animationController,
enableDrag: widget.enableDrag,
onDragStart: _handleDragStart,
onDragEnd: _handleDragEnd,
onClosing: widget.onClosing!,
builder: widget.builder,
backgroundColor: widget.backgroundColor,
elevation: widget.elevation,
shape: widget.shape,
clipBehavior: widget.clipBehavior,
constraints: widget.constraints,
),
),
),
);
}
}
/// A [ScaffoldFeatureController] for standard bottom sheets.
///
/// This is the type of objects returned by [MyScaffoldState.showBottomSheet].
///
/// This controller is used to display both standard and persistent bottom
/// sheets. A bottom sheet is only persistent if it is set as the
/// [MyScaffold.bottomSheet].
class PersistentBottomSheetController<T>
extends ScaffoldFeatureController<_StandardBottomSheet, T> {
const PersistentBottomSheetController._(
super.widget,
super.completer,
super.close,
StateSetter super.setState,
this._isLocalHistoryEntry,
) : super._();
final bool _isLocalHistoryEntry;
}
class _ScaffoldScope extends InheritedWidget {
const _ScaffoldScope({
required this.hasDrawer,
required this.geometryNotifier,
required super.child,
});
final bool hasDrawer;
final _ScaffoldGeometryNotifier geometryNotifier;
@override
bool updateShouldNotify(_ScaffoldScope oldWidget) {
return hasDrawer != oldWidget.hasDrawer;
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Scaffold/my_appbar.dart | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
// Examples can assume:
// late String _logoAsset;
// double _myToolbarHeight = 250.0;
const double _kMaxTitleTextScaleFactor =
1.34; // TODO(perc): Add link to Material spec when available, https://github.com/flutter/flutter/issues/58769.
// Bottom justify the toolbarHeight child which may overflow the top.
class _ToolbarContainerLayout extends SingleChildLayoutDelegate {
const _ToolbarContainerLayout(this.toolbarHeight);
final double toolbarHeight;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return constraints.tighten(height: toolbarHeight);
}
@override
Size getSize(BoxConstraints constraints) {
return Size(constraints.maxWidth, toolbarHeight);
}
@override
Offset getPositionForChild(Size size, Size childSize) {
return Offset(0.0, size.height - childSize.height);
}
@override
bool shouldRelayout(_ToolbarContainerLayout oldDelegate) =>
toolbarHeight != oldDelegate.toolbarHeight;
}
class _PreferredAppBarSize extends Size {
_PreferredAppBarSize(this.toolbarHeight, this.bottomHeight)
: super.fromHeight(
(toolbarHeight ?? kToolbarHeight) + (bottomHeight ?? 0));
final double? toolbarHeight;
final double? bottomHeight;
}
/// A Material Design app bar.
///
/// An app bar consists of a toolbar and potentially other widgets, such as a
/// [TabBar] and a [FlexibleSpaceBar]. App bars typically expose one or more
/// common [actions] with [IconButton]s which are optionally followed by a
/// [PopupMenuButton] for less common operations (sometimes called the "overflow
/// menu").
///
/// App bars are typically used in the [Scaffold.appBar] property, which places
/// the app bar as a fixed-height widget at the top of the screen. For a scrollable
/// app bar, see [SliverAppBar], which embeds an [MyAppBar] in a sliver for use in
/// a [CustomScrollView].
///
/// The AppBar displays the toolbar widgets, [leading], [title], and [actions],
/// above the [bottom] (if any). The [bottom] is usually used for a [TabBar]. If
/// a [flexibleSpace] widget is specified then it is stacked behind the toolbar
/// and the bottom widget. The following diagram shows where each of these slots
/// appears in the toolbar when the writing language is left-to-right (e.g.
/// English):
///
/// The [MyAppBar] insets its content based on the ambient [MediaQuery]'s padding,
/// to avoid system UI intrusions. It's taken care of by [Scaffold] when used in
/// the [Scaffold.appBar] property. When animating an [MyAppBar], unexpected
/// [MediaQuery] changes (as is common in [Hero] animations) may cause the content
/// to suddenly jump. Wrap the [MyAppBar] in a [MediaQuery] widget, and adjust its
/// padding such that the animation is smooth.
///
/// 
///
/// If the [leading] widget is omitted, but the [MyAppBar] is in a [Scaffold] with
/// a [Drawer], then a button will be inserted to open the drawer. Otherwise, if
/// the nearest [Navigator] has any previous routes, a [BackButton] is inserted
/// instead. This behavior can be turned off by setting the [automaticallyImplyLeading]
/// to false. In that case a null leading widget will result in the middle/title widget
/// stretching to start.
///
/// {@tool dartpad}
/// This sample shows an [MyAppBar] with two simple actions. The first action
/// opens a [SnackBar], while the second action navigates to a new page.
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.0.dart **
/// {@end-tool}
///
/// Material Design 3 introduced new types of app bar.
/// {@tool dartpad}
/// This sample shows the creation of an [MyAppBar] widget with the [shadowColor] and
/// [scrolledUnderElevation] properties set, as described in:
/// https://m3.material.io/components/top-app-bar/overview
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.1.dart **
/// {@end-tool}
///
/// ## Troubleshooting
///
/// ### Why don't my TextButton actions appear?
///
/// If the app bar's [actions] contains [TextButton]s, they will not
/// be visible if their foreground (text) color is the same as the
/// app bar's background color.
///
/// In Material v2 (i.e., when [ThemeData.useMaterial3] is false),
/// the default app bar [backgroundColor] is the overall theme's
/// [ColorScheme.primary] if the overall theme's brightness is
/// [Brightness.light]. Unfortunately this is the same as the default
/// [ButtonStyle.foregroundColor] for [TextButton] for light themes.
/// In this case a preferable text button foreground color is
/// [ColorScheme.onPrimary], a color that contrasts nicely with
/// [ColorScheme.primary]. To remedy the problem, override
/// [TextButton.style]:
///
/// {@tool dartpad}
/// This sample shows an [MyAppBar] with two action buttons with their primary
/// color set to [ColorScheme.onPrimary].
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.2.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to listen to a nested Scrollable's scroll notification
/// in a nested scroll view using the [notificationPredicate] property and use it
/// to make [scrolledUnderElevation] take effect.
///
/// ** See code in examples/api/lib/material/app_bar/app_bar.3.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Scaffold], which displays the [MyAppBar] in its [Scaffold.appBar] slot.
/// * [SliverAppBar], which uses [MyAppBar] to provide a flexible app bar that
/// can be used in a [CustomScrollView].
/// * [TabBar], which is typically placed in the [bottom] slot of the [MyAppBar]
/// if the screen has multiple pages arranged in tabs.
/// * [IconButton], which is used with [actions] to show buttons on the app bar.
/// * [PopupMenuButton], to show a popup menu on the app bar, via [actions].
/// * [FlexibleSpaceBar], which is used with [flexibleSpace] when the app bar
/// can expand and collapse.
/// * <https://material.io/design/components/app-bars-top.html>
/// * <https://m3.material.io/components/top-app-bar>
/// * Cookbook: [Place a floating app bar above a list](https://flutter.dev/docs/cookbook/lists/floating-app-bar)
class MyAppBar extends StatefulWidget implements PreferredSizeWidget {
/// Creates a Material Design app bar.
///
/// If [elevation] is specified, it must be non-negative.
///
/// Typically used in the [Scaffold.appBar] property.
MyAppBar({
super.key,
this.leading,
this.automaticallyImplyLeading = true,
this.title,
this.actions,
this.flexibleSpace,
this.bottom,
this.elevation,
this.scrolledUnderElevation,
this.notificationPredicate = defaultScrollNotificationPredicate,
this.shadowColor,
this.surfaceTintColor,
this.shape,
this.backgroundColor,
this.foregroundColor,
this.iconTheme,
this.actionsIconTheme,
this.primary = true,
this.centerTitle,
this.excludeHeaderSemantics = false,
this.titleSpacing,
this.toolbarOpacity = 1.0,
this.bottomOpacity = 1.0,
this.toolbarHeight,
this.leadingWidth,
this.toolbarTextStyle,
this.titleTextStyle,
this.systemOverlayStyle,
this.forceMaterialTransparency = false,
this.clipBehavior,
}) : assert(elevation == null || elevation >= 0.0),
preferredSize =
_PreferredAppBarSize(toolbarHeight, bottom?.preferredSize.height);
/// Used by [Scaffold] to compute its [MyAppBar]'s overall height. The returned value is
/// the same `preferredSize.height` unless [MyAppBar.toolbarHeight] was null and
/// `AppBarTheme.of(context).toolbarHeight` is non-null. In that case the
/// return value is the sum of the theme's toolbar height and the height of
/// the app bar's [MyAppBar.bottom] widget.
static double preferredHeightFor(BuildContext context, Size preferredSize) {
if (preferredSize is _PreferredAppBarSize &&
preferredSize.toolbarHeight == null) {
return (AppBarTheme.of(context).toolbarHeight ?? kToolbarHeight) +
(preferredSize.bottomHeight ?? 0);
}
return preferredSize.height;
}
/// {@template flutter.material.appbar.leading}
/// A widget to display before the toolbar's [title].
///
/// Typically the [leading] widget is an [Icon] or an [IconButton].
///
/// Becomes the leading component of the [MyNavigationToolbar] built
/// by this widget. The [leading] widget's width and height are constrained to
/// be no bigger than [leadingWidth] and [toolbarHeight] respectively.
///
/// If this is null and [automaticallyImplyLeading] is set to true, the
/// [MyAppBar] will imply an appropriate widget. For example, if the [MyAppBar] is
/// in a [Scaffold] that also has a [Drawer], the [Scaffold] will fill this
/// widget with an [IconButton] that opens the drawer (using [Icons.menu]). If
/// there's no [Drawer] and the parent [Navigator] can go back, the [MyAppBar]
/// will use a [BackButton] that calls [Navigator.maybePop].
/// {@endtemplate}
///
/// {@tool snippet}
///
/// The following code shows how the drawer button could be manually specified
/// instead of relying on [automaticallyImplyLeading]:
///
/// ```dart
/// AppBar(
/// leading: Builder(
/// builder: (BuildContext context) {
/// return IconButton(
/// icon: const Icon(Icons.menu),
/// onPressed: () { Scaffold.of(context).openDrawer(); },
/// tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
/// );
/// },
/// ),
/// )
/// ```
/// {@end-tool}
///
/// The [Builder] is used in this example to ensure that the `context` refers
/// to that part of the subtree. That way this code snippet can be used even
/// inside the very code that is creating the [Scaffold] (in which case,
/// without the [Builder], the `context` wouldn't be able to see the
/// [Scaffold], since it would refer to an ancestor of that widget).
///
/// See also:
///
/// * [Scaffold.appBar], in which an [MyAppBar] is usually placed.
/// * [Scaffold.drawer], in which the [Drawer] is usually placed.
final Widget? leading;
/// {@template flutter.material.appbar.automaticallyImplyLeading}
/// Controls whether we should try to imply the leading widget if null.
///
/// If true and [leading] is null, automatically try to deduce what the leading
/// widget should be. If false and [leading] is null, leading space is given to [title].
/// If leading widget is not null, this parameter has no effect.
/// {@endtemplate}
final bool automaticallyImplyLeading;
/// {@template flutter.material.appbar.title}
/// The primary widget displayed in the app bar.
///
/// Becomes the middle component of the [MyNavigationToolbar] built by this widget.
///
/// Typically a [Text] widget that contains a description of the current
/// contents of the app.
/// {@endtemplate}
///
/// The [title]'s width is constrained to fit within the remaining space
/// between the toolbar's [leading] and [actions] widgets. Its height is
/// _not_ constrained. The [title] is vertically centered and clipped to fit
/// within the toolbar, whose height is [toolbarHeight]. Typically this
/// isn't noticeable because a simple [Text] [title] will fit within the
/// toolbar by default. On the other hand, it is noticeable when a
/// widget with an intrinsic height that is greater than [toolbarHeight]
/// is used as the [title]. For example, when the height of an Image used
/// as the [title] exceeds [toolbarHeight], it will be centered and
/// clipped (top and bottom), which may be undesirable. In cases like this
/// the height of the [title] widget can be constrained. For example:
///
/// ```dart
/// MaterialApp(
/// home: Scaffold(
/// appBar: AppBar(
/// title: SizedBox(
/// height: _myToolbarHeight,
/// child: Image.asset(_logoAsset),
/// ),
/// toolbarHeight: _myToolbarHeight,
/// ),
/// ),
/// )
/// ```
final Widget? title;
/// {@template flutter.material.appbar.actions}
/// A list of Widgets to display in a row after the [title] widget.
///
/// Typically these widgets are [IconButton]s representing common operations.
/// For less common operations, consider using a [PopupMenuButton] as the
/// last action.
///
/// The [actions] become the trailing component of the [MyNavigationToolbar] built
/// by this widget. The height of each action is constrained to be no bigger
/// than the [toolbarHeight].
///
/// To avoid having the last action covered by the debug banner, you may want
/// to set the [MaterialApp.debugShowCheckedModeBanner] to false.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// ```dart
/// Scaffold(
/// body: CustomScrollView(
/// primary: true,
/// slivers: <Widget>[
/// SliverAppBar(
/// title: const Text('Hello World'),
/// actions: <Widget>[
/// IconButton(
/// icon: const Icon(Icons.shopping_cart),
/// tooltip: 'Open shopping cart',
/// onPressed: () {
/// // handle the press
/// },
/// ),
/// ],
/// ),
/// // ...rest of body...
/// ],
/// ),
/// )
/// ```
/// {@end-tool}
final List<Widget>? actions;
/// {@template flutter.material.appbar.flexibleSpace}
/// This widget is stacked behind the toolbar and the tab bar. Its height will
/// be the same as the app bar's overall height.
///
/// A flexible space isn't actually flexible unless the [MyAppBar]'s container
/// changes the [MyAppBar]'s size. A [SliverAppBar] in a [CustomScrollView]
/// changes the [MyAppBar]'s height when scrolled.
///
/// Typically a [FlexibleSpaceBar]. See [FlexibleSpaceBar] for details.
/// {@endtemplate}
final Widget? flexibleSpace;
/// {@template flutter.material.appbar.bottom}
/// This widget appears across the bottom of the app bar.
///
/// Typically a [TabBar]. Only widgets that implement [PreferredSizeWidget] can
/// be used at the bottom of an app bar.
/// {@endtemplate}
///
/// See also:
///
/// * [PreferredSize], which can be used to give an arbitrary widget a preferred size.
final PreferredSizeWidget? bottom;
/// {@template flutter.material.appbar.elevation}
/// The z-coordinate at which to place this app bar relative to its parent.
///
/// This property controls the size of the shadow below the app bar if
/// [shadowColor] is not null.
///
/// If [surfaceTintColor] is not null then it will apply a surface tint overlay
/// to the background color (see [Material.surfaceTintColor] for more
/// detail).
///
/// The value must be non-negative.
///
/// If this property is null, then [AppBarTheme.elevation] of
/// [ThemeData.appBarTheme] is used. If that is also null, the
/// default value is 4.
/// {@endtemplate}
///
/// See also:
///
/// * [scrolledUnderElevation], which will be used when the app bar has
/// something scrolled underneath it.
/// * [shadowColor], which is the color of the shadow below the app bar.
/// * [surfaceTintColor], which determines the elevation overlay that will
/// be applied to the background of the app bar.
/// * [shape], which defines the shape of the app bar's [Material] and its
/// shadow.
final double? elevation;
/// {@template flutter.material.appbar.scrolledUnderElevation}
/// The elevation that will be used if this app bar has something
/// scrolled underneath it.
///
/// If non-null then it [AppBarTheme.scrolledUnderElevation] of
/// [ThemeData.appBarTheme] will be used. If that is also null then [elevation]
/// will be used.
///
/// The value must be non-negative.
///
/// {@endtemplate}
///
/// See also:
/// * [elevation], which will be used if there is no content scrolled under
/// the app bar.
/// * [shadowColor], which is the color of the shadow below the app bar.
/// * [surfaceTintColor], which determines the elevation overlay that will
/// be applied to the background of the app bar.
/// * [shape], which defines the shape of the app bar's [Material] and its
/// shadow.
final double? scrolledUnderElevation;
/// A check that specifies which child's [ScrollNotification]s should be
/// listened to.
///
/// By default, checks whether `notification.depth == 0`. Set it to something
/// else for more complicated layouts.
final ScrollNotificationPredicate notificationPredicate;
/// {@template flutter.material.appbar.shadowColor}
/// The color of the shadow below the app bar.
///
/// If this property is null, then [AppBarTheme.shadowColor] of
/// [ThemeData.appBarTheme] is used. If that is also null, the default value
/// is fully opaque black.
/// {@endtemplate}
///
/// See also:
///
/// * [elevation], which defines the size of the shadow below the app bar.
/// * [shape], which defines the shape of the app bar and its shadow.
final Color? shadowColor;
/// {@template flutter.material.appbar.surfaceTintColor}
/// The color of the surface tint overlay applied to the app bar's
/// background color to indicate elevation.
///
/// If null no overlay will be applied.
/// {@endtemplate}
///
/// See also:
/// * [Material.surfaceTintColor], which described this feature in more detail.
final Color? surfaceTintColor;
/// {@template flutter.material.appbar.shape}
/// The shape of the app bar's [Material] as well as its shadow.
///
/// If this property is null, then [AppBarTheme.shape] of
/// [ThemeData.appBarTheme] is used. Both properties default to null.
/// If both properties are null then the shape of the app bar's [Material]
/// is just a simple rectangle.
///
/// A shadow is only displayed if the [elevation] is greater than
/// zero.
/// {@endtemplate}
///
/// See also:
///
/// * [elevation], which defines the size of the shadow below the app bar.
/// * [shadowColor], which is the color of the shadow below the app bar.
final ShapeBorder? shape;
/// {@template flutter.material.appbar.backgroundColor}
/// The fill color to use for an app bar's [Material].
///
/// If null, then the [AppBarTheme.backgroundColor] is used. If that value is also
/// null, then [MyAppBar] uses the overall theme's [ColorScheme.primary] if the
/// overall theme's brightness is [Brightness.light], and [ColorScheme.surface]
/// if the overall theme's brightness is [Brightness.dark].
///
/// If this color is a [MaterialStateColor] it will be resolved against
/// [MaterialState.scrolledUnder] when the content of the app's
/// primary scrollable overlaps the app bar.
/// {@endtemplate}
///
/// See also:
///
/// * [foregroundColor], which specifies the color for icons and text within
/// the app bar.
/// * [Theme.of], which returns the current overall Material theme as
/// a [ThemeData].
/// * [ThemeData.colorScheme], the thirteen colors that most Material widget
/// default colors are based on.
/// * [ColorScheme.brightness], which indicates if the overall [Theme]
/// is light or dark.
final Color? backgroundColor;
/// {@template flutter.material.appbar.foregroundColor}
/// The default color for [Text] and [Icon]s within the app bar.
///
/// If null, then [AppBarTheme.foregroundColor] is used. If that
/// value is also null, then [MyAppBar] uses the overall theme's
/// [ColorScheme.onPrimary] if the overall theme's brightness is
/// [Brightness.light], and [ColorScheme.onSurface] if the overall
/// theme's brightness is [Brightness.dark].
///
/// This color is used to configure [DefaultTextStyle] that contains
/// the toolbar's children, and the default [IconTheme] widgets that
/// are created if [iconTheme] and [actionsIconTheme] are null.
/// {@endtemplate}
///
/// See also:
///
/// * [backgroundColor], which specifies the app bar's background color.
/// * [Theme.of], which returns the current overall Material theme as
/// a [ThemeData].
/// * [ThemeData.colorScheme], the thirteen colors that most Material widget
/// default colors are based on.
/// * [ColorScheme.brightness], which indicates if the overall [Theme]
/// is light or dark.
final Color? foregroundColor;
/// {@template flutter.material.appbar.iconTheme}
/// The color, opacity, and size to use for toolbar icons.
///
/// If this property is null, then a copy of [ThemeData.iconTheme]
/// is used, with the [IconThemeData.color] set to the
/// app bar's [foregroundColor].
/// {@endtemplate}
///
/// See also:
///
/// * [actionsIconTheme], which defines the appearance of icons in
/// the [actions] list.
final IconThemeData? iconTheme;
/// {@template flutter.material.appbar.actionsIconTheme}
/// The color, opacity, and size to use for the icons that appear in the app
/// bar's [actions].
///
/// This property should only be used when the [actions] should be
/// themed differently than the icon that appears in the app bar's [leading]
/// widget.
///
/// If this property is null, then [AppBarTheme.actionsIconTheme] of
/// [ThemeData.appBarTheme] is used. If that is also null, then the value of
/// [iconTheme] is used.
/// {@endtemplate}
///
/// See also:
///
/// * [iconTheme], which defines the appearance of all of the toolbar icons.
final IconThemeData? actionsIconTheme;
/// {@template flutter.material.appbar.primary}
/// Whether this app bar is being displayed at the top of the screen.
///
/// If true, the app bar's toolbar elements and [bottom] widget will be
/// padded on top by the height of the system status bar. The layout
/// of the [flexibleSpace] is not affected by the [primary] property.
/// {@endtemplate}
final bool primary;
/// {@template flutter.material.appbar.centerTitle}
/// Whether the title should be centered.
///
/// If this property is null, then [AppBarTheme.centerTitle] of
/// [ThemeData.appBarTheme] is used. If that is also null, then value is
/// adapted to the current [TargetPlatform].
/// {@endtemplate}
final bool? centerTitle;
/// {@template flutter.material.appbar.excludeHeaderSemantics}
/// Whether the title should be wrapped with header [Semantics].
///
/// Defaults to false.
/// {@endtemplate}
final bool excludeHeaderSemantics;
/// {@template flutter.material.appbar.titleSpacing}
/// The spacing around [title] content on the horizontal axis. This spacing is
/// applied even if there is no [leading] content or [actions]. If you want
/// [title] to take all the space available, set this value to 0.0.
///
/// If this property is null, then [AppBarTheme.titleSpacing] of
/// [ThemeData.appBarTheme] is used. If that is also null, then the
/// default value is [MyNavigationToolbar.kMiddleSpacing].
/// {@endtemplate}
final double? titleSpacing;
/// {@template flutter.material.appbar.toolbarOpacity}
/// How opaque the toolbar part of the app bar is.
///
/// A value of 1.0 is fully opaque, and a value of 0.0 is fully transparent.
///
/// Typically, this value is not changed from its default value (1.0). It is
/// used by [SliverAppBar] to animate the opacity of the toolbar when the app
/// bar is scrolled.
/// {@endtemplate}
final double toolbarOpacity;
/// {@template flutter.material.appbar.bottomOpacity}
/// How opaque the bottom part of the app bar is.
///
/// A value of 1.0 is fully opaque, and a value of 0.0 is fully transparent.
///
/// Typically, this value is not changed from its default value (1.0). It is
/// used by [SliverAppBar] to animate the opacity of the toolbar when the app
/// bar is scrolled.
/// {@endtemplate}
final double bottomOpacity;
/// {@template flutter.material.appbar.preferredSize}
/// A size whose height is the sum of [toolbarHeight] and the [bottom] widget's
/// preferred height.
///
/// [Scaffold] uses this size to set its app bar's height.
/// {@endtemplate}
@override
final Size preferredSize;
/// {@template flutter.material.appbar.toolbarHeight}
/// Defines the height of the toolbar component of an [MyAppBar].
///
/// By default, the value of [toolbarHeight] is [kToolbarHeight].
/// {@endtemplate}
final double? toolbarHeight;
/// {@template flutter.material.appbar.leadingWidth}
/// Defines the width of [leading] widget.
///
/// By default, the value of [leadingWidth] is 56.0.
/// {@endtemplate}
final double? leadingWidth;
/// {@template flutter.material.appbar.toolbarTextStyle}
/// The default text style for the AppBar's [leading], and
/// [actions] widgets, but not its [title].
///
/// If this property is null, then [AppBarTheme.toolbarTextStyle] of
/// [ThemeData.appBarTheme] is used. If that is also null, the default
/// value is a copy of the overall theme's [TextTheme.bodyMedium]
/// [TextStyle], with color set to the app bar's [foregroundColor].
/// {@endtemplate}
///
/// See also:
///
/// * [titleTextStyle], which overrides the default text style for the [title].
/// * [DefaultTextStyle], which overrides the default text style for all of the
/// widgets in a subtree.
final TextStyle? toolbarTextStyle;
/// {@template flutter.material.appbar.titleTextStyle}
/// The default text style for the AppBar's [title] widget.
///
/// If this property is null, then [AppBarTheme.titleTextStyle] of
/// [ThemeData.appBarTheme] is used. If that is also null, the default
/// value is a copy of the overall theme's [TextTheme.titleLarge]
/// [TextStyle], with color set to the app bar's [foregroundColor].
/// {@endtemplate}
///
/// See also:
///
/// * [toolbarTextStyle], which is the default text style for the AppBar's
/// [title], [leading], and [actions] widgets, also known as the
/// AppBar's "toolbar".
/// * [DefaultTextStyle], which overrides the default text style for all of the
/// widgets in a subtree.
final TextStyle? titleTextStyle;
/// {@template flutter.material.appbar.systemOverlayStyle}
/// Specifies the style to use for the system overlays (e.g. the status bar on
/// Android or iOS, the system navigation bar on Android).
///
/// If this property is null, then [AppBarTheme.systemOverlayStyle] of
/// [ThemeData.appBarTheme] is used. If that is also null, an appropriate
/// [SystemUiOverlayStyle] is calculated based on the [backgroundColor].
///
/// The AppBar's descendants are built within a
/// `AnnotatedRegion<SystemUiOverlayStyle>` widget, which causes
/// [SystemChrome.setSystemUIOverlayStyle] to be called
/// automatically. Apps should not enclose an AppBar with their
/// own [AnnotatedRegion].
/// {@endtemplate}
//
/// See also:
///
/// * [AnnotatedRegion], for placing [SystemUiOverlayStyle] in the layer tree.
/// * [SystemChrome.setSystemUIOverlayStyle], the imperative API for setting
/// system overlays style.
final SystemUiOverlayStyle? systemOverlayStyle;
/// {@template flutter.material.appbar.forceMaterialTransparency}
/// Forces the AppBar's Material widget type to be [MaterialType.transparency]
/// (instead of Material's default type).
///
/// This will remove the visual display of [backgroundColor] and [elevation],
/// and affect other characteristics of the AppBar's Material widget.
///
/// Provided for cases where the app bar is to be transparent, and gestures
/// must pass through the app bar to widgets beneath the app bar (i.e. with
/// [Scaffold.extendBodyBehindAppBar] set to true).
///
/// Defaults to false.
/// {@endtemplate}
final bool forceMaterialTransparency;
/// {@macro flutter.material.Material.clipBehavior}
final Clip? clipBehavior;
bool _getEffectiveCenterTitle(ThemeData theme) {
bool platformCenter() {
switch (theme.platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return false;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return actions == null || actions!.length < 2;
}
}
return centerTitle ?? theme.appBarTheme.centerTitle ?? platformCenter();
}
@override
State<MyAppBar> createState() => _MyAppBarState();
}
class _MyAppBarState extends State<MyAppBar> {
ScrollNotificationObserverState? _scrollNotificationObserver;
bool _scrolledUnder = false;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_scrollNotificationObserver?.removeListener(_handleScrollNotification);
_scrollNotificationObserver = ScrollNotificationObserver.maybeOf(context);
_scrollNotificationObserver?.addListener(_handleScrollNotification);
}
@override
void dispose() {
if (_scrollNotificationObserver != null) {
_scrollNotificationObserver!.removeListener(_handleScrollNotification);
_scrollNotificationObserver = null;
}
super.dispose();
}
void _handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification &&
widget.notificationPredicate(notification)) {
final bool oldScrolledUnder = _scrolledUnder;
final ScrollMetrics metrics = notification.metrics;
switch (metrics.axisDirection) {
case AxisDirection.up:
// Scroll view is reversed
_scrolledUnder = metrics.extentAfter > 0;
case AxisDirection.down:
_scrolledUnder = metrics.extentBefore > 0;
case AxisDirection.right:
case AxisDirection.left:
// Scrolled under is only supported in the vertical axis, and should
// not be altered based on horizontal notifications of the same
// predicate since it could be a 2D scroller.
break;
}
if (_scrolledUnder != oldScrolledUnder) {
setState(() {
// React to a change in MaterialState.scrolledUnder
});
}
}
}
Color _resolveColor(Set<MaterialState> states, Color? widgetColor,
Color? themeColor, Color defaultColor) {
return MaterialStateProperty.resolveAs<Color?>(widgetColor, states) ??
MaterialStateProperty.resolveAs<Color?>(themeColor, states) ??
MaterialStateProperty.resolveAs<Color>(defaultColor, states);
}
SystemUiOverlayStyle _systemOverlayStyleForBrightness(Brightness brightness,
[Color? backgroundColor]) {
final SystemUiOverlayStyle style = brightness == Brightness.dark
? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark;
// For backward compatibility, create an overlay style without system navigation bar settings.
return SystemUiOverlayStyle(
statusBarColor: backgroundColor,
statusBarBrightness: style.statusBarBrightness,
statusBarIconBrightness: style.statusBarIconBrightness,
systemStatusBarContrastEnforced: style.systemStatusBarContrastEnforced,
);
}
@override
Widget build(BuildContext context) {
assert(!widget.primary || debugCheckHasMediaQuery(context));
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
final IconButtonThemeData iconButtonTheme = IconButtonTheme.of(context);
final AppBarTheme appBarTheme = AppBarTheme.of(context);
final AppBarTheme defaults = theme.useMaterial3
? _AppBarDefaultsM3(context)
: _AppBarDefaultsM2(context);
final ScaffoldState? scaffold = Scaffold.maybeOf(context);
final ModalRoute<dynamic>? parentRoute = ModalRoute.of(context);
final FlexibleSpaceBarSettings? settings =
context.dependOnInheritedWidgetOfExactType<FlexibleSpaceBarSettings>();
final Set<MaterialState> states = <MaterialState>{
if (settings?.isScrolledUnder ?? _scrolledUnder)
MaterialState.scrolledUnder,
};
final bool hasDrawer = scaffold?.hasDrawer ?? false;
final bool hasEndDrawer = scaffold?.hasEndDrawer ?? false;
final bool useCloseButton =
parentRoute is PageRoute<dynamic> && parentRoute.fullscreenDialog;
final double toolbarHeight =
widget.toolbarHeight ?? appBarTheme.toolbarHeight ?? kToolbarHeight;
final Color backgroundColor = _resolveColor(
states,
widget.backgroundColor,
appBarTheme.backgroundColor,
defaults.backgroundColor!,
);
final Color foregroundColor = widget.foregroundColor ??
appBarTheme.foregroundColor ??
defaults.foregroundColor!;
final double elevation =
widget.elevation ?? appBarTheme.elevation ?? defaults.elevation!;
final double effectiveElevation =
states.contains(MaterialState.scrolledUnder)
? widget.scrolledUnderElevation ??
appBarTheme.scrolledUnderElevation ??
defaults.scrolledUnderElevation ??
elevation
: elevation;
IconThemeData overallIconTheme = widget.iconTheme ??
appBarTheme.iconTheme ??
defaults.iconTheme!.copyWith(color: foregroundColor);
final Color? actionForegroundColor =
widget.foregroundColor ?? appBarTheme.foregroundColor;
IconThemeData actionsIconTheme = widget.actionsIconTheme ??
appBarTheme.actionsIconTheme ??
widget.iconTheme ??
appBarTheme.iconTheme ??
defaults.actionsIconTheme?.copyWith(color: actionForegroundColor) ??
overallIconTheme;
TextStyle? toolbarTextStyle = widget.toolbarTextStyle ??
appBarTheme.toolbarTextStyle ??
defaults.toolbarTextStyle?.copyWith(color: foregroundColor);
TextStyle? titleTextStyle = widget.titleTextStyle ??
appBarTheme.titleTextStyle ??
defaults.titleTextStyle?.copyWith(color: foregroundColor);
if (widget.toolbarOpacity != 1.0) {
final double opacity =
const Interval(0.25, 1.0, curve: Curves.fastOutSlowIn)
.transform(widget.toolbarOpacity);
if (titleTextStyle?.color != null) {
titleTextStyle = titleTextStyle!
.copyWith(color: titleTextStyle.color!.withOpacity(opacity));
}
if (toolbarTextStyle?.color != null) {
toolbarTextStyle = toolbarTextStyle!
.copyWith(color: toolbarTextStyle.color!.withOpacity(opacity));
}
overallIconTheme = overallIconTheme.copyWith(
opacity: opacity * (overallIconTheme.opacity ?? 1.0),
);
actionsIconTheme = actionsIconTheme.copyWith(
opacity: opacity * (actionsIconTheme.opacity ?? 1.0),
);
}
Widget? leading = widget.leading;
if (leading == null && widget.automaticallyImplyLeading) {
if (hasDrawer) {
leading = DrawerButton(
style: IconButton.styleFrom(iconSize: overallIconTheme.size ?? 24),
);
} else if (parentRoute?.impliesAppBarDismissal ?? false) {
leading = useCloseButton ? const CloseButton() : const BackButton();
}
}
if (leading != null) {
if (theme.useMaterial3) {
final IconButtonThemeData effectiveIconButtonTheme;
// This comparison is to check if there is a custom [overallIconTheme]. If true, it means that no
// custom [overallIconTheme] is provided, so [iconButtonTheme] is applied. Otherwise, we generate
// a new [IconButtonThemeData] based on the values from [overallIconTheme]. If [iconButtonTheme] only
// has null values, the default [overallIconTheme] will be applied below by [IconTheme.merge]
if (overallIconTheme == defaults.iconTheme) {
effectiveIconButtonTheme = iconButtonTheme;
} else {
// The [IconButton.styleFrom] method is used to generate a correct [overlayColor] based on the [foregroundColor].
final ButtonStyle leadingIconButtonStyle = IconButton.styleFrom(
foregroundColor: overallIconTheme.color,
iconSize: overallIconTheme.size,
);
effectiveIconButtonTheme = IconButtonThemeData(
style: iconButtonTheme.style?.copyWith(
foregroundColor: leadingIconButtonStyle.foregroundColor,
overlayColor: leadingIconButtonStyle.overlayColor,
iconSize: leadingIconButtonStyle.iconSize,
));
}
leading = IconButtonTheme(
data: effectiveIconButtonTheme,
child: leading is IconButton ? Center(child: leading) : leading,
);
// Based on the Material Design 3 specs, the leading IconButton should have
// a size of 48x48, and a highlight size of 40x40. Users can also put other
// type of widgets on leading with the original config.
// leading = ConstrainedBox(
// constraints: BoxConstraints.tightFor(
// width: widget.leadingWidth ?? _kLeadingWidth),
// child: leading,
// );
} else {
// leading = ConstrainedBox(
// constraints: BoxConstraints.tightFor(
// width: widget.leadingWidth ?? _kLeadingWidth),
// child: leading,
// );
}
}
Widget? title = widget.title;
if (title != null) {
title = _AppBarTitleBox(child: title);
if (!widget.excludeHeaderSemantics) {
title = Semantics(
namesRoute: switch (theme.platform) {
TargetPlatform.android ||
TargetPlatform.fuchsia ||
TargetPlatform.linux ||
TargetPlatform.windows =>
true,
TargetPlatform.iOS || TargetPlatform.macOS => null,
},
header: true,
child: title,
);
}
title = DefaultTextStyle(
style: titleTextStyle!,
softWrap: false,
overflow: TextOverflow.ellipsis,
child: title,
);
// Set maximum text scale factor to [_kMaxTitleTextScaleFactor] for the
// title to keep the visual hierarchy the same even with larger font
// sizes. To opt out, wrap the [title] widget in a [MediaQuery] widget
// with a different `TextScaler`.
title = MediaQuery.withClampedTextScaling(
maxScaleFactor: _kMaxTitleTextScaleFactor,
child: title,
);
}
Widget? actions;
if (widget.actions != null && widget.actions!.isNotEmpty) {
actions = Row(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: theme.useMaterial3
? CrossAxisAlignment.center
: CrossAxisAlignment.stretch,
children: widget.actions!,
);
} else if (hasEndDrawer) {
actions = EndDrawerButton(
style: IconButton.styleFrom(iconSize: overallIconTheme.size ?? 24),
);
}
// Allow the trailing actions to have their own theme if necessary.
if (actions != null) {
final IconButtonThemeData effectiveActionsIconButtonTheme;
if (actionsIconTheme == defaults.actionsIconTheme) {
effectiveActionsIconButtonTheme = iconButtonTheme;
} else {
final ButtonStyle actionsIconButtonStyle = IconButton.styleFrom(
foregroundColor: actionsIconTheme.color,
iconSize: actionsIconTheme.size,
);
effectiveActionsIconButtonTheme = IconButtonThemeData(
style: iconButtonTheme.style?.copyWith(
foregroundColor: actionsIconButtonStyle.foregroundColor,
overlayColor: actionsIconButtonStyle.overlayColor,
iconSize: actionsIconButtonStyle.iconSize,
));
}
actions = IconButtonTheme(
data: effectiveActionsIconButtonTheme,
child: IconTheme.merge(
data: actionsIconTheme,
child: actions,
),
);
}
final Widget toolbar = MyNavigationToolbar(
leading: leading,
middle: title,
trailing: actions,
centerMiddle: widget._getEffectiveCenterTitle(theme),
middleSpacing: widget.titleSpacing ??
appBarTheme.titleSpacing ??
MyNavigationToolbar.kMiddleSpacing,
);
// If the toolbar is allocated less than toolbarHeight make it
// appear to scroll upwards within its shrinking container.
Widget appBar = ClipRect(
clipBehavior: widget.clipBehavior ?? Clip.hardEdge,
child: CustomSingleChildLayout(
delegate: _ToolbarContainerLayout(toolbarHeight),
child: IconTheme.merge(
data: overallIconTheme,
child: DefaultTextStyle(
style: toolbarTextStyle!,
child: toolbar,
),
),
),
);
if (widget.bottom != null) {
appBar = Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: toolbarHeight),
child: appBar,
),
),
if (widget.bottomOpacity == 1.0)
widget.bottom!
else
Opacity(
opacity: const Interval(0.25, 1.0, curve: Curves.fastOutSlowIn)
.transform(widget.bottomOpacity),
child: widget.bottom,
),
],
);
}
// The padding applies to the toolbar and tabbar, not the flexible space.
if (widget.primary) {
appBar = SafeArea(
bottom: false,
child: appBar,
);
}
appBar = Align(
alignment: Alignment.topCenter,
child: appBar,
);
if (widget.flexibleSpace != null) {
appBar = Stack(
fit: StackFit.passthrough,
children: <Widget>[
Semantics(
sortKey: const OrdinalSortKey(1.0),
explicitChildNodes: true,
child: widget.flexibleSpace,
),
Semantics(
sortKey: const OrdinalSortKey(0.0),
explicitChildNodes: true,
// Creates a material widget to prevent the flexibleSpace from
// obscuring the ink splashes produced by appBar children.
child: Material(
type: MaterialType.transparency,
child: appBar,
),
),
],
);
}
final SystemUiOverlayStyle overlayStyle = widget.systemOverlayStyle ??
appBarTheme.systemOverlayStyle ??
defaults.systemOverlayStyle ??
_systemOverlayStyleForBrightness(
ThemeData.estimateBrightnessForColor(backgroundColor),
// Make the status bar transparent for M3 so the elevation overlay
// color is picked up by the statusbar.
theme.useMaterial3 ? const Color(0x00000000) : null,
);
return Semantics(
container: true,
child: AnnotatedRegion<SystemUiOverlayStyle>(
value: overlayStyle,
child: Material(
color: backgroundColor,
elevation: effectiveElevation,
type: widget.forceMaterialTransparency
? MaterialType.transparency
: MaterialType.canvas,
shadowColor: widget.shadowColor ??
appBarTheme.shadowColor ??
defaults.shadowColor,
surfaceTintColor: widget.surfaceTintColor ??
appBarTheme.surfaceTintColor ??
defaults.surfaceTintColor,
shape: widget.shape ?? appBarTheme.shape ?? defaults.shape,
child: Semantics(
explicitChildNodes: true,
child: appBar,
),
),
),
);
}
}
// Layout the AppBar's title with unconstrained height, vertically
// center it within its (NavigationToolbar) parent, and allow the
// parent to constrain the title's actual height.
class _AppBarTitleBox extends SingleChildRenderObjectWidget {
const _AppBarTitleBox({required Widget super.child});
@override
_RenderAppBarTitleBox createRenderObject(BuildContext context) {
return _RenderAppBarTitleBox(
textDirection: Directionality.of(context),
);
}
@override
void updateRenderObject(
BuildContext context, _RenderAppBarTitleBox renderObject) {
renderObject.textDirection = Directionality.of(context);
}
}
class _RenderAppBarTitleBox extends RenderAligningShiftedBox {
_RenderAppBarTitleBox({
super.textDirection,
}) : super(alignment: Alignment.center);
@override
Size computeDryLayout(BoxConstraints constraints) {
final BoxConstraints innerConstraints =
constraints.copyWith(maxHeight: double.infinity);
final Size childSize = child!.getDryLayout(innerConstraints);
return constraints.constrain(childSize);
}
@override
void performLayout() {
final BoxConstraints innerConstraints =
constraints.copyWith(maxHeight: double.infinity);
child!.layout(innerConstraints, parentUsesSize: true);
size = constraints.constrain(child!.size);
alignChild();
}
}
// Hand coded defaults based on Material Design 2.
class _AppBarDefaultsM2 extends AppBarTheme {
_AppBarDefaultsM2(this.context)
: super(
elevation: 4.0,
shadowColor: const Color(0xFF000000),
titleSpacing: MyNavigationToolbar.kMiddleSpacing,
toolbarHeight: kToolbarHeight,
);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final ColorScheme _colors = _theme.colorScheme;
@override
Color? get backgroundColor =>
_colors.brightness == Brightness.dark ? _colors.surface : _colors.primary;
@override
Color? get foregroundColor => _colors.brightness == Brightness.dark
? _colors.onSurface
: _colors.onPrimary;
@override
IconThemeData? get iconTheme => _theme.iconTheme;
@override
TextStyle? get toolbarTextStyle => _theme.textTheme.bodyMedium;
@override
TextStyle? get titleTextStyle => _theme.textTheme.titleLarge;
}
// BEGIN GENERATED TOKEN PROPERTIES - AppBar
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _AppBarDefaultsM3 extends AppBarTheme {
_AppBarDefaultsM3(this.context)
: super(
elevation: 0.0,
scrolledUnderElevation: 3.0,
titleSpacing: MyNavigationToolbar.kMiddleSpacing,
toolbarHeight: 64.0,
);
final BuildContext context;
late final ThemeData _theme = Theme.of(context);
late final ColorScheme _colors = _theme.colorScheme;
late final TextTheme _textTheme = _theme.textTheme;
@override
Color? get backgroundColor => _colors.surface;
@override
Color? get foregroundColor => _colors.onSurface;
@override
Color? get shadowColor => Colors.transparent;
@override
Color? get surfaceTintColor => _colors.surfaceTint;
@override
IconThemeData? get iconTheme => IconThemeData(
color: _colors.onSurface,
size: 24.0,
);
@override
IconThemeData? get actionsIconTheme => IconThemeData(
color: _colors.onSurfaceVariant,
size: 24.0,
);
@override
TextStyle? get toolbarTextStyle => _textTheme.bodyMedium;
@override
TextStyle? get titleTextStyle => _textTheme.titleLarge;
}
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// [MyNavigationToolbar] is a layout helper to position 3 widgets or groups of
/// widgets along a horizontal axis that's sensible for an application's
/// navigation bar such as in Material Design and in iOS.
///
/// The [leading] and [trailing] widgets occupy the edges of the widget with
/// reasonable size constraints while the [middle] widget occupies the remaining
/// space in either a center aligned or start aligned fashion.
///
/// Either directly use the themed app bars such as the Material [AppBar] or
/// the iOS [CupertinoNavigationBar] or wrap this widget with more theming
/// specifications for your own custom app bar.
class MyNavigationToolbar extends StatelessWidget {
/// Creates a widget that lays out its children in a manner suitable for a
/// toolbar.
const MyNavigationToolbar({
super.key,
this.leading,
this.middle,
this.trailing,
this.centerMiddle = true,
this.middleSpacing = kMiddleSpacing,
});
/// The default spacing around the [middle] widget in dp.
static const double kMiddleSpacing = 0.0;
/// Widget to place at the start of the horizontal toolbar.
final Widget? leading;
/// Widget to place in the middle of the horizontal toolbar, occupying
/// as much remaining space as possible.
final Widget? middle;
/// Widget to place at the end of the horizontal toolbar.
final Widget? trailing;
/// Whether to align the [middle] widget to the center of this widget or
/// next to the [leading] widget when false.
final bool centerMiddle;
/// The spacing around the [middle] widget on horizontal axis.
///
/// Defaults to [kMiddleSpacing].
final double middleSpacing;
@override
Widget build(BuildContext context) {
assert(debugCheckHasDirectionality(context));
final TextDirection textDirection = Directionality.of(context);
return CustomMultiChildLayout(
delegate: _ToolbarLayout(
centerMiddle: centerMiddle,
middleSpacing: middleSpacing,
textDirection: textDirection,
),
children: <Widget>[
if (leading != null)
LayoutId(id: _ToolbarSlot.leading, child: leading!),
if (middle != null) LayoutId(id: _ToolbarSlot.middle, child: middle!),
if (trailing != null)
LayoutId(id: _ToolbarSlot.trailing, child: trailing!),
],
);
}
}
enum _ToolbarSlot {
leading,
middle,
trailing,
}
class _ToolbarLayout extends MultiChildLayoutDelegate {
_ToolbarLayout({
required this.centerMiddle,
required this.middleSpacing,
required this.textDirection,
});
// If false the middle widget should be start-justified within the space
// between the leading and trailing widgets.
// If true the middle widget is centered within the toolbar (not within the horizontal
// space between the leading and trailing widgets).
final bool centerMiddle;
/// The spacing around middle widget on horizontal axis.
final double middleSpacing;
final TextDirection textDirection;
@override
void performLayout(Size size) {
double leadingWidth = 0.0;
double trailingWidth = 0.0;
if (hasChild(_ToolbarSlot.leading)) {
final BoxConstraints constraints = BoxConstraints(
maxWidth: size.width,
minHeight:
size.height, // The height should be exactly the height of the bar.
maxHeight: size.height,
);
leadingWidth = layoutChild(_ToolbarSlot.leading, constraints).width;
final double leadingX;
switch (textDirection) {
case TextDirection.rtl:
leadingX = size.width - leadingWidth;
case TextDirection.ltr:
leadingX = 0.0;
}
positionChild(_ToolbarSlot.leading, Offset(leadingX, 0.0));
}
if (hasChild(_ToolbarSlot.trailing)) {
final BoxConstraints constraints = BoxConstraints.loose(size);
final Size trailingSize = layoutChild(_ToolbarSlot.trailing, constraints);
final double trailingX;
switch (textDirection) {
case TextDirection.rtl:
trailingX = 0.0;
case TextDirection.ltr:
trailingX = size.width - trailingSize.width;
}
final double trailingY = (size.height - trailingSize.height) / 2.0;
trailingWidth = trailingSize.width;
positionChild(_ToolbarSlot.trailing, Offset(trailingX, trailingY));
}
if (hasChild(_ToolbarSlot.middle)) {
final double maxWidth = math.max(
size.width - leadingWidth - trailingWidth - middleSpacing * 2.0, 0.0);
final BoxConstraints constraints =
BoxConstraints.loose(size).copyWith(maxWidth: maxWidth);
final Size middleSize = layoutChild(_ToolbarSlot.middle, constraints);
final double middleStartMargin = leadingWidth + middleSpacing;
double middleStart = middleStartMargin;
final double middleY = (size.height - middleSize.height) / 2.0;
// If the centered middle will not fit between the leading and trailing
// widgets, then align its left or right edge with the adjacent boundary.
if (centerMiddle) {
middleStart = (size.width - middleSize.width) / 2.0;
if (middleStart + middleSize.width > size.width - trailingWidth) {
middleStart =
size.width - trailingWidth - middleSize.width - middleSpacing;
} else if (middleStart < middleStartMargin) {
middleStart = middleStartMargin;
}
}
final double middleX;
switch (textDirection) {
case TextDirection.rtl:
middleX = size.width - middleSize.width - middleStart;
case TextDirection.ltr:
middleX = middleStart;
}
positionChild(_ToolbarSlot.middle, Offset(middleX, middleY));
}
}
@override
bool shouldRelayout(_ToolbarLayout oldDelegate) {
return oldDelegate.centerMiddle != centerMiddle ||
oldDelegate.middleSpacing != middleSpacing ||
oldDelegate.textDirection != textDirection;
}
}
// END GENERATED TOKEN PROPERTIES - AppBar
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/no_shadow_scroll_behavior.dart | import 'package:flutter/material.dart';
class NoShadowScrollBehavior extends ScrollBehavior {
@override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
switch (getPlatform(context)) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return child;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
default:
return GlowingOverscrollIndicator(
showLeading: false,
showTrailing: false,
axisDirection: details.direction,
color: Theme.of(context).colorScheme.secondary,
child: child,
);
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/github_calendar.dart | import 'dart:math';
import 'package:flutter/material.dart';
class GithubCalendar extends StatelessWidget {
const GithubCalendar({
super.key,
required this.color,
required this.data,
this.initialColor = const Color.fromARGB(255, 235, 237, 240),
this.boxSize = 12,
this.boxPadding = 5,
this.height = 119,
this.style = const TextStyle(),
});
final Color color;
final List<int> data;
final Color initialColor;
final double boxPadding;
final double boxSize;
final double height;
final TextStyle style;
final _monthsHeight = 15.0;
final _days = const [
'Mon',
'Tues',
'Wed',
'Thur',
'Fri',
'Sat',
'Sun',
];
final _months = const [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
@override
Widget build(BuildContext context) {
final boxSizeAndPadding = boxSize + boxPadding;
final now = DateTime.now();
var days = now.weekday + 16 * 7;
final dr = Duration(days: days);
final yy = now.subtract(dr);
final listM = <int>[];
var lastM = yy.month;
var lastP = 0;
for (var i = 0; i <= 16; i++) {
final cM = yy.add(Duration(days: 7 * i)).month;
if (cM != lastM) {
listM.add(i - lastP);
lastP = i;
lastM = cM;
}
}
listM.add((now.day.toDouble() / 7).ceil());
days = 0;
for (var element in listM) {
days += element;
}
days *= 7;
return DefaultTextStyle(
style: style,
child: Row(
children: <Widget>[
SizedBox(
width: 25,
child: Column(
children: <Widget>[
SizedBox(height: _monthsHeight),
SizedBox(
height: boxSizeAndPadding,
child: Text(_days[(now.weekday - 7 + 7) % 7])),
SizedBox(height: boxSizeAndPadding * 2 + 2),
SizedBox(
height: boxSizeAndPadding,
child: Text(_days[(now.weekday - 4 + 7) % 7])),
SizedBox(height: boxSizeAndPadding * 2 + 2),
SizedBox(
height: boxSizeAndPadding,
child: Text(_days[(now.weekday - 1 + 7) % 7])),
],
),
),
Expanded(
child: Column(
children: <Widget>[
Row(
children: List.generate(
listM.length,
(index) {
final m = ((now.month - (listM.length - index)) % 12);
final int width =
listM[index] * boxSizeAndPadding.toInt();
return Container(
alignment: Alignment.centerLeft,
height: _monthsHeight,
width: width.toDouble() + 2.0,
child: Text(_months[m]),
);
},
),
),
SizedBox(
height: boxSizeAndPadding * 7,
child: SquareWall(
color: color,
initialColor: initialColor,
boxSize: boxSize,
days: days,
data: data,
max: data.reduce(max),
boxPadding: boxPadding,
),
),
],
),
),
],
),
);
}
}
class SquareWall extends StatelessWidget {
const SquareWall({
super.key,
required this.days,
required this.initialColor,
required this.boxSize,
required this.boxPadding,
required this.color,
required this.data,
required this.max,
});
final int days;
final Color initialColor;
final double boxSize;
final double boxPadding;
final Color color;
final List<int> data;
final int max;
@override
Widget build(BuildContext context) {
return GridView.count(
physics: const ClampingScrollPhysics(),
scrollDirection: Axis.horizontal,
crossAxisSpacing: boxPadding,
mainAxisSpacing: boxPadding,
crossAxisCount: 7,
children: List.generate(
days,
(index) {
final curColor = index >= data.length
? initialColor
: Color.lerp(initialColor, color, data[index] / max * 1.5);
return Container(
width: boxSize,
height: boxSize,
decoration: BoxDecoration(
border: index == days - 1
? Border.all(
color: Theme.of(context).primaryColor,
width: 1,
style: BorderStyle.solid)
: Border.all(style: BorderStyle.none),
borderRadius: BorderRadius.circular(3),
color: curColor,
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/color_list.dart | import 'package:flutter/material.dart';
class ColorList extends StatefulWidget {
final int starCount;
final double rating;
final Color color;
final Color borderColor;
final double size;
final bool readonly;
final bool showFullOnly;
final bool showRTL;
final double spacing;
final Function(double) onRatingChanged;
const ColorList({
super.key,
this.starCount = 5,
this.rating = 0.0,
this.color = Colors.amber,
this.borderColor = Colors.grey,
this.size = 20,
required this.onRatingChanged,
this.readonly = true,
this.showFullOnly = false,
this.showRTL = false,
this.spacing = 0.0,
});
@override
ColorListState createState() => ColorListState();
}
class ColorListState extends State<ColorList> {
late double _currentRating = widget.rating;
@override
void initState() {
super.initState();
}
Widget _buildStar(BuildContext context, int index) {
IconData iconData = Icons.star_border;
Color iconColor = widget.borderColor;
if (index < _currentRating.floor()) {
iconData = Icons.star;
iconColor = widget.color;
} else if (index == _currentRating.floor() &&
_currentRating - _currentRating.floor() > 0.0) {
iconData = Icons.star_half;
iconColor = widget.color;
}
return widget.showFullOnly && _currentRating <= index
? Container()
: InkWell(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: () {
if (!widget.readonly) {
setState(() {
_currentRating = index + 1.0;
});
widget.onRatingChanged.call(_currentRating);
}
},
child: Container(
margin: widget.showRTL
? EdgeInsets.only(left: widget.spacing)
: EdgeInsets.only(right: widget.spacing),
child: Icon(
iconData,
color: iconColor,
size: widget.size,
),
),
);
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment:
widget.showRTL ? MainAxisAlignment.end : MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: List.generate(
widget.starCount, (index) => _buildStar(context, index)),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/star_rating.dart | import 'package:flutter/material.dart';
class StarRating extends StatefulWidget {
final int starCount;
final double rating;
final Color color;
final Color borderColor;
final double size;
final bool readonly;
final bool showFullOnly;
final bool showRTL;
final double spacing;
final Function(double) onRatingChanged;
const StarRating({
super.key,
this.starCount = 5,
this.rating = 0.0,
this.color = Colors.amber,
this.borderColor = Colors.grey,
this.size = 20,
required this.onRatingChanged,
this.readonly = true,
this.showFullOnly = false,
this.showRTL = false,
this.spacing = 0.0,
});
@override
StarRatingState createState() => StarRatingState();
}
class StarRatingState extends State<StarRating> {
late double _currentRating = widget.rating;
@override
void initState() {
super.initState();
}
Widget _buildStar(BuildContext context, int index) {
IconData iconData = Icons.star_border;
Color iconColor = widget.borderColor;
if (index < _currentRating.floor()) {
iconData = Icons.star;
iconColor = widget.color;
} else if (index == _currentRating.floor() &&
_currentRating - _currentRating.floor() > 0.0) {
iconData = Icons.star_half;
iconColor = widget.color;
}
return widget.showFullOnly && _currentRating <= index
? Container()
: InkWell(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
onTap: () {
if (!widget.readonly) {
setState(() {
_currentRating = index + 1.0;
});
widget.onRatingChanged.call(_currentRating);
}
},
child: Container(
margin: widget.showRTL
? EdgeInsets.only(left: widget.spacing)
: EdgeInsets.only(right: widget.spacing),
child: Icon(
iconData,
color: iconColor,
size: widget.size,
),
),
);
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment:
widget.showRTL ? MainAxisAlignment.end : MainAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: List.generate(
widget.starCount, (index) => _buildStar(context, index)),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/salomon_bottom_bar.dart | import 'package:readar/Resources/gaps.dart';
import 'package:flutter/material.dart';
class SalomonBottomBar extends StatelessWidget {
/// A bottom bar that faithfully follows the design by Aurélien Salomon
///
/// https://dribbble.com/shots/5925052-Google-Bottom-Bar-Navigation-Pattern/
const SalomonBottomBar({
super.key,
required this.items,
this.backgroundColor,
this.currentIndex = 0,
this.onTap,
this.selectedItemColor,
this.unselectedItemColor,
this.selectedColorOpacity,
this.boxShadow,
this.title,
this.borderRadius = 0,
this.itemShape = const StadiumBorder(),
this.margin = const EdgeInsets.all(8),
this.itemPadding = const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
this.duration = const Duration(milliseconds: 500),
this.curve = Curves.easeOutQuint,
});
/// A list of tabs to display, ie `Home`, `Likes`, etc
final List<SalomonBottomBarItem> items;
/// The tab to display.
final int currentIndex;
/// Returns the index of the tab that was tapped.
final Function(int)? onTap;
/// The background color of the bar.
final Color? backgroundColor;
/// The color of the icon and text when the item is selected.
final Color? selectedItemColor;
/// The color of the icon and text when the item is not selected.
final Color? unselectedItemColor;
/// The opacity of color of the touchable background when the item is selected.
final double? selectedColorOpacity;
/// The border shape of each item.
final ShapeBorder itemShape;
/// A convenience field for the margin surrounding the entire widget.
final EdgeInsets margin;
/// The padding of each item.
final EdgeInsets itemPadding;
/// The transition duration
final Duration duration;
/// The transition curve
final Curve curve;
final Widget? title;
final double borderRadius;
final List<BoxShadow>? boxShadow;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Container(
decoration: BoxDecoration(
boxShadow: boxShadow ??
[
BoxShadow(
color: Theme.of(context).shadowColor.withAlpha(70),
offset: const Offset(0, 14),
blurRadius: 18,
spreadRadius: 0,
),
],
color: backgroundColor ?? Colors.transparent,
borderRadius: BorderRadius.vertical(
top: Radius.circular(borderRadius),
bottom: Radius.circular(borderRadius),
),
),
child: SafeArea(
minimum: margin,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: [
title ?? MyGaps.empty,
Row(
/// Using a different alignment when there are 2 items or less
/// so it behaves the same as BottomNavigationBar.
mainAxisAlignment: items.length <= 2
? MainAxisAlignment.spaceEvenly
: MainAxisAlignment.spaceBetween,
children: [
for (final item in items)
TweenAnimationBuilder<double>(
tween: Tween(
end: items.indexOf(item) == currentIndex ? 1.0 : 0.0,
),
curve: curve,
duration: duration,
builder: (context, t, _) {
final selectedColor = item.selectedColor ??
selectedItemColor ??
theme.primaryColor;
final unselectedColor = item.unselectedColor ??
unselectedItemColor ??
theme.iconTheme.color;
return Material(
color: Color.lerp(
selectedColor.withOpacity(0.0),
selectedColor
.withOpacity(selectedColorOpacity ?? 0.1),
t),
shape: itemShape,
child: InkWell(
onTap: () => onTap?.call(items.indexOf(item)),
customBorder: itemShape,
focusColor: selectedColor.withOpacity(0.1),
highlightColor: selectedColor.withOpacity(0.1),
splashColor: selectedColor.withOpacity(0.1),
hoverColor: selectedColor.withOpacity(0.1),
child: Padding(
padding: itemPadding -
(Directionality.of(context) == TextDirection.ltr
? EdgeInsets.only(
right: itemPadding.right * t)
: EdgeInsets.only(
left: itemPadding.left * t)),
child: Row(
children: [
IconTheme(
data: IconThemeData(
color: Color.lerp(
unselectedColor, selectedColor, t),
size: 24,
),
child: items.indexOf(item) == currentIndex
? item.activeIcon ?? item.icon
: item.icon,
),
ClipRect(
clipBehavior: Clip.antiAlias,
child: SizedBox(
/// TODO: Constrain item height without a fixed value
///
/// The Align property appears to make these full height, would be
/// best to find a way to make it respond only to padding.
height: 20,
child: Align(
alignment: const Alignment(-0.2, 0.0),
widthFactor: t,
child: Padding(
padding: Directionality.of(context) ==
TextDirection.ltr
? EdgeInsets.only(
left: itemPadding.left / 2,
right: itemPadding.right)
: EdgeInsets.only(
left: itemPadding.left,
right: itemPadding.right / 2),
child: DefaultTextStyle(
style: TextStyle(
color: Color.lerp(
selectedColor.withOpacity(0.0),
selectedColor,
t),
fontWeight: FontWeight.w600,
),
child: item.title,
),
),
),
),
),
],
),
),
),
);
},
),
],
),
],
),
),
);
}
}
/// A tab to display in a [SalomonBottomBar]
class SalomonBottomBarItem {
/// An icon to display.
final Widget icon;
/// An icon to display when this tab bar is active.
final Widget? activeIcon;
/// Text to display, ie `Home`
final Widget title;
/// A primary color to use for this tab.
final Color? selectedColor;
/// The color to display when this tab is not selected.
final Color? unselectedColor;
SalomonBottomBarItem({
required this.icon,
required this.title,
this.selectedColor,
this.unselectedColor,
this.activeIcon,
});
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/progress_bar.dart | import 'package:flutter/material.dart';
class ProgressBar extends StatelessWidget {
const ProgressBar({
super.key,
this.color = Colors.red,
this.backgroundColor = Colors.grey,
this.enableAnimation = true,
required this.progress,
});
final Color backgroundColor;
final Color color;
final double progress;
final bool enableAnimation;
@override
Widget build(BuildContext context) {
final child = Container(
decoration: ShapeDecoration(
shape: const StadiumBorder(),
color: color,
),
);
return Container(
clipBehavior: Clip.hardEdge,
height: 3,
alignment: Alignment.centerLeft,
decoration: ShapeDecoration(
shape: const StadiumBorder(),
color: backgroundColor,
),
child: enableAnimation
? AnimatedAlign(
duration: const Duration(milliseconds: 260),
alignment: const Alignment(1, 0),
widthFactor: progress,
child: child,
)
: FractionallySizedBox(
widthFactor: progress,
child: child,
),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Custom/tab_indicator.dart | import 'package:flutter/material.dart';
class TabIndicator extends Decoration {
final TabController? tabController;
final double indicatorBottom;
final double indicatorWidth;
const TabIndicator({
this.borderSide = const BorderSide(width: 6),
this.tabController,
this.indicatorBottom = 16,
this.indicatorWidth = 34,
});
final BorderSide borderSide;
@override
BoxPainter createBoxPainter([VoidCallback? onChanged]) {
return _UnderlinePainter(
this,
onChanged,
tabController?.animation,
indicatorWidth,
);
}
Rect _indicatorRectFor(Rect indicator, TextDirection textDirection) {
double w = indicatorWidth;
double centerWidth = (indicator.left + indicator.right) / 2;
return Rect.fromLTWH(
tabController?.animation == null ? centerWidth - w / 2 : centerWidth - 1,
indicator.bottom - borderSide.width - indicatorBottom,
w,
borderSide.width,
);
}
@override
Path getClipPath(Rect rect, TextDirection textDirection) {
return Path()..addRect(_indicatorRectFor(rect, textDirection));
}
}
class _UnderlinePainter extends BoxPainter {
Animation<double>? animation;
double indicatorWidth;
_UnderlinePainter(this.decoration, VoidCallback? onChanged, this.animation,
this.indicatorWidth)
: super(onChanged);
final TabIndicator decoration;
@override
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
assert(configuration.size != null);
final Rect rect = offset & configuration.size!;
final TextDirection textDirection = configuration.textDirection!;
final Rect indicator = decoration._indicatorRectFor(rect, textDirection)
..deflate(decoration.borderSide.width / 2.0);
final Paint paint = decoration.borderSide.toPaint()
..style = PaintingStyle.fill
..strokeCap = StrokeCap.round;
if (animation != null) {
num x = animation!.value;
num d = x - x.truncate();
num? y;
if (d < 0.5) {
y = 2 * d;
} else if (d > 0.5) {
y = 1 - 2 * (d - 0.5);
} else {
y = 1;
}
canvas.drawRRect(
RRect.fromRectXY(
Rect.fromCenter(
center: indicator.centerLeft,
width: indicatorWidth * 6 * y + indicatorWidth,
height: indicatorWidth),
2,
2),
paint);
} else {
canvas.drawLine(indicator.bottomLeft, indicator.bottomRight, paint);
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_lists.dart | /// Drag and drop list reordering for two level lists.
///
/// [DragAndDropLists] is the main widget, and contains numerous options for controlling overall list presentation.
///
/// The children of [DragAndDropLists] are [DragAndDropList] or another class that inherits from
/// [DragAndDropListInterface] such as [DragAndDropListExpansion]. These lists can be reordered at will.
/// Each list contains its own properties, and can be styled separately if the defaults provided to [DragAndDropLists]
/// should be overridden.
///
/// The children of a [DragAndDropListInterface] are [DragAndDropItem]. These are the individual elements and can be
/// reordered within their own list and into other lists. If they should not be able to be reordered, they can also
/// be locked individually.
library drag_and_drop_lists;
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'drag_and_drop_builder_parameters.dart';
import 'drag_and_drop_item.dart';
import 'drag_and_drop_item_target.dart';
import 'drag_and_drop_list_interface.dart';
import 'drag_and_drop_list_target.dart';
import 'drag_and_drop_list_wrapper.dart';
import 'drag_handle.dart';
export 'drag_and_drop_builder_parameters.dart';
export 'drag_and_drop_item.dart';
export 'drag_and_drop_item_target.dart';
export 'drag_and_drop_item_wrapper.dart';
export 'drag_and_drop_list.dart';
export 'drag_and_drop_list_expansion.dart';
export 'drag_and_drop_list_target.dart';
export 'drag_and_drop_list_wrapper.dart';
export 'drag_handle.dart';
typedef OnItemReorder = void Function(
int oldItemIndex,
int oldListIndex,
int newItemIndex,
int newListIndex,
);
typedef OnItemAdd = void Function(
DragAndDropItem newItem,
int listIndex,
int newItemIndex,
);
typedef OnListAdd = void Function(
DragAndDropListInterface newList, int newListIndex);
typedef OnListReorder = void Function(int oldListIndex, int newListIndex);
typedef OnListDraggingChanged = void Function(
DragAndDropListInterface? list,
bool dragging,
);
typedef ListOnWillAccept = bool Function(
DragAndDropListInterface? incoming,
DragAndDropListInterface? target,
);
typedef ListOnAccept = void Function(
DragAndDropListInterface incoming,
DragAndDropListInterface target,
);
typedef ListTargetOnWillAccept = bool Function(
DragAndDropListInterface? incoming, DragAndDropListTarget target);
typedef ListTargetOnAccept = void Function(
DragAndDropListInterface incoming, DragAndDropListTarget target);
typedef OnItemDraggingChanged = void Function(
DragAndDropItem item,
bool dragging,
);
typedef ItemOnWillAccept = bool Function(
DragAndDropItem? incoming,
DragAndDropItem target,
);
typedef ItemOnAccept = void Function(
DragAndDropItem incoming,
DragAndDropItem target,
);
typedef ItemTargetOnWillAccept = bool Function(
DragAndDropItem? incoming, DragAndDropItemTarget target);
typedef ItemTargetOnAccept = void Function(
DragAndDropItem incoming,
DragAndDropListInterface parentList,
DragAndDropItemTarget target,
);
class DragAndDropLists extends StatefulWidget {
/// The child lists to be displayed.
/// If any of these children are [DragAndDropListExpansion] or inherit from
/// [DragAndDropListExpansionInterface], [listGhost] must not be null.
final List<DragAndDropListInterface> children;
/// Calls this function when a list element is reordered.
/// Takes into account the index change when removing an item, so the
/// [newItemIndex] can be used directly when inserting.
final OnItemReorder onItemReorder;
/// Calls this function when a list is reordered.
/// Takes into account the index change when removing a list, so the
/// [newListIndex] can be used directly when inserting.
final OnListReorder onListReorder;
/// Calls this function when a new item has been added.
final OnItemAdd? onItemAdd;
/// Calls this function when a new list has been added.
final OnListAdd? onListAdd;
/// Set in order to provide custom acceptance criteria for when a list can be
/// dropped onto a specific other list
final ListOnWillAccept? listOnWillAccept;
/// Set in order to get the lists involved in a drag and drop operation after
/// a list has been accepted. For general use cases where only reordering is
/// necessary, only [onListReorder] or [onListAdd] is needed, and this should
/// be left null. [onListReorder] or [onListAdd] will be called after this.
final ListOnAccept? listOnAccept;
/// Set in order to provide custom acceptance criteria for when a list can be
/// dropped onto a specific target. This target always exists as the last
/// target the DragAndDropLists, and also can be used independently.
final ListTargetOnWillAccept? listTargetOnWillAccept;
/// Set in order to get the list and target involved in a drag and drop
/// operation after a list has been accepted. For general use cases where only
/// reordering is necessary, only [onListReorder] or [onListAdd] is needed,
/// and this should be left null. [onListReorder] or [onListAdd] will be
/// called after this.
final ListTargetOnAccept? listTargetOnAccept;
/// Called when a list dragging is starting or ending
final OnListDraggingChanged? onListDraggingChanged;
/// Set in order to provide custom acceptance criteria for when a item can be
/// dropped onto a specific other item
final ItemOnWillAccept? itemOnWillAccept;
/// Set in order to get the items involved in a drag and drop operation after
/// an item has been accepted. For general use cases where only reordering is
/// necessary, only [onItemReorder] or [onItemAdd] is needed, and this should
/// be left null. [onItemReorder] or [onItemAdd] will be called after this.
final ItemOnAccept? itemOnAccept;
/// Set in order to provide custom acceptance criteria for when a item can be
/// dropped onto a specific target. This target always exists as the last
/// target for list of items, and also can be used independently.
final ItemTargetOnWillAccept? itemTargetOnWillAccept;
/// Set in order to get the item and target involved in a drag and drop
/// operation after a item has been accepted. For general use cases where only
/// reordering is necessary, only [onItemReorder] or [onItemAdd] is needed,
/// and this should be left null. [onItemReorder] or [onItemAdd] will be
/// called after this.
final ItemTargetOnAccept? itemTargetOnAccept;
/// Called when an item dragging is starting or ending
final OnItemDraggingChanged? onItemDraggingChanged;
/// Width of a list item when it is being dragged.
final double? itemDraggingWidth;
/// The widget that will be displayed at a potential drop position in a list
/// when an item is being dragged.
final Widget? itemGhost;
/// The opacity of the [itemGhost]. This must be between 0 and 1.
final double itemGhostOpacity;
/// Length of animation for the change in an item size when displaying the [itemGhost].
final int itemSizeAnimationDurationMilliseconds;
/// If true, drag an item after doing a long press. If false, drag immediately.
final bool itemDragOnLongPress;
/// The decoration surrounding an item while it is in the process of being dragged.
final Decoration? itemDecorationWhileDragging;
/// The opacity of the item while it is in the process of being dragged.
final double? itemOpacityWhileDragging;
/// A widget that will be displayed between each individual item.
final Widget? itemDivider;
/// The width of a list when dragging.
final double? listDraggingWidth;
/// The widget to be displayed as the last element in the DragAndDropLists,
/// where a list will be accepted as the last list.
final Widget? listTarget;
/// The widget to be displayed at a potential list position while a list is being dragged.
/// This must not be null when [children] includes one or more
/// [DragAndDropListExpansion] or other class that inherit from [DragAndDropListExpansionInterface].
final Widget? listGhost;
/// The opacity of [listGhost]. It must be between 0 and 1.
final double listGhostOpacity;
/// The duration of the animation for the change in size when a [listGhost] is
/// displayed at list position.
final int listSizeAnimationDurationMilliseconds;
/// Whether a list should be dragged on a long or short press.
/// When true, the list will be dragged after a long press.
/// When false, it will be dragged immediately.
final bool listDragOnLongPress;
/// The decoration surrounding a list.
final Decoration? listDecoration;
/// The decoration surrounding a list while it is in the process of being dragged.
final Decoration? listDecorationWhileDragging;
/// The decoration surrounding the inner list of items.
final Decoration? listInnerDecoration;
/// A widget that will be displayed between each individual list.
final Widget? listDivider;
/// A widget that will be displayed above the list.
final Widget? header;
/// Whether it should put a divider on the last list or not.
final bool listDividerOnLastChild;
/// The padding between each individual list.
final EdgeInsets? listPadding;
/// A widget that will be displayed whenever a list contains no items.
final Widget? contentsWhenEmpty;
/// The width of each individual list. This must be set to a finite value when
/// [axis] is set to Axis.horizontal.
final double listWidth;
/// The height of the target for the last item in a list. This should be large
/// enough to easily drag an item into the last position of a list.
final double lastItemTargetHeight;
/// Add the same height as the lastItemTargetHeight to the top of the list.
/// This is useful when setting the [listInnerDecoration] to maintain visual
/// continuity between the top and the bottom
final bool addLastItemTargetHeightToTop;
/// The height of the target for the last list. This should be large
/// enough to easily drag a list to the last position in the DragAndDropLists.
final double lastListTargetSize;
/// The default vertical alignment of list contents.
final CrossAxisAlignment verticalAlignment;
/// The default horizontal alignment of list contents.
final MainAxisAlignment horizontalAlignment;
/// Determines whether the DragAndDropLists are displayed in a horizontal or
/// vertical manner.
/// Set [axis] to Axis.vertical for vertical arrangement of the lists.
/// Set [axis] to Axis.horizontal for horizontal arrangement of the lists.
/// If [axis] is set to Axis.horizontal, [listWidth] must be set to some finite number.
final Axis axis;
/// Whether or not to return a widget or a sliver-compatible list.
/// Set to true if using as a sliver. If true, a [scrollController] must be provided.
/// Set to false if using in a widget only.
final bool sliverList;
/// A scroll controller that can be used for the scrolling of the first level lists.
/// This must be set if [sliverList] is set to true.
final ScrollController? scrollController;
/// Set to true in order to disable all scrolling of the lists.
/// Note: to disable scrolling for sliver lists, it is also necessary in your
/// parent CustomScrollView to set physics to NeverScrollableScrollPhysics()
final bool disableScrolling;
/// Set a custom drag handle to use iOS-like handles to drag rather than long
/// or short presses
final DragHandle? listDragHandle;
/// Set a custom drag handle to use iOS-like handles to drag rather than long
/// or short presses
final DragHandle? itemDragHandle;
/// Constrain the dragging axis in a vertical list to only allow dragging on
/// the vertical axis. By default this is set to true. This may be useful to
/// disable when setting customDragTargets
final bool constrainDraggingAxis;
/// If you put a widget before DragAndDropLists there's an unexpected padding
/// before the list renders. This is the default behaviour for ListView which
/// is used internally. To remove the padding, set this field to true
/// https://github.com/flutter/flutter/issues/14842#issuecomment-371344881
final bool removeTopPadding;
DragAndDropLists({
required this.children,
required this.onItemReorder,
required this.onListReorder,
this.onItemAdd,
this.onListAdd,
this.onListDraggingChanged,
this.listOnWillAccept,
this.listOnAccept,
this.listTargetOnWillAccept,
this.listTargetOnAccept,
this.onItemDraggingChanged,
this.itemOnWillAccept,
this.itemOnAccept,
this.itemTargetOnWillAccept,
this.itemTargetOnAccept,
this.itemDraggingWidth,
this.itemGhost,
this.header,
this.itemGhostOpacity = 0.3,
this.itemSizeAnimationDurationMilliseconds = 150,
this.itemDragOnLongPress = true,
this.itemDecorationWhileDragging,
this.itemOpacityWhileDragging,
this.itemDivider,
this.listDraggingWidth,
this.listTarget,
this.listGhost,
this.listGhostOpacity = 0.3,
this.listSizeAnimationDurationMilliseconds = 150,
this.listDragOnLongPress = true,
this.listDecoration,
this.listDecorationWhileDragging,
this.listInnerDecoration,
this.listDivider,
this.listDividerOnLastChild = true,
this.listPadding,
this.contentsWhenEmpty,
this.listWidth = double.infinity,
this.lastItemTargetHeight = 20,
this.addLastItemTargetHeightToTop = false,
this.lastListTargetSize = 110,
this.verticalAlignment = CrossAxisAlignment.start,
this.horizontalAlignment = MainAxisAlignment.start,
this.axis = Axis.vertical,
this.sliverList = false,
this.scrollController,
this.disableScrolling = false,
this.listDragHandle,
this.itemDragHandle,
this.constrainDraggingAxis = true,
this.removeTopPadding = false,
super.key,
}) {
if (listGhost == null &&
children.whereType<DragAndDropListExpansionInterface>().isNotEmpty) {
throw Exception(
'If using DragAndDropListExpansion, you must provide a non-null listGhost');
}
if (sliverList && scrollController == null) {
throw Exception(
'A scroll controller must be provided when using sliver lists');
}
if (axis == Axis.horizontal && listWidth == double.infinity) {
throw Exception(
'A finite width must be provided when setting the axis to horizontal');
}
if (axis == Axis.horizontal && sliverList) {
throw Exception(
'Combining a sliver list with a horizontal list is currently unsupported');
}
}
@override
State<StatefulWidget> createState() => DragAndDropListsState();
}
class DragAndDropListsState extends State<DragAndDropLists> {
ScrollController? _scrollController;
bool _pointerDown = false;
double? _pointerYPosition;
double? _pointerXPosition;
bool _scrolling = false;
final PageStorageBucket _pageStorageBucket = PageStorageBucket();
@override
void initState() {
if (widget.scrollController != null) {
_scrollController = widget.scrollController;
} else {
_scrollController = ScrollController();
}
super.initState();
}
@override
Widget build(BuildContext context) {
var parameters = DragAndDropBuilderParameters(
listGhost: widget.listGhost,
listGhostOpacity: widget.listGhostOpacity,
listDraggingWidth: widget.listDraggingWidth,
itemDraggingWidth: widget.itemDraggingWidth,
listSizeAnimationDuration: widget.listSizeAnimationDurationMilliseconds,
listDragOnLongPress: widget.listDragOnLongPress,
itemDragOnLongPress: widget.itemDragOnLongPress,
listPadding: widget.listPadding,
itemSizeAnimationDuration: widget.itemSizeAnimationDurationMilliseconds,
onPointerDown: _onPointerDown,
onPointerUp: _onPointerUp,
onPointerMove: _onPointerMove,
onItemReordered: _internalOnItemReorder,
onItemDropOnLastTarget: _internalOnItemDropOnLastTarget,
onListReordered: _internalOnListReorder,
onItemDraggingChanged: widget.onItemDraggingChanged,
onListDraggingChanged: widget.onListDraggingChanged,
listOnWillAccept: widget.listOnWillAccept,
listTargetOnWillAccept: widget.listTargetOnWillAccept,
itemOnWillAccept: widget.itemOnWillAccept,
itemTargetOnWillAccept: widget.itemTargetOnWillAccept,
itemGhostOpacity: widget.itemGhostOpacity,
itemDivider: widget.itemDivider,
itemDecorationWhileDragging: widget.itemDecorationWhileDragging,
itemOpacityWhileDragging: widget.itemOpacityWhileDragging,
verticalAlignment: widget.verticalAlignment,
axis: widget.axis,
itemGhost: widget.itemGhost,
listDecoration: widget.listDecoration,
listDecorationWhileDragging: widget.listDecorationWhileDragging,
listInnerDecoration: widget.listInnerDecoration,
listWidth: widget.listWidth,
lastItemTargetHeight: widget.lastItemTargetHeight,
addLastItemTargetHeightToTop: widget.addLastItemTargetHeightToTop,
listDragHandle: widget.listDragHandle,
itemDragHandle: widget.itemDragHandle,
constrainDraggingAxis: widget.constrainDraggingAxis,
disableScrolling: widget.disableScrolling,
);
DragAndDropListTarget dragAndDropListTarget = DragAndDropListTarget(
parameters: parameters,
onDropOnLastTarget: _internalOnListDropOnLastTarget,
lastListTargetSize: widget.lastListTargetSize,
child: widget.listTarget,
);
if (widget.children.isNotEmpty) {
Widget outerListHolder;
if (widget.sliverList) {
outerListHolder = _buildSliverList(dragAndDropListTarget, parameters);
} else if (widget.disableScrolling) {
outerListHolder =
_buildUnscrollableList(dragAndDropListTarget, parameters);
} else {
outerListHolder = _buildListView(parameters, dragAndDropListTarget);
}
if (widget.children
.whereType<DragAndDropListExpansionInterface>()
.isNotEmpty) {
outerListHolder = PageStorage(
bucket: _pageStorageBucket,
child: outerListHolder,
);
}
return outerListHolder;
} else {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
widget.header ?? Container(),
widget.contentsWhenEmpty ?? const Text('Empty'),
dragAndDropListTarget,
],
),
);
}
}
SliverList _buildSliverList(DragAndDropListTarget dragAndDropListTarget,
DragAndDropBuilderParameters parameters) {
bool includeSeparators = widget.listDivider != null;
int childrenCount = _calculateChildrenCount(includeSeparators);
return SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return _buildInnerList(index, childrenCount, dragAndDropListTarget,
includeSeparators, parameters);
},
childCount: childrenCount,
),
);
}
Widget _buildUnscrollableList(DragAndDropListTarget dragAndDropListTarget,
DragAndDropBuilderParameters parameters) {
if (widget.axis == Axis.vertical) {
return Column(
children: _buildOuterList(dragAndDropListTarget, parameters),
);
} else {
return Row(
children: _buildOuterList(dragAndDropListTarget, parameters),
);
}
}
Widget _buildListView(DragAndDropBuilderParameters parameters,
DragAndDropListTarget dragAndDropListTarget) {
Widget listView = ListView(
scrollDirection: widget.axis,
controller: _scrollController,
children: _buildOuterList(dragAndDropListTarget, parameters),
);
return widget.removeTopPadding
? MediaQuery.removePadding(
removeTop: true,
context: context,
child: listView,
)
: listView;
}
List<Widget> _buildOuterList(DragAndDropListTarget dragAndDropListTarget,
DragAndDropBuilderParameters parameters) {
bool includeSeparators = widget.listDivider != null;
int childrenCount = _calculateChildrenCount(includeSeparators);
List<Widget> list = [widget.header ?? Container()];
list.addAll(List.generate(childrenCount, (index) {
return _buildInnerList(index, childrenCount, dragAndDropListTarget,
includeSeparators, parameters);
}));
return list;
}
int _calculateChildrenCount(bool includeSeparators) {
if (includeSeparators) {
return (widget.children.length * 2) -
(widget.listDividerOnLastChild ? 0 : 1) +
1;
} else {
return widget.children.length + 1;
}
}
Widget _buildInnerList(
int index,
int childrenCount,
DragAndDropListTarget dragAndDropListTarget,
bool includeSeparators,
DragAndDropBuilderParameters parameters) {
if (index == childrenCount - 1) {
return dragAndDropListTarget;
} else if (includeSeparators && index.isOdd) {
return widget.listDivider!;
} else {
return DragAndDropListWrapper(
dragAndDropList:
widget.children[(includeSeparators ? index / 2 : index).toInt()],
parameters: parameters,
);
}
}
_internalOnItemReorder(DragAndDropItem reordered, DragAndDropItem receiver) {
if (widget.itemOnAccept != null) {
widget.itemOnAccept!(reordered, receiver);
}
int reorderedListIndex = -1;
int reorderedItemIndex = -1;
int receiverListIndex = -1;
int receiverItemIndex = -1;
for (int i = 0; i < widget.children.length; i++) {
if (reorderedItemIndex == -1) {
reorderedItemIndex =
widget.children[i].children!.indexWhere((e) => reordered == e);
if (reorderedItemIndex != -1) reorderedListIndex = i;
}
if (receiverItemIndex == -1) {
receiverItemIndex =
widget.children[i].children!.indexWhere((e) => receiver == e);
if (receiverItemIndex != -1) receiverListIndex = i;
}
if (reorderedItemIndex != -1 && receiverItemIndex != -1) {
break;
}
}
if (reorderedItemIndex == -1) {
// this is a new item
if (widget.onItemAdd != null) {
widget.onItemAdd!(reordered, receiverListIndex, receiverItemIndex);
}
} else {
if (reorderedListIndex == receiverListIndex &&
receiverItemIndex > reorderedItemIndex) {
// same list, so if the new position is after the old position, the removal of the old item must be taken into account
receiverItemIndex--;
}
widget.onItemReorder(reorderedItemIndex, reorderedListIndex,
receiverItemIndex, receiverListIndex);
}
}
_internalOnListReorder(
DragAndDropListInterface reordered, DragAndDropListInterface receiver) {
int reorderedListIndex = widget.children.indexWhere((e) => reordered == e);
int receiverListIndex = widget.children.indexWhere((e) => receiver == e);
int newListIndex = receiverListIndex;
if (widget.listOnAccept != null) widget.listOnAccept!(reordered, receiver);
if (reorderedListIndex == -1) {
// this is a new list
if (widget.onListAdd != null) widget.onListAdd!(reordered, newListIndex);
} else {
if (newListIndex > reorderedListIndex) {
// same list, so if the new position is after the old position, the removal of the old item must be taken into account
newListIndex--;
}
widget.onListReorder(reorderedListIndex, newListIndex);
}
}
_internalOnItemDropOnLastTarget(DragAndDropItem newOrReordered,
DragAndDropListInterface parentList, DragAndDropItemTarget receiver) {
if (widget.itemTargetOnAccept != null) {
widget.itemTargetOnAccept!(newOrReordered, parentList, receiver);
}
int reorderedListIndex = -1;
int reorderedItemIndex = -1;
int receiverListIndex = -1;
int receiverItemIndex = -1;
if (widget.children.isNotEmpty) {
for (int i = 0; i < widget.children.length; i++) {
if (reorderedItemIndex == -1) {
reorderedItemIndex = widget.children[i].children
?.indexWhere((e) => newOrReordered == e) ??
-1;
if (reorderedItemIndex != -1) reorderedListIndex = i;
}
if (receiverItemIndex == -1 && widget.children[i] == parentList) {
receiverListIndex = i;
receiverItemIndex = widget.children[i].children?.length ?? -1;
}
if (reorderedItemIndex != -1 && receiverItemIndex != -1) {
break;
}
}
}
if (reorderedItemIndex == -1) {
if (widget.onItemAdd != null) {
widget.onItemAdd!(
newOrReordered, receiverListIndex, reorderedItemIndex);
}
} else {
if (reorderedListIndex == receiverListIndex &&
receiverItemIndex > reorderedItemIndex) {
// same list, so if the new position is after the old position, the removal of the old item must be taken into account
receiverItemIndex--;
}
widget.onItemReorder(reorderedItemIndex, reorderedListIndex,
receiverItemIndex, receiverListIndex);
}
}
_internalOnListDropOnLastTarget(
DragAndDropListInterface newOrReordered, DragAndDropListTarget receiver) {
// determine if newOrReordered is new or existing
int reorderedListIndex =
widget.children.indexWhere((e) => newOrReordered == e);
if (widget.listOnAccept != null) {
widget.listTargetOnAccept!(newOrReordered, receiver);
}
if (reorderedListIndex >= 0) {
widget.onListReorder(reorderedListIndex, widget.children.length - 1);
} else {
if (widget.onListAdd != null) {
widget.onListAdd!(newOrReordered, reorderedListIndex);
}
}
}
_onPointerMove(PointerMoveEvent event) {
if (_pointerDown) {
_pointerYPosition = event.position.dy;
_pointerXPosition = event.position.dx;
_scrollList();
}
}
_onPointerDown(PointerDownEvent event) {
_pointerDown = true;
_pointerYPosition = event.position.dy;
_pointerXPosition = event.position.dx;
}
_onPointerUp(PointerUpEvent event) {
_pointerDown = false;
}
final int _duration = 30; // in ms
final int _scrollAreaSize = 20;
final double _overDragMin = 5.0;
final double _overDragMax = 20.0;
final double _overDragCoefficient = 3.3;
_scrollList() async {
if (!widget.disableScrolling &&
!_scrolling &&
_pointerDown &&
_pointerYPosition != null &&
_pointerXPosition != null) {
double? newOffset;
var rb = context.findRenderObject()!;
late Size size;
if (rb is RenderBox) {
size = rb.size;
} else if (rb is RenderSliver) {
size = rb.paintBounds.size;
}
var topLeftOffset = localToGlobal(rb, Offset.zero);
var bottomRightOffset = localToGlobal(rb, size.bottomRight(Offset.zero));
try {
if (widget.axis == Axis.vertical) {
newOffset = _scrollListVertical(topLeftOffset, bottomRightOffset);
} else {
var directionality = Directionality.of(context);
if (directionality == TextDirection.ltr) {
newOffset =
_scrollListHorizontalLtr(topLeftOffset, bottomRightOffset);
} else {
newOffset =
_scrollListHorizontalRtl(topLeftOffset, bottomRightOffset);
}
}
} catch (_) {}
if (newOffset != null) {
_scrolling = true;
await _scrollController!.animateTo(newOffset,
duration: Duration(milliseconds: _duration), curve: Curves.linear);
_scrolling = false;
if (_pointerDown) _scrollList();
}
}
}
double? _scrollListVertical(Offset topLeftOffset, Offset bottomRightOffset) {
double top = topLeftOffset.dy;
double bottom = bottomRightOffset.dy;
double? newOffset;
var pointerYPosition = _pointerYPosition;
var scrollController = _scrollController;
if (scrollController != null && pointerYPosition != null) {
if (pointerYPosition < (top + _scrollAreaSize) &&
scrollController.position.pixels >
scrollController.position.minScrollExtent) {
final overDrag =
max((top + _scrollAreaSize) - pointerYPosition, _overDragMax);
newOffset = max(scrollController.position.minScrollExtent,
scrollController.position.pixels - overDrag / _overDragCoefficient);
} else if (pointerYPosition > (bottom - _scrollAreaSize) &&
scrollController.position.pixels <
scrollController.position.maxScrollExtent) {
final overDrag = max<double>(
pointerYPosition - (bottom - _scrollAreaSize), _overDragMax);
newOffset = min(scrollController.position.maxScrollExtent,
scrollController.position.pixels + overDrag / _overDragCoefficient);
}
}
return newOffset;
}
double? _scrollListHorizontalLtr(
Offset topLeftOffset, Offset bottomRightOffset) {
double left = topLeftOffset.dx;
double right = bottomRightOffset.dx;
double? newOffset;
var pointerXPosition = _pointerXPosition;
var scrollController = _scrollController;
if (scrollController != null && pointerXPosition != null) {
if (pointerXPosition < (left + _scrollAreaSize) &&
scrollController.position.pixels >
scrollController.position.minScrollExtent) {
// scrolling toward minScrollExtent
final overDrag = min(
(left + _scrollAreaSize) - pointerXPosition + _overDragMin,
_overDragMax);
newOffset = max(scrollController.position.minScrollExtent,
scrollController.position.pixels - overDrag / _overDragCoefficient);
} else if (pointerXPosition > (right - _scrollAreaSize) &&
scrollController.position.pixels <
scrollController.position.maxScrollExtent) {
// scrolling toward maxScrollExtent
final overDrag = min(
pointerXPosition - (right - _scrollAreaSize) + _overDragMin,
_overDragMax);
newOffset = min(scrollController.position.maxScrollExtent,
scrollController.position.pixels + overDrag / _overDragCoefficient);
}
}
return newOffset;
}
double? _scrollListHorizontalRtl(
Offset topLeftOffset, Offset bottomRightOffset) {
double left = topLeftOffset.dx;
double right = bottomRightOffset.dx;
double? newOffset;
var pointerXPosition = _pointerXPosition;
var scrollController = _scrollController;
if (scrollController != null && pointerXPosition != null) {
if (pointerXPosition < (left + _scrollAreaSize) &&
scrollController.position.pixels <
scrollController.position.maxScrollExtent) {
// scrolling toward maxScrollExtent
final overDrag = min(
(left + _scrollAreaSize) - pointerXPosition + _overDragMin,
_overDragMax);
newOffset = min(scrollController.position.maxScrollExtent,
scrollController.position.pixels + overDrag / _overDragCoefficient);
} else if (pointerXPosition > (right - _scrollAreaSize) &&
scrollController.position.pixels >
scrollController.position.minScrollExtent) {
// scrolling toward minScrollExtent
final overDrag = min(
pointerXPosition - (right - _scrollAreaSize) + _overDragMin,
_overDragMax);
newOffset = max(scrollController.position.minScrollExtent,
scrollController.position.pixels - overDrag / _overDragCoefficient);
}
}
return newOffset;
}
static Offset localToGlobal(RenderObject object, Offset point,
{RenderObject? ancestor}) {
return MatrixUtils.transformPoint(object.getTransformTo(ancestor), point);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_builder_parameters.dart | import 'package:flutter/widgets.dart';
import 'drag_and_drop_list_interface.dart';
import 'drag_and_drop_lists.dart';
typedef OnPointerMove = void Function(PointerMoveEvent event);
typedef OnPointerUp = void Function(PointerUpEvent event);
typedef OnPointerDown = void Function(PointerDownEvent event);
typedef OnItemReordered = void Function(
DragAndDropItem reorderedItem,
DragAndDropItem receiverItem,
);
typedef OnItemDropOnLastTarget = void Function(
DragAndDropItem newOrReorderedItem,
DragAndDropListInterface parentList,
DragAndDropItemTarget receiver,
);
typedef OnListReordered = void Function(
DragAndDropListInterface reorderedList,
DragAndDropListInterface receiverList,
);
class DragAndDropBuilderParameters {
final OnPointerMove? onPointerMove;
final OnPointerUp? onPointerUp;
final OnPointerDown? onPointerDown;
final OnItemReordered? onItemReordered;
final OnItemDropOnLastTarget? onItemDropOnLastTarget;
final OnListReordered? onListReordered;
final ListOnWillAccept? listOnWillAccept;
final ListTargetOnWillAccept? listTargetOnWillAccept;
final OnListDraggingChanged? onListDraggingChanged;
final ItemOnWillAccept? itemOnWillAccept;
final ItemTargetOnWillAccept? itemTargetOnWillAccept;
final OnItemDraggingChanged? onItemDraggingChanged;
final Axis axis;
final CrossAxisAlignment verticalAlignment;
final double? listDraggingWidth;
final bool listDragOnLongPress;
final bool itemDragOnLongPress;
final int itemSizeAnimationDuration;
final Widget? itemGhost;
final double itemGhostOpacity;
final Widget? itemDivider;
final double? itemDraggingWidth;
final Decoration? itemDecorationWhileDragging;
final double? itemOpacityWhileDragging;
final int listSizeAnimationDuration;
final Widget? listGhost;
final double listGhostOpacity;
final EdgeInsets? listPadding;
final Decoration? listDecoration;
final Decoration? listDecorationWhileDragging;
final Decoration? listInnerDecoration;
final double listWidth;
final double lastItemTargetHeight;
final bool addLastItemTargetHeightToTop;
final DragHandle? listDragHandle;
final DragHandle? itemDragHandle;
final bool constrainDraggingAxis;
final bool disableScrolling;
DragAndDropBuilderParameters({
this.onPointerMove,
this.onPointerUp,
this.onPointerDown,
this.onItemReordered,
this.onItemDropOnLastTarget,
this.onListReordered,
this.listDraggingWidth,
this.listOnWillAccept,
this.listTargetOnWillAccept,
this.onListDraggingChanged,
this.itemOnWillAccept,
this.itemTargetOnWillAccept,
this.onItemDraggingChanged,
this.listDragOnLongPress = true,
this.itemDragOnLongPress = true,
this.axis = Axis.vertical,
this.verticalAlignment = CrossAxisAlignment.start,
this.itemSizeAnimationDuration = 150,
this.itemGhostOpacity = 0.3,
this.itemGhost,
this.itemDivider,
this.itemDraggingWidth,
this.itemDecorationWhileDragging,
this.itemOpacityWhileDragging,
this.listSizeAnimationDuration = 150,
this.listGhostOpacity = 0.3,
this.listGhost,
this.listPadding,
this.listDecoration,
this.listDecorationWhileDragging,
this.listInnerDecoration,
this.listWidth = double.infinity,
this.lastItemTargetHeight = 20,
this.addLastItemTargetHeightToTop = false,
this.listDragHandle,
this.itemDragHandle,
this.constrainDraggingAxis = true,
this.disableScrolling = false,
});
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_list_wrapper.dart | import 'package:flutter/material.dart';
import 'drag_and_drop_builder_parameters.dart';
import 'drag_and_drop_list_interface.dart';
import 'drag_handle.dart';
import 'measure_size.dart';
class DragAndDropListWrapper extends StatefulWidget {
final DragAndDropListInterface dragAndDropList;
final DragAndDropBuilderParameters parameters;
DragAndDropListWrapper(
{required this.dragAndDropList, required this.parameters, Key? key})
: super(key: key);
@override
State<StatefulWidget> createState() => _DragAndDropListWrapper();
}
class _DragAndDropListWrapper extends State<DragAndDropListWrapper>
with TickerProviderStateMixin {
DragAndDropListInterface? _hoveredDraggable;
bool _dragging = false;
Size _containerSize = Size.zero;
Size _dragHandleSize = Size.zero;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
Widget dragAndDropListContents =
widget.dragAndDropList.generateWidget(widget.parameters);
Widget draggable;
if (widget.dragAndDropList.canDrag) {
if (widget.parameters.listDragHandle != null) {
Widget dragHandle = MouseRegion(
cursor: SystemMouseCursors.grab,
child: widget.parameters.listDragHandle,
);
Widget feedback =
buildFeedbackWithHandle(dragAndDropListContents, dragHandle);
draggable = MeasureSize(
onSizeChange: (size) {
setState(() {
_containerSize = size!;
});
},
child: Stack(
children: [
Visibility(
visible: !_dragging,
child: dragAndDropListContents,
),
// dragAndDropListContents,
Positioned(
right: widget.parameters.listDragHandle!.onLeft ? null : 0,
left: widget.parameters.listDragHandle!.onLeft ? 0 : null,
top: _dragHandleDistanceFromTop(),
child: Draggable<DragAndDropListInterface>(
data: widget.dragAndDropList,
axis: draggableAxis(),
child: MeasureSize(
onSizeChange: (size) {
setState(() {
_dragHandleSize = size!;
});
},
child: dragHandle,
),
feedback: Transform.translate(
offset: _feedbackContainerOffset(),
child: feedback,
),
childWhenDragging: Container(),
onDragStarted: () => _setDragging(true),
onDragCompleted: () => _setDragging(false),
onDraggableCanceled: (_, __) => _setDragging(false),
onDragEnd: (_) => _setDragging(false),
),
),
],
),
);
} else if (widget.parameters.listDragOnLongPress) {
draggable = LongPressDraggable<DragAndDropListInterface>(
data: widget.dragAndDropList,
axis: draggableAxis(),
child: dragAndDropListContents,
feedback:
buildFeedbackWithoutHandle(context, dragAndDropListContents),
childWhenDragging: Container(),
onDragStarted: () => _setDragging(true),
onDragCompleted: () => _setDragging(false),
onDraggableCanceled: (_, __) => _setDragging(false),
onDragEnd: (_) => _setDragging(false),
);
} else {
draggable = Draggable<DragAndDropListInterface>(
data: widget.dragAndDropList,
axis: draggableAxis(),
child: dragAndDropListContents,
feedback:
buildFeedbackWithoutHandle(context, dragAndDropListContents),
childWhenDragging: Container(),
onDragStarted: () => _setDragging(true),
onDragCompleted: () => _setDragging(false),
onDraggableCanceled: (_, __) => _setDragging(false),
onDragEnd: (_) => _setDragging(false),
);
}
} else {
draggable = dragAndDropListContents;
}
var rowOrColumnChildren = <Widget>[
AnimatedSize(
duration:
Duration(milliseconds: widget.parameters.listSizeAnimationDuration),
alignment: widget.parameters.axis == Axis.vertical
? Alignment.bottomCenter
: Alignment.centerLeft,
child: _hoveredDraggable != null
? Opacity(
opacity: widget.parameters.listGhostOpacity,
child: widget.parameters.listGhost ??
Container(
padding: widget.parameters.axis == Axis.vertical
? EdgeInsets.all(0)
: EdgeInsets.symmetric(
horizontal:
widget.parameters.listPadding!.horizontal),
child:
_hoveredDraggable!.generateWidget(widget.parameters),
),
)
: Container(),
),
Listener(
child: draggable,
onPointerMove: _onPointerMove,
onPointerDown: widget.parameters.onPointerDown,
onPointerUp: widget.parameters.onPointerUp,
),
];
var stack = Stack(
children: <Widget>[
widget.parameters.axis == Axis.vertical
? Column(
children: rowOrColumnChildren,
)
: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: rowOrColumnChildren,
),
Positioned.fill(
child: DragTarget<DragAndDropListInterface>(
builder: (context, candidateData, rejectedData) {
if (candidateData.isNotEmpty) {}
return Container();
},
onWillAccept: (incoming) {
bool accept = true;
if (widget.parameters.listOnWillAccept != null) {
accept = widget.parameters.listOnWillAccept!(
incoming, widget.dragAndDropList);
}
if (accept && mounted) {
setState(() {
_hoveredDraggable = incoming;
});
}
return accept;
},
onLeave: (incoming) {
if (_hoveredDraggable != null) {
if (mounted) {
setState(() {
_hoveredDraggable = null;
});
}
}
},
onAccept: (incoming) {
if (mounted) {
setState(() {
widget.parameters.onListReordered!(
incoming, widget.dragAndDropList);
_hoveredDraggable = null;
});
}
},
),
),
],
);
Widget toReturn = stack;
if (widget.parameters.listPadding != null) {
toReturn = Padding(
padding: widget.parameters.listPadding!,
child: stack,
);
}
if (widget.parameters.axis == Axis.horizontal &&
!widget.parameters.disableScrolling) {
toReturn = SingleChildScrollView(
child: Container(
child: toReturn,
),
);
}
return toReturn;
}
Material buildFeedbackWithHandle(
Widget dragAndDropListContents, Widget dragHandle) {
return Material(
color: Colors.transparent,
child: Container(
decoration: widget.parameters.listDecorationWhileDragging,
child: Container(
width: widget.parameters.listDraggingWidth ?? _containerSize.width,
child: Stack(
children: [
Directionality(
textDirection: Directionality.of(context),
child: dragAndDropListContents,
),
Positioned(
right: widget.parameters.listDragHandle!.onLeft ? null : 0,
left: widget.parameters.listDragHandle!.onLeft ? 0 : null,
top: widget.parameters.listDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.bottom
? null
: 0,
bottom: widget.parameters.listDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.top
? null
: 0,
child: dragHandle,
),
],
),
),
),
);
}
Container buildFeedbackWithoutHandle(
BuildContext context, Widget dragAndDropListContents) {
return Container(
width: widget.parameters.axis == Axis.vertical
? (widget.parameters.listDraggingWidth ??
MediaQuery.of(context).size.width)
: (widget.parameters.listDraggingWidth ??
widget.parameters.listWidth),
child: Material(
color: Colors.transparent,
child: Container(
decoration: widget.parameters.listDecorationWhileDragging,
child: Directionality(
textDirection: Directionality.of(context),
child: dragAndDropListContents,
),
),
),
);
}
Axis? draggableAxis() {
return widget.parameters.axis == Axis.vertical &&
widget.parameters.constrainDraggingAxis
? Axis.vertical
: null;
}
double _dragHandleDistanceFromTop() {
switch (widget.parameters.listDragHandle!.verticalAlignment) {
case DragHandleVerticalAlignment.top:
return 0;
case DragHandleVerticalAlignment.center:
return (_containerSize.height / 2.0) - (_dragHandleSize.height / 2.0);
case DragHandleVerticalAlignment.bottom:
return _containerSize.height - _dragHandleSize.height;
default:
return 0;
}
}
Offset _feedbackContainerOffset() {
double xOffset;
double yOffset;
if (widget.parameters.listDragHandle!.onLeft) {
xOffset = 0;
} else {
xOffset = -_containerSize.width + _dragHandleSize.width;
}
if (widget.parameters.listDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.bottom) {
yOffset = -_containerSize.height + _dragHandleSize.width;
} else {
yOffset = 0;
}
return Offset(xOffset, yOffset);
}
void _setDragging(bool dragging) {
if (_dragging != dragging && mounted) {
setState(() {
_dragging = dragging;
});
if (widget.parameters.onListDraggingChanged != null) {
widget.parameters.onListDraggingChanged!(
widget.dragAndDropList, dragging);
}
}
}
void _onPointerMove(PointerMoveEvent event) {
if (_dragging) widget.parameters.onPointerMove!(event);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_list.dart | import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'drag_and_drop_builder_parameters.dart';
import 'drag_and_drop_item.dart';
import 'drag_and_drop_item_target.dart';
import 'drag_and_drop_item_wrapper.dart';
import 'drag_and_drop_list_interface.dart';
class DragAndDropList implements DragAndDropListInterface {
/// The widget that is displayed at the top of the list.
Widget? header;
/// The widget that is displayed at the bottom of the list.
Widget? footer;
/// The widget that is displayed to the left of the list.
final Widget? leftSide;
/// The widget that is displayed to the right of the list.
final Widget? rightSide;
/// The widget to be displayed when a list is empty.
/// If this is not null, it will override that set in [DragAndDropLists.contentsWhenEmpty].
final Widget? contentsWhenEmpty;
/// The widget to be displayed as the last element in the list that will accept
/// a dragged item.
Widget? lastTarget;
/// The decoration displayed around a list.
/// If this is not null, it will override that set in [DragAndDropLists.listDecoration].
final Decoration? decoration;
/// The vertical alignment of the contents in this list.
/// If this is not null, it will override that set in [DragAndDropLists.verticalAlignment].
final CrossAxisAlignment verticalAlignment;
/// The horizontal alignment of the contents in this list.
/// If this is not null, it will override that set in [DragAndDropLists.horizontalAlignment].
final MainAxisAlignment horizontalAlignment;
/// The child elements that will be contained in this list.
/// It is possible to not provide any children when an empty list is desired.
@override
final List<DragAndDropItem> children;
/// Whether or not this item can be dragged.
/// Set to true if it can be reordered.
/// Set to false if it must remain fixed.
@override
final bool canDrag;
DragAndDropList({
required this.children,
this.header,
this.footer,
this.leftSide,
this.rightSide,
this.contentsWhenEmpty,
this.lastTarget,
this.decoration,
this.horizontalAlignment = MainAxisAlignment.start,
this.verticalAlignment = CrossAxisAlignment.start,
this.canDrag = true,
});
@override
Widget generateWidget(DragAndDropBuilderParameters params) {
var contents = <Widget>[];
if (header != null) {
contents.add(Flexible(child: header!));
}
Widget intrinsicHeight = IntrinsicHeight(
child: Row(
mainAxisAlignment: horizontalAlignment,
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _generateDragAndDropListInnerContents(params),
),
);
if (params.axis == Axis.horizontal) {
intrinsicHeight = SizedBox(
width: params.listWidth,
child: intrinsicHeight,
);
}
if (params.listInnerDecoration != null) {
intrinsicHeight = Container(
decoration: params.listInnerDecoration,
child: intrinsicHeight,
);
}
contents.add(intrinsicHeight);
if (footer != null) {
contents.add(Flexible(child: footer!));
}
return Container(
width: params.axis == Axis.vertical
? double.infinity
: params.listWidth - params.listPadding!.horizontal,
decoration: decoration ?? params.listDecoration,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: verticalAlignment,
children: contents,
),
);
}
List<Widget> _generateDragAndDropListInnerContents(
DragAndDropBuilderParameters parameters) {
var contents = <Widget>[];
if (leftSide != null) {
contents.add(leftSide!);
}
if (children.isNotEmpty) {
List<Widget> allChildren = <Widget>[];
if (parameters.addLastItemTargetHeightToTop) {
allChildren.add(Padding(
padding: EdgeInsets.only(top: parameters.lastItemTargetHeight),
));
}
for (int i = 0; i < children.length; i++) {
allChildren.add(DragAndDropItemWrapper(
child: children[i],
parameters: parameters,
));
if (parameters.itemDivider != null && i < children.length - 1) {
allChildren.add(parameters.itemDivider!);
}
}
allChildren.add(
DragAndDropItemTarget(
parent: this,
parameters: parameters,
onReorderOrAdd: parameters.onItemDropOnLastTarget!,
child: lastTarget ??
Container(
height: parameters.lastItemTargetHeight,
),
),
);
contents.add(
Expanded(
child: SingleChildScrollView(
physics: const NeverScrollableScrollPhysics(),
child: Column(
crossAxisAlignment: verticalAlignment,
mainAxisSize: MainAxisSize.max,
children: allChildren,
),
),
),
);
} else {
contents.add(
Expanded(
child: SingleChildScrollView(
physics: const NeverScrollableScrollPhysics(),
child: Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
contentsWhenEmpty ??
const Text(
'Empty list',
style: TextStyle(
fontStyle: FontStyle.italic,
),
),
DragAndDropItemTarget(
parent: this,
parameters: parameters,
onReorderOrAdd: parameters.onItemDropOnLastTarget!,
child: lastTarget ??
Container(
height: parameters.lastItemTargetHeight,
),
),
],
),
),
),
);
}
if (rightSide != null) {
contents.add(rightSide!);
}
return contents;
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_list_target.dart | import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'drag_and_drop_builder_parameters.dart';
import 'drag_and_drop_list_interface.dart';
typedef void OnDropOnLastTarget(
DragAndDropListInterface newOrReordered,
DragAndDropListTarget receiver,
);
class DragAndDropListTarget extends StatefulWidget {
final Widget? child;
final DragAndDropBuilderParameters parameters;
final OnDropOnLastTarget onDropOnLastTarget;
final double lastListTargetSize;
DragAndDropListTarget(
{this.child,
required this.parameters,
required this.onDropOnLastTarget,
this.lastListTargetSize = 110,
Key? key})
: super(key: key);
@override
State<StatefulWidget> createState() => _DragAndDropListTarget();
}
class _DragAndDropListTarget extends State<DragAndDropListTarget>
with TickerProviderStateMixin {
DragAndDropListInterface? _hoveredDraggable;
@override
Widget build(BuildContext context) {
Widget visibleContents = Column(
children: <Widget>[
AnimatedSize(
duration: Duration(
milliseconds: widget.parameters.listSizeAnimationDuration),
alignment: widget.parameters.axis == Axis.vertical
? Alignment.bottomCenter
: Alignment.centerLeft,
child: _hoveredDraggable != null
? Opacity(
opacity: widget.parameters.listGhostOpacity,
child: widget.parameters.listGhost ??
_hoveredDraggable!.generateWidget(widget.parameters),
)
: Container(),
),
widget.child ??
Container(
height: widget.parameters.axis == Axis.vertical
? widget.lastListTargetSize
: null,
width: widget.parameters.axis == Axis.horizontal
? widget.lastListTargetSize
: null,
),
],
);
if (widget.parameters.listPadding != null) {
visibleContents = Padding(
padding: widget.parameters.listPadding!,
child: visibleContents,
);
}
if (widget.parameters.axis == Axis.horizontal) {
visibleContents = SingleChildScrollView(child: visibleContents);
}
return Stack(
children: <Widget>[
visibleContents,
Positioned.fill(
child: DragTarget<DragAndDropListInterface>(
builder: (context, candidateData, rejectedData) {
if (candidateData.isNotEmpty) {}
return Container();
},
onWillAccept: (incoming) {
bool accept = true;
if (widget.parameters.listTargetOnWillAccept != null) {
accept =
widget.parameters.listTargetOnWillAccept!(incoming, widget);
}
if (accept && mounted) {
setState(() {
_hoveredDraggable = incoming;
});
}
return accept;
},
onLeave: (incoming) {
if (mounted) {
setState(() {
_hoveredDraggable = null;
});
}
},
onAccept: (incoming) {
if (mounted) {
setState(() {
widget.onDropOnLastTarget(incoming, widget);
_hoveredDraggable = null;
});
}
},
),
),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_item_target.dart | import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'drag_and_drop_list_interface.dart';
import 'drag_and_drop_lists.dart';
class DragAndDropItemTarget extends StatefulWidget {
final Widget child;
final DragAndDropListInterface? parent;
final DragAndDropBuilderParameters parameters;
final OnItemDropOnLastTarget onReorderOrAdd;
const DragAndDropItemTarget(
{required this.child,
required this.onReorderOrAdd,
required this.parameters,
this.parent,
super.key});
@override
State<StatefulWidget> createState() => _DragAndDropItemTarget();
}
class _DragAndDropItemTarget extends State<DragAndDropItemTarget>
with TickerProviderStateMixin {
DragAndDropItem? _hoveredDraggable;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Column(
crossAxisAlignment: widget.parameters.verticalAlignment,
children: <Widget>[
AnimatedSize(
duration: Duration(
milliseconds: widget.parameters.itemSizeAnimationDuration),
alignment: Alignment.bottomCenter,
child: _hoveredDraggable != null
? Opacity(
opacity: widget.parameters.itemGhostOpacity,
child: widget.parameters.itemGhost ??
_hoveredDraggable!.child,
)
: Container(),
),
widget.child,
],
),
Positioned.fill(
child: DragTarget<DragAndDropItem>(
builder: (context, candidateData, rejectedData) {
if (candidateData.isNotEmpty) {}
return Container();
},
onWillAccept: (incoming) {
bool accept = true;
if (widget.parameters.itemTargetOnWillAccept != null) {
accept =
widget.parameters.itemTargetOnWillAccept!(incoming, widget);
}
if (accept && mounted) {
setState(() {
_hoveredDraggable = incoming;
});
}
return accept;
},
onLeave: (incoming) {
if (mounted) {
setState(() {
_hoveredDraggable = null;
});
}
},
onAccept: (incoming) {
if (mounted) {
setState(() {
widget.onReorderOrAdd(incoming, widget.parent!, widget);
_hoveredDraggable = null;
});
}
},
),
),
],
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/measure_size.dart | import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
typedef void OnWidgetSizeChange(Size? size);
class MeasureSize extends StatefulWidget {
final Widget? child;
final OnWidgetSizeChange onSizeChange;
const MeasureSize({
Key? key,
required this.onSizeChange,
required this.child,
}) : super(key: key);
@override
_MeasureSizeState createState() => _MeasureSizeState();
}
class _MeasureSizeState extends State<MeasureSize> {
@override
Widget build(BuildContext context) {
SchedulerBinding.instance.addPostFrameCallback(postFrameCallback);
return Container(
key: widgetKey,
child: widget.child,
);
}
var widgetKey = GlobalKey();
var oldSize;
var topLeftPosition = Offset.zero;
void postFrameCallback(_) {
var context = widgetKey.currentContext;
if (context == null) return;
var newSize = context.size;
if (oldSize != newSize) {
widget.onSizeChange(newSize);
oldSize = newSize;
}
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_handle.dart | import 'package:flutter/widgets.dart';
enum DragHandleVerticalAlignment {
top,
center,
bottom,
}
class DragHandle extends StatelessWidget {
/// Set the drag handle to be on the left side instead of the default right side
final bool onLeft;
/// Align the list drag handle to the top, center, or bottom
final DragHandleVerticalAlignment verticalAlignment;
/// Child widget to displaying the drag handle
final Widget child;
const DragHandle({
super.key,
required this.child,
this.onLeft = false,
this.verticalAlignment = DragHandleVerticalAlignment.center,
});
@override
Widget build(BuildContext context) {
return child;
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_list_interface.dart | import 'package:flutter/material.dart';
import 'drag_and_drop_builder_parameters.dart';
import 'drag_and_drop_interface.dart';
import 'drag_and_drop_item.dart';
abstract class DragAndDropListInterface implements DragAndDropInterface {
List<DragAndDropItem>? get children;
/// Whether or not this item can be dragged.
/// Set to true if it can be reordered.
/// Set to false if it must remain fixed.
bool get canDrag;
Widget generateWidget(DragAndDropBuilderParameters params);
}
abstract class DragAndDropListExpansionInterface
implements DragAndDropListInterface {
final List<DragAndDropItem>? children;
DragAndDropListExpansionInterface({this.children});
get isExpanded;
toggleExpanded();
expand();
collapse();
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_item.dart | import 'package:flutter/widgets.dart';
import 'drag_and_drop_interface.dart';
class DragAndDropItem implements DragAndDropInterface {
/// The child widget of this item.
final Widget child;
/// Widget when draggable
final Widget? feedbackWidget;
/// Whether or not this item can be dragged.
/// Set to true if it can be reordered.
/// Set to false if it must remain fixed.
final bool canDrag;
dynamic data;
DragAndDropItem({
required this.child,
this.feedbackWidget,
this.canDrag = true,
this.data,
});
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_interface.dart | abstract class DragAndDropInterface {}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_list_expansion.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'drag_and_drop_builder_parameters.dart';
import 'drag_and_drop_item.dart';
import 'drag_and_drop_item_target.dart';
import 'drag_and_drop_item_wrapper.dart';
import 'drag_and_drop_list_interface.dart';
import 'programmatic_expansion_tile.dart';
typedef void OnExpansionChanged(bool expanded);
/// This class mirrors flutter's [ExpansionTile], with similar options.
class DragAndDropListExpansion implements DragAndDropListExpansionInterface {
final Widget? title;
final Widget? subtitle;
final Widget? trailing;
final Widget? leading;
final bool initiallyExpanded;
/// Set this to a unique key that will remain unchanged over the lifetime of the list.
/// Used to maintain the expanded/collapsed states
final Key listKey;
/// This function will be called when the expansion of a tile is changed.
final OnExpansionChanged? onExpansionChanged;
final Color? backgroundColor;
final List<DragAndDropItem>? children;
final Widget? contentsWhenEmpty;
final Widget? lastTarget;
/// Whether or not this item can be dragged.
/// Set to true if it can be reordered.
/// Set to false if it must remain fixed.
final bool canDrag;
/// Disable to borders displayed at the top and bottom when expanded
final bool disableTopAndBottomBorders;
final ValueNotifier<bool> _expanded = ValueNotifier<bool>(true);
final GlobalKey<ProgrammaticExpansionTileState> _expansionKey =
GlobalKey<ProgrammaticExpansionTileState>();
DragAndDropListExpansion({
this.children,
this.title,
this.subtitle,
this.trailing,
this.leading,
this.initiallyExpanded = false,
this.backgroundColor,
this.onExpansionChanged,
this.contentsWhenEmpty,
this.lastTarget,
required this.listKey,
this.canDrag = true,
this.disableTopAndBottomBorders = false,
}) {
_expanded.value = initiallyExpanded;
}
@override
Widget generateWidget(DragAndDropBuilderParameters params) {
var contents = _generateDragAndDropListInnerContents(params);
Widget expandable = ProgrammaticExpansionTile(
title: title,
listKey: listKey,
subtitle: subtitle,
trailing: trailing,
leading: leading,
disableTopAndBottomBorders: disableTopAndBottomBorders,
backgroundColor: backgroundColor,
initiallyExpanded: initiallyExpanded,
onExpansionChanged: _onSetExpansion,
key: _expansionKey,
children: contents,
);
if (params.listDecoration != null) {
expandable = Container(
decoration: params.listDecoration,
child: expandable,
);
}
if (params.listPadding != null) {
expandable = Padding(
padding: params.listPadding!,
child: expandable,
);
}
Widget toReturn = ValueListenableBuilder(
valueListenable: _expanded,
child: expandable,
builder: (context, dynamic error, child) {
if (!_expanded.value) {
return Stack(children: <Widget>[
child!,
Positioned.fill(
child: DragTarget<DragAndDropItem>(
builder: (context, candidateData, rejectedData) {
if (candidateData.isNotEmpty) {}
return Container();
},
onWillAccept: (incoming) {
_startExpansionTimer();
return false;
},
onLeave: (incoming) {
_stopExpansionTimer();
},
onAccept: (incoming) {},
),
)
]);
} else {
return child!;
}
},
);
return toReturn;
}
List<Widget> _generateDragAndDropListInnerContents(
DragAndDropBuilderParameters parameters) {
var contents = <Widget>[];
if (children != null && children!.isNotEmpty) {
for (int i = 0; i < children!.length; i++) {
contents.add(DragAndDropItemWrapper(
child: children![i],
parameters: parameters,
));
if (parameters.itemDivider != null && i < children!.length - 1) {
contents.add(parameters.itemDivider!);
}
}
contents.add(
DragAndDropItemTarget(
parent: this,
parameters: parameters,
onReorderOrAdd: parameters.onItemDropOnLastTarget!,
child: lastTarget ??
Container(
height: parameters.lastItemTargetHeight,
),
),
);
} else {
contents.add(
contentsWhenEmpty ??
const Text(
'Empty list',
style: TextStyle(
fontStyle: FontStyle.italic,
),
),
);
contents.add(
DragAndDropItemTarget(
parent: this,
parameters: parameters,
onReorderOrAdd: parameters.onItemDropOnLastTarget!,
child: lastTarget ??
Container(
height: parameters.lastItemTargetHeight,
),
),
);
}
return contents;
}
@override
toggleExpanded() {
if (isExpanded) {
collapse();
} else {
expand();
}
}
@override
collapse() {
if (!isExpanded) {
_expanded.value = false;
_expansionKey.currentState!.collapse();
}
}
@override
expand() {
if (!isExpanded) {
_expanded.value = true;
_expansionKey.currentState!.expand();
}
}
_onSetExpansion(bool expanded) {
_expanded.value = expanded;
if (onExpansionChanged != null) onExpansionChanged!(expanded);
}
@override
get isExpanded => _expanded.value;
late Timer _expansionTimer;
_startExpansionTimer() async {
_expansionTimer =
Timer(const Duration(milliseconds: 400), _expansionCallback);
}
_stopExpansionTimer() async {
if (_expansionTimer.isActive) {
_expansionTimer.cancel();
}
}
_expansionCallback() {
expand();
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/programmatic_expansion_tile.dart | // Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
const Duration _kExpand = Duration(milliseconds: 200);
/// A single-line [ListTile] with a trailing button that expands or collapses
/// the tile to reveal or hide the [children].
///
/// This widget is typically used with [ListView] to create an
/// "expand / collapse" list entry. When used with scrolling widgets like
/// [ListView], a unique [PageStorageKey] must be specified to enable the
/// [ProgrammaticExpansionTile] to save and restore its expanded state when it is scrolled
/// in and out of view.
///
/// See also:
///
/// * [ListTile], useful for creating expansion tile [children] when the
/// expansion tile represents a sublist.
/// * The "Expand/collapse" section of
/// <https://material.io/guidelines/components/lists-controls.html>.
class ProgrammaticExpansionTile extends StatefulWidget {
/// Creates a single-line [ListTile] with a trailing button that expands or collapses
/// the tile to reveal or hide the [children]. The [initiallyExpanded] property must
/// be non-null.
const ProgrammaticExpansionTile({
required Key key,
required this.listKey,
this.leading,
required this.title,
this.subtitle,
this.isThreeLine = false,
this.backgroundColor,
this.onExpansionChanged,
this.children = const <Widget>[],
this.trailing,
this.initiallyExpanded = false,
this.disableTopAndBottomBorders = false,
}) : super(key: key);
final Key listKey;
/// A widget to display before the title.
///
/// Typically a [CircleAvatar] widget.
final Widget? leading;
/// The primary content of the list item.
///
/// Typically a [Text] widget.
final Widget? title;
/// Additional content displayed below the title.
///
/// Typically a [Text] widget.
final Widget? subtitle;
/// Additional content displayed below the title.
///
/// Typically a [Text] widget.
final bool isThreeLine;
/// Called when the tile expands or collapses.
///
/// When the tile starts expanding, this function is called with the value
/// true. When the tile starts collapsing, this function is called with
/// the value false.
final ValueChanged<bool>? onExpansionChanged;
/// The widgets that are displayed when the tile expands.
///
/// Typically [ListTile] widgets.
final List<Widget?> children;
/// The color to display behind the sublist when expanded.
final Color? backgroundColor;
/// A widget to display instead of a rotating arrow icon.
final Widget? trailing;
/// Specifies if the list tile is initially expanded (true) or collapsed (false, the default).
final bool initiallyExpanded;
/// Disable to borders displayed at the top and bottom when expanded
final bool disableTopAndBottomBorders;
@override
ProgrammaticExpansionTileState createState() =>
ProgrammaticExpansionTileState();
}
class ProgrammaticExpansionTileState extends State<ProgrammaticExpansionTile>
with SingleTickerProviderStateMixin {
static final Animatable<double> _easeOutTween =
CurveTween(curve: Curves.easeOut);
static final Animatable<double> _easeInTween =
CurveTween(curve: Curves.easeIn);
static final Animatable<double> _halfTween =
Tween<double>(begin: 0.0, end: 0.5);
final ColorTween _borderColorTween = ColorTween();
final ColorTween _headerColorTween = ColorTween();
final ColorTween _iconColorTween = ColorTween();
final ColorTween _backgroundColorTween = ColorTween();
late AnimationController _controller;
late Animation<double> _iconTurns;
late Animation<double> _heightFactor;
late Animation<Color?> _borderColor;
late Animation<Color?> _headerColor;
late Animation<Color?> _iconColor;
late Animation<Color?> _backgroundColor;
bool _isExpanded = false;
@override
void initState() {
super.initState();
_controller = AnimationController(duration: _kExpand, vsync: this);
_heightFactor = _controller.drive(_easeInTween);
_iconTurns = _controller.drive(_halfTween.chain(_easeInTween));
_borderColor = _controller.drive(_borderColorTween.chain(_easeOutTween));
_headerColor = _controller.drive(_headerColorTween.chain(_easeInTween));
_iconColor = _controller.drive(_iconColorTween.chain(_easeInTween));
_backgroundColor =
_controller.drive(_backgroundColorTween.chain(_easeOutTween));
_isExpanded = PageStorage.of(context)
?.readState(context, identifier: widget.listKey) as bool? ??
widget.initiallyExpanded;
if (_isExpanded) _controller.value = 1.0;
// Schedule the notification that widget has changed for after init
// to ensure that the parent widget maintains the correct state
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
if (widget.onExpansionChanged != null &&
_isExpanded != widget.initiallyExpanded) {
widget.onExpansionChanged!(_isExpanded);
}
});
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
void expand() {
_setExpanded(true);
}
void collapse() {
_setExpanded(false);
}
void toggle() {
_setExpanded(!_isExpanded);
}
void _setExpanded(bool expanded) {
if (_isExpanded != expanded) {
setState(() {
_isExpanded = expanded;
if (_isExpanded) {
_controller.forward();
} else {
_controller.reverse().then<void>((void value) {
if (!mounted) return;
setState(() {
// Rebuild without widget.children.
});
});
}
PageStorage.of(context)
?.writeState(context, _isExpanded, identifier: widget.listKey);
});
if (widget.onExpansionChanged != null) {
widget.onExpansionChanged!(_isExpanded);
}
}
}
Widget _buildChildren(BuildContext context, Widget? child) {
final Color borderSideColor = _borderColor.value ?? Colors.transparent;
bool setBorder = !widget.disableTopAndBottomBorders;
return Container(
decoration: BoxDecoration(
color: _backgroundColor.value ?? Colors.transparent,
border: setBorder
? Border(
top: BorderSide(color: borderSideColor),
bottom: BorderSide(color: borderSideColor),
)
: null,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTileTheme.merge(
iconColor: _iconColor.value,
textColor: _headerColor.value,
child: ListTile(
onTap: toggle,
leading: widget.leading,
title: widget.title,
subtitle: widget.subtitle,
isThreeLine: widget.isThreeLine,
trailing: widget.trailing ??
RotationTransition(
turns: _iconTurns,
child: const Icon(Icons.expand_more),
),
),
),
ClipRect(
child: Align(
heightFactor: _heightFactor.value,
child: child,
),
),
],
),
);
}
@override
void didChangeDependencies() {
final ThemeData theme = Theme.of(context);
_borderColorTween.end = theme.dividerColor;
_headerColorTween
..begin = theme.textTheme.subtitle1!.color
..end = theme.colorScheme.secondary;
_iconColorTween
..begin = theme.unselectedWidgetColor
..end = theme.colorScheme.secondary;
_backgroundColorTween.end = widget.backgroundColor;
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
final bool closed = !_isExpanded && _controller.isDismissed;
return AnimatedBuilder(
animation: _controller.view,
builder: _buildChildren,
child: closed ? null : Column(children: widget.children as List<Widget>),
);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Draggable/drag_and_drop_item_wrapper.dart | import 'package:flutter/material.dart';
import 'drag_and_drop_lists.dart';
import 'measure_size.dart';
class DragAndDropItemWrapper extends StatefulWidget {
final DragAndDropItem child;
final DragAndDropBuilderParameters? parameters;
const DragAndDropItemWrapper(
{required this.child, required this.parameters, super.key});
@override
State<StatefulWidget> createState() => _DragAndDropItemWrapper();
}
class _DragAndDropItemWrapper extends State<DragAndDropItemWrapper>
with TickerProviderStateMixin {
DragAndDropItem? _hoveredDraggable;
bool _dragging = false;
Size _containerSize = Size.zero;
Size _dragHandleSize = Size.zero;
@override
Widget build(BuildContext context) {
Widget draggable;
if (widget.child.canDrag) {
if (widget.parameters!.itemDragHandle != null) {
Widget feedback = SizedBox(
width: widget.parameters!.itemDraggingWidth ?? _containerSize.width,
child: Stack(
children: [
widget.child.child,
Positioned(
right: widget.parameters!.itemDragHandle!.onLeft ? null : 0,
left: widget.parameters!.itemDragHandle!.onLeft ? 0 : null,
top: widget.parameters!.itemDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.bottom
? null
: 0,
bottom: widget.parameters!.itemDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.top
? null
: 0,
child: widget.parameters!.itemDragHandle!,
),
],
),
);
var positionedDragHandle = Positioned(
right: widget.parameters!.itemDragHandle!.onLeft ? null : 0,
left: widget.parameters!.itemDragHandle!.onLeft ? 0 : null,
top: widget.parameters!.itemDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.bottom
? null
: 0,
bottom: widget.parameters!.itemDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.top
? null
: 0,
child: MouseRegion(
cursor: SystemMouseCursors.grab,
child: Draggable<DragAndDropItem>(
data: widget.child,
axis: widget.parameters!.axis == Axis.vertical &&
widget.parameters!.constrainDraggingAxis
? Axis.vertical
: null,
feedback: Transform.translate(
offset: _feedbackContainerOffset(),
child: Opacity(
opacity: widget.parameters!.itemOpacityWhileDragging ?? 1,
child: Material(
color: Colors.transparent,
child: Container(
decoration:
widget.parameters!.itemDecorationWhileDragging,
child: Directionality(
textDirection: Directionality.of(context),
child: feedback,
),
),
),
),
),
childWhenDragging: Container(),
onDragStarted: () => _setDragging(true),
onDragCompleted: () => _setDragging(false),
onDraggableCanceled: (_, __) => _setDragging(false),
onDragEnd: (_) => _setDragging(false),
child: MeasureSize(
onSizeChange: (size) {
setState(() {
_dragHandleSize = size!;
});
},
child: widget.parameters!.itemDragHandle,
),
),
),
);
draggable = MeasureSize(
onSizeChange: _setContainerSize,
child: Stack(
children: [
Visibility(
visible: !_dragging,
child: widget.child.child,
),
// dragAndDropListContents,
positionedDragHandle,
],
),
);
} else if (widget.parameters!.itemDragOnLongPress) {
draggable = MeasureSize(
onSizeChange: _setContainerSize,
child: LongPressDraggable<DragAndDropItem>(
data: widget.child,
axis: widget.parameters!.axis == Axis.vertical &&
widget.parameters!.constrainDraggingAxis
? Axis.vertical
: null,
feedback: SizedBox(
width:
widget.parameters!.itemDraggingWidth ?? _containerSize.width,
child: Opacity(
opacity: widget.parameters!.itemOpacityWhileDragging ?? 1,
child: Material(
color: Colors.transparent,
child: Container(
decoration: widget.parameters!.itemDecorationWhileDragging,
child: Directionality(
textDirection: Directionality.of(context),
child:
widget.child.feedbackWidget ?? widget.child.child),
),
),
),
),
childWhenDragging: Container(),
onDragStarted: () => _setDragging(true),
onDragCompleted: () => _setDragging(false),
onDraggableCanceled: (_, __) => _setDragging(false),
onDragEnd: (_) => _setDragging(false),
child: widget.child.child,
),
);
} else {
draggable = MeasureSize(
onSizeChange: _setContainerSize,
child: Draggable<DragAndDropItem>(
data: widget.child,
axis: widget.parameters!.axis == Axis.vertical &&
widget.parameters!.constrainDraggingAxis
? Axis.vertical
: null,
feedback: SizedBox(
width:
widget.parameters!.itemDraggingWidth ?? _containerSize.width,
child: Opacity(
opacity: widget.parameters!.itemOpacityWhileDragging ?? 1,
child: Material(
color: Colors.transparent,
child: Container(
decoration: widget.parameters!.itemDecorationWhileDragging,
child: Directionality(
textDirection: Directionality.of(context),
child: widget.child.feedbackWidget ?? widget.child.child,
),
),
),
),
),
childWhenDragging: Container(),
onDragStarted: () => _setDragging(true),
onDragCompleted: () => _setDragging(false),
onDraggableCanceled: (_, __) => _setDragging(false),
onDragEnd: (_) => _setDragging(false),
child: widget.child.child,
),
);
}
} else {
draggable = AnimatedSize(
duration: Duration(
milliseconds: widget.parameters!.itemSizeAnimationDuration),
alignment: Alignment.bottomCenter,
child: _hoveredDraggable != null ? Container() : widget.child.child,
);
}
return Stack(
children: <Widget>[
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: widget.parameters!.verticalAlignment,
children: <Widget>[
AnimatedSize(
duration: Duration(
milliseconds: widget.parameters!.itemSizeAnimationDuration),
alignment: Alignment.topLeft,
child: _hoveredDraggable != null
? Opacity(
opacity: widget.parameters!.itemGhostOpacity,
child: widget.parameters!.itemGhost ??
_hoveredDraggable!.child,
)
: Container(),
),
Listener(
onPointerMove: _onPointerMove,
onPointerDown: widget.parameters!.onPointerDown,
onPointerUp: widget.parameters!.onPointerUp,
child: draggable,
),
],
),
Positioned.fill(
child: DragTarget<DragAndDropItem>(
builder: (context, candidateData, rejectedData) {
if (candidateData.isNotEmpty) {}
return Container();
},
onWillAccept: (incoming) {
bool accept = true;
if (widget.parameters!.itemOnWillAccept != null) {
accept = widget.parameters!.itemOnWillAccept!(
incoming, widget.child);
}
if (accept && mounted) {
setState(() {
_hoveredDraggable = incoming;
});
}
return accept;
},
onLeave: (incoming) {
if (mounted) {
setState(() {
_hoveredDraggable = null;
});
}
},
onAccept: (incoming) {
if (mounted) {
setState(() {
if (widget.parameters!.onItemReordered != null) {
widget.parameters!.onItemReordered!(incoming, widget.child);
}
_hoveredDraggable = null;
});
}
},
),
)
],
);
}
Offset _feedbackContainerOffset() {
double xOffset;
double yOffset;
if (widget.parameters!.itemDragHandle!.onLeft) {
xOffset = 0;
} else {
xOffset = -_containerSize.width + _dragHandleSize.width;
}
if (widget.parameters!.itemDragHandle!.verticalAlignment ==
DragHandleVerticalAlignment.bottom) {
yOffset = -_containerSize.height + _dragHandleSize.width;
} else {
yOffset = 0;
}
return Offset(xOffset, yOffset);
}
void _setContainerSize(Size? size) {
if (mounted) {
setState(() {
_containerSize = size!;
});
}
}
void _setDragging(bool dragging) {
if (_dragging != dragging && mounted) {
setState(() {
_dragging = dragging;
});
if (widget.parameters!.onItemDraggingChanged != null) {
widget.parameters!.onItemDraggingChanged!(widget.child, dragging);
}
}
}
void _onPointerMove(PointerMoveEvent event) {
if (_dragging) widget.parameters!.onPointerMove!(event);
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Popup/ipopup_child.dart | import 'package:flutter/material.dart';
mixin IPopupChild implements Widget {
dismiss();
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Popup/dropdown_menu.dart | import 'package:flutter/material.dart';
import 'ipopup_child.dart';
class DropDownMenu extends StatefulWidget with IPopupChild {
final PopController controller;
final AnimationController? animationController;
final Widget? child;
final Color maskColor;
final EdgeInsets? padding;
DropDownMenu({
super.key,
this.padding,
required this.controller,
this.animationController,
this.maskColor = Colors.black54,
this.child,
});
@override
DropDownMenuState createState() => DropDownMenuState();
@override
dismiss() {
controller.dismiss();
}
}
class DropDownMenuState extends State<DropDownMenu>
with SingleTickerProviderStateMixin {
late Animation<double> _animation;
late AnimationController _controller;
double _maskColorOpacity = 0;
@override
void initState() {
super.initState();
widget.controller._bindState(this);
_controller = widget.animationController ??
AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
// _animation = Tween<Offset>(begin: const Offset(0, -1), end: Offset.zero)
// .animate(_controller);
_animation = Tween<double>(begin: 0, end: 1).animate(_controller);
_animation.addListener(_controllerListener);
_controller.forward();
}
dismiss() {
_controller.reverse();
}
get isOpen => _controller.isCompleted;
void _controllerListener() {
if (mounted) {
setState(() {
_maskColorOpacity = widget.maskColor.opacity * _animation.value;
});
}
}
@override
void dispose() {
if (widget.animationController == null) {
_controller.dispose();
}
_animation.removeListener(_controllerListener);
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
padding: widget.padding,
child: Stack(
children: [
Container(
color: widget.maskColor.withOpacity(_maskColorOpacity),
height: MediaQuery.of(context).size.height,
),
SizeTransition(
sizeFactor: _animation,
child: widget.child,
),
// widget.child ?? Container(),
],
),
);
}
}
class PopController {
DropDownMenuState? state;
_bindState(DropDownMenuState state) {
this.state = state;
}
addListener(Function() listener) {
state?._controller.addListener(listener);
}
dismiss() {
state?.dismiss();
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Popup/ipopup_route.dart | import 'package:flutter/material.dart';
import 'ipopup_child.dart';
class IPopupRoute extends PopupRoute {
final IPopupChild child;
final Offset? offsetLT, offsetRB;
final Duration duration;
final bool cancelable;
final bool outsideTouchCancelable;
final bool darkEnable;
final List<RRect>? highlights;
IPopupRoute({
required this.child,
this.offsetLT,
this.offsetRB,
this.cancelable = true,
this.outsideTouchCancelable = true,
this.darkEnable = true,
this.duration = const Duration(milliseconds: 300),
this.highlights,
});
@override
Color? get barrierColor => null;
@override
bool get barrierDismissible => true;
@override
String? get barrierLabel => null;
@override
Widget buildPage(BuildContext context, Animation<double> animation,
Animation<double> secondaryAnimation) {
return _PopRouteWidget(
offsetLT: offsetLT,
offsetRB: offsetRB,
duration: duration,
cancelable: cancelable,
outsideTouchCancelable: outsideTouchCancelable,
darkEnable: darkEnable,
highlights: highlights,
child: child,
);
}
@override
Duration get transitionDuration => duration;
static pop(BuildContext context) {
__PopRouteWidgetState.of(context)?.dismiss();
Navigator.of(context).pop();
}
static setHighlights(BuildContext context, List<RRect> highlights) {
__PopRouteWidgetState.of(context)?.highlights = highlights;
}
}
class _PopRouteWidget extends StatefulWidget {
final IPopupChild child;
final Offset? offsetLT, offsetRB;
final Duration duration;
final bool cancelable;
final bool outsideTouchCancelable;
final bool darkEnable;
final List<RRect>? highlights;
const _PopRouteWidget({
required this.child,
this.offsetLT,
this.offsetRB,
required this.duration,
required this.cancelable,
required this.outsideTouchCancelable,
required this.darkEnable,
this.highlights,
});
@override
__PopRouteWidgetState createState() => __PopRouteWidgetState();
}
class __PopRouteWidgetState extends State<_PopRouteWidget>
with SingleTickerProviderStateMixin {
late Animation<double> alphaAnim;
late AnimationController alphaController;
List<RRect> _highlights = [];
@override
void initState() {
super.initState();
highlights = widget.highlights ?? [];
alphaController = AnimationController(
vsync: this,
duration: widget.duration,
);
alphaAnim = Tween<double>(begin: 0, end: 127).animate(alphaController);
alphaController.forward();
}
static __PopRouteWidgetState? of(BuildContext context) {
return context.findAncestorStateOfType<__PopRouteWidgetState>();
}
dismiss() {
alphaController.reverse();
widget.child.dismiss();
}
set highlights(List<RRect> value) {
setState(() {
_highlights = value;
});
}
@override
void dispose() {
alphaController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
if (widget.cancelable) {
dismiss();
return true;
}
return false;
},
child: GestureDetector(
onTap: () {
if (widget.outsideTouchCancelable) {
dismiss();
Navigator.of(context).pop();
}
},
child: Stack(
children: <Widget>[
widget.darkEnable
? AnimatedBuilder(
animation: alphaController,
builder: (_, __) {
return Padding(
padding: EdgeInsets.only(
left: widget.offsetLT?.dx ?? 0,
top: widget.offsetLT?.dy ?? 0,
right: widget.offsetRB?.dx ?? 0,
bottom: widget.offsetRB?.dy ?? 0,
),
child: ColorFiltered(
colorFilter: ColorFilter.mode(
Colors.black.withAlpha(alphaAnim.value.toInt()),
BlendMode.srcOut,
),
child: Stack(
children: _buildDark(),
),
),
);
},
)
: Container(),
widget.child,
],
),
),
);
}
List<Widget> _buildDark() {
List<Widget> widgets = [];
widgets.add(Container(
color: Colors.transparent,
));
for (RRect highlight in _highlights) {
widgets.add(
Positioned(
left: highlight.left,
top: highlight.top,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: highlight.tlRadius,
topRight: highlight.trRadius,
bottomLeft: highlight.blRadius,
bottomRight: highlight.brRadius,
),
),
width: highlight.width,
height: highlight.height,
),
),
);
}
return widgets;
}
}
| 0 |
mirrored_repositories/Readar/lib/Widgets | mirrored_repositories/Readar/lib/Widgets/Popup/ipopup.dart | import 'package:flutter/material.dart';
import 'ipopup_child.dart';
import 'ipopup_route.dart';
class IPopup {
static pop(BuildContext context) {
IPopupRoute.pop(context);
}
static show(
BuildContext context,
IPopupChild child, {
Offset? offsetLT,
Offset? offsetRB,
bool cancelable = true,
bool outsideTouchCancelable = true,
bool darkEnable = true,
Duration duration = const Duration(milliseconds: 300),
List<RRect>? highlights,
}) {
Navigator.of(context).push(
IPopupRoute(
child: child,
offsetLT: offsetLT,
offsetRB: offsetRB,
cancelable: cancelable,
outsideTouchCancelable: outsideTouchCancelable,
darkEnable: darkEnable,
duration: duration,
highlights: highlights,
),
);
}
static setHighlights(BuildContext context, List<RRect> highlights) {
IPopupRoute.setHighlights(context, highlights);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.