repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Readar/lib/Widgets
mirrored_repositories/Readar/lib/Widgets/BottomSheet/input_bottom_sheet.dart
import 'package:flutter/material.dart'; class InputBottomSheet extends StatefulWidget { const InputBottomSheet({ super.key, this.maxLines = 5, this.minLines = 1, this.hint, this.controller, required this.buttonText, this.onConfirm, required this.text, }); final String? hint; final String text; final int maxLines; final int minLines; final Function(String)? onConfirm; final TextEditingController? controller; final String buttonText; @override InputBottomSheetState createState() => InputBottomSheetState(); } class InputBottomSheetState extends State<InputBottomSheet> { TextEditingController controller = TextEditingController(); @override void initState() { super.initState(); controller.value = TextEditingValue(text: widget.text); } @override Widget build(BuildContext context) { return AnimatedPadding( padding: MediaQuery.of(context).viewInsets, duration: const Duration(milliseconds: 100), child: Container( height: 100, padding: const EdgeInsets.symmetric(horizontal: 20), decoration: BoxDecoration( color: Theme.of(context).canvasColor, borderRadius: const BorderRadius.vertical(top: Radius.circular(24)), ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: TextField( autofocus: true, controller: controller, maxLines: widget.maxLines, minLines: widget.minLines, cursorColor: Theme.of(context).primaryColor, cursorHeight: 22, cursorRadius: const Radius.circular(3), decoration: InputDecoration( border: InputBorder.none, hintText: widget.hint, ), ), ), const SizedBox(width: 8.0), GestureDetector( onTap: () { widget.onConfirm!(controller.text); }, child: Container( height: 30, alignment: Alignment.center, padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), decoration: BoxDecoration( color: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(20), ), child: Text( widget.buttonText, style: Theme.of(context).textTheme.titleMedium, ), ), ), ], ), ), ); } }
0
mirrored_repositories/Readar/lib/Widgets
mirrored_repositories/Readar/lib/Widgets/BottomSheet/bottom_sheet_builder.dart
import 'package:flutter/material.dart'; class BottomSheetBuilder { static void showListBottomSheet( BuildContext context, WidgetBuilder builder, { Color backgroundColor = Colors.transparent, ShapeBorder shape = const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(top: Radius.circular(10))), }) { showModalBottomSheet( context: context, elevation: 0, backgroundColor: backgroundColor, shape: shape, constraints: BoxConstraints( maxHeight: MediaQuery.of(context).size.height - MediaQuery.of(context).viewPadding.top), builder: builder, ); } }
0
mirrored_repositories/Readar/lib/Widgets
mirrored_repositories/Readar/lib/Widgets/BottomSheet/list_bottom_sheet.dart
import 'package:readar/Widgets/Item/item_builder.dart'; import 'package:flutter/material.dart'; import 'package:tuple/tuple.dart'; class TileList extends StatelessWidget { const TileList(this.children, {required this.title, required Key key, this.onCloseTap}) : super(key: key); TileList.fromOptions( List<Tuple2<String, dynamic>> options, dynamic selected, Function onSelected, { this.onCloseTap, required this.title, required BuildContext context, super.key, }) : children = options .map( (t) => ItemBuilder.buildEntryItem( title: t.item1, trailing: Icons.done_rounded, showTrailing: t.item2 == selected, onTap: () { onSelected(t.item2); }, context: context, ), ) .toList(); final Iterable<Widget> children; final String title; final Function()? onCloseTap; @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 20), decoration: BoxDecoration( color: Theme.of(context).canvasColor, border: const Border(), borderRadius: const BorderRadius.vertical(top: Radius.circular(10)), ), child: Text(title, style: Theme.of(context).textTheme.titleLarge), ), Container( height: 0, decoration: BoxDecoration( border: Border( bottom: BorderSide( color: Theme.of(context).dividerColor, width: 1.2, style: BorderStyle.solid, ), ), ), ), ...children, ], ); } }
0
mirrored_repositories/Readar/lib/Api
mirrored_repositories/Readar/lib/Api/Rss/google_reader_service_handler.dart
// ignore_for_file: unnecessary_null_comparison import 'dart:convert'; import 'dart:math'; import 'package:readar/Database/create_table_sql.dart'; import 'package:readar/Database/feed_dao.dart'; import 'package:readar/Database/rss_service_dao.dart'; import 'package:readar/Models/rss_service.dart'; import 'package:html/parser.dart'; import 'package:http/http.dart' as http; import 'package:tuple/tuple.dart'; import '../../Handler/rss_service_handler.dart'; import '../../Models/feed.dart'; import '../../Models/rss_item.dart'; import '../../Providers/provider_manager.dart'; import '../../Utils/iprint.dart'; class GoogleReaderRssServiceHandler extends RssServiceHandler { static const _tagAll = "user/-/state/com.google/reading-list"; static const _tagHasRead = "user/-/state/com.google/read"; static const _tagStarred = "user/-/state/com.google/starred"; static final _authRegex = RegExp(r"Auth=(\S+)"); RssService feedService; GoogleReaderRssServiceHandler(this.feedService); @override void removeService() { RssServiceDao.delete(feedService); } @override Future<http.Response> fetchResponse(String path, {dynamic body}) async { final headers = <String, String>{}; if (feedService.authorization != null) { headers["Authorization"] = feedService.authorization!; } if (feedService.appId != null && feedService.appKey != null) { headers["AppId"] = feedService.appId!; headers["AppKey"] = feedService.appKey!; } var uri = Uri.parse(feedService.endpoint + path); if (body == null) { return await http.get(uri, headers: headers); } else { headers["Content-Type"] = "application/x-www-form-urlencoded"; return await http.post(uri, headers: headers, body: body); } } @override Future<bool> validate() async { try { final result = await fetchResponse("/reader/api/0/user-info"); return result.statusCode == 200; } catch (exp) { return false; } } @override Future<bool> authenticate() async { if (!await validate()) { final body = { "Email": feedService.username, "Passwd": feedService.password, }; final result = await fetchResponse("/accounts/ClientLogin", body: body); if (result.statusCode != 200) { return false; } else { final match = _authRegex.firstMatch(result.body); if (match != null && match.groupCount > 0) { feedService.authorization = "GoogleLogin auth=${match.group(1)}"; return true; } else { return false; } } } return true; } @override Future<Tuple2<List<Feed>, Map<String, List<String>>>> fetchFeedsAndGroups() async { final response = await fetchResponse("/reader/api/0/subscription/list?output=json"); if (response.statusCode != 200) { return const Tuple2([], {}); } var rawFeeds = jsonDecode(response.body)["subscriptions"]; final groupsMap = <String, List<String>>{}; for (var s in rawFeeds) { final categories = s["categories"]; if (categories != null) { for (var c in categories) { groupsMap.putIfAbsent(c["label"], () => []); groupsMap[c["label"]]!.add(s["id"]); } } } final sources = rawFeeds.map<Feed>((s) { return Feed(s["id"], s["url"] ?? s["htmlUrl"], s["title"], serviceId: feedService.id!); }).toList(); return Tuple2(sources, groupsMap); } @override Future<List<RssItem>> fetchItems() async { List rawItems = []; List fetchedItems; String? continuation; do { try { //构造请求串 final limit = min(feedService.fetchLimit - rawItems.length, 1000); var params = "/reader/api/0/stream/contents?output=json&n=$limit"; if (feedService.latestFetchedTime != null) { params += "&ot=${feedService.latestFetchedTime}"; } if (continuation != null) params += "&c=$continuation"; final response = await fetchResponse(params); if (response.statusCode != 200) { break; } //如果不超过fetchLimit则添加到items final responseBody = jsonDecode(response.body); fetchedItems = responseBody["items"]; for (var i in fetchedItems) { i["id"] = _compactId(i["id"]); if (i["id"] == feedService.lastedFetchedId || rawItems.length >= feedService.fetchLimit) { break; } else { rawItems.add(i); } } // continuation = responseBody["continuation"]; continuation = ""; } catch (exp) { IPrint.debug(exp); break; } } while (continuation != null && rawItems.length < feedService.fetchLimit); //更新最新拉取信息 if (rawItems.isNotEmpty) { feedService.lastedFetchedId = rawItems[0]["id"]; feedService.latestFetchedTime = DateTime.fromMillisecondsSinceEpoch( int.parse(rawItems[0]["crawlTimeMsec"])); } //解析到RSSItem对象 List<RssItem> parsedItems = []; for (var i in rawItems) { final dom = parse(i["summary"]["content"]); if (feedService.params != null && feedService.params!['removeInoreaderAd'] != null && feedService.params!['removeInoreaderAd'] is bool && feedService.params!['removeInoreaderAd'] as bool) { if (dom.documentElement!.text.trim().startsWith("Ads from Inoreader")) { dom.body!.firstChild!.remove(); } } final item = RssItem( iid: i["id"], feedFid: i["origin"]["streamId"], title: i["title"], url: i["canonical"][0]["href"], date: DateTime.fromMillisecondsSinceEpoch(i["published"] * 1000), content: dom.body!.innerHtml, snippet: dom.documentElement!.text.trim(), creator: i["author"], hasRead: false, starred: false, feedId: await FeedDao.getIdByFid(i["origin"]["streamId"]), ); if (feedService.appId != null) { item.title = parse(item.title).documentElement!.text; } var img = dom.querySelector("img"); if (img != null && img.attributes["src"] != null) { var thumb = img.attributes["src"]; if (thumb!.startsWith("http")) { item.thumb = thumb; } } for (var c in i["categories"]) { if (!item.hasRead && c.endsWith("/state/com.google/read")) { item.hasRead = true; } else if (!item.starred && c.endsWith("/state/com.google/starred")) { item.starred = true; } } parsedItems.add(item); } return parsedItems; } @override Future<Tuple2<Set<String>, Set<String>>> syncItems() async { List<Set<String>> results; if (feedService.appId != null) { results = await Future.wait([ _fetchAll( "/reader/api/0/stream/items/ids?output=json&xt=$_tagHasRead&n=1000"), _fetchAll( "/reader/api/0/stream/items/ids?output=json&it=$_tagStarred&n=1000"), ]); } else { results = await Future.wait([ _fetchAll( "/reader/api/0/stream/items/ids?output=json&s=$_tagAll&xt=$_tagHasRead&n=1000"), _fetchAll( "/reader/api/0/stream/items/ids?output=json&s=$_tagStarred&n=1000"), ]); } return Tuple2.fromList(results); } @override Future<void> markAllRead( Set<String> sids, DateTime? date, bool before) async { if (date != null) { List<String> predicates = ["hasRead = 0"]; if (sids.isNotEmpty) { predicates .add("source IN (${List.filled(sids.length, "?").join(" , ")})"); } predicates .add("date ${before ? "<=" : ">="} ${date.millisecondsSinceEpoch}"); final rows = await ProviderManager.db.query( CreateTableSql.rssItems.tableName, columns: ["iid"], where: predicates.join(" AND "), whereArgs: sids.toList(), ); final iids = rows.map((r) => r["iid"]).iterator; List<String> refs = []; while (iids.moveNext()) { refs.add(iids.current as String); if (refs.length >= 1000) { _editTag(refs.join("&i="), _tagHasRead); refs = []; } } if (refs.isNotEmpty) _editTag(refs.join("&i="), _tagHasRead); } else { if (sids.isEmpty) { sids = Set.from(ProviderManager.rssProvider.currentRssServiceManager .getFeeds() .map((s) => s.fid)); } for (var sid in sids) { final body = {"s": sid}; fetchResponse("/reader/api/0/mark-all-as-read", body: body); } } } @override Future<void> markRead(RssItem item) async { await _editTag(item.iid, _tagHasRead); } @override Future<void> markUnread(RssItem item) async { await _editTag(item.iid, _tagHasRead, add: false); } @override Future<void> star(RssItem item) async { await _editTag(item.iid, _tagStarred); } @override Future<void> unstar(RssItem item) async { await _editTag(item.iid, _tagStarred, add: false); } Future<Set<String>> _fetchAll(String params) async { final results = List<String>.empty(growable: true); List fetched; String? continuation; do { var p = params; p += "&c=$continuation"; final response = await fetchResponse(p); assert(response.statusCode == 200); final parsed = jsonDecode(response.body); fetched = parsed["itemRefs"]; if (fetched.isNotEmpty) { for (var i in fetched) { results.add(i["id"]); } } continuation = parsed["continuation"]; } while (continuation != null && fetched.length >= 1000); return Set.from(results); } Future<http.Response> _editTag(String ref, String tag, {add = true}) async { final body = "i=$ref&${add ? "a" : "r"}=$tag"; return await fetchResponse("/reader/api/0/edit-tag", body: body); } String _compactId(String longId) { final last = longId.split("/").last; if (feedService.params == null || feedService.params!['useInt64'] == null || feedService.params!['useInt64'] is! bool || !(feedService.params!['useInt64'] as bool)) return last; return int.parse(last, radix: 16).toString(); } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/rss_service.dart
import 'dart:convert'; import 'feed_setting.dart'; /// /// Rss服务类型 /// enum RssServiceType { inoreader("Inoreader", [ "https://www.inoreader.com", "https://www.innoreader.com", "https://jp.inoreader.com", ]), feedbin("Feedbin", [ "https://api.feedbin.me/v2", "https://api.feedbin.com/v2", ]), feedHQ("FeedHQ", [""]), theOldReader("TheOldReader", ["https://theoldreader.com"]), bazQuxReader("BazQuxReader", ["https://bazqux.com"]), feedWrangler("FeedWrangler", [""]), newsBlur("NewsBlur", [""]), feverAPI("FeverAPI", [""]), freshRssAPI("FreshRssAPI", [""]), googleReaderAPI("GoogleReaderAPI", [""]), miniflux("Miniflux", [""]), nextcloudNewsAPI("NextcloudNewsAPI", [""]); const RssServiceType(this.name, this.endpoint); final String name; final List<String> endpoint; } /// /// Rss服务 /// class RssService { int? id; String endpoint; String name; RssServiceType feedServiceType; String? username; String? password; String? appId; String? appKey; String? authorization; int fetchLimit; bool pullOnStartUp; SyncStatus? lastSyncStatus; DateTime? lastSyncTime; DateTime? latestFetchedTime; String? lastedFetchedId; Map<String, Object?>? params; RssService( this.endpoint, this.name, this.feedServiceType, { this.id, this.username, this.password, this.appId, this.appKey, this.authorization, this.fetchLimit = 500, this.pullOnStartUp = true, this.lastSyncStatus, this.lastSyncTime, this.lastedFetchedId, this.latestFetchedTime, this.params, }); RssService._privateConstructor( this.id, this.endpoint, this.name, this.feedServiceType, this.username, this.password, this.appId, this.appKey, this.authorization, this.fetchLimit, this.pullOnStartUp, this.lastSyncStatus, this.lastSyncTime, this.lastedFetchedId, this.latestFetchedTime, this.params, ); RssService clone() { return RssService._privateConstructor( id, endpoint, name, feedServiceType, username, password, appId, appKey, authorization, fetchLimit, pullOnStartUp, lastSyncStatus, lastSyncTime, lastedFetchedId, latestFetchedTime, params, ); } Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, 'endpoint': endpoint, "name": name, 'feedServiceType': feedServiceType.index, 'username': username, 'password': password, 'appId': appId, 'appKey': appKey, 'authorization': authorization, 'fetchLimit': fetchLimit, 'pullOnStartUp': pullOnStartUp ? 1 : 0, 'lastSyncStatus': lastSyncStatus?.index, 'lastSyncTime': lastSyncTime?.millisecondsSinceEpoch, 'latestFetchedTime': latestFetchedTime?.millisecondsSinceEpoch, 'lastedFetchedId': lastedFetchedId, 'params': jsonEncode(params), }; factory RssService.fromJson(Map<String, dynamic> map) => RssService( map['endpoint'] as String, map['name'] as String, RssServiceType.values[map['feedServiceType']], id: map['id'] as int?, username: map['username'] as String?, password: map['password'] as String?, appId: map['appId'] as String?, appKey: map['appKey'] as String?, authorization: map['authorization'] as String?, fetchLimit: map['fetchLimit'] as int? ?? 500, pullOnStartUp: map['pullOnStartUp'] == 0 ? false : true, lastSyncStatus: map['lastSyncStatus'] == null ? null : SyncStatus.values[map['lastSyncStatus']], lastSyncTime: map['lastSyncTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['lastSyncTime']), lastedFetchedId: map['lastedFetchedId'] as String?, latestFetchedTime: map['latestFetchedTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['latestFetchedTime']), params: jsonDecode(map['params']), ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/feed_setting.dart
/// 文章拉取方式:跟随全局设置、RSS、全文、Web页面、外部浏览器 enum CrawlType { unspecified, rss, full, web, external } /// 文章列表布局:跟随全局设置、卡片、瀑布流、杂志、紧凑、画廊、播客 enum ArticleListLayoutType { unspecified, card, flow, magazine, compact, gallery, podcast } /// 文章详情布局:跟随全局设置、单个文章、左右滑动卡片、上下滑动文章 enum ArticleDetailLayoutType { unspecified, single, leftAndRight, upAndDown, } /// 文章详情头图显示选项:跟随全局设置、不显示头图、首张图片、随机图片、画廊、幻灯片 enum ArticleDetailHeadImageViewType { unspecified, hide, first, random, gallery, slideshow } /// 文章详情视频显示选项:跟随全局设置、不显示、截取图片、视频控件 enum ArticleDetailVideoViewType { unspecified, hide, screenshot, video } /// 文章Mobilizer选项:跟随全局设置、Feedbin Parser、FeedMe、Google Web Light enum MobilizerType { unspecified, feedbinParser, feedMe, googleWebLight } /// 缓存选项:跟随全局设置、始终缓存、仅在充电时缓存、仅在WiFi下缓存、仅在充电且WiFi下缓存、不缓存 enum CacheType { unspecified, enable, onlyUnderCharge, onlyUnderWiFi, onlyUnderChargeAndWiFi, disable } /// 布尔表达式选项:跟随全局设置、启用、禁用 enum BoolType { unspecified, enable, diable } /// 同步状态:尚未同步、成功、失败 enum SyncStatus { unspecified, success, fail } /// (全局)订阅源设置,包含文章抓取方式、文章列表布局、文章详情布局、文章详情头图显示选项、文章详情视频显示选项、拉取时是否下载图片、拉取时是否下载Web页面、阅读时是否下载Web页面、 /// 软件启动时是否拉取、是否显示相关文章、是否显示图片标题、是否移除重复文章、滚动时是否自动标为已读、自动拉取频率 class FeedSetting { CrawlType? crawlType; ArticleListLayoutType? listLayoutType; ArticleDetailLayoutType? detailLayoutType; ArticleDetailHeadImageViewType? headImageViewType; ArticleDetailVideoViewType? videoViewType; MobilizerType? mobilizerType; CacheType? cacheImageTypeOnPull; CacheType? cacheWebTypeOnPull; CacheType? cacheWebTypeOnRead; CacheType? pullType; BoolType? pullOnStartUp; BoolType? autoTranslate; BoolType? showAiAbstract; BoolType? showRelatedArticles; BoolType? showImageAlt; BoolType? removeDuplicateArticles; BoolType? autoReadOnScroll; int? autoPullFrequency; FeedSetting({ this.crawlType, this.listLayoutType, this.detailLayoutType, this.headImageViewType, this.videoViewType, this.mobilizerType, this.cacheImageTypeOnPull, this.cacheWebTypeOnPull, this.cacheWebTypeOnRead, this.pullType, this.pullOnStartUp, this.autoTranslate, this.showAiAbstract, this.showRelatedArticles, this.showImageAlt, this.removeDuplicateArticles, this.autoReadOnScroll, this.autoPullFrequency, }); Map<String, dynamic> toJson() => <String, dynamic>{ 'crawlType': crawlType?.index, 'listLayoutType': listLayoutType?.index, 'detailLayoutType': detailLayoutType?.index, 'headImageViewType': headImageViewType?.index, 'videoViewType': videoViewType?.index, 'mobilizerType': mobilizerType?.index, 'cacheImageTypeOnPull': cacheImageTypeOnPull?.index, 'cacheWebTypeOnPull': cacheWebTypeOnPull?.index, 'cacheWebTypeOnRead': cacheWebTypeOnRead?.index, 'pullType': pullType?.index, 'pullOnStartUp': pullOnStartUp?.index, 'autoTranslate': autoTranslate?.index, 'showAiAbstract': showAiAbstract?.index, 'showRelatedArticles': showRelatedArticles?.index, 'showImageAlt': showImageAlt?.index, 'removeDuplicateArticles': removeDuplicateArticles?.index, 'autoReadOnScroll': autoReadOnScroll?.index, 'autoPullFrequency': autoPullFrequency, }; factory FeedSetting.fromJson(Map<String, dynamic> json) => FeedSetting( crawlType: json['crawlType'] != null ? CrawlType.values[json['crawlType']] : null, listLayoutType: json['listLayoutType'] != null ? ArticleListLayoutType.values[json['listLayoutType']] : null, detailLayoutType: json['detailLayoutType'] != null ? ArticleDetailLayoutType.values[json['detailLayoutType']] : null, headImageViewType: json['headImageViewType'] != null ? ArticleDetailHeadImageViewType.values[json['headImageViewType']] : null, videoViewType: json['videoViewType'] != null ? ArticleDetailVideoViewType.values[json['videoViewType']] : null, mobilizerType: json['mobilizerType'] != null ? MobilizerType.values[json['mobilizerType']] : null, cacheImageTypeOnPull: json['cacheImageTypeOnPull'] != null ? CacheType.values[json['cacheImageTypeOnPull']] : null, cacheWebTypeOnPull: json['cacheWebTypeOnPull'] != null ? CacheType.values[json['cacheWebTypeOnPull']] : null, cacheWebTypeOnRead: json['cacheWebTypeOnRead'] != null ? CacheType.values[json['cacheWebTypeOnRead']] : null, pullType: json['pullType'] != null ? CacheType.values[json['pullType']] : null, pullOnStartUp: json['pullOnStartUp'] != null ? BoolType.values[json['pullOnStartUp']] : null, showRelatedArticles: json['showRelatedArticles'] != null ? BoolType.values[json['showRelatedArticles']] : null, showImageAlt: json['showImageAlt'] != null ? BoolType.values[json['showImageAlt']] : null, removeDuplicateArticles: json['removeDuplicateArticles'] != null ? BoolType.values[json['removeDuplicateArticles']] : null, autoReadOnScroll: json['autoReadOnScroll'] != null ? BoolType.values[json['autoReadOnScroll']] : null, autoPullFrequency: json['autoPullFrequency'] as int?, ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/nav_entry.dart
import 'package:readar/Screens/Navigation/title_screen.dart'; import 'package:flutter/material.dart'; import '../Providers/provider_manager.dart'; import '../generated/l10n.dart'; class NavEntry { String id; int index; bool visible; NavEntry({ required this.id, required this.index, required this.visible, }); Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, 'index': index, 'visible': visible ? 1 : 0, }; factory NavEntry.fromJson(Map<String, dynamic> json) => NavEntry( id: json['id'] as String, index: json['index'] as int, visible: json['visible'] == 0 ? false : true, ); static NavEntry libraryEntry = NavEntry( id: "library", index: 1, visible: true, ); static List<NavEntry> defaultEntries = <NavEntry>[ NavEntry( id: "explore", index: 2, visible: true, ), ]; static List<NavEntry> changableEntries = <NavEntry>[ NavEntry( id: "feed", index: 1, visible: true, ), NavEntry( id: "star", index: 2, visible: true, ), NavEntry( id: "readLater", index: 3, visible: true, ), NavEntry( id: "highlights", index: 4, visible: false, ), NavEntry( id: "saved", index: 5, visible: false, ), NavEntry( id: "history", index: 6, visible: false, ), NavEntry( id: "statistics", index: 7, visible: false, ), ]; static Map<String, IconData> idToIconMap = { "feed": Icons.rss_feed_rounded, 'star': Icons.star_outline_rounded, "readLater": Icons.checklist_rounded, 'highlights': Icons.lightbulb_outline_rounded, 'saved': Icons.save_alt_rounded, 'history': Icons.history_outlined, "statistics": Icons.show_chart_rounded, "explore": Icons.explore_outlined, "library": Icons.library_books_outlined, }; static Map<String, Widget> idToPageMap = { "feed": const TitleScreen("feed"), 'star': const TitleScreen("star"), "readLater": const TitleScreen("readLater"), 'highlights': const TitleScreen("highlights"), 'saved': const TitleScreen("saved"), 'history': const TitleScreen("history"), "statistics": const TitleScreen("statistics"), "explore": const TitleScreen("explore"), "library": const TitleScreen("library"), }; static int compare(NavEntry a, NavEntry b) { return a.index - b.index; } static String getLabel(String id) { Map<String, String> idToLabelMap = { "feed": S.current.feed, 'star': S.current.star, "readLater": S.current.readLater, 'highlights': S.current.highlights, 'saved': S.current.saved, 'history': S.current.history, "statistics": S.current.statistics, "explore": S.current.explore, "library": S.current.library, }; return idToLabelMap[id] ?? ""; } static IconData getIcon(String id) { return idToIconMap[id] ?? Icons.add; } static Widget getPage(String id) { return idToPageMap[id]!; } static List<NavEntry> getNavs() { List<NavEntry> navs = ProviderManager.globalProvider.navEntries; navs.sort(compare); return navs; } static List<NavEntry> getHiddenEntries() { List<NavEntry> navEntries = ProviderManager.globalProvider.navEntries; navEntries.sort(compare); List<NavEntry> hiddenEntries = []; for (NavEntry entry in navEntries) { if (!entry.visible) hiddenEntries.add(entry); } return hiddenEntries; } static List<NavEntry> getShownEntries() { List<NavEntry> navEntries = ProviderManager.globalProvider.navEntries; navEntries.sort(compare); List<NavEntry> showEntries = []; List<String> ids = List.generate(navEntries.length, (index) => navEntries[index].id); for (NavEntry entry in navEntries) { if (entry.visible) showEntries.add(entry); } for (NavEntry entry in NavEntry.changableEntries) { if (!ids.contains(entry.id)) showEntries.add(entry); } return showEntries; } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/extension_service.dart
import 'dart:convert'; import 'feed_setting.dart'; /// /// 插件服务 /// class ExtensionService { int id; String endpoint; String? username; String? password; String? appId; String? appKey; int articleCount; SyncStatus? lastPullStatus; DateTime? lastPullTime; Map<String, Object?>? params; ExtensionService( this.endpoint, { required this.id, this.username, this.password, this.appId, this.appKey, this.lastPullStatus, this.lastPullTime, this.articleCount = 0, this.params, }); ExtensionService._privateConstructor( this.id, this.endpoint, this.username, this.password, this.appId, this.appKey, this.lastPullStatus, this.lastPullTime, this.articleCount, this.params, ); ExtensionService clone() { return ExtensionService._privateConstructor( id, endpoint, username, password, appId, appKey, lastPullStatus, lastPullTime, articleCount, params, ); } Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, 'endpoint': endpoint, 'username': username, 'password': password, 'appId': appId, 'appKey': appKey, 'articleCount': articleCount, 'lastPullStatus': lastPullStatus?.index, 'lastPullTime': lastPullTime?.millisecondsSinceEpoch, 'params': jsonEncode(params), }; factory ExtensionService.fromJson(Map<String, dynamic> map) => ExtensionService( map['endpoint'] as String, id: map['id'] as int, username: map['username'] as String?, password: map['password'] as String?, appId: map['appId'] as String?, appKey: map['appKey'] as String?, lastPullStatus: map['lastPullStatus'] == null ? null : SyncStatus.values[map['lastPullStatus']], lastPullTime: map['lastPullTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['lastPullTime']), articleCount: map['articleCount'] as int? ?? 0, params: jsonDecode(map['params']), ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/rss_item.dart
import 'dart:convert'; /// /// RSS文章条目 /// class RssItem { String iid; int feedId; String feedFid; String title; String url; DateTime date; String content; String snippet; String? creator; String? thumb; bool hasRead; bool starred; DateTime? readTime; DateTime? starTime; Map<String, Object?>? params; RssItem({ required this.iid, required this.feedId, required this.feedFid, required this.title, required this.url, required this.date, required this.content, required this.snippet, this.creator, this.thumb, this.hasRead = false, this.starred = false, this.readTime, this.starTime, this.params, }); RssItem._privateConstructor( this.iid, this.feedId, this.feedFid, this.title, this.url, this.date, this.content, this.snippet, this.creator, this.thumb, this.hasRead, this.starred, this.readTime, this.starTime, this.params, ); RssItem clone() { return RssItem._privateConstructor( iid, feedId, feedFid, title, url, date, content, snippet, creator, thumb, hasRead, starred, readTime, starTime, params, ); } Map<String, dynamic> toJson() => <String, dynamic>{ 'iid': iid, 'feedId': feedId, 'feedFid': feedFid, 'title': title, 'url': url, 'date': date.millisecondsSinceEpoch, 'content': content, 'snippet': snippet, 'creator': creator, 'thumb': thumb, 'hasRead': hasRead ? 1 : 0, 'starred': starred ? 1 : 0, 'readTime': readTime?.millisecondsSinceEpoch, 'starTime': starTime?.millisecondsSinceEpoch, 'params': jsonEncode(params), }; factory RssItem.fromJson(Map<String, dynamic> map) => RssItem( iid: map['iid'] as String, feedId: map['feedId'] as int, feedFid: map['feedFid'] as String, title: map['title'] as String, url: map['url'] as String, date: DateTime.fromMillisecondsSinceEpoch(map['date']), content: map['content'] as String, snippet: map['snippet'] as String, creator: map['creator'] as String?, thumb: map['thumb'] as String?, hasRead: map['hasRead'] == 0 ? false : true, starred: map['starred'] == 0 ? false : true, readTime: map['readTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['readTime']), starTime: map['starTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['starTime']), params: jsonDecode(map['params']), ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/backup_service.dart
import 'dart:convert'; import 'feed_setting.dart'; /// /// 云盘备份服务 /// class BackupService { int id; String endpoint; String? username; String? password; String? appId; String? appKey; SyncStatus? lastPullStatus; DateTime? lastPullTime; SyncStatus? lastPushStatus; DateTime? lastPushTime; Map<String, Object?>? params; BackupService( this.endpoint, { required this.id, this.username, this.password, this.appId, this.appKey, this.lastPullStatus, this.lastPullTime, this.lastPushStatus, this.lastPushTime, this.params, }); BackupService._privateConstructor( this.id, this.endpoint, this.username, this.password, this.appId, this.appKey, this.lastPullStatus, this.lastPullTime, this.lastPushStatus, this.lastPushTime, this.params, ); BackupService clone() { return BackupService._privateConstructor( id, endpoint, username, password, appId, appKey, lastPullStatus, lastPullTime, lastPushStatus, lastPushTime, params, ); } Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, 'endpoint': endpoint, 'username': username, 'password': password, 'appId': appId, 'appKey': appKey, 'lastPullStatus': lastPullStatus?.index, 'lastPullTime': lastPullTime?.millisecondsSinceEpoch, 'lastPushStatus': lastPullStatus?.index, 'lastPushTime': lastPushTime?.millisecondsSinceEpoch, 'params': jsonEncode(params), }; factory BackupService.fromJson(Map<String, dynamic> map) => BackupService( map['endpoint'] as String, id: map['id'] as int, username: map['username'] as String?, password: map['password'] as String?, appId: map['appId'] as String?, appKey: map['appKey'] as String?, lastPullStatus: map['lastPullStatus'] == null ? null : SyncStatus.values[map['lastPullStatus']], lastPullTime: map['lastPullTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['lastPullTime']), lastPushStatus: map['lastPushStatus'] == null ? null : SyncStatus.values[map['lastPushStatus']], lastPushTime: map['lastPushTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['lastPushTime']), params: jsonDecode(map['params']), ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/feed.dart
import 'dart:convert'; import 'feed_setting.dart'; /// /// 订阅源 /// class Feed { int? id; int serviceId; String fid; String url; String? iconUrl; String name; int unReadCount; FeedSetting? feedSetting; SyncStatus? lastPullStatus; DateTime? lastPullTime; DateTime? latestArticleTime; String? latestArticleTitle; Map<String, Object?>? params; Feed( this.fid, this.url, this.name, { this.id, required this.serviceId, this.unReadCount = 0, this.feedSetting, this.lastPullTime, this.lastPullStatus, this.iconUrl, this.latestArticleTime, this.latestArticleTitle, this.params, }) { latestArticleTime = DateTime.now(); latestArticleTitle = ""; } Feed._privateConstructor( this.id, this.serviceId, this.fid, this.url, this.iconUrl, this.name, this.unReadCount, this.latestArticleTime, this.latestArticleTitle, this.lastPullStatus, this.lastPullTime, this.feedSetting, this.params, ); Feed clone() { return Feed._privateConstructor( id, serviceId, fid, url, iconUrl, name, unReadCount, latestArticleTime, latestArticleTitle, lastPullStatus, lastPullTime, feedSetting, params, ); } Map<String, dynamic> toJson() => <String, dynamic>{ 'id': id, 'serviceId': serviceId, 'fid': fid, 'url': url, 'iconUrl': iconUrl, 'name': name, "unReadCount": unReadCount, 'feedSetting': feedSetting != null ? jsonEncode(feedSetting!.toJson()) : null, 'lastPullStatus': lastPullStatus?.index, 'lastPullTime': lastPullTime?.millisecondsSinceEpoch, 'latestArticleTime': latestArticleTime?.millisecondsSinceEpoch, 'latestArticleTitle': latestArticleTitle, 'params': jsonEncode(params), }; factory Feed.fromJson(Map<String, dynamic> map) => Feed( map['fid'] as String, map['url'] as String, map['name'] as String, id: map['id'] as int, serviceId: map['serviceId'] as int, unReadCount: map['unReadCount'] as int, feedSetting: map['feedSetting'] == null ? null : FeedSetting.fromJson(jsonDecode(map['feedSetting'])), lastPullTime: map['lastPullTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['lastPullTime']), lastPullStatus: map['lastPullStatus'] == null ? null : SyncStatus.values[map['lastPullStatus']], iconUrl: map['iconUrl'] as String?, latestArticleTime: map['latestArticleTime'] == null ? null : DateTime.fromMillisecondsSinceEpoch(map['latestArticleTime']), latestArticleTitle: map['latestArticleTitle'] as String?, params: jsonDecode(map['params']), ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Models/rss_item_list.dart
import 'package:readar/Database/rss_item_dao.dart'; import 'package:readar/Models/rss_item.dart'; import 'package:tuple/tuple.dart'; import '../Providers/provider_manager.dart'; /// /// 过滤类型:全部、未读、已读、已标星标、未标星标、已保存 /// enum FilterType { all, unread, read, starred, unstarred, saved } /// 一次加载文章条数 const loadLimit = 50; /// /// 文章列表类,当加载某个订阅源时使用 /// class RssItemList { /// 是否已经初始化 bool initialized = false; /// 是否正在加载数据 bool loading = false; /// 是否已经加载完毕 bool allLoaded = false; /// 需要加载的订阅源Fid列表 Set<String> fids; /// 文章条目列表 List<String> iids = []; /// 过滤类型 FilterType filterType; /// 查询关键字 String query = ""; RssItemList({ required this.fids, this.filterType = FilterType.all, }) { //TODO 修改为存储类型 filterType = FilterType.values[0]; } /// /// 初始化列表 /// Future<void> init() async { if (loading) return; loading = true; var conditions = _getConditions(); var items = (await RssItemDao.query( loadLimit: loadLimit, where: conditions.item1, whereArgs: conditions.item2)); allLoaded = items.length < loadLimit; ProviderManager.rssProvider.currentRssServiceManager.mappingItems(items); iids = items.map((i) => i.iid).toList(); loading = false; initialized = true; } /// /// 加载更多条目 /// Future<void> loadMore() async { if (loading || allLoaded) return; loading = true; var conditions = _getConditions(); var offset = iids .map((iid) => ProviderManager.rssProvider.currentRssServiceManager.getItem(iid)) .fold(0, (c, i) => c + (testItem(i) ? 1 : 0)); var items = (await RssItemDao.query( loadLimit: loadLimit, where: conditions.item1, offset: offset, whereArgs: conditions.item2)); if (items.length < loadLimit) { allLoaded = true; } ProviderManager.rssProvider.currentRssServiceManager.mappingItems(items); iids.addAll(items.map((i) => i.iid)); loading = false; } /// /// 获取查询条件 /// Tuple2<String, List<String>> _getConditions() { List<String> where = ["1 = 1"]; List<String> whereArgs = []; if (fids.isNotEmpty) { var placeholders = List.filled(fids.length, "?").join(" , "); where.add("feedFid IN ($placeholders)"); whereArgs.addAll(fids); } if (filterType == FilterType.unread) { where.add("hasRead = 0"); } else if (filterType == FilterType.starred) { where.add("starred = 1"); } if (query != "") { where.add("(UPPER(title) LIKE ? OR UPPER(snippet) LIKE ?)"); var keyword = "%$query%".toUpperCase(); whereArgs.add(keyword); whereArgs.add(keyword); } return Tuple2(where.join(" AND "), whereArgs); } /// /// 测试某个文章条目是否符合过滤要求 /// bool testItem(RssItem item) { if (fids.isNotEmpty && !fids.contains(item.feedFid)) return false; if (filterType == FilterType.unread && item.hasRead) return false; if (filterType == FilterType.starred && !item.starred) return false; if (query != "") { var keyword = query.toUpperCase(); if (item.title.toUpperCase().contains(keyword)) return true; if (item.snippet.toUpperCase().contains(keyword)) return true; return false; } return true; } /// /// 设置过滤条件 /// Future<void> setFilter(FilterType filter) async { if (filterType == filter && filter == FilterType.all) return; filterType = filter; await init(); } /// /// 设置搜索关键词 /// Future<void> performSearch(String keyword) async { if (query == keyword) return; query = keyword; await init(); } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/generated/l10n.dart
// GENERATED CODE - DO NOT MODIFY BY HAND import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'intl/messages_all.dart'; // ************************************************************************** // Generator: Flutter Intl IDE plugin // Made by Localizely // ************************************************************************** // ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars // ignore_for_file: join_return_with_assignment, prefer_final_in_for_each // ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes class S { S(); static S? _current; static S get current { assert(_current != null, 'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.'); return _current!; } static const AppLocalizationDelegate delegate = AppLocalizationDelegate(); static Future<S> load(Locale locale) { final name = (locale.countryCode?.isEmpty ?? false) ? locale.languageCode : locale.toString(); final localeName = Intl.canonicalizedLocale(name); return initializeMessages(localeName).then((_) { Intl.defaultLocale = localeName; final instance = S(); S._current = instance; return instance; }); } static S of(BuildContext context) { final instance = S.maybeOf(context); assert(instance != null, 'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?'); return instance!; } static S? maybeOf(BuildContext context) { return Localizations.of<S>(context, S); } /// `Readar` String get appName { return Intl.message( 'Readar', name: 'appName', desc: '', args: [], ); } /// `Content` String get content { return Intl.message( 'Content', name: 'content', desc: '', args: [], ); } /// `Articles` String get article { return Intl.message( 'Articles', name: 'article', desc: '', args: [], ); } /// `All Articles` String get allArticle { return Intl.message( 'All Articles', name: 'allArticle', desc: '', args: [], ); } /// `Feed` String get feed { return Intl.message( 'Feed', name: 'feed', desc: '', args: [], ); } /// `Star` String get star { return Intl.message( 'Star', name: 'star', desc: '', args: [], ); } /// `Read Later` String get readLater { return Intl.message( 'Read Later', name: 'readLater', desc: '', args: [], ); } /// `Highlights` String get highlights { return Intl.message( 'Highlights', name: 'highlights', desc: '', args: [], ); } /// `Library` String get library { return Intl.message( 'Library', name: 'library', desc: '', args: [], ); } /// `Saved` String get saved { return Intl.message( 'Saved', name: 'saved', desc: '', args: [], ); } /// `History` String get history { return Intl.message( 'History', name: 'history', desc: '', args: [], ); } /// `Hot Links` String get hotLinks { return Intl.message( 'Hot Links', name: 'hotLinks', desc: '', args: [], ); } /// `Calm Feeds` String get calmFeeds { return Intl.message( 'Calm Feeds', name: 'calmFeeds', desc: '', args: [], ); } /// `Linked List` String get linkedList { return Intl.message( 'Linked List', name: 'linkedList', desc: '', args: [], ); } /// `Explore` String get explore { return Intl.message( 'Explore', name: 'explore', desc: '', args: [], ); } /// `Statistics` String get statistics { return Intl.message( 'Statistics', name: 'statistics', desc: '', args: [], ); } /// `TTS` String get tts { return Intl.message( 'TTS', name: 'tts', desc: '', args: [], ); } /// `Setting` String get setting { return Intl.message( 'Setting', name: 'setting', desc: '', args: [], ); } /// `Basic Setting` String get basicSetting { return Intl.message( 'Basic Setting', name: 'basicSetting', desc: '', args: [], ); } /// `Advanced Setting` String get advancedSetting { return Intl.message( 'Advanced Setting', name: 'advancedSetting', desc: '', args: [], ); } /// `General` String get generalSetting { return Intl.message( 'General', name: 'generalSetting', desc: '', args: [], ); } /// `Global` String get globalSetting { return Intl.message( 'Global', name: 'globalSetting', desc: '', args: [], ); } /// `Apprearance` String get apprearanceSetting { return Intl.message( 'Apprearance', name: 'apprearanceSetting', desc: '', args: [], ); } /// `Service` String get serviceSetting { return Intl.message( 'Service', name: 'serviceSetting', desc: '', args: [], ); } /// `Extension` String get extensionSetting { return Intl.message( 'Extension', name: 'extensionSetting', desc: '', args: [], ); } /// `Backup` String get backupSetting { return Intl.message( 'Backup', name: 'backupSetting', desc: '', args: [], ); } /// `Operation` String get operationSetting { return Intl.message( 'Operation', name: 'operationSetting', desc: '', args: [], ); } /// `Privacy` String get privacySetting { return Intl.message( 'Privacy', name: 'privacySetting', desc: '', args: [], ); } /// `Experiment` String get experimentSetting { return Intl.message( 'Experiment', name: 'experimentSetting', desc: '', args: [], ); } /// `Help` String get help { return Intl.message( 'Help', name: 'help', desc: '', args: [], ); } /// `About` String get about { return Intl.message( 'About', name: 'about', desc: '', args: [], ); } /// `Contributor` String get contributor { return Intl.message( 'Contributor', name: 'contributor', desc: '', args: [], ); } /// `Change Log` String get changeLog { return Intl.message( 'Change Log', name: 'changeLog', desc: '', args: [], ); } /// `Participate In Translation` String get participateInTranslation { return Intl.message( 'Participate In Translation', name: 'participateInTranslation', desc: '', args: [], ); } /// `Bug Report` String get bugReport { return Intl.message( 'Bug Report', name: 'bugReport', desc: '', args: [], ); } /// `Github Repo` String get githubRepo { return Intl.message( 'Github Repo', name: 'githubRepo', desc: '', args: [], ); } /// `License` String get license { return Intl.message( 'License', name: 'license', desc: '', args: [], ); } /// `Privacy Policy` String get privacyPolicy { return Intl.message( 'Privacy Policy', name: 'privacyPolicy', desc: '', args: [], ); } /// `Rate Us` String get rate { return Intl.message( 'Rate Us', name: 'rate', desc: '', args: [], ); } /// `Contact Us` String get contact { return Intl.message( 'Contact Us', name: 'contact', desc: '', args: [], ); } /// `Website` String get officialWebsite { return Intl.message( 'Website', name: 'officialWebsite', desc: '', args: [], ); } /// `Telegram Group` String get telegramGroup { return Intl.message( 'Telegram Group', name: 'telegramGroup', desc: '', args: [], ); } /// `Language` String get language { return Intl.message( 'Language', name: 'language', desc: '', args: [], ); } /// `Choose Language` String get chooseLanguage { return Intl.message( 'Choose Language', name: 'chooseLanguage', desc: '', args: [], ); } /// `Choose Theme Mode` String get chooseThemeMode { return Intl.message( 'Choose Theme Mode', name: 'chooseThemeMode', desc: '', args: [], ); } /// `Follow System` String get followSystem { return Intl.message( 'Follow System', name: 'followSystem', desc: '', args: [], ); } /// `Theme Setting` String get themeSetting { return Intl.message( 'Theme Setting', name: 'themeSetting', desc: '', args: [], ); } /// `Select Theme` String get selectTheme { return Intl.message( 'Select Theme', name: 'selectTheme', desc: '', args: [], ); } /// `Theme Mode` String get themeMode { return Intl.message( 'Theme Mode', name: 'themeMode', desc: '', args: [], ); } /// `Primary Color` String get primaryColor { return Intl.message( 'Primary Color', name: 'primaryColor', desc: '', args: [], ); } /// `Light Theme` String get lightTheme { return Intl.message( 'Light Theme', name: 'lightTheme', desc: '', args: [], ); } /// `Dark Theme` String get darkTheme { return Intl.message( 'Dark Theme', name: 'darkTheme', desc: '', args: [], ); } /// `侧边栏入口设置` String get sideBarEntriesSetting { return Intl.message( '侧边栏入口设置', name: 'sideBarEntriesSetting', desc: '', args: [], ); } /// `显示的入口` String get shownEntries { return Intl.message( '显示的入口', name: 'shownEntries', desc: '', args: [], ); } /// `隐藏的入口(将被移动到{library}页面中)` String hiddenEntries(Object library) { return Intl.message( '隐藏的入口(将被移动到$library页面中)', name: 'hiddenEntries', desc: '', args: [library], ); } /// `已显示所有入口` String get allEntriesShownTip { return Intl.message( '已显示所有入口', name: 'allEntriesShownTip', desc: '', args: [], ); } /// `已隐藏所有入口` String get allEntriesHiddenTip { return Intl.message( '已隐藏所有入口', name: 'allEntriesHiddenTip', desc: '', args: [], ); } /// `Long press and drag an item here to move it to the end of the list.` String get dragTip { return Intl.message( 'Long press and drag an item here to move it to the end of the list.', name: 'dragTip', desc: '', args: [], ); } /// `Article Crawl option` String get crawlType { return Intl.message( 'Article Crawl option', name: 'crawlType', desc: '', args: [], ); } /// `Article list layout` String get articleListLayoutType { return Intl.message( 'Article list layout', name: 'articleListLayoutType', desc: '', args: [], ); } /// `Article detail layout` String get articleDetailLayoutType { return Intl.message( 'Article detail layout', name: 'articleDetailLayoutType', desc: '', args: [], ); } /// `Header image option` String get articleDetailHeaderImageViewType { return Intl.message( 'Header image option', name: 'articleDetailHeaderImageViewType', desc: '', args: [], ); } /// `Video option` String get articleDetailVideoViewType { return Intl.message( 'Video option', name: 'articleDetailVideoViewType', desc: '', args: [], ); } /// `Show related articles` String get articleDetailShowRelatedArticles { return Intl.message( 'Show related articles', name: 'articleDetailShowRelatedArticles', desc: '', args: [], ); } /// `Show image title` String get articleDetailShowImageAlt { return Intl.message( 'Show image title', name: 'articleDetailShowImageAlt', desc: '', args: [], ); } /// `Remove duplicate articles` String get removeDuplicateArticles { return Intl.message( 'Remove duplicate articles', name: 'removeDuplicateArticles', desc: '', args: [], ); } /// `Mobilizer` String get mobilizerType { return Intl.message( 'Mobilizer', name: 'mobilizerType', desc: '', args: [], ); } /// `Pull articles when starting` String get pullWhenStartUp { return Intl.message( 'Pull articles when starting', name: 'pullWhenStartUp', desc: '', args: [], ); } /// `Automatically mark as read when scrolling` String get autoReadWhenScrolling { return Intl.message( 'Automatically mark as read when scrolling', name: 'autoReadWhenScrolling', desc: '', args: [], ); } /// `Cache images when pulling` String get cacheImageWhenPull { return Intl.message( 'Cache images when pulling', name: 'cacheImageWhenPull', desc: '', args: [], ); } /// `Cache articles when pulling` String get cacheWebPageWhenPull { return Intl.message( 'Cache articles when pulling', name: 'cacheWebPageWhenPull', desc: '', args: [], ); } /// `Cache articles when reading` String get cacheWebPageWhenReading { return Intl.message( 'Cache articles when reading', name: 'cacheWebPageWhenReading', desc: '', args: [], ); } /// `Pull Strategy` String get pullStrategy { return Intl.message( 'Pull Strategy', name: 'pullStrategy', desc: '', args: [], ); } /// `TTS Setting` String get ttsSetting { return Intl.message( 'TTS Setting', name: 'ttsSetting', desc: '', args: [], ); } /// `Enable TTS` String get ttsEnable { return Intl.message( 'Enable TTS', name: 'ttsEnable', desc: '', args: [], ); } /// `TTS Engine` String get ttsEngine { return Intl.message( 'TTS Engine', name: 'ttsEngine', desc: '', args: [], ); } /// `Reading Speed` String get ttsSpeed { return Intl.message( 'Reading Speed', name: 'ttsSpeed', desc: '', args: [], ); } /// `Ignore audio focus` String get ttsSpot { return Intl.message( 'Ignore audio focus', name: 'ttsSpot', desc: '', args: [], ); } /// `Allow simultaneous audio playback with other applications` String get ttsSpotTip { return Intl.message( 'Allow simultaneous audio playback with other applications', name: 'ttsSpotTip', desc: '', args: [], ); } /// `Automatically mark as read` String get ttsAutoHaveRead { return Intl.message( 'Automatically mark as read', name: 'ttsAutoHaveRead', desc: '', args: [], ); } /// `The article will be automatically marked as read after it is read aloud` String get ttsAutoHaveReadTip { return Intl.message( 'The article will be automatically marked as read after it is read aloud', name: 'ttsAutoHaveReadTip', desc: '', args: [], ); } /// `Wake Lock` String get ttsWakeLock { return Intl.message( 'Wake Lock', name: 'ttsWakeLock', desc: '', args: [], ); } /// `Enable wake lock when reading (may be killed in the background)` String get ttsWakeLockTip { return Intl.message( 'Enable wake lock when reading (may be killed in the background)', name: 'ttsWakeLockTip', desc: '', args: [], ); } /// `System TTS settings` String get ttsSystemSetting { return Intl.message( 'System TTS settings', name: 'ttsSystemSetting', desc: '', args: [], ); } /// `Check for Updates` String get checkUpdates { return Intl.message( 'Check for Updates', name: 'checkUpdates', desc: '', args: [], ); } /// `Last checked:` String get checkUpdatesTip { return Intl.message( 'Last checked:', name: 'checkUpdatesTip', desc: '', args: [], ); } /// `Already the latest version` String get checkUpdatesAlreadyLatest { return Intl.message( 'Already the latest version', name: 'checkUpdatesAlreadyLatest', desc: '', args: [], ); } /// `Clear Cache` String get clearCache { return Intl.message( 'Clear Cache', name: 'clearCache', desc: '', args: [], ); } /// `Clear cache successfully` String get clearCacheSuccess { return Intl.message( 'Clear cache successfully', name: 'clearCacheSuccess', desc: '', args: [], ); } } class AppLocalizationDelegate extends LocalizationsDelegate<S> { const AppLocalizationDelegate(); List<Locale> get supportedLocales { return const <Locale>[ Locale.fromSubtags(languageCode: 'en'), Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'), ]; } @override bool isSupported(Locale locale) => _isSupported(locale); @override Future<S> load(Locale locale) => S.load(locale); @override bool shouldReload(AppLocalizationDelegate old) => false; bool _isSupported(Locale locale) { for (var supportedLocale in supportedLocales) { if (supportedLocale.languageCode == locale.languageCode) { return true; } } return false; } }
0
mirrored_repositories/Readar/lib/generated
mirrored_repositories/Readar/lib/generated/intl/messages_en.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a en locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'en'; static String m0(library) => "隐藏的入口(将被移动到${library}页面中)"; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{ "about": MessageLookupByLibrary.simpleMessage("About"), "advancedSetting": MessageLookupByLibrary.simpleMessage("Advanced Setting"), "allArticle": MessageLookupByLibrary.simpleMessage("All Articles"), "allEntriesHiddenTip": MessageLookupByLibrary.simpleMessage("已隐藏所有入口"), "allEntriesShownTip": MessageLookupByLibrary.simpleMessage("已显示所有入口"), "appName": MessageLookupByLibrary.simpleMessage("Readar"), "apprearanceSetting": MessageLookupByLibrary.simpleMessage("Apprearance"), "article": MessageLookupByLibrary.simpleMessage("Articles"), "articleDetailHeaderImageViewType": MessageLookupByLibrary.simpleMessage("Header image option"), "articleDetailLayoutType": MessageLookupByLibrary.simpleMessage("Article detail layout"), "articleDetailShowImageAlt": MessageLookupByLibrary.simpleMessage("Show image title"), "articleDetailShowRelatedArticles": MessageLookupByLibrary.simpleMessage("Show related articles"), "articleDetailVideoViewType": MessageLookupByLibrary.simpleMessage("Video option"), "articleListLayoutType": MessageLookupByLibrary.simpleMessage("Article list layout"), "autoReadWhenScrolling": MessageLookupByLibrary.simpleMessage( "Automatically mark as read when scrolling"), "backupSetting": MessageLookupByLibrary.simpleMessage("Backup"), "basicSetting": MessageLookupByLibrary.simpleMessage("Basic Setting"), "bugReport": MessageLookupByLibrary.simpleMessage("Bug Report"), "cacheImageWhenPull": MessageLookupByLibrary.simpleMessage("Cache images when pulling"), "cacheWebPageWhenPull": MessageLookupByLibrary.simpleMessage("Cache articles when pulling"), "cacheWebPageWhenReading": MessageLookupByLibrary.simpleMessage("Cache articles when reading"), "calmFeeds": MessageLookupByLibrary.simpleMessage("Calm Feeds"), "changeLog": MessageLookupByLibrary.simpleMessage("Change Log"), "checkUpdates": MessageLookupByLibrary.simpleMessage("Check for Updates"), "checkUpdatesAlreadyLatest": MessageLookupByLibrary.simpleMessage("Already the latest version"), "checkUpdatesTip": MessageLookupByLibrary.simpleMessage("Last checked:"), "chooseLanguage": MessageLookupByLibrary.simpleMessage("Choose Language"), "chooseThemeMode": MessageLookupByLibrary.simpleMessage("Choose Theme Mode"), "clearCache": MessageLookupByLibrary.simpleMessage("Clear Cache"), "clearCacheSuccess": MessageLookupByLibrary.simpleMessage("Clear cache successfully"), "contact": MessageLookupByLibrary.simpleMessage("Contact Us"), "content": MessageLookupByLibrary.simpleMessage("Content"), "contributor": MessageLookupByLibrary.simpleMessage("Contributor"), "crawlType": MessageLookupByLibrary.simpleMessage("Article Crawl option"), "darkTheme": MessageLookupByLibrary.simpleMessage("Dark Theme"), "dragTip": MessageLookupByLibrary.simpleMessage( "Long press and drag an item here to move it to the end of the list."), "experimentSetting": MessageLookupByLibrary.simpleMessage("Experiment"), "explore": MessageLookupByLibrary.simpleMessage("Explore"), "extensionSetting": MessageLookupByLibrary.simpleMessage("Extension"), "feed": MessageLookupByLibrary.simpleMessage("Feed"), "followSystem": MessageLookupByLibrary.simpleMessage("Follow System"), "generalSetting": MessageLookupByLibrary.simpleMessage("General"), "githubRepo": MessageLookupByLibrary.simpleMessage("Github Repo"), "globalSetting": MessageLookupByLibrary.simpleMessage("Global"), "help": MessageLookupByLibrary.simpleMessage("Help"), "hiddenEntries": m0, "highlights": MessageLookupByLibrary.simpleMessage("Highlights"), "history": MessageLookupByLibrary.simpleMessage("History"), "hotLinks": MessageLookupByLibrary.simpleMessage("Hot Links"), "language": MessageLookupByLibrary.simpleMessage("Language"), "library": MessageLookupByLibrary.simpleMessage("Library"), "license": MessageLookupByLibrary.simpleMessage("License"), "lightTheme": MessageLookupByLibrary.simpleMessage("Light Theme"), "linkedList": MessageLookupByLibrary.simpleMessage("Linked List"), "mobilizerType": MessageLookupByLibrary.simpleMessage("Mobilizer"), "officialWebsite": MessageLookupByLibrary.simpleMessage("Website"), "operationSetting": MessageLookupByLibrary.simpleMessage("Operation"), "participateInTranslation": MessageLookupByLibrary.simpleMessage("Participate In Translation"), "primaryColor": MessageLookupByLibrary.simpleMessage("Primary Color"), "privacyPolicy": MessageLookupByLibrary.simpleMessage("Privacy Policy"), "privacySetting": MessageLookupByLibrary.simpleMessage("Privacy"), "pullStrategy": MessageLookupByLibrary.simpleMessage("Pull Strategy"), "pullWhenStartUp": MessageLookupByLibrary.simpleMessage("Pull articles when starting"), "rate": MessageLookupByLibrary.simpleMessage("Rate Us"), "readLater": MessageLookupByLibrary.simpleMessage("Read Later"), "removeDuplicateArticles": MessageLookupByLibrary.simpleMessage("Remove duplicate articles"), "saved": MessageLookupByLibrary.simpleMessage("Saved"), "selectTheme": MessageLookupByLibrary.simpleMessage("Select Theme"), "serviceSetting": MessageLookupByLibrary.simpleMessage("Service"), "setting": MessageLookupByLibrary.simpleMessage("Setting"), "shownEntries": MessageLookupByLibrary.simpleMessage("显示的入口"), "sideBarEntriesSetting": MessageLookupByLibrary.simpleMessage("侧边栏入口设置"), "star": MessageLookupByLibrary.simpleMessage("Star"), "statistics": MessageLookupByLibrary.simpleMessage("Statistics"), "telegramGroup": MessageLookupByLibrary.simpleMessage("Telegram Group"), "themeMode": MessageLookupByLibrary.simpleMessage("Theme Mode"), "themeSetting": MessageLookupByLibrary.simpleMessage("Theme Setting"), "tts": MessageLookupByLibrary.simpleMessage("TTS"), "ttsAutoHaveRead": MessageLookupByLibrary.simpleMessage("Automatically mark as read"), "ttsAutoHaveReadTip": MessageLookupByLibrary.simpleMessage( "The article will be automatically marked as read after it is read aloud"), "ttsEnable": MessageLookupByLibrary.simpleMessage("Enable TTS"), "ttsEngine": MessageLookupByLibrary.simpleMessage("TTS Engine"), "ttsSetting": MessageLookupByLibrary.simpleMessage("TTS Setting"), "ttsSpeed": MessageLookupByLibrary.simpleMessage("Reading Speed"), "ttsSpot": MessageLookupByLibrary.simpleMessage("Ignore audio focus"), "ttsSpotTip": MessageLookupByLibrary.simpleMessage( "Allow simultaneous audio playback with other applications"), "ttsSystemSetting": MessageLookupByLibrary.simpleMessage("System TTS settings"), "ttsWakeLock": MessageLookupByLibrary.simpleMessage("Wake Lock"), "ttsWakeLockTip": MessageLookupByLibrary.simpleMessage( "Enable wake lock when reading (may be killed in the background)") }; }
0
mirrored_repositories/Readar/lib/generated
mirrored_repositories/Readar/lib/generated/intl/messages_all.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that looks up messages for specific locales by // delegating to the appropriate library. // Ignore issues from commonly used lints in this file. // ignore_for_file:implementation_imports, file_names, unnecessary_new // ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering // ignore_for_file:argument_type_not_assignable, invalid_assignment // ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases // ignore_for_file:comment_references import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; import 'package:intl/src/intl_helpers.dart'; import 'messages_en.dart' as messages_en; import 'messages_zh_CN.dart' as messages_zh_cn; typedef Future<dynamic> LibraryLoader(); Map<String, LibraryLoader> _deferredLibraries = { 'en': () => new SynchronousFuture(null), 'zh_CN': () => new SynchronousFuture(null), }; MessageLookupByLibrary? _findExact(String localeName) { switch (localeName) { case 'en': return messages_en.messages; case 'zh_CN': return messages_zh_cn.messages; default: return null; } } /// User programs should call this before using [localeName] for messages. Future<bool> initializeMessages(String localeName) { var availableLocale = Intl.verifiedLocale( localeName, (locale) => _deferredLibraries[locale] != null, onFailure: (_) => null); if (availableLocale == null) { return new SynchronousFuture(false); } var lib = _deferredLibraries[availableLocale]; lib == null ? new SynchronousFuture(false) : lib(); initializeInternalMessageLookup(() => new CompositeMessageLookup()); messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor); return new SynchronousFuture(true); } bool _messagesExistFor(String locale) { try { return _findExact(locale) != null; } catch (e) { return false; } } MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) { var actualLocale = Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null); if (actualLocale == null) return null; return _findExact(actualLocale); }
0
mirrored_repositories/Readar/lib/generated
mirrored_repositories/Readar/lib/generated/intl/messages_zh_CN.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a zh_CN locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'zh_CN'; static String m0(library) => "隐藏的入口(将被移动到${library}页面中)"; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{ "about": MessageLookupByLibrary.simpleMessage("关于"), "advancedSetting": MessageLookupByLibrary.simpleMessage("高级设置"), "allArticle": MessageLookupByLibrary.simpleMessage("全部文章"), "allEntriesHiddenTip": MessageLookupByLibrary.simpleMessage("已隐藏所有入口"), "allEntriesShownTip": MessageLookupByLibrary.simpleMessage("已显示所有入口"), "appName": MessageLookupByLibrary.simpleMessage("Readar"), "apprearanceSetting": MessageLookupByLibrary.simpleMessage("外观"), "article": MessageLookupByLibrary.simpleMessage("文章"), "articleDetailHeaderImageViewType": MessageLookupByLibrary.simpleMessage("头图显示方式"), "articleDetailLayoutType": MessageLookupByLibrary.simpleMessage("文章详情布局"), "articleDetailShowImageAlt": MessageLookupByLibrary.simpleMessage("显示图片标题"), "articleDetailShowRelatedArticles": MessageLookupByLibrary.simpleMessage("显示相关文章"), "articleDetailVideoViewType": MessageLookupByLibrary.simpleMessage("视频显示方式"), "articleListLayoutType": MessageLookupByLibrary.simpleMessage("文章列表布局"), "autoReadWhenScrolling": MessageLookupByLibrary.simpleMessage("滚动时自动标记为已读"), "backupSetting": MessageLookupByLibrary.simpleMessage("备份"), "basicSetting": MessageLookupByLibrary.simpleMessage("基本设置"), "bugReport": MessageLookupByLibrary.simpleMessage("报告BUG"), "cacheImageWhenPull": MessageLookupByLibrary.simpleMessage("拉取时缓存图片"), "cacheWebPageWhenPull": MessageLookupByLibrary.simpleMessage("拉取时缓存文章"), "cacheWebPageWhenReading": MessageLookupByLibrary.simpleMessage("阅读时缓存文章"), "calmFeeds": MessageLookupByLibrary.simpleMessage("角落里的文章"), "changeLog": MessageLookupByLibrary.simpleMessage("更新日志"), "checkUpdates": MessageLookupByLibrary.simpleMessage("检查更新"), "checkUpdatesAlreadyLatest": MessageLookupByLibrary.simpleMessage("已经是最新版本"), "checkUpdatesTip": MessageLookupByLibrary.simpleMessage("上次检查更新:"), "chooseLanguage": MessageLookupByLibrary.simpleMessage("选择语言"), "chooseThemeMode": MessageLookupByLibrary.simpleMessage("选择主题模式"), "clearCache": MessageLookupByLibrary.simpleMessage("清除缓存"), "clearCacheSuccess": MessageLookupByLibrary.simpleMessage("清除缓存成功"), "contact": MessageLookupByLibrary.simpleMessage("联系我们"), "content": MessageLookupByLibrary.simpleMessage("内容"), "contributor": MessageLookupByLibrary.simpleMessage("贡献者"), "crawlType": MessageLookupByLibrary.simpleMessage("文章抓取方式"), "darkTheme": MessageLookupByLibrary.simpleMessage("深色模式"), "dragTip": MessageLookupByLibrary.simpleMessage("长按项目拖动到此处,将其移至列表末尾"), "experimentSetting": MessageLookupByLibrary.simpleMessage("实验室"), "explore": MessageLookupByLibrary.simpleMessage("探索"), "extensionSetting": MessageLookupByLibrary.simpleMessage("插件"), "feed": MessageLookupByLibrary.simpleMessage("订阅"), "followSystem": MessageLookupByLibrary.simpleMessage("跟随系统"), "generalSetting": MessageLookupByLibrary.simpleMessage("通用"), "githubRepo": MessageLookupByLibrary.simpleMessage("Github仓库"), "globalSetting": MessageLookupByLibrary.simpleMessage("全局"), "help": MessageLookupByLibrary.simpleMessage("使用指南"), "hiddenEntries": m0, "highlights": MessageLookupByLibrary.simpleMessage("集锦"), "history": MessageLookupByLibrary.simpleMessage("阅读历史"), "hotLinks": MessageLookupByLibrary.simpleMessage("热门链接"), "language": MessageLookupByLibrary.simpleMessage("语言"), "library": MessageLookupByLibrary.simpleMessage("内容库"), "license": MessageLookupByLibrary.simpleMessage("开源许可证"), "lightTheme": MessageLookupByLibrary.simpleMessage("浅色模式"), "linkedList": MessageLookupByLibrary.simpleMessage("含多个链接的文章"), "mobilizerType": MessageLookupByLibrary.simpleMessage("Mobilizer"), "officialWebsite": MessageLookupByLibrary.simpleMessage("官方网站"), "operationSetting": MessageLookupByLibrary.simpleMessage("操作"), "participateInTranslation": MessageLookupByLibrary.simpleMessage("参与翻译"), "primaryColor": MessageLookupByLibrary.simpleMessage("主色调"), "privacyPolicy": MessageLookupByLibrary.simpleMessage("隐私政策"), "privacySetting": MessageLookupByLibrary.simpleMessage("隐私"), "pullStrategy": MessageLookupByLibrary.simpleMessage("拉取策略"), "pullWhenStartUp": MessageLookupByLibrary.simpleMessage("软件启动时拉取文章"), "rate": MessageLookupByLibrary.simpleMessage("评个分吧"), "readLater": MessageLookupByLibrary.simpleMessage("稍后读"), "removeDuplicateArticles": MessageLookupByLibrary.simpleMessage("移除重复文章"), "saved": MessageLookupByLibrary.simpleMessage("已保存"), "selectTheme": MessageLookupByLibrary.simpleMessage("选择主题"), "serviceSetting": MessageLookupByLibrary.simpleMessage("服务"), "setting": MessageLookupByLibrary.simpleMessage("设置"), "shownEntries": MessageLookupByLibrary.simpleMessage("显示的入口"), "sideBarEntriesSetting": MessageLookupByLibrary.simpleMessage("侧边栏入口设置"), "star": MessageLookupByLibrary.simpleMessage("星标"), "statistics": MessageLookupByLibrary.simpleMessage("统计"), "telegramGroup": MessageLookupByLibrary.simpleMessage("Telegram频道"), "themeMode": MessageLookupByLibrary.simpleMessage("主题模式"), "themeSetting": MessageLookupByLibrary.simpleMessage("主题设置"), "tts": MessageLookupByLibrary.simpleMessage("TTS"), "ttsAutoHaveRead": MessageLookupByLibrary.simpleMessage("自动标记为已读"), "ttsAutoHaveReadTip": MessageLookupByLibrary.simpleMessage("文章朗读完毕后自动标记为已读"), "ttsEnable": MessageLookupByLibrary.simpleMessage("启用TTS"), "ttsEngine": MessageLookupByLibrary.simpleMessage("TTS引擎"), "ttsSetting": MessageLookupByLibrary.simpleMessage("TTS设置"), "ttsSpeed": MessageLookupByLibrary.simpleMessage("默认朗读速度"), "ttsSpot": MessageLookupByLibrary.simpleMessage("忽略音频焦点"), "ttsSpotTip": MessageLookupByLibrary.simpleMessage("允许与其他应用同时播放音频"), "ttsSystemSetting": MessageLookupByLibrary.simpleMessage("系统TTS设置"), "ttsWakeLock": MessageLookupByLibrary.simpleMessage("唤醒锁"), "ttsWakeLockTip": MessageLookupByLibrary.simpleMessage("朗读时启用唤醒锁(可能会被杀后台)") }; }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/resources.dart
export 'colors.dart'; export 'dimens.dart'; export 'gaps.dart'; export 'styles.dart';
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/theme_color_data.dart
import 'package:readar/Resources/colors.dart'; import 'package:flutter/material.dart'; class ThemeColorData { bool isDarkMode; String name; String? description; Color primaryColor; Color background; Color appBarBackgroundColor; Color appBarSurfaceTintColor; Color appBarShadowColor; double appBarElevation; double appBarScrollUnderElevation; Color splashColor; Color highlightColor; Color iconColor; Color shadowColor; Color canvasBackground; Color textColor; Color textGrayColor; Color textDisabledColor; Color buttonTextColor; Color buttonDisabledColor; Color dividerColor; ThemeColorData({ this.isDarkMode = false, required this.name, this.description, required this.primaryColor, required this.background, required this.appBarBackgroundColor, required this.appBarSurfaceTintColor, required this.appBarShadowColor, this.appBarElevation = 0.0, this.appBarScrollUnderElevation = 1.0, required this.splashColor, required this.highlightColor, required this.iconColor, required this.shadowColor, required this.canvasBackground, required this.textColor, required this.textGrayColor, required this.textDisabledColor, required this.buttonTextColor, required this.buttonDisabledColor, required this.dividerColor, }); static List<ThemeColorData> defaultLightThemes = [ ThemeColorData( name: "极简白", background: const Color(0xFFF7F8F9), canvasBackground: const Color(0xFFFFFFFF), primaryColor: const Color(0xFF444444), iconColor: const Color(0xFF333333), splashColor: const Color(0x44c8c8c8), highlightColor: const Color(0x44bcbcbc), shadowColor: const Color(0xFFF6F6F6), appBarShadowColor: const Color(0xFFF6F6F6), appBarBackgroundColor: const Color(0xFFF7F8F9), appBarSurfaceTintColor: const Color(0xFFF7F8F9), textColor: const Color(0xFF333333), textGrayColor: const Color(0xFF999999), textDisabledColor: const Color(0xFFD4E2FA), buttonTextColor: const Color(0xFFF2F2F2), buttonDisabledColor: const Color(0xFF96BBFA), dividerColor: const Color(0xFFF5F6F7), ), // ThemeColorData( // name: "墨水屏", // background: const Color(0xFFFFFFFF), // canvasBackground: const Color(0xFFFFFFFF), // primaryColor: const Color(0xFF444444), // iconColor: const Color(0xFF333333), // splashColor: const Color(0x44c8c8c8), // highlightColor: const Color(0x44bcbcbc), // shadowColor: const Color(0xFFF6F6F6), // appBarShadowColor: const Color(0xFFF5F6F7), // appBarBackgroundColor: const Color(0xFFFFFFFF), // appBarSurfaceTintColor: const Color(0xFFFFFFFF), // textColor: const Color(0xFF333333), // textGrayColor: const Color(0xFF999999), // textDisabledColor: const Color(0xFFD4E2FA), // buttonTextColor: const Color(0xFFF2F2F2), // buttonDisabledColor: const Color(0xFF96BBFA), // dividerColor: const Color(0xFFF5F6F7), // ), ThemeColorData( name: "灰度", background: const Color(0xFFC6C6C5), canvasBackground: const Color(0xFFDADAD8), primaryColor: const Color(0xFF4A4A4A), iconColor: const Color(0xFF52524F), splashColor: const Color(0x44c1c1c1), highlightColor: const Color(0x44bcbcbc), shadowColor: const Color(0xFFF6F6F6), appBarShadowColor: const Color(0xFFF6F6F6), appBarBackgroundColor: const Color(0xFFDADAD8), appBarSurfaceTintColor: const Color(0xFFDADAD8), textColor: const Color(0xFF333333), textGrayColor: const Color(0xFF555555), textDisabledColor: const Color(0xFFD4E2FA), buttonTextColor: const Color(0xFFF2F2F2), buttonDisabledColor: const Color(0xFF96BBFA), dividerColor: const Color(0xFFCFCFCF), ), ]; static List<ThemeColorData> defaultDarkThemes = [ ThemeColorData( name: "极简黑", background: const Color(0xFF121212), canvasBackground: const Color(0xFF1A1A1A), primaryColor: const Color(0xFFBABABA), iconColor: const Color(0xFFB8B8B8), splashColor: const Color(0x12cccccc), highlightColor: const Color(0x12cfcfcf), shadowColor: const Color(0xFF1F1F1F), appBarShadowColor: const Color(0xFF1F1F1F), appBarBackgroundColor: const Color(0xFF121212), appBarSurfaceTintColor: const Color(0xFF121212), textColor: const Color(0xFFB8B8B8), textGrayColor: const Color(0xFF666666), textDisabledColor: const Color(0xFFCEDBF2), buttonTextColor: const Color(0xFFF2F2F2), buttonDisabledColor: const Color(0xFF83A5E0), dividerColor: const Color(0xFF222222), ), // ThemeColorData( // name: "墨水屏", // background: const Color(0xFF121212), // canvasBackground: const Color(0xFF121212), // primaryColor: const Color(0xFFBABABA), // iconColor: const Color(0xFFB8B8B8), // splashColor: const Color(0x12cccccc), // highlightColor: const Color(0x12cfcfcf), // shadowColor: const Color(0xFF1F1F1F), // appBarShadowColor: const Color(0xFF1F1F1F), // appBarBackgroundColor: const Color(0xFF121212), // appBarSurfaceTintColor: const Color(0xFF121212), // textColor: const Color(0xFFB8B8B8), // textGrayColor: const Color(0xFF666666), // textDisabledColor: const Color(0xFFCEDBF2), // buttonTextColor: const Color(0xFFF2F2F2), // buttonDisabledColor: const Color(0xFF83A5E0), // dividerColor: const Color(0xFF222222), // ), ThemeColorData( name: "静谧之夜", background: const Color(0xFF181819), canvasBackground: const Color(0xFF232326), primaryColor: const Color(0xFF50A5DC), iconColor: const Color(0xFFB8B8B8), splashColor: const Color(0x12cccccc), highlightColor: const Color(0x12cfcfcf), shadowColor: const Color(0xFF1F1F1F), appBarShadowColor: const Color(0xFF1F1F1F), appBarBackgroundColor: const Color(0xFF232326), appBarSurfaceTintColor: const Color(0xFF232326), textColor: const Color(0xFFB8B8B8), textGrayColor: const Color(0xFF666666), textDisabledColor: const Color(0xFFCEDBF2), buttonTextColor: const Color(0xFFF2F2F2), buttonDisabledColor: const Color(0xFF83A5E0), dividerColor: const Color(0xFF303030), ), ThemeColorData( name: "蓝铁", background: const Color(0xFF1D2733), canvasBackground: const Color(0xFF242E39), primaryColor: const Color(0xFF61A3D7), iconColor: const Color(0xFFB8B8B8), splashColor: const Color(0x0Acccccc), highlightColor: const Color(0x0Acfcfcf), shadowColor: const Color(0xFF1B2530), appBarShadowColor: const Color(0xFF1B2530), appBarBackgroundColor: const Color(0xFF252E3A), appBarSurfaceTintColor: const Color(0xFF252E3A), textColor: const Color(0xFFB8B8B8), textGrayColor: const Color(0xFF6B7783), textDisabledColor: const Color(0xFFCEDBF2), buttonTextColor: const Color(0xFFF2F2F2), buttonDisabledColor: const Color(0xFF83A5E0), dividerColor: const Color(0xFF2D3743), ), ]; ThemeData toThemeData() { TextStyle text = TextStyle( fontSize: 14, color: textColor, textBaseline: TextBaseline.alphabetic, ); TextStyle labelSmall = TextStyle( fontWeight: FontWeight.normal, fontSize: 12, letterSpacing: 0.1, color: textGrayColor, ); TextStyle caption = TextStyle( fontWeight: FontWeight.normal, fontSize: 13, letterSpacing: 0.1, color: textGrayColor, ); TextStyle title = TextStyle( fontWeight: FontWeight.normal, fontSize: 16, letterSpacing: 0.1, color: textColor, ); TextStyle titleLarge = TextStyle( fontWeight: FontWeight.bold, fontSize: 17, letterSpacing: 0.18, color: textColor, ); TextStyle bodySmall = TextStyle( fontWeight: FontWeight.normal, fontSize: 13, letterSpacing: 0.1, color: textColor, ); TextStyle bodyMedium = TextStyle( fontWeight: FontWeight.normal, fontSize: 14, letterSpacing: 0.1, color: textColor, ); return ThemeData( brightness: isDarkMode ? Brightness.dark : Brightness.light, primaryColor: primaryColor, hintColor: primaryColor, indicatorColor: primaryColor, scaffoldBackgroundColor: background, canvasColor: canvasBackground, dividerColor: dividerColor, shadowColor: shadowColor, splashColor: splashColor, highlightColor: highlightColor, switchTheme: SwitchThemeData( thumbColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return canvasBackground; } else { return textGrayColor.withAlpha(200); } }), trackOutlineColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return primaryColor; } else { return textGrayColor.withAlpha(40); } }), trackColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return primaryColor; } else { return canvasBackground; } }), ), radioTheme: RadioThemeData( fillColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return primaryColor; } else { return canvasBackground; } }), ), iconTheme: IconThemeData( size: 24, color: iconColor, ), textSelectionTheme: TextSelectionThemeData( selectionColor: primaryColor.withAlpha(70), selectionHandleColor: primaryColor, ), textTheme: TextTheme( labelSmall: labelSmall, titleSmall: caption, titleMedium: title, bodySmall: bodySmall, bodyMedium: bodyMedium, titleLarge: titleLarge, bodyLarge: text, ), appBarTheme: AppBarTheme( elevation: appBarElevation, scrolledUnderElevation: appBarScrollUnderElevation, shadowColor: appBarShadowColor, backgroundColor: appBarBackgroundColor, surfaceTintColor: appBarSurfaceTintColor, ), ); } Map<String, dynamic> toJson() => <String, dynamic>{ "isDarkMode": isDarkMode ? 1 : 0, "name": name, "description": description, "primaryColor": primaryColor.toHex(), "background": background.toHex(), "appBarBackground": appBarBackgroundColor.toHex(), "appBarSurfaceTintColor": appBarSurfaceTintColor.toHex(), "appBarShadowColor": appBarShadowColor.toHex(), "appBarElevation": appBarElevation, "appBarScrollUnderElevation": appBarScrollUnderElevation, "splashColor": splashColor.toHex(), "highlightColor": highlightColor.toHex(), "iconColor": iconColor.toHex(), "shadowColor": shadowColor.toHex(), "materialBackground": canvasBackground.toHex(), "textColor": textColor.toHex(), "textGrayColor": textGrayColor.toHex(), "textDisabledColor": textDisabledColor.toHex(), "buttonTextColor": buttonTextColor.toHex(), "buttonDisabledColor": buttonDisabledColor.toHex(), "dividerColor": dividerColor.toHex(), }; factory ThemeColorData.fromJson(Map<String, dynamic> map) => ThemeColorData( isDarkMode: map['isDarkMode'] == 0 ? false : true, name: map['name'] as String, description: map['description'] as String, primaryColor: HexColor.fromHex(map['primaryColor'] as String), background: HexColor.fromHex(map['background'] as String), appBarShadowColor: HexColor.fromHex(map['appBarShadowColor'] as String), appBarBackgroundColor: HexColor.fromHex(map['appBarBackground'] as String), appBarSurfaceTintColor: HexColor.fromHex(map['appBarSurfaceTintColor'] as String), appBarElevation: map['appBarElevation'] as double, appBarScrollUnderElevation: map['appBarScrollUnderElevation'] as double, splashColor: HexColor.fromHex(map['splashColor'] as String), highlightColor: HexColor.fromHex(map['highlightColor'] as String), iconColor: HexColor.fromHex(map['iconColor'] as String), shadowColor: HexColor.fromHex(map['shadowColor'] as String), canvasBackground: HexColor.fromHex(map['materialBackground'] as String), textColor: HexColor.fromHex(map['textColor'] as String), textGrayColor: HexColor.fromHex(map['textGrayColor'] as String), textDisabledColor: HexColor.fromHex(map['textDisabledColor'] as String), buttonTextColor: HexColor.fromHex(map['buttonTextColor'] as String), buttonDisabledColor: HexColor.fromHex(map['buttonDisabledColor'] as String), dividerColor: HexColor.fromHex(map['dividerColor'] as String), ); static bool isImmersive(BuildContext context) { return Theme.of(context).scaffoldBackgroundColor == Theme.of(context).canvasColor; } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/styles.dart
import 'package:flutter/material.dart'; import 'colors.dart'; import 'dimens.dart'; class MyStyles { static const TextStyle textSize12 = TextStyle( fontSize: MyDimens.font_sp12, ); static const TextStyle textSize16 = TextStyle( fontSize: MyDimens.font_sp16, ); static const TextStyle textBold14 = TextStyle(fontSize: MyDimens.font_sp14, fontWeight: FontWeight.bold); static const TextStyle textBold16 = TextStyle(fontSize: MyDimens.font_sp16, fontWeight: FontWeight.bold); static const TextStyle textBold18 = TextStyle(fontSize: MyDimens.font_sp18, fontWeight: FontWeight.bold); static const TextStyle textBold24 = TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold); static const TextStyle textBold26 = TextStyle(fontSize: 26.0, fontWeight: FontWeight.bold); static const TextStyle textGray14 = TextStyle( fontSize: MyDimens.font_sp14, color: MyColors.textGrayColor, ); static const TextStyle textDarkGray14 = TextStyle( fontSize: MyDimens.font_sp14, color: MyColors.textGrayColorDark, ); static const TextStyle textWhite14 = TextStyle( fontSize: MyDimens.font_sp14, color: Colors.white, ); static const TextStyle text = TextStyle( fontSize: MyDimens.font_sp14, color: MyColors.textColor, textBaseline: TextBaseline.alphabetic); static const TextStyle textDark = TextStyle( fontSize: MyDimens.font_sp14, color: MyColors.textColorDark, textBaseline: TextBaseline.alphabetic); static const TextStyle labelSmallDark = TextStyle( fontWeight: FontWeight.normal, fontSize: 12, letterSpacing: 0.1, color: MyColors.textGrayColorDark, ); static const TextStyle labelSmall = TextStyle( fontWeight: FontWeight.normal, fontSize: 12, letterSpacing: 0.1, color: MyColors.textGrayColor, ); static const TextStyle captionDark = TextStyle( fontWeight: FontWeight.normal, fontSize: 13, letterSpacing: 0.1, color: MyColors.textGrayColorDark, ); static const TextStyle caption = TextStyle( fontWeight: FontWeight.normal, fontSize: 13, letterSpacing: 0.1, color: MyColors.textGrayColor, ); static const TextStyle titleDark = TextStyle( fontWeight: FontWeight.normal, fontSize: 16, letterSpacing: 0.1, color: MyColors.textColorDark, ); static const TextStyle title = TextStyle( fontWeight: FontWeight.normal, fontSize: 16, letterSpacing: 0.1, color: MyColors.textColor, ); static const TextStyle titleLargeDark = TextStyle( fontWeight: FontWeight.bold, fontSize: 17, letterSpacing: 0.18, color: MyColors.textColorDark, ); static const TextStyle titleLarge = TextStyle( fontWeight: FontWeight.bold, fontSize: 17, letterSpacing: 0.18, color: MyColors.textColor, ); static const TextStyle bodySmallDark = TextStyle( fontWeight: FontWeight.normal, fontSize: 13, letterSpacing: 0.1, color: MyColors.textColorDark, ); static const TextStyle bodySmall = TextStyle( fontWeight: FontWeight.normal, fontSize: 13, letterSpacing: 0.1, color: MyColors.textColor, ); static const TextStyle bodyMediumDark = TextStyle( fontWeight: FontWeight.normal, fontSize: 14, letterSpacing: 0.1, color: MyColors.textColorDark, ); static const TextStyle bodyMedium = TextStyle( fontWeight: FontWeight.normal, fontSize: 14, letterSpacing: 0.1, color: MyColors.textColor, ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/gaps.dart
import 'package:flutter/material.dart'; import 'dimens.dart'; class MyGaps { /// 水平间隔 static const Widget hGap4 = SizedBox(width: MyDimens.gap_dp4); static const Widget hGap5 = SizedBox(width: MyDimens.gap_dp5); static const Widget hGap8 = SizedBox(width: MyDimens.gap_dp8); static const Widget hGap10 = SizedBox(width: MyDimens.gap_dp10); static const Widget hGap12 = SizedBox(width: MyDimens.gap_dp12); static const Widget hGap15 = SizedBox(width: MyDimens.gap_dp15); static const Widget hGap16 = SizedBox(width: MyDimens.gap_dp16); static const Widget hGap32 = SizedBox(width: MyDimens.gap_dp32); /// 垂直间隔 static const Widget vGap4 = SizedBox(height: MyDimens.gap_dp4); static const Widget vGap5 = SizedBox(height: MyDimens.gap_dp5); static const Widget vGap8 = SizedBox(height: MyDimens.gap_dp8); static const Widget vGap10 = SizedBox(height: MyDimens.gap_dp10); static const Widget vGap12 = SizedBox(height: MyDimens.gap_dp12); static const Widget vGap15 = SizedBox(height: MyDimens.gap_dp15); static const Widget vGap16 = SizedBox(height: MyDimens.gap_dp16); static const Widget vGap24 = SizedBox(height: MyDimens.gap_dp24); static const Widget vGap32 = SizedBox(height: MyDimens.gap_dp32); static const Widget vGap50 = SizedBox(height: MyDimens.gap_dp50); static const Widget line = Divider(); static const Widget vLine = SizedBox( width: 0.6, height: 24.0, child: VerticalDivider(), ); static Widget verticleDivider(BuildContext context) { return Container( decoration: BoxDecoration( border: Border( left: BorderSide( color: Theme.of(context).dividerColor, width: 0.5, style: BorderStyle.solid, ), right: BorderSide( color: Theme.of(context).dividerColor, width: 0.5, style: BorderStyle.solid, ), ), ), ); } static const Widget empty = SizedBox.shrink(); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/dimens.dart
class MyDimens { static const double font_sp10 = 10.0; static const double font_sp12 = 12.0; static const double font_sp14 = 14.0; static const double font_sp15 = 15.0; static const double font_sp16 = 16.0; static const double font_sp18 = 18.0; static const double gap_dp4 = 4; static const double gap_dp5 = 5; static const double gap_dp8 = 8; static const double gap_dp10 = 10; static const double gap_dp12 = 12; static const double gap_dp15 = 15; static const double gap_dp16 = 16; static const double gap_dp24 = 24; static const double gap_dp32 = 32; static const double gap_dp50 = 50; }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/colors.dart
import 'package:flutter/material.dart'; class MyColors { static const Color defaultPrimaryColor = Color(0xFF009BFF); static const Color defaultPrimaryColorDark = Color(0xFF009BFF); static const Color deepGreenPrimaryColor = Color(0xFF3790a4); static const Color deepGreenPrimaryColorDark = Color(0xFF3790a4); static const Color biliPinkPrimaryColor = Color(0xFFF588a8); static const Color biliPinkPrimaryColorDark = Color(0xFFF588a8); static const Color kuanGreenPrimaryColor = Color(0xFF11b667); static const Color kuanGreenPrimaryColorDark = Color(0xFF11b667); static const Color quietGreyPrimaryColor = Color(0xFF454d66); static const Color quietGreyPrimaryColorDark = Color(0xFF454d66); static const Color noblePurplePrimaryColor = Color(0xFF272643); static const Color noblePurplePrimaryColorDark = Color(0xFF272643); static const Color cherryRedPrimaryColor = Color(0xFFe74645); static const Color cherryRedPrimaryColorDark = Color(0xFFe74645); static const Color mysteriousBrownPrimaryColor = Color(0xFF361d32); static const Color mysteriousBrownPrimaryColorDark = Color(0xFF361d32); static const Color brightYellowPrimaryColor = Color(0xFFf8be5f); static const Color brightYellowPrimaryColorDark = Color(0xFFf8be5f); static const Color zhihuBluePrimaryColor = Color(0xFF0084ff); static const Color zhihuBluePrimaryColorDark = Color(0xFF0084ff); static const Color background = Color(0xFFF7F8F9); static const Color backgroundDark = Color(0xFF121212); static const Color appBarBackground = Color(0xFFF7F8F9); static const Color appBarBackgroundDark = Color(0xFF121212); static const Color materialBackground = Color(0xFFFFFFFF); static const Color materialBackgroundDark = Color(0xFF252525); static const Color splashColor = Color(0x44c8c8c8); static const Color splashColorDark = Color(0x20cccccc); static const Color highlightColor = Color(0x44bcbcbc); static const Color highlightColorDark = Color(0x20cfcfcf); static const Color iconColor = Color(0xFF333333); static const Color iconColorDark = Color(0xFFB8B8B8); static const Color shadowColor = Color(0xFF666666); static const Color shadowColorDark = Color(0xFFFFFFFF); static const Color textColor = Color(0xFF333333); static const Color textColorDark = Color(0xFFB8B8B8); static const Color textGrayColor = Color(0xFF999999); static const Color textGrayColorDark = Color(0xFF666666); static const Color textDisabledColor = Color(0xFFD4E2FA); static const Color textDisabledColorDark = Color(0xFFCEDBF2); static const Color buttonTextColor = Color(0xFFF2F2F2); static const Color buttonTextColorDark = Color(0xFFF2F2F2); static const Color buttonDisabledColor = Color(0xFF96BBFA); static const Color buttonDisabledColorDark = Color(0xFF83A5E0); static const Color dividerColor = Color(0xFFF5F6F7); static const Color dividerColorDark = Color(0xFF393939); MaterialColor createMaterialColor(Color color) { List strengths = <double>[.05]; Map<int, Color> swatch = {}; final int r = color.red, g = color.green, b = color.blue; for (int i = 1; i < 10; i++) { strengths.add(0.1 * i); } for (var strength in strengths) { final double ds = 0.5 - strength; swatch[(strength * 1000).round()] = Color.fromRGBO( r + ((ds < 0 ? r : (255 - r)) * ds).round(), g + ((ds < 0 ? g : (255 - g)) * ds).round(), b + ((ds < 0 ? b : (255 - b)) * ds).round(), 1, ); } return MaterialColor(color.value, swatch); } } extension HexColor on Color { static Color fromHex(String hexString) { final buffer = StringBuffer(); if (hexString.length == 6 || hexString.length == 7) buffer.write('ff'); buffer.write(hexString.replaceFirst('#', '')); return Color(int.parse(buffer.toString(), radix: 16)); } String toHex({bool leadingHashSign = true}) => '${leadingHashSign ? '#' : ''}' '${alpha.toRadixString(16).padLeft(2, '0')}' '${red.toRadixString(16).padLeft(2, '0')}' '${green.toRadixString(16).padLeft(2, '0')}' '${blue.toRadixString(16).padLeft(2, '0')}'; }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/theme.dart
import 'package:flutter/material.dart'; import 'colors.dart'; import 'styles.dart'; class AppTheme { AppTheme._(); bool isDarkMode(BuildContext context) { return Theme.of(context).brightness == Brightness.dark; } static ThemeData getTheme({required bool isDarkMode}) { return ThemeData( brightness: isDarkMode ? Brightness.dark : Brightness.light, primaryColor: isDarkMode ? MyColors.defaultPrimaryColorDark : MyColors.defaultPrimaryColor, hintColor: isDarkMode ? MyColors.defaultPrimaryColorDark : MyColors.defaultPrimaryColor, indicatorColor: isDarkMode ? MyColors.defaultPrimaryColorDark : MyColors.defaultPrimaryColor, scaffoldBackgroundColor: isDarkMode ? MyColors.backgroundDark : MyColors.background, canvasColor: isDarkMode ? MyColors.materialBackgroundDark : MyColors.materialBackground, dividerColor: isDarkMode ? MyColors.dividerColorDark : MyColors.dividerColor, shadowColor: isDarkMode ? MyColors.shadowColorDark : MyColors.shadowColor, splashColor: isDarkMode ? MyColors.splashColorDark : MyColors.splashColor, highlightColor: isDarkMode ? MyColors.highlightColorDark : MyColors.highlightColor, switchTheme: SwitchThemeData( thumbColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return isDarkMode ? MyColors.materialBackgroundDark : MyColors.materialBackground; } else { return isDarkMode ? MyColors.textGrayColorDark : MyColors.textGrayColor; } }), trackColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return isDarkMode ? MyColors.defaultPrimaryColorDark : MyColors.defaultPrimaryColor; } else { return null; } }), ), radioTheme: RadioThemeData( fillColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return isDarkMode ? MyColors.defaultPrimaryColorDark : MyColors.defaultPrimaryColor; } else { return isDarkMode ? MyColors.materialBackgroundDark : MyColors.materialBackground; } }), ), iconTheme: IconThemeData( size: 24, color: isDarkMode ? MyColors.iconColorDark : MyColors.iconColor, ), textSelectionTheme: TextSelectionThemeData( selectionColor: MyColors.defaultPrimaryColor.withAlpha(70), selectionHandleColor: MyColors.defaultPrimaryColor, ), textTheme: TextTheme( labelSmall: isDarkMode ? MyStyles.labelSmallDark : MyStyles.labelSmall, titleSmall: isDarkMode ? MyStyles.captionDark : MyStyles.caption, titleMedium: isDarkMode ? MyStyles.titleDark : MyStyles.title, bodySmall: isDarkMode ? MyStyles.bodySmallDark : MyStyles.bodySmall, bodyMedium: isDarkMode ? MyStyles.bodyMediumDark : MyStyles.bodyMedium, titleLarge: isDarkMode ? MyStyles.titleLargeDark : MyStyles.titleLarge, bodyLarge: isDarkMode ? MyStyles.textDark : MyStyles.text, ), appBarTheme: AppBarTheme( elevation: 0.0, backgroundColor: isDarkMode ? MyColors.appBarBackgroundDark : MyColors.appBarBackground, ), ); } static const TextTheme textTheme = TextTheme( headlineMedium: display1, headlineSmall: headline, titleLarge: title, titleSmall: subtitle, bodyMedium: body2, bodyLarge: body1, bodySmall: caption, ); static const TextStyle display1 = TextStyle( fontWeight: FontWeight.bold, fontSize: 36, letterSpacing: 0.4, height: 0.9, ); static const TextStyle headline = TextStyle( fontWeight: FontWeight.bold, fontSize: 24, letterSpacing: 0.27, ); static const TextStyle title = TextStyle( fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 0.18, ); static const TextStyle itemTitle = TextStyle( fontWeight: FontWeight.w400, fontSize: 16, letterSpacing: 0.1, ); static const TextStyle itemTitleLittle = TextStyle( fontWeight: FontWeight.w400, fontSize: 13, letterSpacing: 0.1, ); static const TextStyle itemTip = TextStyle( fontWeight: FontWeight.w400, fontSize: 13, letterSpacing: 0.1, ); static const TextStyle itemTipLittle = TextStyle( fontWeight: FontWeight.normal, fontSize: 11, letterSpacing: 0.1, ); static const TextStyle subtitle = TextStyle( fontWeight: FontWeight.w400, fontSize: 14, letterSpacing: -0.04, ); static const TextStyle body2 = TextStyle( fontWeight: FontWeight.w400, fontSize: 14, letterSpacing: 0.2, ); static const TextStyle body1 = TextStyle( fontWeight: FontWeight.w400, fontSize: 16, letterSpacing: -0.05, ); static const TextStyle caption = TextStyle( fontWeight: FontWeight.w400, fontSize: 12, letterSpacing: 0.2, ); }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Resources/constant.dart
import 'package:flutter/foundation.dart'; class Constant { static const bool inProduction = kReleaseMode; static bool isDriverTest = false; static bool isUnitTest = false; static const String data = 'data'; static const String message = 'message'; static const String code = 'code'; static const String keyGuide = 'keyGuide'; static const String phone = 'phone'; static const String accessToken = 'accessToken'; static const String refreshToken = 'refreshToken'; static const String theme = 'AppTheme'; static const String locale = 'locale'; }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Database/rss_item_dao.dart
import 'package:readar/Database/feed_dao.dart'; import 'package:readar/Models/feed.dart'; import 'package:sqflite/sqflite.dart'; import '../Models/rss_item.dart'; import '../Providers/provider_manager.dart'; import 'create_table_sql.dart'; class RssItemDao { static final String tableName = CreateTableSql.rssItems.tableName; static Future<int> insert(RssItem item) async { return await ProviderManager.db.insert(tableName, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } static Future<List<Object?>> insertAll(List<RssItem> items) async { Batch batch = ProviderManager.db.batch(); for (RssItem item in items) { batch.insert(tableName, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } return await batch.commit(); } static Future<List<RssItem>> query( {required int? loadLimit, required String where, int offset = 0, required List whereArgs}) async { List<Map<String, Object?>> result = await ProviderManager.db.query( tableName, orderBy: "date DESC", limit: loadLimit, offset: offset, where: where, whereArgs: whereArgs, ); return result.map((e) => RssItem.fromJson(e)).toList(); } static Future<void> delete(RssItem item) async { await ProviderManager.db.delete(tableName, where: 'feedId = ? and url = ?', whereArgs: [item.feedId, item.url]); } static Future<void> update(RssItem item) async { await ProviderManager.db.update(tableName, item.toJson()); } static Future<void> updateAll(List<RssItem> items) async { Batch batch = ProviderManager.db.batch(); for (RssItem item in items) { batch.update(tableName, item.toJson()); } await batch.commit(noResult: true); } static Future<dynamic> queryUnReadCountByFeedFid() async { return await ProviderManager.db.rawQuery( "SELECT feedFid, COUNT(iid) FROM rssItems WHERE hasRead=0 GROUP BY feedFid;"); } static Future<List<RssItem>> queryByFeedFid(String feedFid) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'feedFid = ?', whereArgs: [feedFid]); return result.map<RssItem>((e) => RssItem.fromJson(e)).toList(); } static Future<List<RssItem>> queryByFeedid(int feedId) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'feedId = ?', whereArgs: [feedId]); return result.map<RssItem>((e) => RssItem.fromJson(e)).toList(); } static Future<List<RssItem>> queryByServiceId(int serviceId) async { List<Feed> feeds = await FeedDao.queryByServiceId(serviceId); List<RssItem> items = []; for (var feed in feeds) { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'feedId = ?', whereArgs: [feed.id]); items.addAll(result.map<RssItem>((e) => RssItem.fromJson(e)).toList()); } return items; } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Database/rss_service_dao.dart
import 'package:readar/Database/create_table_sql.dart'; import 'package:sqflite/sqflite.dart'; import '../../Models/rss_service.dart'; import '../../Providers/provider_manager.dart'; class RssServiceDao { static final String tableName = CreateTableSql.rssService.tableName; static Future<int> insert(RssService rssService) async { return await ProviderManager.db.insert(tableName, rssService.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } static Future<List<Object?>> insertAll(List<RssService> rssServices) async { Batch batch = ProviderManager.db.batch(); for (RssService item in rssServices) { batch.insert(tableName, item.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } return await batch.commit(); } static Future<void> deleteAll() async { ProviderManager.db.rawDelete("delete from $tableName where 1 = 1"); } static Future<void> delete(RssService rssService) async { ProviderManager.db .delete(tableName, where: 'id = ?', whereArgs: [rssService.id]); } static Future<void> update(RssService rssService) async { ProviderManager.db.update(tableName, rssService.toJson()); } static Future<RssService?> queryById(int id) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'id = ?', whereArgs: [id]); if (result.isNotEmpty) { return RssService.fromJson(result[0]); } else { return null; } } static Future<List<RssService>> queryAll() async { List<Map<String, Object?>> result = await ProviderManager.db.query(tableName); return result.map((e) => RssService.fromJson(e)).toList(); } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Database/database_manager.dart
import 'dart:async'; import 'package:readar/Database/create_table_sql.dart'; import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; class DatabaseManager { static const _dbName = "readar.db"; static const _dbVersion = 1; static Database? _database; static Future<Database> getDataBase() async { if (_database == null) { await _initDataBase(); } return _database!; } static Future<void> _initDataBase() async { if (_database == null) { String path = join(await getDatabasesPath(), _dbName); _database = await openDatabase(path, version: _dbVersion, onCreate: _onCreate); } } static Future<void> _onCreate(Database db, int version) async { await db.execute(CreateTableSql.rssService.sql); await db.execute(CreateTableSql.feed.sql); await db.execute(CreateTableSql.rssItems.sql); // await db.execute(''' // CREATE TABLE sources ( // sid TEXT PRIMARY KEY, // url TEXT NOT NULL, // iconUrl TEXT, // name TEXT NOT NULL, // openTarget INTEGER NOT NULL, // latest INTEGER NOT NULL, // lastTitle INTEGER NOT NULL // ); // '''); // await db.execute(''' // CREATE TABLE items ( // iid TEXT PRIMARY KEY, // source TEXT NOT NULL, // title TEXT NOT NULL, // link TEXT NOT NULL, // date INTEGER NOT NULL, // content TEXT NOT NULL, // snippet TEXT NOT NULL, // hasRead INTEGER NOT NULL, // starred INTEGER NOT NULL, // creator TEXT, // thumb TEXT // ); // '''); // await db.execute("CREATE INDEX itemsDate ON items (date DESC);"); } static Future<void> createTable({ required String tableName, required String sql, }) async { if (await isTableExist(tableName) == false) { await (await getDataBase()).execute(sql); } } static Future<bool> isTableExist(String tableName) async { var result = await (await getDataBase()).rawQuery( "select * from Sqlite_master where type = 'table' and name = '$tableName'"); return result.isNotEmpty; } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Database/create_table_sql.dart
enum CreateTableSql { rssService("rssService", ''' CREATE TABLE rssService ( id INTEGER PRIMARY KEY AUTOINCREMENT, endpoint TEXT NOT NULL, name TEXT NOT NULL, feedServiceType INTEGER NOT NULL, username TEXT, password TEXT, appId TEXT, appKey TEXT, authorization TEXT, fetchLimit INTEGER, pullOnStartUp INTEGER, lastSyncStatus INTEGER, lastSyncTime INTEGER, lastedFetchedId TEXT, latestFetchedTime INTEGER, params TEXT ); '''), feed( "feed", ''' CREATE TABLE feed ( id INTEGER PRIMARY KEY AUTOINCREMENT, serviceId INTEGER NOT NULL, fid TEXT NOT NULL, url TEXT NOT NULL, name TEXT NOT NULL, iconUrl TEXT, unReadCount INTEGER NOT NULL, feedSetting TEXT, lastPullStatus INTEGER, lastPullTime INTEGER, latestArticleTime INTEGER, latestArticleTitle TEXT, params TEXT ); ''', ), rssItems( "rssItems", ''' CREATE TABLE rssItems ( iid TEXT NOT NULL, feedId INTEGER NOT NULL, feedFid TEXT NOT NULL, title TEXT NOT NULL, url TEXT NOT NULL, date INTEGER NOT NULL, content TEXT NOT NULL, snippet TEXT NOT NULL, creator TEXT, thumb TEXT, hasRead INTEGER NOT NULL, starred INTEGER NOT NULL, readTime INTEGER, starTime INTEGER, params TEXT, PRIMARY KEY(feedId,url) ); ''', ); const CreateTableSql(this.tableName, this.sql); final String tableName; final String sql; }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Database/feed_dao.dart
import 'package:readar/Database/create_table_sql.dart'; import 'package:sqflite/sqflite.dart'; import '../../Models/feed.dart'; import '../../Providers/provider_manager.dart'; class FeedDao { static final String tableName = CreateTableSql.feed.tableName; static Future<int> insert(Feed feed) async { return await ProviderManager.db.insert(tableName, feed.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } static Future<List<Object?>> insertAll(List<Feed> feeds) async { Batch batch = ProviderManager.db.batch(); for (Feed feed in feeds) { batch.insert(tableName, feed.toJson(), conflictAlgorithm: ConflictAlgorithm.replace); } return await batch.commit(); } static Future<void> delete(Feed feed) async { await ProviderManager.db .delete(tableName, where: 'id = ?', whereArgs: [feed.id]); } static Future<void> deleteAll(List<String> fids) async { final batch = ProviderManager.db.batch(); for (var fid in fids) { batch.delete( CreateTableSql.rssItems.tableName, where: "feedFid = ?", whereArgs: [fid], ); batch.delete( CreateTableSql.feed.tableName, where: "fid = ?", whereArgs: [fid], ); } await batch.commit(noResult: true); } static Future<void> update(Feed feed) async { await ProviderManager.db.update(tableName, feed.toJson()); } static Future<void> updateAll(List<Feed> feeds) async { Batch batch = ProviderManager.db.batch(); for (Feed feed in feeds) { batch.update(tableName, feed.toJson()); } await batch.commit(noResult: true); } static Future<List<Feed>> queryByServiceId(int serviceId) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'serviceId = ?', whereArgs: [serviceId]); List<Feed> feeds = []; for (dynamic json in result) { feeds.add(Feed.fromJson(json)); } return feeds; } static Future<Feed> queryById(int id) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'id = ?', whereArgs: [id]); return Feed.fromJson(result[0]); } static Future<Feed> queryByFid(String fid) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'fid = ?', whereArgs: [fid]); return Feed.fromJson(result[0]); } static Future<int> getIdByFid(String fid) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'fid = ?', whereArgs: [fid]); return Feed.fromJson(result[0]).id ?? 0; } static Future<Feed> queryByUrl(String url) async { List<Map<String, Object?>> result = await ProviderManager.db .query(tableName, where: 'url = ?', whereArgs: [url]); return Feed.fromJson(result[0]); } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Handler/rss_service_manager.dart
import 'package:readar/Api/Rss/google_reader_service_handler.dart'; import 'package:readar/Handler/rss_service_handler.dart'; import 'package:readar/Models/feed_setting.dart'; import 'package:readar/Models/rss_service.dart'; import 'package:sqflite/sqflite.dart'; import '../Database/create_table_sql.dart'; import '../Database/feed_dao.dart'; import '../Database/rss_item_dao.dart'; import '../Models/feed.dart'; import '../Models/rss_item.dart'; import '../Providers/provider_manager.dart'; import '../Utils/iprint.dart'; import '../Utils/utils.dart'; /// /// 具体管理某个RSS服务,包含同步订阅源、获取/更新文章条目等操作 /// class RssServiceManager { /// RSS服务对象 RssService rssService; /// RSS服务处理类 late RssServiceHandler rssServiceHandler; /// 服务是否正在同步 bool serviceSyncing = false; RssServiceManager(this.rssService) { rssServiceHandler = GoogleReaderRssServiceHandler(rssService); } /// /// 初始化管理类:读取数据库中存储的订阅源并同步服务 /// Future<void> init({bool forceSync = false}) async { FeedDao.queryByServiceId(rssService.id!).then((value) async { for (Feed feed in value) { _fidToFeedMap[feed.fid] = feed; } await updateAllUnreadCount(); }); if (forceSync || rssService.pullOnStartUp) { await syncService(); } } /// /// 同步服务 /// Future<void> syncService() async { if (serviceSyncing) return; serviceSyncing = true; try { await rssServiceHandler.authenticate(); await syncFeeds(); await syncItems(); await fetchItems(); rssService.lastSyncStatus = SyncStatus.success; IPrint.debug("同步成功"); } catch (exp) { rssService.lastSyncStatus = SyncStatus.fail; IPrint.debug("同步失败"); } rssService.lastSyncTime = DateTime.now(); serviceSyncing = false; } /// /// 移除服务 /// Future<void> removeService() async { if (serviceSyncing) return; serviceSyncing = true; var feeds = getFeeds().map((s) => s.fid).toList(); await deleteFeeds(feeds); rssServiceHandler.removeService(); serviceSyncing = false; } /// 订阅源FID到订阅源对象的映射 final Map<String, Feed> _fidToFeedMap = {}; /// 已删除的订阅源FID到订阅源对象的映射 final Map<String, Feed> _deletedFidToFeedMap = {}; /// 文章IID到文章对象的映射 final Map<String, RssItem> _iidToItemMap = {}; bool containsFeed(String id) => _fidToFeedMap.containsKey(id); Feed getFeed(String id) => _fidToFeedMap[id] ?? _deletedFidToFeedMap[id]!; List<Feed> getFeeds() => _fidToFeedMap.values.toList(); bool containsItem(String id) => _iidToItemMap.containsKey(id); RssItem getItem(String id) => _iidToItemMap[id]!; List<RssItem> getItems() => _iidToItemMap.values.toList(); /// /// 添加订阅源 /// /// [feed] 待添加订阅源 /// /// [force] 是否强制添加 /// Future<void> insertFeed(Feed feed, {force = false}) async { if (_deletedFidToFeedMap.containsKey(feed.fid) && !force) return; _fidToFeedMap[feed.fid] = feed; await FeedDao.insert(feed); await FeedDao.queryByFid(feed.fid).then((value) async { _fidToFeedMap[value.fid] = value; }); } /// /// 添加一系列订阅源 /// /// [feeds] 待添加订阅源列表 /// /// [force] 是否强制添加 /// Future<void> insertFeeds(Iterable<Feed> feeds, {force = false}) async { List<Feed> batchedFeeds = []; for (var feed in feeds) { if (_deletedFidToFeedMap.containsKey(feed.fid) && !force) continue; _fidToFeedMap[feed.fid] = feed; feed.serviceId = rssService.id!; batchedFeeds.add(feed); } await FeedDao.insertAll(batchedFeeds).then((value) { for (var (index, feed) in feeds.indexed) { _fidToFeedMap[feed.fid]?.id = value[index] as int?; } }); } /// /// 同步订阅源 /// Future<void> syncFeeds() async { final feedsAndGroupsTuple = await rssServiceHandler.fetchFeedsAndGroups(); final feeds = feedsAndGroupsTuple.item1; var oldSids = Set<String>.from(_fidToFeedMap.keys); List<Feed> newFeeds = []; for (var feed in feeds) { if (oldSids.contains(feed.fid)) { oldSids.remove(feed.fid); } else { newFeeds.add(feed); } } await insertFeeds(newFeeds, force: true); await deleteFeeds(oldSids); // ProviderManager.groupsProvider.groups = feedsAndGroupsTuple.item2; fetchFeedFavicons(); } /// /// 更新某订阅源的未读条数 /// void updateUnreadCount(String fid, int diff) { _fidToFeedMap[fid]!.unReadCount = _fidToFeedMap[fid]!.unReadCount + diff; } /// /// 更新所有订阅源的未读条数 /// Future<void> updateAllUnreadCount() async { final rows = await RssItemDao.queryUnReadCountByFeedFid(); for (var feed in _fidToFeedMap.values) { var cloned = feed.clone(); _fidToFeedMap[feed.fid] = cloned; cloned.unReadCount = 0; } for (var row in rows) { _fidToFeedMap[row["feedFid"]]!.unReadCount = row["COUNT(iid)"]!; } } /// /// 删除订阅源 /// /// [fids] 待删除订阅源的FID列表 /// Future<void> deleteFeeds(Iterable<String> fids) async { List<String> batchedFids = []; for (var fid in fids) { if (!_fidToFeedMap.containsKey(fid)) continue; batchedFids.add(fid); _deletedFidToFeedMap[fid] = _fidToFeedMap[fid]!; _fidToFeedMap.remove(fid); } await FeedDao.deleteAll(batchedFids); // ProviderManager.feedContentProvider.initAll(); } /// /// 获取图标,在同步订阅源后调用 /// Future<void> fetchFeedFavicons() async { for (var fid in _fidToFeedMap.keys) { if (_fidToFeedMap[fid]?.iconUrl == null) { Utils.fetchFeedFavicon(_fidToFeedMap[fid]!.url).then((url) { if (!_fidToFeedMap.containsKey(fid)) return; var feed = _fidToFeedMap[fid]!.clone(); feed.iconUrl = url; insertFeed(feed); }); } } } /// /// 映射Item /// void mappingItems(Iterable<RssItem> items) { for (var item in items) { _iidToItemMap[item.iid] = item; } } /// /// 更新某个文章条目 /// Future<void> updateItem( String iid, { Batch? batch, bool? read, bool? starred, local = false, }) async { Map<String, dynamic> updateMap = {}; if (_iidToItemMap.containsKey(iid)) { final item = _iidToItemMap[iid]!.clone(); if (read != null) { item.hasRead = read; if (!local) { if (read) { rssServiceHandler.markRead(item); } else { rssServiceHandler.markUnread(item); } } updateUnreadCount(item.feedFid, read ? -1 : 1); } if (starred != null) { item.starred = starred; if (!local) { if (starred) { rssServiceHandler.star(item); } else { rssServiceHandler.unstar(item); } } } _iidToItemMap[iid] = item; } if (read != null) updateMap["hasRead"] = read ? 1 : 0; if (starred != null) updateMap["starred"] = starred ? 1 : 0; if (batch != null) { batch.update(CreateTableSql.rssItems.tableName, updateMap, where: "iid = ?", whereArgs: [iid]); } else { await ProviderManager.db.update( CreateTableSql.rssItems.tableName, updateMap, where: "iid = ?", whereArgs: [iid]); } } Future<void> syncItems() async { final tuple = await rssServiceHandler.syncItems(); final unreadIds = tuple.item1; final starredIds = tuple.item2; final rows = await ProviderManager.db.query( CreateTableSql.rssItems.tableName, columns: ["iid", "hasRead", "starred"], where: "hasRead = 0 OR starred = 1", ); final batch = ProviderManager.db.batch(); for (var row in rows) { final id = row["iid"]; if (row["hasRead"] == 0 && !unreadIds.remove(id)) { await updateItem(id as String, read: true, batch: batch, local: true); } if (row["starred"] == 1 && !starredIds.remove(id)) { await updateItem(id as String, starred: false, batch: batch, local: true); } } for (var unread in unreadIds) { await updateItem(unread, read: false, batch: batch, local: true); } for (var starred in starredIds) { await updateItem(starred, starred: true, batch: batch, local: true); } await batch.commit(noResult: true); updateAllUnreadCount(); } Future<void> fetchItems() async { final items = await rssServiceHandler.fetchItems(); List<RssItem> batchedItems = []; for (var item in items) { if (!containsFeed(item.feedFid)) continue; _iidToItemMap[item.iid] = item; batchedItems.add(item); } RssItemDao.insertAll(batchedItems); mergeFetchedItems(items); // ProviderManager.feedContentProvider.mergeFetchedItems(items); } /// /// 合并拉取的条目 /// Future<void> mergeFetchedItems(Iterable<RssItem> items) async { Set<String> changed = {}; for (var item in items) { var feed = _fidToFeedMap[item.feedFid]!; if (!item.hasRead) feed.unReadCount = feed.unReadCount + 1; if (item.date.compareTo(feed.latestArticleTime!) > 0 || feed.latestArticleTitle!.isEmpty) { feed.latestArticleTime = item.date; feed.latestArticleTitle = item.title; changed.add(feed.fid); } } if (changed.isNotEmpty) { var batch = ProviderManager.db.batch(); for (var fid in changed) { var feed = _fidToFeedMap[fid]!; batch.update( CreateTableSql.feed.tableName, { "latestArticleTime": feed.latestArticleTime!.millisecondsSinceEpoch, "latestArticleTitle": feed.latestArticleTitle!, }, where: "fid = ?", whereArgs: [feed.fid], ); } await batch.commit(); } } /// /// 全部标为已读 /// Future<void> markAllRead( Set<String> sids, { required DateTime date, before = true, }) async { rssServiceHandler.markAllRead(sids, date, before); List<String> predicates = ["hasRead = 0"]; if (sids.isNotEmpty) { predicates .add("feedFid IN (${List.filled(sids.length, "?").join(" , ")})"); } predicates .add("date ${before ? "<=" : ">="} ${date.millisecondsSinceEpoch}"); await ProviderManager.db.update( CreateTableSql.rssItems.tableName, {"hasRead": 1}, where: predicates.join(" AND "), whereArgs: sids.toList(), ); for (var item in _iidToItemMap.values.toList()) { if (sids.isNotEmpty && !sids.contains(item.feedFid)) continue; if ((before ? item.date.compareTo(date) > 0 : item.date.compareTo(date) < 0)) continue; item.hasRead = true; } updateAllUnreadCount(); } }
0
mirrored_repositories/Readar/lib
mirrored_repositories/Readar/lib/Handler/rss_service_handler.dart
import 'package:http/http.dart' as http; import 'package:tuple/tuple.dart'; import '../Models/feed.dart'; import '../Models/rss_item.dart'; enum SyncService { none, fever, feedbin, googleReader, inoreader } /// /// RSS服务处理接口 /// 定义登录认证、发送请求、获取订阅源、获取文章、更新文章状态等接口 /// abstract class RssServiceHandler { /// /// 删除服务 /// void removeService(); /// /// 发送HTTP请求接口 /// /// [path] 请求路径 /// /// [body] 请求体 /// Future<http.Response> fetchResponse(String path, {dynamic body}); /// /// 验证登陆状态 /// Future<bool> validate(); /// /// 登录认证 /// Future<void> authenticate() async {} /// /// 获取订阅源 /// Future<Tuple2<List<Feed>, Map<String, List<String>>>> fetchFeedsAndGroups(); /// /// 获取文章列表 /// Future<List<RssItem>> fetchItems(); Future<Tuple2<Set<String>, Set<String>>> syncItems(); Future<void> markAllRead(Set<String> sids, DateTime date, bool before); Future<void> markRead(RssItem item); Future<void> markUnread(RssItem item); Future<void> star(RssItem item); Future<void> unstar(RssItem item); }
0
mirrored_repositories/Readar
mirrored_repositories/Readar/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 in the flutter_test package. 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:psychology/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/chat_ui_stream_ii_example
mirrored_repositories/chat_ui_stream_ii_example/lib/chats_page.dart
import 'package:chat_ui_stream_ii_example/widget/active_users_row_widget.dart'; import 'package:chat_ui_stream_ii_example/widget/chats_widget.dart'; import 'package:flutter/material.dart'; class ChatsPage extends StatelessWidget { @override Widget build(BuildContext context) => Column( children: [ const SizedBox(height: 12), Container( height: 100, child: ActiveUsersRowWidget(), ), Divider(), Expanded(child: ChatsWidget()), ], ); }
0
mirrored_repositories/chat_ui_stream_ii_example
mirrored_repositories/chat_ui_stream_ii_example/lib/main.dart
import 'package:chat_ui_stream_ii_example/api/stream_api.dart'; import 'package:chat_ui_stream_ii_example/api/stream_user_api.dart'; import 'package:chat_ui_stream_ii_example/page/home/home_page_mobile.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:uuid/uuid.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); await Firebase.initializeApp(); // final idUser = Uuid().v4(); // print('IdUser: $idUser'); // await StreamUserApi.createUser( // idUser: idUser, // username: 'Johannes', // urlImage: // 'https://images.unsplash.com/photo-1497551060073-4c5ab6435f12?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=667&q=80', // ); final idUser = '2b2f371d-06a0-4731-b5fc-74b31ea99fbc'; await StreamUserApi.login(idUser: idUser); // await StreamChannelApi.createChannelWithUsers( // name: 'My First Channel', // urlImage: // 'https://images.unsplash.com/photo-1611448747042-8c791ed8af9a?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=700&q=80', // idMembers: [idUser], // ); runApp(MyApp()); } class MyApp extends StatelessWidget { static final String title = 'Facebook Messenger'; @override Widget build(BuildContext context) => StreamChat( streamChatThemeData: StreamChatThemeData(), client: StreamApi.client, child: ChannelsBloc( child: MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData( primaryColor: Colors.white, ), home: HomePageMobile(), ), ), ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/page/participants_page.dart
import 'package:chat_ui_stream_ii_example/api/stream_user_api.dart'; import 'package:chat_ui_stream_ii_example/page/createroom/create_room_page.dart'; import 'package:chat_ui_stream_ii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart' hide User; import 'package:chat_ui_stream_ii_example/model/user.dart'; class ParticipantsPage extends StatefulWidget { @override _ParticipantsPageState createState() => _ParticipantsPageState(); } class _ParticipantsPageState extends State<ParticipantsPage> { Future<List<User>> allUsers; List<User> selectedUsers = []; @override void initState() { super.initState(); allUsers = StreamUserApi.getAllUsers(); } @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Add Participants'), actions: [ TextButton( child: Text('CREATE'), onPressed: selectedUsers.isEmpty ? null : () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => CreateRoomPage(participants: selectedUsers), )); }, ), const SizedBox(width: 8), ], ), body: FutureBuilder<List<User>>( future: allUsers, builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: return Center(child: CircularProgressIndicator()); default: if (snapshot.hasError) { return Center(child: Text('Something Went Wrong Try later')); } else { final users = snapshot.data .where((User user) => user.idUser != StreamChat.of(context).user.id) .toList(); return buildUsers(users); } } }, ), ); Widget buildUsers(List<User> users) => ListView.builder( itemCount: users.length, itemBuilder: (context, index) { final user = users[index]; return CheckboxListTile( value: selectedUsers.contains(user), onChanged: (isAdded) => setState(() => isAdded ? selectedUsers.add(user) : selectedUsers.remove(user)), title: Row( children: [ ProfileImageWidget(imageUrl: user.imageUrl), const SizedBox(width: 16), Expanded( child: Text( user.name, style: TextStyle(fontWeight: FontWeight.bold), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), ); }, ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/page/people_page.dart
import 'package:chat_ui_stream_ii_example/widget/stories_grid_widget.dart'; import 'package:flutter/material.dart'; class PeoplePage extends StatelessWidget { @override Widget build(BuildContext context) { return DefaultTabController( length: 1, child: Column( children: [ const SizedBox(height: 12), TabBar( indicatorPadding: EdgeInsets.symmetric(horizontal: 8), tabs: [ Tab( child: Text( 'STORIES', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), ), ], ), Expanded( child: TabBarView( children: [ StoriesGridWidget(), ], ), ) ], ), ); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib/page
mirrored_repositories/chat_ui_stream_ii_example/lib/page/chat/chat_page_mobile.dart
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChatPageMobile extends StatefulWidget { final Channel channel; const ChatPageMobile({ @required this.channel, }); @override _ChatPageMobileState createState() => _ChatPageMobileState(); } class _ChatPageMobileState extends State<ChatPageMobile> { @override Widget build(BuildContext context) => StreamChannel( channel: widget.channel, child: Scaffold( appBar: buildAppBar(), body: Column( children: [ Expanded(child: MessageListView()), MessageInput(), ], ), ), ); Widget buildAppBar() { final channelName = widget.channel.extraData['name']; return AppBar( backgroundColor: Colors.white, title: Text(channelName), actions: [ IconButton( onPressed: () {}, icon: Icon(Icons.phone), ), IconButton( onPressed: () {}, icon: Icon(Icons.videocam), ), const SizedBox(width: 8), ], ); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib/page
mirrored_repositories/chat_ui_stream_ii_example/lib/page/home/home_page_mobile.dart
import 'package:chat_ui_stream_ii_example/chats_page.dart'; import 'package:chat_ui_stream_ii_example/page/people_page.dart'; import 'package:chat_ui_stream_ii_example/widget/chats_widget.dart'; import 'package:chat_ui_stream_ii_example/widget/user_image_widget.dart'; import 'package:flutter/material.dart'; class HomePageMobile extends StatefulWidget { @override _HomePageMobileState createState() => _HomePageMobileState(); } class _HomePageMobileState extends State<HomePageMobile> { int tabIndex = 1; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Chats'), centerTitle: true, leading: UserImageWidget(), actions: [ IconButton(icon: Icon(Icons.edit), onPressed: () {}), SizedBox(width: 8), ], ), body: IndexedStack( index: tabIndex, children: [ ChatsPage(), PeoplePage(), ], ), bottomNavigationBar: BottomNavigationBar( currentIndex: tabIndex, selectedItemColor: Colors.black, unselectedItemColor: Colors.black38, onTap: (index) => setState(() => tabIndex = index), items: [ BottomNavigationBarItem( icon: Icon(Icons.chat), label: 'Chats', ), BottomNavigationBarItem( icon: Icon(Icons.people), label: 'People', ), ], ), ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib/page
mirrored_repositories/chat_ui_stream_ii_example/lib/page/createroom/create_room_page.dart
import 'dart:io'; import 'package:chat_ui_stream_ii_example/api/stream_channel_api.dart'; import 'package:chat_ui_stream_ii_example/model/user.dart'; import 'package:chat_ui_stream_ii_example/page/home/home_page_mobile.dart'; import 'package:chat_ui_stream_ii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; class CreateRoomPage extends StatefulWidget { final List<User> participants; const CreateRoomPage({ Key key, @required this.participants, }) : super(key: key); @override _CreateRoomPageState createState() => _CreateRoomPageState(); } class _CreateRoomPageState extends State<CreateRoomPage> { String name = ''; File imageFile; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text('Create Room'), actions: [ IconButton( icon: Icon(Icons.done), onPressed: () async { final idParticipants = widget.participants .map((participant) => participant.idUser) .toList(); await StreamChannelApi.createChannel( context, name: name, imageFile: imageFile, idMembers: idParticipants, ); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => HomePageMobile()), ModalRoute.withName('/'), ); }, ), const SizedBox(width: 8), ], ), body: ListView( padding: EdgeInsets.all(24), children: [ GestureDetector( onTap: () async { final pickedFile = await ImagePicker().getImage(source: ImageSource.gallery); if (pickedFile == null) return; setState(() { imageFile = File(pickedFile.path); }); }, child: buildImage(context), ), const SizedBox(height: 48), buildTextField(), const SizedBox(height: 12), Text( 'Participants', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24), ), const SizedBox(height: 12), buildMembers(), ], ), ); Widget buildImage(BuildContext context) { if (imageFile == null) { return CircleAvatar( radius: 64, backgroundColor: Theme.of(context).accentColor, child: Icon(Icons.add, color: Colors.white, size: 64), ); } else { return CircleAvatar( radius: 64, backgroundColor: Theme.of(context).accentColor, child: ClipOval( child: Image.file(imageFile, fit: BoxFit.cover, width: 128, height: 128), ), ); } } Widget buildTextField() => TextFormField( decoration: InputDecoration( labelText: 'Channel Name', labelStyle: TextStyle(color: Colors.black), border: OutlineInputBorder(), focusedBorder: OutlineInputBorder(), ), maxLength: 30, onChanged: (value) => setState(() => name = value), ); Widget buildMembers() => Column( children: widget.participants .map((member) => ListTile( contentPadding: EdgeInsets.zero, leading: ProfileImageWidget(imageUrl: member.imageUrl), title: Text( member.name, style: TextStyle(fontWeight: FontWeight.bold), maxLines: 1, overflow: TextOverflow.ellipsis, ), )) .toList(), ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/model/user.dart
import 'package:meta/meta.dart'; class User { final String idUser; final String name; final String imageUrl; final bool isOnline; const User({ @required this.idUser, @required this.name, @required this.imageUrl, this.isOnline = false, }); User copy({ String idUser, String name, String imageUrl, bool isOnline, }) => User( idUser: idUser ?? this.idUser, name: name ?? this.name, imageUrl: imageUrl ?? this.imageUrl, isOnline: isOnline ?? this.isOnline, ); static User fromJson(Map<String, dynamic> json) => User( idUser: json['idUser'], name: json['name'], imageUrl: json['imageUrl'], isOnline: json['isOnline'], ); Map<String, dynamic> toJson() => { 'idUser': idUser, 'name': name, 'imageUrl': imageUrl, 'isOnline': isOnline, }; int get hashCode => idUser.hashCode ^ name.hashCode ^ imageUrl.hashCode; bool operator ==(other) => other is User && other.name == name && other.imageUrl == imageUrl && other.idUser == idUser; }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/chats_widget.dart
import 'package:chat_ui_stream_ii_example/widget/channel_list_widget.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChatsWidget extends StatelessWidget { @override Widget build(BuildContext context) { final idUser = StreamChat.of(context).user.id; return ChannelListView( filter: { 'members': { '\$in': [idUser], } }, sort: [SortOption('last_message_at')], pagination: PaginationParams(limit: 20), channelPreviewBuilder: (context, channel) => ChannelListWidget(channel: channel), ); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/story_card_widget.dart
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class AddStoryCardWidget extends StatelessWidget { @override Widget build(BuildContext context) => StoryCardWidget( title: '', urlImage: '', onClicked: () {}, ); } class StoryCardWidget extends StatelessWidget { final String title; final String urlImage; final String urlAvatar; final VoidCallback onClicked; const StoryCardWidget({ Key key, @required this.title, @required this.urlImage, @required this.onClicked, this.urlAvatar, }) : super(key: key); @override Widget build(BuildContext context) { return GestureDetector( onTap: onClicked, child: Container( padding: EdgeInsets.all(12), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(12), ), child: buildAdd(), ), ); } Widget buildAdd() => Center( child: Icon(Icons.add, size: 72, color: Colors.white), ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/profile_image_widget.dart
import 'package:flutter/material.dart'; class ProfileImageWidget extends StatelessWidget { final String imageUrl; final double radius; const ProfileImageWidget({ Key key, @required this.imageUrl, this.radius = 20, }) : super(key: key); @override Widget build(BuildContext context) => CircleAvatar( radius: radius, backgroundImage: NetworkImage(imageUrl), ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/channel_list_widget.dart
import 'package:chat_ui_stream_ii_example/page/chat/chat_page_mobile.dart'; import 'package:chat_ui_stream_ii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChannelListWidget extends StatelessWidget { final Channel channel; const ChannelListWidget({ Key key, @required this.channel, }) : super(key: key); @override Widget build(BuildContext context) { final name = channel.extraData['name']; final urlImage = channel.extraData['image']; final hasMessage = channel.state.messages.isNotEmpty; final lastMessage = hasMessage ? channel.state.messages.last.text : ''; final lastMessageAt = _formatDateTime(channel.lastMessageAt); return buildChannel( context, channel: channel, name: name, urlImage: urlImage, lastMessage: lastMessage, lastMessageAt: lastMessageAt, ); } Widget buildChannel( BuildContext context, { @required Channel channel, @required String name, @required String urlImage, @required String lastMessage, @required String lastMessageAt, }) => ListTile( onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => ChatPageMobile(channel: channel), )); }, leading: ProfileImageWidget(imageUrl: urlImage), title: Text( name, style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: Row( children: [ Expanded(child: Text(lastMessage)), Text(lastMessageAt), ], ), ); String _formatDateTime(DateTime lastMessageAt) { if (lastMessageAt == null) return ''; final isRecently = lastMessageAt.difference(DateTime.now()).inDays == 0; final dateFormat = isRecently ? DateFormat.jm() : DateFormat.MMMd(); return dateFormat.format(lastMessageAt); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/active_users_row_widget.dart
import 'package:chat_ui_stream_ii_example/api/stream_channel_api.dart'; import 'package:chat_ui_stream_ii_example/api/stream_user_api.dart'; import 'package:chat_ui_stream_ii_example/page/participants_page.dart'; import 'package:chat_ui_stream_ii_example/widget/profile_image_widget.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ActiveUsersRowWidget extends StatelessWidget { @override Widget build(BuildContext context) => buildCreateRoom(context); Widget buildCreateRoom(BuildContext context) => GestureDetector( onTap: () => Navigator.push( context, MaterialPageRoute(builder: (context) => ParticipantsPage()), ), child: Container( width: 75, child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ CircleAvatar( backgroundColor: Colors.grey.shade100, child: Icon(Icons.video_call, size: 28, color: Colors.black), radius: 25, ), Text( 'Create\nRoom', style: TextStyle(fontSize: 14), ), ], ), ), ); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/user_image_widget.dart
import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class UserImageWidget extends StatelessWidget { @override Widget build(BuildContext context) { final user = StreamChat.of(context).user; final urlImage = user.extraData['image']; return GestureDetector( onTap: () {}, child: Container( padding: const EdgeInsets.all(12), child: CircleAvatar( backgroundImage: NetworkImage(urlImage), ), ), ); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/widget/stories_grid_widget.dart
import 'package:chat_ui_stream_ii_example/widget/story_card_widget.dart'; import 'package:flutter/material.dart'; class StoriesGridWidget extends StatelessWidget { @override Widget build(BuildContext context) { final double padding = 10; return GridView.builder( itemCount: 1, padding: EdgeInsets.all(padding), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 3 / 4, ), itemBuilder: (context, index) { if (index == 0) { return AddStoryCardWidget(); } else { return Container(); } }, ); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/api/stream_channel_api.dart
import 'dart:io'; import 'package:chat_ui_stream_ii_example/api/firebase_google_api.dart'; import 'package:chat_ui_stream_ii_example/api/stream_api.dart'; import 'package:flutter/material.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart' hide Channel; import 'package:meta/meta.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:uuid/uuid.dart'; class StreamChannelApi { static Future<Channel> createChannel( BuildContext context, { @required String name, @required File imageFile, List<String> idMembers = const [], }) async { final idChannel = Uuid().v4(); final urlImage = await FirebaseGoogleApi.uploadImage('images/$idChannel', imageFile); return createChannelWithUsers( context, name: name, urlImage: urlImage, idMembers: idMembers, idChannel: idChannel, ); } static Future<Channel> createChannelWithUsers( BuildContext context, { @required String name, @required String urlImage, List<String> idMembers = const [], String idChannel, }) async { final id = idChannel ?? Uuid().v4(); final idSelfUser = StreamChat.of(context).user.id; final channel = StreamApi.client.channel( 'messaging', id: id, extraData: { 'name': name, 'image': urlImage, 'members': idMembers..add(idSelfUser), }, ); await channel.create(); await channel.watch(); return channel; } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/api/stream_user_api.dart
import 'package:chat_ui_stream_ii_example/api/stream_api.dart'; import 'package:flutter/foundation.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; import 'package:chat_ui_stream_ii_example/model/user.dart' as model; class StreamUserApi { static Future<List<model.User>> getAllUsers({bool includeMe = false}) async { final sort = SortOption('last_message_at'); final response = await StreamApi.client.queryUsers(sort: [sort]); final defaultImage = 'https://images.unsplash.com/photo-1580907114587-148483e7bd5f?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=634&q=80'; final allUsers = response.users .map((user) => model.User( idUser: user.id, name: user.name, imageUrl: user.extraData['image'] ?? defaultImage, isOnline: user.online, )) .toList(); return allUsers; } static Future createUser({ @required String idUser, @required String username, @required String urlImage, }) async { final token = StreamApi.client.devToken(idUser); final user = User( id: idUser, extraData: { 'name': username, 'image': urlImage, }, ); await StreamApi.client.setUser(user, token); } static Future login({@required String idUser}) async { final token = StreamApi.client.devToken(idUser); final user = User(id: idUser); await StreamApi.client.setUser(user, token); } }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/api/stream_api.dart
import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class StreamApi { static const apiKey = '8vntah2jsw8x'; static final client = Client(apiKey, logLevel: Level.SEVERE); }
0
mirrored_repositories/chat_ui_stream_ii_example/lib
mirrored_repositories/chat_ui_stream_ii_example/lib/api/firebase_google_api.dart
import 'dart:io'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; class FirebaseGoogleApi { static Future<String> uploadImage(String path, File file) async { final ref = FirebaseStorage.instance.ref(path); final uploadTask = ref.putFile(file); await uploadTask.whenComplete(() {}); return await ref.getDownloadURL(); } }
0
mirrored_repositories/safearea_example
mirrored_repositories/safearea_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:safearea_example/page/appbar_page.dart'; import 'package:safearea_example/page/safearea_page.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); runApp(MyApp()); } class MyApp extends StatelessWidget { static final String title = 'Safe Area VS AppBar'; @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData(primarySwatch: Colors.pink), home: MainPage(), ); } class MainPage extends StatefulWidget { @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { int index = 0; @override Widget build(BuildContext context) => Scaffold( body: buildPages(), bottomNavigationBar: buildBottomBar(), ); Widget buildBottomBar() => BottomNavigationBar( backgroundColor: Theme.of(context).primaryColor, selectedItemColor: Colors.white, unselectedItemColor: Colors.white70, currentIndex: index, items: [ BottomNavigationBarItem( icon: Icon(Icons.health_and_safety), label: 'Safe Area', ), BottomNavigationBarItem( icon: Icon(Icons.label), label: 'App Bar', ), ], onTap: (index) => setState(() => this.index = index), ); Widget buildPages() { switch (index) { case 0: return SafeAreaPage(); case 1: default: return AppBarPage(); } } }
0
mirrored_repositories/safearea_example/lib
mirrored_repositories/safearea_example/lib/page/safearea_page.dart
import 'package:flutter/material.dart'; class SafeAreaPage extends StatelessWidget { @override Widget build(BuildContext context) { final padding = MediaQuery.of(context).viewPadding; print('Applied padding: $padding'); return Scaffold( backgroundColor: Colors.blue.shade300, body: SafeArea( //top: false, child: ListView( children: List.generate( 100, (index) => ListTile(title: Text('Item $index')), ), ), ), ); } }
0
mirrored_repositories/safearea_example/lib
mirrored_repositories/safearea_example/lib/page/appbar_page.dart
import 'package:flutter/material.dart'; import 'package:safearea_example/main.dart'; class AppBarPage extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: Text(MyApp.title), centerTitle: true, ), body: ListView( children: List.generate( 100, (index) => ListTile(title: Text('Item $index')), ), ), ); }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR/lib/display.dart
import 'package:bluebirds/model.dart'; import 'package:flutter/material.dart'; class LCD extends StatefulWidget { final Model object; LCD(this.object); //object received and initialized @override _LCDState createState() => _LCDState(object); //object passed to _LCDState class } class _LCDState extends State<LCD> { Model object; _LCDState(this.object); @override Widget build(BuildContext context) { return SafeArea( child: GestureDetector( onTap: () { setState( () { object.expression = object.expression.substring(0, object.expression.length - 1); }, ); }, child: Container( decoration: BoxDecoration( color: Color(0xAFa0a69a), borderRadius: BorderRadius.circular(7)), margin: EdgeInsets.all(8), alignment: Alignment.topRight, child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Text( object.history, style: TextStyle( fontFamily: 'digital', fontSize: 18, fontWeight: FontWeight.w600), ), ), Padding( padding: const EdgeInsets.fromLTRB(3, 8, 8, 3), child: Text( object.expression, style: TextStyle( fontFamily: 'digital', fontSize: 28, fontWeight: FontWeight.w600), ), ), ], ), ), ), ); } }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR/lib/button.dart
import 'package:flutter/material.dart'; class Button extends StatelessWidget { final String s; final Function function; Button(this.s, this.function); //width = 740 - 16 = 624/4 = 131 @override Widget build(BuildContext context) { double breadth = (MediaQuery.of(context).size.width - 45) / 4; return Center( child: Container( width: s == '=' ? breadth * 2 + 9 : breadth, height: 40, margin: EdgeInsets.fromLTRB(9, 9, 0, 0), child: RaisedButton( onPressed: () { function(s); }, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), elevation: 4.0, child: Text(s, style: TextStyle( color:Colors.white, fontSize: 15, fontWeight: FontWeight.w800 ), ), color: s == '=' || s == 'AC' ? Colors.redAccent[400] : Colors.grey[850], ), ), ); } }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR/lib/model.dart
import 'package:math_expressions/math_expressions.dart'; class Model { dynamic expression; //2 + (4 * 5) + 34 - 63 String history; Model(this.expression, this.history); void equalsTo(){ expression = expression.replaceAll('MOD','%'); expression = expression.replaceAll('log','log10'); expression = expression.replaceAll('√','sqrt'); print(expression); try{ Parser p = Parser(); Expression exp = p.parse(expression); ContextModel cm = ContextModel(); double eval = exp.evaluate(EvaluationType.REAL, cm); expression = eval.toString(); }catch(e){ expression = 'Incorrect Syntax'; history =''; } } void baseConversion(int base){ print('demo'); history = expression; expression = int.parse(expression).toRadixString(base); } }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR/lib/main.dart
import 'package:bluebirds/home.dart'; import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: CalcApp(), debugShowCheckedModeBanner: false, ), ); }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/CALCULATOR/lib/home.dart
import 'package:bluebirds/button.dart'; import 'package:bluebirds/display.dart'; import 'package:bluebirds/model.dart'; import 'package:flutter/material.dart'; class CalcApp extends StatefulWidget { @override _CalcAppState createState() => _CalcAppState(); } class _CalcAppState extends State<CalcApp> { Model object = new Model('', ''); //creating object of class Model tap(String x) { if(x == 'e') x = 'e^'; if(x == 'D to B' || x == 'D to O' || x == 'D to H'){ if(x == 'D to B') object.baseConversion(2); else if(x == 'D to O') object.baseConversion(8); else if(x == 'D to H') object.baseConversion(16); x = ''; } setState(() { if(object.expression == 'Incorrect Syntax') object.expression = ''; object.expression += x; }); } allclear(String x) { setState(() { object.expression = ''; object.history = ''; }); } equal(String x){ setState(() { object.history = object.expression; object.equalsTo(); }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color(0xAF202125), body: Column( children: <Widget>[ Expanded( flex: 3, child: LCD(object),//object passed to LCD widget ), Expanded( flex: 7, child: Column( children: <Widget>[ //represent column1 Row( children: <Widget>[ Button('AC', allclear), Button('(', tap), Button(')', tap), Button('log', tap), ], ), //represent column3 Row( children: <Widget>[ Button('^',tap), Button('√',tap), Button('e',tap), Button('ln',tap), ], ), //represent column4 Row( children: <Widget>[ Button('sin',tap), Button('cos',tap), Button('tan',tap), Button('MOD',tap), ], ), //represent column5 Row( children: <Widget>[ Button('D to B',tap), Button('D to O',tap), Button('D to H',tap), Button('*',tap), ], ), //represent column6 Row( children: <Widget>[ Button('7',tap), Button('8',tap), Button('9',tap), Button('/',tap), ], ), //represent column7 Row( children: <Widget>[ Button('4',tap), Button('5',tap), Button('6',tap), Button('+',tap), ], ), //represent column8 Row( children: <Widget>[ Button('1',tap), Button('2',tap), Button('3',tap), Button('-',tap), ], ), //represent column9 Row( children: <Widget>[ Button('0', tap), Button('.', tap), Button('=', equal), ], ) ], ), ), ], ), ); } }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/PROFILE_PAGE_PROFILE
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/PROFILE_PAGE_PROFILE/lib/main.dart
import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Profile Page', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Profile Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<Color> _colorsb = [ //Get list of colors Colors.deepPurple, Colors.indigo, Colors.blue, Colors.green, Colors.yellow, Colors.orange, Colors.red ]; //list of colors of the background int _currentIndex = 0; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ //this container loads profile image new Container( width: 180.0, height: 180.0, decoration: new BoxDecoration( shape: BoxShape.circle, image: new DecorationImage( fit: BoxFit.fill, image: new AssetImage("images/profile.jpg")))), //this box is for name Text( 'Name', style: TextStyle( fontSize: 40, color: Colors.white, fontStyle: FontStyle.italic, fontWeight: FontWeight.bold, ), ), Padding( padding: EdgeInsets.only( top: 7.0, bottom: 7.0, right: 40.0, left: 7.0), ), //this is just for commenting your work position Text('Flutter Developer', style: TextStyle( fontSize: 30, color: Colors.white, fontStyle: FontStyle.italic, fontWeight: FontWeight.bold, )), Padding( padding: EdgeInsets.only( top: 7.0, bottom: 7.0, right: 40.0, left: 7.0), ), Padding( padding: EdgeInsets.only( top: 7.0, bottom: 7.0, right: 40.0, left: 7.0), ), Padding( padding: const EdgeInsets.fromLTRB(30.0, 20.0, 30.0, 10.0), child: ClipRRect( borderRadius: BorderRadius.circular(5.0), child: Container( color: Colors.white, child: ListTile( leading: Icon( Icons.phone_android, color: _colorsb[_currentIndex], ), title: Text( "YOUR PHONE NUMBER", style: TextStyle(color: _colorsb[_currentIndex]), ), ), ), ), ), Padding( padding: const EdgeInsets.fromLTRB(30.0, 20.0, 30.0, 10.0), child: ClipRRect( borderRadius: BorderRadius.circular(5.0), child: Container( color: Colors.white, child: ListTile( leading: Icon( Icons.email, color: _colorsb[_currentIndex], ), title: Text( "YOUR EMAIL", style: TextStyle(color: _colorsb[_currentIndex]), ), ), ), ), ), //all the button functions new ButtonTheme.bar( child: new ButtonBar( alignment: MainAxisAlignment.center, children: <Widget>[ Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 0; }); }, color: _colorsb[0], ), ), Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 1; }); }, color: _colorsb[1], ), ), Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 2; }); }, color: _colorsb[2], ), ), Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 3; }); }, color: _colorsb[3], ), ), Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 4; }); }, color: _colorsb[4], ), ), Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 5; }); }, color: _colorsb[5], ), ), Container( width: 30, child: new RaisedButton( onPressed: () { setState(() { _currentIndex = 6; }); }, color: _colorsb[6], ), ), ], ), ) ], ), ), backgroundColor: _colorsb[_currentIndex], //changes background color ); } }
0
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/PROFILE_PAGE_PROFILE
mirrored_repositories/AppDevelopmentCollection/CROSS-PLATFORM/PROFILE_PAGE_PROFILE/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:profile_page_bgchange/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(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/autosize_text_example
mirrored_repositories/autosize_text_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'page/home_page.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); await SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, DeviceOrientation.portraitDown, ]); runApp(MyApp()); } class MyApp extends StatelessWidget { static final String title = 'Auto Size Text'; @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, title: title, theme: ThemeData(primarySwatch: Colors.purple), home: MainPage(title: title), ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/page/home_page.dart
import 'package:autosize_text_example/widget/basic_widget.dart'; import 'package:autosize_text_example/widget/fontsize_widget.dart'; import 'package:autosize_text_example/widget/group_widget.dart'; import 'package:autosize_text_example/widget/maxlines_widget.dart'; import 'package:autosize_text_example/widget/overflow_replacement_widget.dart'; import 'package:autosize_text_example/widget/preset_fontsize_widget.dart'; import 'package:autosize_text_example/widget/rich_text_widget.dart'; import 'package:autosize_text_example/widget/step_granularity_widget.dart'; import 'package:flutter/material.dart'; import '../widget/tabbar_widget.dart'; class MainPage extends StatelessWidget { final String title; const MainPage({ @required this.title, }); Widget build(BuildContext context) => TabBarWidget( children: [ BasicWidget(), MaxLinesWidget(), FontSizeWidget(), OverflowReplacementWidget(), PresetFontSizeWidget(), StepGranularityWidget(), GroupWidget(), RichTextWidget() ], tabs: [ Tab(icon: Icon(Icons.home), text: 'Basic'), Tab(icon: Icon(Icons.list_rounded), text: 'Max Lines'), Tab(icon: Icon(Icons.format_size), text: 'FontSize'), Tab(icon: Icon(Icons.fiber_new_outlined), text: 'Replacement'), Tab( icon: Icon(Icons.photo_size_select_large), text: 'PresetFontSize'), Tab(icon: Icon(Icons.storage_sharp), text: 'StepGranularity'), Tab(icon: Icon(Icons.group), text: 'Group'), Tab(icon: Icon(Icons.style), text: 'RichText'), ], title: title, ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/group_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class GroupWidget extends StatefulWidget { @override _GroupWidgetState createState() => _GroupWidgetState(); } class _GroupWidgetState extends State<GroupWidget> { bool hasGroups = false; final autoSizeGroup = AutoSizeGroup(); @override Widget build(BuildContext context) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ AutoSizeText( 'This Text is in a group and receives smallest font size of members.', group: hasGroups ? autoSizeGroup : null, style: TextStyle( fontSize: 32, color: Colors.blue, fontWeight: FontWeight.bold, ), maxLines: 1, ), SizedBox(height: 32), AutoSizeText( 'This Text is in a group and receives smallest font size of members.', group: hasGroups ? autoSizeGroup : null, style: TextStyle(fontSize: 48, color: Colors.red), maxLines: 2, ), SizedBox(height: 32), buildSwitch(), ], ), ); Widget buildSwitch() => Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( 'Activate', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold), ), const SizedBox(height: 16), Transform.scale( scale: 1.5, child: Switch.adaptive( value: hasGroups, onChanged: (value) => setState(() => this.hasGroups = value), ), ), ], ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/maxlines_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class MaxLinesWidget extends StatefulWidget { @override _MaxLinesWidgetState createState() => _MaxLinesWidgetState(); } class _MaxLinesWidgetState extends State<MaxLinesWidget> { @override Widget build(BuildContext context) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ buildOneLine(context), const SizedBox(height: 32), buildTwoLines(context), ], ), ); Widget buildOneLine(BuildContext context) { final maxLines = 1; return Container( color: Colors.red, width: MediaQuery.of(context).size.width, child: AutoSizeText( 'This Text will fit to maximum $maxLines line. Lorem ipsum.', style: TextStyle(fontSize: 48), maxLines: maxLines, ), ); } Widget buildTwoLines(BuildContext context) { final maxLines = 2; return Container( color: Colors.blue, width: MediaQuery.of(context).size.width, child: AutoSizeText( 'This Text will fit to maximum $maxLines lines. Lorem ipsum.', style: TextStyle(fontSize: 48), maxLines: maxLines, ), ); } }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/overflow_replacement_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class OverflowReplacementWidget extends StatelessWidget { @override Widget build(BuildContext context) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ buildReplaceByWidthText(), const SizedBox(height: 32), buildReplaceByHeightText(), ], ), ); Widget buildReplaceByWidthText() { final longText = 'This is a long description that will be displayed as long as it fits.'; final shortText = 'This is a shorter description.'; final style = TextStyle(fontSize: 32); return Container( color: Colors.red, child: AutoSizeText( longText, maxLines: 1, minFontSize: 32, style: style, overflowReplacement: Text(shortText, style: style), ), ); } Widget buildReplaceByHeightText() { final longText = 'This is a long description that will be displayed as long as it fits.'; final shortText = 'This is a shorter description.'; final style = TextStyle(fontSize: 32); return Container( color: Colors.blue, child: AutoSizeText( longText, maxLines: 1, minFontSize: 20, style: style, overflowReplacement: Text(shortText, style: style), ), ); } }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/preset_fontsize_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class PresetFontSizeWidget extends StatefulWidget { @override _PresetFontSizeWidgetState createState() => _PresetFontSizeWidgetState(); } class _PresetFontSizeWidgetState extends State<PresetFontSizeWidget> { @override Widget build(BuildContext context) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ buildPresetText(), const SizedBox(height: 32), buildPresetFixedText(), ], ), ); Widget buildPresetText() => Container( color: Colors.red, child: AutoSizeText( 'This Text has a Preset Font Size.', presetFontSizes: [48, 40, 32], maxLines: 1, overflow: TextOverflow.ellipsis, ), ); Widget buildPresetFixedText() => Container( color: Colors.blue, constraints: BoxConstraints(minWidth: 180), width: MediaQuery.of(context).size.width * 0.3, child: AutoSizeText( 'Some Title', presetFontSizes: [48, 40, 32], maxLines: 1, style: TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis, ), ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/step_granularity_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class StepGranularityWidget extends StatefulWidget { @override _StepGranularityWidgetState createState() => _StepGranularityWidgetState(); } class _StepGranularityWidgetState extends State<StepGranularityWidget> { @override Widget build(BuildContext context) { return Center( child: buildFontSizeSteps(), ); } Widget buildFontSizeSteps() => AutoSizeText( 'This Text decreases by Font Size steps.', minFontSize: 20, stepGranularity: 10, style: TextStyle(fontSize: 60), maxLines: 1, overflow: TextOverflow.ellipsis, ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/rich_text_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class RichTextWidget extends StatefulWidget { @override _RichTextWidgetState createState() => _RichTextWidgetState(); } class _RichTextWidgetState extends State<RichTextWidget> { @override Widget build(BuildContext context) => Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ buildRichText(), ], ), ); AutoSizeText buildRichText() { return AutoSizeText.rich( TextSpan( text: 'This ', children: [ TextSpan( text: 'Text ', style: TextStyle(fontStyle: FontStyle.italic), ), TextSpan(text: 'is a responsive '), TextSpan( text: 'RichText', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 90)), ], ), style: TextStyle(fontSize: 48), minFontSize: 30, maxLines: 1, ); } }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/tabbar_widget.dart
import 'package:flutter/material.dart'; class TabBarWidget extends StatelessWidget { final String title; final List<Tab> tabs; final List<Widget> children; const TabBarWidget({ Key key, @required this.title, @required this.tabs, @required this.children, }) : super(key: key); @override Widget build(BuildContext context) => DefaultTabController( length: tabs.length, child: Scaffold( appBar: AppBar( title: Text(title), centerTitle: true, flexibleSpace: Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.blue, Colors.red], begin: Alignment.bottomRight, end: Alignment.topLeft, ), ), ), bottom: TabBar( isScrollable: true, indicatorColor: Colors.white, indicatorWeight: 5, tabs: tabs, ), elevation: 20, titleSpacing: 20, ), body: TabBarView(children: children), ), ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/basic_widget.dart
import 'package:flutter/material.dart'; class BasicWidget extends StatefulWidget { @override _BasicWidgetState createState() => _BasicWidgetState(); } class _BasicWidgetState extends State<BasicWidget> { @override Widget build(BuildContext context) => Center( child: Padding( padding: EdgeInsets.all(64), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ buildText(), const SizedBox(height: 32), buildFittedHeightText(), const SizedBox(height: 32), buildFittedWidthText(), ], ), ), ); Widget buildText() => Text( 'This Is A Normal Text', style: TextStyle(fontSize: 64), maxLines: 1, overflow: TextOverflow.ellipsis, ); Widget buildFittedHeightText() => Container( color: Colors.red, height: 100, child: FittedBox( child: Text('This Text Is Responsive'), ), ); Widget buildFittedWidthText() => Container( color: Colors.blue, width: MediaQuery.of(context).size.width * 0.5, child: FittedBox( child: Text('This Text Is Responsive'), ), ); }
0
mirrored_repositories/autosize_text_example/lib
mirrored_repositories/autosize_text_example/lib/widget/fontsize_widget.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; class FontSizeWidget extends StatefulWidget { @override _FontSizeWidgetState createState() => _FontSizeWidgetState(); } class _FontSizeWidgetState extends State<FontSizeWidget> { @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ buildMinimumText(), const SizedBox(height: 32), buildMinimumAndLinesText(), const SizedBox(height: 32), ], ), ); } Widget buildMinimumText() => Container( color: Colors.red, child: AutoSizeText( 'This Text has a Minimum Font Size and 1 Line.', minFontSize: 32, maxFontSize: 48, style: TextStyle(fontSize: 48), maxLines: 1, overflow: TextOverflow.ellipsis, ), ); Widget buildMinimumAndLinesText() => Container( color: Colors.blue, child: AutoSizeText( 'This Text has a Minimum Font Size and max. 2 Lines.', minFontSize: 32, style: TextStyle(fontSize: 48), maxLines: 2, overflow: TextOverflow.ellipsis, ), ); }
0
mirrored_repositories/Travel_App_Flutter_Travel_App
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/main.dart
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:myapp/screens/detail_hotel.dart'; import 'package:myapp/screens/home.dart'; void main() { runApp(const App()); } class App extends StatelessWidget { const App({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: HotelDetailScreen(), // home: MyHomePage(), routes: { HotelDetailScreen.routeName: (ctx) => HotelDetailScreen(), }, ); } }
0
mirrored_repositories/Travel_App_Flutter_Travel_App/lib
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/widgets/travelcard.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; class TravelCard extends StatelessWidget { final String imgUrl; final String hotelName; final String location; final double rating; final int price; const TravelCard({ Key? key, required this.imgUrl, required this.hotelName, required this.location, required this.rating, required this.price, }) : super(key: key); @override Widget build(BuildContext context) { return Card( margin: EdgeInsets.only(right: 22.0), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), elevation: 0.0, child: InkWell( onTap: () {}, child: Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage(imgUrl), fit: BoxFit.cover, colorFilter: ColorFilter.mode( Colors.black.withOpacity(0.3), BlendMode.darken), ), ), width: 175.0, child: Padding( padding: EdgeInsets.all(12.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( hotelName, style: TextStyle( color: Colors.white, fontSize: 17.0, fontWeight: FontWeight.w600, ), ), SizedBox( height: 8.0, ), Row( children: [ Icon( Icons.place_outlined, color: Colors.grey, size: 18, ), Text( location, style: TextStyle( color: Colors.grey, fontSize: 15.0, fontWeight: FontWeight.w500, ), ), ], ), SizedBox( height: 5, ), Row( children: [ Text( "\$$price/", style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, ), ), Text( "night", style: TextStyle( color: Colors.grey, ), ), Spacer(), Icon( Icons.star, color: Colors.amber, size: 18, ), Text( rating.toString(), style: TextStyle( color: Colors.white, fontSize: 13, fontWeight: FontWeight.w400), ), ], ), SizedBox( height: 5, ) ], ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/Travel_App_Flutter_Travel_App/lib
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/widgets/hospitalities.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; Widget hospitalityCard( String title, IconData icon, Color col, Color colIcon, Color colText) { return Card( margin: EdgeInsets.only(right: 22.0, bottom: 20), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ), elevation: 9.0, child: Material( child: Container( decoration: BoxDecoration( color: col, borderRadius: BorderRadius.circular(25.0), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(1), spreadRadius: 4, blurRadius: 10, offset: Offset( 0, 5), // Adjust the offset for desired shadow direction ), ], ), child: InkWell( // onTap: handleClick, child: SizedBox( width: 85.0, child: Padding( padding: EdgeInsets.all(0.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( icon, size: 35, color: colIcon, ), SizedBox( height: 15, ), Text( title, style: TextStyle( color: colText, fontSize: 13, ), ) ], ), ), ), ), ), ), ); }
0
mirrored_repositories/Travel_App_Flutter_Travel_App/lib
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/widgets/hotdeals.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; Widget hotDealsCard( String imgUrl, String hotelName, String location, int rating) { return Card( margin: EdgeInsets.only(right: 22.0), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), elevation: 0.0, child: InkWell( onTap: () {}, child: Container( decoration: BoxDecoration( image: DecorationImage( image: NetworkImage(imgUrl), fit: BoxFit.cover, colorFilter: ColorFilter.mode(Colors.black.withOpacity(0.5), BlendMode.darken), scale: 2.0, )), width: 390.0, child: Padding( padding: EdgeInsets.all(12.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Padding( padding: EdgeInsets.only(left: 10.0, top: 10.0), child: Container( width: 80, height: 30, decoration: BoxDecoration( color: Colors.orange.shade300, borderRadius: BorderRadius.circular(15.0), ), child: Center( child: Text( "25% OFF", style: TextStyle( color: Colors.white, fontWeight: FontWeight.w800), textAlign: TextAlign.center, ), ), ), ), ], ), Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Row( children: [ SizedBox( width: 10, ), Text( "BaLi Motel Vung Tau", style: TextStyle( color: Colors.white, fontSize: 17.0, fontWeight: FontWeight.w600, ), ), ], ), Spacer(), Icon( Icons.star, color: Colors.amber, size: 18, ), Text( " 4.9", style: TextStyle( color: Colors.white, fontSize: 13, fontWeight: FontWeight.w400), ), ], ), SizedBox( height: 5.0, ), Row( children: [ Row( children: [ SizedBox( width: 10, ), Icon( Icons.place_outlined, color: Colors.grey, size: 18, ), SizedBox( width: 10, ), Text( location, style: TextStyle( color: Colors.grey, fontSize: 15.0, fontWeight: FontWeight.w500, ), ), ], ), Spacer(), Text( "\$580/", style: TextStyle( color: Colors.white, fontWeight: FontWeight.w700, fontSize: 17, ), ), Text( "night", style: TextStyle( color: Colors.grey, fontWeight: FontWeight.w300, ), ), ], ), SizedBox( height: 8, ), ], ), ), ], ), ), ), ), ); }
0
mirrored_repositories/Travel_App_Flutter_Travel_App/lib
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/widgets/offer.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; Widget offerCard(String title, IconData icon, bool isClicked) { return Card( margin: EdgeInsets.only(right: 22.0, bottom: 20), clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ), elevation: 9.0, child: Material( child: Container( decoration: BoxDecoration( color: isClicked ? Colors.blue : Colors.white, borderRadius: BorderRadius.circular(25.0), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(1), spreadRadius: 4, blurRadius: 10, offset: Offset( 0, 5), // Adjust the offset for desired shadow direction ), ], ), child: InkWell( // onTap: handleClick, child: SizedBox( width: 85.0, child: Padding( padding: EdgeInsets.all(0.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( icon, size: 35, color: isClicked ? Colors.white : Colors.grey, ), SizedBox( height: 15, ), Text( title, style: TextStyle( color: isClicked ? Colors.white : Colors.black, fontSize: 13, ), ) ], ), ), ), ), ), ), ); }
0
mirrored_repositories/Travel_App_Flutter_Travel_App/lib
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/screens/detail_hotel.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:myapp/widgets/offer.dart'; class HotelDetailScreen extends StatefulWidget { const HotelDetailScreen({super.key}); static const routeName = '/hotel-detail'; @override State<HotelDetailScreen> createState() => _HotelDetailScreenState(); } class _HotelDetailScreenState extends State<HotelDetailScreen> { List<String> urls = [ "https://resofrance.eu/wp-content/uploads/2018/09/hotel-luxe-mandarin-oriental-paris.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTVxhEywKtPw82WX-VBfVz4q9ZtFnMUwTO8EH9_ndor&s", "https://lh3.googleusercontent.com/proxy/wTkD1USQGpbVXzZFNLCZBDCL1OQS1bFzSgPa44cHwiheaY9DpoqMdNjBgEJcCIZSQeSkCO-2q5gfuhtnuz4cDhtpansOcWos093YsGvogdQqWnpWlA", "https://images.squarespace-cdn.com/content/v1/57d5245815d5db80eadeef3b/1558864684068-1CX3SZ0SFYZA1DFJSCYD/ke17ZwdGBToddI8pDm48kIpXjvpiLxnd0TWe793Q1fcUqsxRUqqbr1mOJYKfIPR7LoDQ9mXPOjoJoqy81S2I8N_N4V1vUb5AoIIIbLZhVYxCRW4BPu10St3TBAUQYVKcZwk0euuUA52dtKj-h3u7rSTnusqQy-ueHttlzqk_avnQ5Fuy2HU38XIezBtUAeHK/Marataba+Safari+lodge", "https://lh3.googleusercontent.com/proxy/ovCSxeucYYoir_rZdSYq8FfCHPeot49lbYqlk7nXs7sXjqAfbZ2uw_1E9iivLT85LwIZiGSnXuqkdbQ_xKFhd91M7Y05G94d", "https://q-xx.bstatic.com/xdata/images/hotel/max500/216968639.jpg?k=a65c7ca7141416ffec244cbc1175bf3bae188d1b4919d5fb294fab5ec8ee2fd2&o=", "https://hubinstitute.com/sites/default/files/styles/1200x500_crop/public/2018-06/photo-1439130490301-25e322d88054.jpeg?h=f720410d&itok=HI5-oD_g", "https://cdn.contexttravel.com/image/upload/c_fill,q_60,w_2600/v1549318570/production/city/hero_image_2_1549318566.jpg", "https://www.shieldsgazette.com/images-i.jpimedia.uk/imagefetch/https://jpgreatcontent.co.uk/wp-content/uploads/2020/04/spain.jpg", "https://www.telegraph.co.uk/content/dam/Travel/2017/November/tunisia-sidi-bou-GettyImages-575664325.jpg", "https://lp-cms-production.imgix.net/features/2018/06/byrsa-hill-carthage-tunis-tunisia-2d96efe7b9bf.jpg", "https://www.newhomeco.com/sites/all/themes/nwhm/images/icons/Text_Orange.png", ]; @override Widget build(BuildContext context) { // ignore: no_leading_underscores_for_local_identifiers _buildHospitality() { bool isClicked = false; return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( height: 110, child: Padding( padding: EdgeInsets.only(left: 20.0), child: ListView( scrollDirection: Axis.horizontal, children: [ offerCard("2 Bed", Icons.single_bed_sharp, isClicked), offerCard("Dinner", Icons.dining_outlined, isClicked), offerCard("Hot Tub", Icons.bathtub_outlined, isClicked), offerCard("1 AC", Icons.ac_unit_rounded, isClicked), ], ), ), ), ], ); } return Scaffold( body: SizedBox( width: double.maxFinite, height: double.maxFinite, child: Stack( children: [ Positioned( left: 0, right: 0, child: Container( width: double.maxFinite, height: 310, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage( "https://lp-cms-production.imgix.net/features/2018/06/byrsa-hill-carthage-tunis-tunisia-2d96efe7b9bf.jpg", ), fit: BoxFit.cover, ), ), ), ), Positioned( left: 20, top: 70, child: Row( children: [ CircleAvatar( backgroundColor: Colors.white, radius: 23, child: Icon( Icons.arrow_back_outlined, color: Colors.black, size: 25, ), ), ], ), ), Positioned( left: 300, top: 70, child: Row( children: [ CircleAvatar( backgroundColor: Colors.white, radius: 20, child: Icon( Icons.share_outlined, color: Colors.black, size: 25, ), ), ], ), ), Positioned( left: 360, top: 70, child: Row( children: [ CircleAvatar( backgroundColor: Colors.white, radius: 20, child: Icon( Icons.favorite_border_sharp, color: Colors.black, size: 25, ), ), ], ), ), Positioned( left: 170, top: 250, child: Row( children: [ Container( width: 90, height: 30, decoration: BoxDecoration( color: Colors.black.withOpacity(0.5), borderRadius: BorderRadius.circular(15.0), ), child: ClipRect( child: Align( alignment: Alignment.center, child: Text( "124 photos", style: TextStyle( fontSize: 12, color: Colors.white, ), ), ), ), ), ], ), ), Positioned( top: 290, child: Container( width: MediaQuery.of(context).size.width, height: 700, decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.horizontal( left: Radius.circular(20), right: Radius.circular(20), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 20), child: Text( "BaLi Motel", textAlign: TextAlign.left, style: TextStyle( color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), ), Padding( padding: const EdgeInsets.only(left: 20), child: Text( "Vung Tau", textAlign: TextAlign.left, style: TextStyle( color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), ), SizedBox( height: 6, ), Row( children: [ SizedBox( width: 20, ), Icon( Icons.place_outlined, color: Colors.grey, size: 18, ), SizedBox( width: 5, ), Text( "Indonesia", style: TextStyle( color: Colors.grey, fontSize: 15.0, fontWeight: FontWeight.w500, ), ), ], ), Row( children: [ SizedBox( width: 20, ), Icon( Icons.star, color: Colors.amber, size: 23, ), Text( " 4.9", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.w400), ), SizedBox( width: 3, ), Text( "(6.8K review)", style: TextStyle( color: Colors.grey, fontSize: 15, fontWeight: FontWeight.w400), ), Spacer(), Text( "\$580/", style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 28, shadows: [ Shadow( color: Colors.black.withOpacity(0.2), offset: Offset(0, 3), blurRadius: 5, ), ], ), ), Text( "night", style: TextStyle( color: Colors.grey.shade900, fontSize: 18, ), ), SizedBox( width: 20, ), ], ), SizedBox( height: 5, ), Padding( padding: EdgeInsets.only(left: 20, right: 15), child: SizedBox( width: 500, child: Divider( color: Colors.grey.shade300, thickness: 1.5, ), ), ), SizedBox( height: 10, ), Padding( padding: const EdgeInsets.only(left: 20), child: RichText( text: TextSpan( children: [ TextSpan( text: 'Set in Vung Tau, 100 meters from Front Beach, BaLi Motel Vung Tau offers accommodation with a garden, private parking and a shared...', style: TextStyle( color: Colors.grey, fontWeight: FontWeight.bold, ), ), TextSpan( text: 'Read more', style: TextStyle(color: Colors.amber), ), ], ), ), ), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 20), child: Text( "What we offer", textAlign: TextAlign.left, style: TextStyle( color: Colors.black, fontSize: 30, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), ), SizedBox( height: 5, ), SizedBox( height: 130, // Set the desired height child: _buildHospitality(), ), Padding( padding: const EdgeInsets.only(left: 20), child: Text( "Hosted by", textAlign: TextAlign.left, style: TextStyle( color: Colors.black, fontSize: 30, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), ), SizedBox( height: 15, ), Wrap( children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ SizedBox( width: 20, ), Container( width: 60, height: 60, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Colors.blue, ), child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image( image: NetworkImage(urls[1]), fit: BoxFit.cover, ), ), ), Column( children: [ Text( " Harleen Smith", style: TextStyle( fontSize: 20, fontWeight: FontWeight.w600), ), Row( children: [ SizedBox( width: 8, ), Icon( Icons.star, color: Colors.amber, size: 23, ), Text( " 4.9", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.w400), ), SizedBox( width: 3, ), Text( "(6.8K review)", style: TextStyle( color: Colors.grey, fontSize: 15, fontWeight: FontWeight.w400), ), ], ), ], ), Spacer(), SizedBox( width: 60, height: 60, child: Image( image: NetworkImage(urls[11]), ), ), SizedBox( width: 10, ), ], ), ], ), SizedBox( height: 15, ), Padding( padding: EdgeInsets.only(left: 20), child: Container( width: 390, height: 70, decoration: BoxDecoration( color: Colors.blue.shade300, borderRadius: BorderRadius.all(Radius.circular(25)), ), alignment: Alignment.center, child: Text( "Book Now", textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), ], ), ), ), ], ), ), ); } }
0
mirrored_repositories/Travel_App_Flutter_Travel_App/lib
mirrored_repositories/Travel_App_Flutter_Travel_App/lib/screens/home.dart
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables import 'package:flutter/material.dart'; import 'package:myapp/widgets/hospitalities.dart'; import 'package:myapp/widgets/hotdeals.dart'; import '../widgets/travelcard.dart'; class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> urls = [ "https://i.ytimg.com/vi/EllQfqlng4Q/maxresdefault.jpg", "https://static.barcelo.com/content/dam/bhg/master/es/hoteles/spain/andalucia/cadiz/royal-hideaway-sancti-petri-part-of-barcelo-hotel-group/main-photos/hotel/RHSANC_POOL_05.jpg", "https://q-xx.bstatic.com/xdata/images/hotel/max500/357194040.jpg?k=53738a170b156a69595b74b6ecbad4992578f21364d6b44cdfb67c1b517a1cb7&o=", ]; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: CustomScrollView( slivers: [ SliverAppBar( backgroundColor: Colors.white, pinned: true, snap: true, floating: true, title: _buildAppBar(), toolbarHeight: 120, ), SliverToBoxAdapter( child: SizedBox( height: 140, // Set the desired height child: _buildHospitality(), ), ), SliverToBoxAdapter( child: _buildBody(), ), ], ), ); } Widget _buildAppBar() { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Column( children: [ SizedBox( height: 15, ), Text( "Where you", style: TextStyle( color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), Text( "wanna go?", style: TextStyle( color: Colors.black, fontSize: 40, fontWeight: FontWeight.bold, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), ], ), Padding( padding: const EdgeInsets.only(right: 15.0), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.3), spreadRadius: 2, blurRadius: 5, offset: const Offset( 0, 2), // Adjust the shadow position if needed ), ], ), child: const CircleAvatar( backgroundColor: Colors.white, radius: 27, child: Icon( Icons.search_sharp, color: Colors.black, size: 37, ), ), ), ), ], ); } _buildBody() { return SingleChildScrollView( padding: const EdgeInsets.only(top: 5, bottom: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.only(left: 20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Popular Hotels", style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: Colors.black, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), Padding( padding: EdgeInsets.only( right: 20, ), child: Text( "See all", style: TextStyle( fontSize: 15, fontWeight: FontWeight.bold, color: Colors.amber.shade600, ), ), ), ], ), ), SizedBox( height: 280, child: _buildFeatured(), ), SizedBox( height: 25, ), Padding( padding: EdgeInsets.only(left: 20.0, bottom: 10.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Hot Deals", style: TextStyle( fontSize: 28, fontWeight: FontWeight.bold, color: Colors.black, shadows: [ Shadow( color: Colors.black.withOpacity(0.3), offset: Offset(0, 2), blurRadius: 4, ), ], ), ), ], ), ), SizedBox( height: 230, child: _buildHotDeals(), ), ], ), ); } _buildHospitality() { return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( height: 135, child: Padding( padding: EdgeInsets.only(left: 20.0), child: ListView( scrollDirection: Axis.horizontal, children: [ hospitalityCard( "Hotel", Icons.apartment, Colors.blue.shade400, Colors.white, Colors.white, ), hospitalityCard( "Flight", Icons.flight, Colors.white, Colors.grey, Colors.black, ), hospitalityCard( "Place", Icons.place_outlined, Colors.white, Colors.grey, Colors.black, ), hospitalityCard( "Food", Icons.fastfood_outlined, Colors.white, Colors.grey, Colors.black, ), ], ), ), ), ], ); } Widget _buildFeatured() { return Column( children: [ SizedBox(height: 20.0), Padding( padding: EdgeInsets.only(left: 17.0), child: SizedBox( height: 260.0, child: ListView( scrollDirection: Axis.horizontal, children: [ TravelCard( imgUrl: urls[0], hotelName: 'Santorini', location: "Greece", rating: 4.9, price: 488, ), TravelCard( imgUrl: urls[1], hotelName: "Hotel Royal", location: "Spain", rating: 4.8, price: 280, ), TravelCard( imgUrl: urls[2], hotelName: "Safari Hotel", location: "Africa", rating: 5, price: 580, ), ], ), ), ), ], ); } Widget _buildHotDeals() { return Padding( padding: EdgeInsets.only(left: 17.0), child: SizedBox( height: 230.0, child: ListView( scrollDirection: Axis.horizontal, children: [ hotDealsCard(urls[2], "BaLi Motel Vung Tau", "Indonesia", 5), hotDealsCard(urls[0], "Luxury Hotel", "Caroline", 3), hotDealsCard(urls[1], "Plaza Hotel", "Italy", 4), ], ), ), ); } }
0
mirrored_repositories/Travel_App_Flutter_Travel_App
mirrored_repositories/Travel_App_Flutter_Travel_App/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 in the flutter_test package. 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:myapp/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const App()); // 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/FlutterWidgetsSnippets
mirrored_repositories/FlutterWidgetsSnippets/lib/app.dart
import 'package:flutter/material.dart'; import 'package:widgetssamples/utils/utils.dart'; import 'package:widgetssamples/widgets/widgets.dart'; class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeConfig.darkTheme, home: const MyHomePage(title: 'Widgets'), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key, required this.title}); final String title; final List<Widget> widgetSections = const [ FloatingActionBarAnimation(), GlassContainer(), SearchBarWidget(), CalenderWidget(), AboutDialogWidget(), AboutListTileWidget(), AbsorbPointerWidget(), AlertDialogWidget(), AnimatedAlignWidget(), AnimatedBuilderWidget(), AnimatedContainerWidget(), AnimatedCrossFadeWidget(), AnimatedIconWidget(), AnimatedListWidget(), AnimatedModalBarrierWidget(), AnimatedOpacityWidget(), AnimatedPaddingWidget(), AnimatedPhysicalModelWidget(), AnimatedPositionWidget(), AnimatedRotationWidget(), AnimatedSizeWidget(), AnimatedSwitcherWidget(), AppBarWidget(), AspectRatioWidget(), AutoCompleteWidget(), BackdropFilterWidget(), BannerWidget(), BaselineWidget(), BottomNavigationBarWidget(), ModelBottomSheetWidget(), BuilderWidget(), CardWidget(), CheckBoxListTileWidget(), ChipWidget(), CupertinoContextMenuWidget(), CupertinoPickerWidget(), CustomPaintWidget(), CustomScrollViewWidget() ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), actions: [ IconButton( onPressed: () { showSearch( context: context, delegate: CustomSearchDelegate(widgetSections)); }, icon: const Icon(Icons.search), ) ], ), body: SingleChildScrollView( padding: const EdgeInsets.only(top: 10), physics: const PageScrollPhysics(), scrollDirection: Axis.vertical, child: Column(children: [ const CustomDivider(heading: "Widgets List"), ListView.builder( physics: const NeverScrollableScrollPhysics(), padding: const EdgeInsets.only(left: 10), shrinkWrap: true, itemCount: widgetSections.length, itemBuilder: ((context, index) { return ListTile( dense: true, contentPadding: const EdgeInsets.all(0), leading: Text( (index + 1).toString(), style: const TextStyle(color: Colors.grey), ), title: Text( widgetSections[index].toString(), style: const TextStyle(fontSize: 15), ), trailing: IconButton( onPressed: () { Navigate.pushPage(context, widgetSections[index]); }, icon: const Icon( Icons.arrow_forward_ios, size: 15, color: Colors.grey, )), ); }), ), ]), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets
mirrored_repositories/FlutterWidgetsSnippets/lib/main.dart
import 'package:flutter/material.dart'; import 'package:widgetssamples/app.dart'; void main() { runApp(const MyApp()); }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/aboutdialog.dart
import 'package:flutter/material.dart'; class AboutDialogWidget extends StatelessWidget { const AboutDialogWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("About Dialog"), ), body: Center( child: ElevatedButton( onPressed: () { showDialog( context: context, builder: (context) => const AboutDialog( applicationIcon: FlutterLogo(), applicationLegalese: 'Legalese', applicationName: 'Flutter App', applicationVersion: 'version 1..0', children: [Text("This is a text created by Ashwin")], ), ); }, child: const Text("Show About Dialog")), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/animatedopacity.dart
import 'package:flutter/material.dart'; class AnimatedOpacityWidget extends StatefulWidget { const AnimatedOpacityWidget({super.key}); @override State<AnimatedOpacityWidget> createState() => _AnimatedOpacityWidgetState(); } class _AnimatedOpacityWidgetState extends State<AnimatedOpacityWidget> { double opacity = 1.0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Widget Name"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ AnimatedOpacity( opacity: opacity, duration: const Duration(seconds: 2), child: const FlutterLogo(size: 59), ), ElevatedButton( onPressed: (() { setState(() { opacity = opacity == 0 ? 1.0 : 0.0; }); }), child: const Text( 'Fade Logo', style: TextStyle(color: Colors.black), ), ) ], ), ), ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/custompaint.dart
import 'package:flutter/material.dart'; class CustomPaintWidget extends StatelessWidget { const CustomPaintWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("CustomPaint"), ), body: Padding( padding: const EdgeInsets.all(20.0), child: Center( child: CustomPaint( painter: DemoPainter(), child: const Text( 'This is Pac man', style: TextStyle( color: Colors.black, backgroundColor: Colors.white, fontSize: 30.0), ), )), )); } } class DemoPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { var center = size / 2; var paint = Paint()..color = Colors.yellow; canvas.drawArc( Rect.fromCenter( center: Offset(center.width, center.height), width: 250, height: 250), 0.4, 2 * 3.14 - 0.8, true, paint); } @override bool shouldRepaint(DemoPainter oldDelegate) => false; @override bool shouldRebuildSemantics(DemoPainter oldDelegate) => false; }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/modelbottomsheet.dart
import 'package:flutter/material.dart'; class ModelBottomSheetWidget extends StatelessWidget { const ModelBottomSheetWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("ModelBottomSheetWidget"), ), body: Center( child: ElevatedButton( child: const Text('Show Sheet'), onPressed: () { showModalBottomSheet( context: context, builder: ((context) { return SizedBox( height: 400, child: Center( child: ElevatedButton( onPressed: (() { Navigator.of(context).pop(); }), child: const Text('Close'), )), ); })); }, ), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/cupertinocontextmenu.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; class CupertinoContextMenuWidget extends StatelessWidget { const CupertinoContextMenuWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("CupertinoContextMenu"), ), body: Center( child: Container( color: Colors.orangeAccent, width: 100, height: 100, child: CupertinoContextMenu( actions: [ CupertinoContextMenuAction( onPressed: (() { Navigator.of(context).pop(); }), child: const Text('Action One'), ), CupertinoContextMenuAction( onPressed: (() { Navigator.of(context).pop(); }), child: const Text('Action Two'), ) ], child: Image.network( "https://upload.wikimedia.org/wikipedia/commons/e/ef/Youtube_logo.png")), ), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/glasseffect.dart
import 'dart:ui'; import 'package:flutter/material.dart'; // ignore: depend_on_referenced_packages import 'package:google_fonts/google_fonts.dart'; class GlassContainer extends StatelessWidget { const GlassContainer({super.key}); @override Widget build(BuildContext context) { return Stack( children: [ Image.asset( "assets/bg/asthetic_bg.jpg", height: MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, fit: BoxFit.cover, ), Scaffold( backgroundColor: Colors.transparent, appBar: AppBar( backgroundColor: Colors.transparent, title: const Text("Glass Container")), body: Center( child: ClipRRect( borderRadius: BorderRadius.circular(25), child: BackdropFilter( filter: ImageFilter.blur(sigmaX: 15, sigmaY: 15), child: Container( height: 250, width: 350, decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), color: const Color.fromARGB(115, 34, 126, 163)), child: Center( child: Text( "Glass Text", style: GoogleFonts.lato( textStyle: const TextStyle( fontSize: 25, color: Colors.white), fontStyle: FontStyle.normal), ), ), ), ), ), ), ), ], ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/appbar.dart
import 'package:flutter/material.dart'; class AppBarWidget extends StatelessWidget { const AppBarWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('AppBar Widget'), centerTitle: true, actions: [ IconButton( onPressed: () {}, icon: const Icon(Icons.refresh), ) ], leading: IconButton( onPressed: () { Navigator.of(context).pop(); }, icon: const Icon(Icons.home), ), backgroundColor: Colors.grey, shape: const RoundedRectangleBorder( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(25), bottomRight: Radius.circular(25))), ), body: const Center( child: Text( 'Body', style: TextStyle(fontSize: 24), ), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/cupertinopicker.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; class CupertinoPickerWidget extends StatefulWidget { const CupertinoPickerWidget({super.key}); @override State<CupertinoPickerWidget> createState() => _CupertinoPickerWidgetState(); } class _CupertinoPickerWidgetState extends State<CupertinoPickerWidget> { int selectedValue = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("CupertinoPicker"), ), body: SafeArea( child: Center( child: CupertinoButton.filled( onPressed: (() => showCupertinoModalPopup( context: context, builder: ((context) => SizedBox( width: double.infinity, height: 250, child: CupertinoPicker( backgroundColor: Colors.white10, itemExtent: 30, scrollController: FixedExtentScrollController( initialItem: 1), children: const [ Text('0'), Text('1'), Text('2'), ], onSelectedItemChanged: (value) { setState(() { selectedValue = value; }); }, ), )), )), child: Text( 'Value = $selectedValue', style: const TextStyle(color: Colors.black), ))))); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/aboutlisttile.dart
import 'package:flutter/material.dart'; class AboutListTileWidget extends StatelessWidget { const AboutListTileWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("AboutListTile"), ), body: const Center( child: AboutListTile( icon: Icon(Icons.info), applicationIcon: FlutterLogo(), applicationLegalese: 'legalese', applicationName: 'Flutter Widget Demo', applicationVersion: 'verison 1.0.0', aboutBoxChildren: [Text('This is a text created by Ashwin')], ), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/searchbar.dart
import 'package:flutter/material.dart'; class SearchBarWidget extends StatelessWidget { const SearchBarWidget({super.key}); final List<String> fruits = const ['apple', 'oranges', 'melon']; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('SeachBar Widget'), actions: [ IconButton( onPressed: () { showSearch( context: context, delegate: CustomSearchDelegateString(fruits)); }, icon: const Icon(Icons.search), ) ], ), ); } } class CustomSearchDelegateString extends SearchDelegate { CustomSearchDelegateString(this.fruits); List<String> fruits; // clear the search tex @override List<Widget>? buildActions(BuildContext context) { return [ IconButton( onPressed: () { query = ''; }, icon: const Icon(Icons.clear), ), ]; } // second overwrite to pop out of search menu @override Widget? buildLeading(BuildContext context) { return IconButton( onPressed: () { close(context, null); }, icon: const Icon(Icons.arrow_back), ); } // third overwrite to show query result @override Widget buildResults(BuildContext context) { List<String> matchQuery = []; for (var fruit in fruits) { if (fruit.contains(query.toLowerCase())) { matchQuery.add(fruit); } } return ListView.builder( itemCount: matchQuery.length, padding: const EdgeInsets.only(left: 10), shrinkWrap: true, itemBuilder: (context, index) { String fruit = matchQuery[index]; return ListTile( dense: true, contentPadding: const EdgeInsets.all(0), title: Text( fruit, style: const TextStyle(fontSize: 15), )); }, ); } // last overwrite to show the // querying process at the runtime @override Widget buildSuggestions(BuildContext context) { List<String> matchQuery = []; for (var fruit in fruits) { if (fruit.contains(query.toLowerCase())) { matchQuery.add(fruit); } } return ListView.builder( itemCount: matchQuery.length, padding: const EdgeInsets.only(left: 10), shrinkWrap: true, itemBuilder: (context, index) { String fruit = matchQuery[index]; return ListTile( dense: true, contentPadding: const EdgeInsets.all(0), title: Text( fruit, style: const TextStyle(fontSize: 15), )); }, ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/animatedalign.dart
import 'package:flutter/material.dart'; class AnimatedAlignWidget extends StatefulWidget { const AnimatedAlignWidget({super.key}); @override State<AnimatedAlignWidget> createState() => _AnimatedAlignWidgetState(); } class _AnimatedAlignWidgetState extends State<AnimatedAlignWidget> { bool selected = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("AnimatedAlign"), ), body: GestureDetector( onTap: (() { setState(() { selected = !selected; }); }), child: Center( child: Container( width: double.infinity, height: 250.0, color: Colors.blueGrey, child: AnimatedAlign( alignment: selected ? Alignment.topLeft : Alignment.bottomRight, duration: const Duration(seconds: 1), curve: Curves.fastOutSlowIn, child: const FlutterLogo( size: 60, ), ), ), ), ), ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/card.dart
import 'package:flutter/material.dart'; class CardWidget extends StatelessWidget { const CardWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Card"), ), body: Center( child: Card( shadowColor: Colors.white, elevation: 20, color: Colors.orange, child: Padding( padding: const EdgeInsets.all(15.0), child: Column(mainAxisSize: MainAxisSize.min, children: [ const SizedBox( height: 8.0, ), const Text('This is a Flutter card'), TextButton( onPressed: () {}, child: const Text('Press'), ) ]), ), ), )); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/baseline.dart
import 'package:flutter/material.dart'; class BaselineWidget extends StatelessWidget { const BaselineWidget({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Baseline"), ), body: Center( child: Container( width: 200, height: 200, color: Colors.orange, child: const Baseline( baseline: 50, baselineType: TextBaseline.alphabetic, child: FlutterLogo( size: 50, ), ), ))); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/floatingactionbar.dart
import 'package:flutter/material.dart'; class FloatingActionBarAnimation extends StatefulWidget { const FloatingActionBarAnimation({super.key}); @override State<FloatingActionBarAnimation> createState() => _FloatingActionBarAnimationState(); } class _FloatingActionBarAnimationState extends State<FloatingActionBarAnimation> with TickerProviderStateMixin { int _counter = 0; late AnimationController _controller; late Animation<double> _myAnimtion; void floatingAction() { if (_controller.isCompleted) { _controller.reverse(); } else { _controller.forward(); } _incrementCounter(); } void _incrementCounter() { setState(() { _counter++; }); } @override void initState() { super.initState(); _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 200)); _myAnimtion = CurvedAnimation(parent: _controller, curve: Curves.linear); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Floating Action Bar"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), bottomNavigationBar: BottomAppBar( shape: const CircularNotchedRectangle(), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ IconButton( icon: const Icon(Icons.menu), onPressed: () {}, ), IconButton( icon: const Icon(Icons.search), onPressed: () {}, ), ], ), ), extendBody: true, floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, floatingActionButton: FloatingActionButton( onPressed: floatingAction, tooltip: 'Increment', child: AnimatedIcon( icon: AnimatedIcons.add_event, progress: _myAnimtion, ), ), ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/animatedcrossfade.dart
import 'package:flutter/material.dart'; class AnimatedCrossFadeWidget extends StatefulWidget { const AnimatedCrossFadeWidget({super.key}); @override State<AnimatedCrossFadeWidget> createState() => _AnimatedCrossFadeWidgetState(); } class _AnimatedCrossFadeWidgetState extends State<AnimatedCrossFadeWidget> { bool _bool = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Animation Cross Fade'), ), body: Column( children: [ const SizedBox( width: double.infinity, height: 100, ), TextButton( onPressed: () { setState(() { _bool = !_bool; }); }, child: const Text('Switch'), ), AnimatedCrossFade( firstChild: Image.asset( 'assets/bg/asthetic_bg.jpg', width: 150, height: 400, ), secondChild: Image.asset('assets/bg/asthetic_night_bg.jpg', width: 150, height: 400), crossFadeState: _bool ? CrossFadeState.showFirst : CrossFadeState.showSecond, duration: const Duration(seconds: 2), ), ], ), ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/animatedposition.dart
import 'package:flutter/material.dart'; class AnimatedPositionWidget extends StatefulWidget { const AnimatedPositionWidget({super.key}); @override State<AnimatedPositionWidget> createState() => _AnimatedPositionWidgetState(); } class _AnimatedPositionWidgetState extends State<AnimatedPositionWidget> { bool selected = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("AnimatedPosition"), ), body: SizedBox( width: 250, height: 350, child: Stack(children: [ AnimatedPositioned( width: selected ? 200 : 50, height: selected ? 50 : 200, top: selected ? 50 : 150, duration: const Duration(seconds: 2), curve: Curves.fastOutSlowIn, child: GestureDetector( onTap: () { setState(() { selected = !selected; }); }, child: Container( decoration: BoxDecoration( color: Colors.orange, borderRadius: BorderRadius.circular(25)), child: const Center(child: Text('Click')), ), ), ) ]), ), ); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/checkboxlisttile.dart
import 'package:flutter/material.dart'; class CheckBoxListTileWidget extends StatefulWidget { const CheckBoxListTileWidget({super.key}); @override State<CheckBoxListTileWidget> createState() => _CheckBoxListTileWidgetState(); } class _CheckBoxListTileWidgetState extends State<CheckBoxListTileWidget> { bool? _isChecked = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("CheckBoxListTile"), ), body: Center( child: CheckboxListTile( title: const Text('CheckBox List Tile'), value: _isChecked, onChanged: (value) { setState(() { _isChecked = value; }); }, activeColor: Colors.orangeAccent, checkColor: Colors.white, tileColor: Colors.grey, subtitle: const Text('This is a subtitle'), controlAffinity: ListTileControlAffinity.leading, tristate: true, ))); } }
0
mirrored_repositories/FlutterWidgetsSnippets/lib
mirrored_repositories/FlutterWidgetsSnippets/lib/widgets/bottomnavigationbar.dart
import 'package:flutter/material.dart'; class BottomNavigationBarWidget extends StatefulWidget { const BottomNavigationBarWidget({super.key}); @override State<BottomNavigationBarWidget> createState() => _BottomNavigationBarWidgetState(); } class _BottomNavigationBarWidgetState extends State<BottomNavigationBarWidget> { int _currentIndex = 0; List<Widget> body = const [ Icon(Icons.home), Icon(Icons.menu), Icon(Icons.person), ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("BottomNavigationBar"), ), body: Center( child: body[_currentIndex], ), bottomNavigationBar: BottomNavigationBar( currentIndex: _currentIndex, items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.menu), label: 'Menu'), BottomNavigationBarItem(icon: Icon(Icons.person), label: 'Person') ], onTap: ((value) { setState(() { _currentIndex = value; }); }), ), ); } }
0