repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/GreatPlaces/lib
|
mirrored_repositories/GreatPlaces/lib/Widgets/PhotoInput.dart
|
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart' as pathDir;
class PhotInput extends StatefulWidget {
final Function addImage;
const PhotInput({
required this.addImage,
Key? key,
}) : super(key: key);
@override
State<PhotInput> createState() => _PhotInputState();
}
class _PhotInputState extends State<PhotInput> {
XFile? file = XFile("");
bool isloading = false;
///take image if device have camera
Future _takeImage() async {
final _picker = ImagePicker();
final imageFile =
await _picker.pickImage(source: ImageSource.camera, maxWidth: 600);
//if has taken
if (imageFile != null) {
//enable CircularProgressIndicator
isloading = true;
setState(() {});
// get root level app directory
final appDir = await pathDir.getApplicationDocumentsDirectory();
// temp file name
final fileName = path.basename(imageFile.path);
//save file
await imageFile.saveTo("${appDir.path}/$fileName");
print("Image saved ${imageFile.path}");
file = imageFile;
await widget.addImage(file);
//disable CircularProgressIndicator
isloading = false;
setState(() {});
}
}
///choose an image from device
Future _chooseImage() async {
final _picker = ImagePicker();
final _pickedImage =
await _picker.pickImage(source: ImageSource.gallery, maxWidth: 600);
//if an image has choosen
if (_pickedImage != null) {
//enable CircularProgressIndicator
isloading = true;
setState(() {});
print("Picked image: ${_pickedImage.path}");
file = _pickedImage;
await widget.addImage(file);
//disable CircularProgressIndicator
isloading = false;
setState(() {});
}
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (ctx, imagePart) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
//buttons
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
// chooese button
ElevatedButton(
onPressed: _chooseImage,
child: const Icon(Icons.photo_album),
),
//capture button
ElevatedButton(
onPressed: _takeImage,
child: const Icon(
Icons.camera_alt,
),
),
],
),
Expanded(
//photo preview
child: isloading
? const Center(child: CircularProgressIndicator())
: file!.path == ""
? Padding(
padding: const EdgeInsets.all(8),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.red)),
child:
const Center(child: Text("No image has chosen!")),
),
)
: kIsWeb
? Padding(
padding: const EdgeInsets.all(8),
child: Image.network(
file!.path,
fit: BoxFit.fill,
),
)
: Padding(
padding: const EdgeInsets.all(8),
child: Image.file(
File(file!.path),
fit: BoxFit.fill,
),
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/GreatPlaces/lib
|
mirrored_repositories/GreatPlaces/lib/Models/UserType.dart
|
import 'package:flutter/material.dart';
class UserType {
final String name;
final String id;
List<String> favoritePlaces;
UserType({required this.name, required this.id, this.favoritePlaces = const []});
}
| 0
|
mirrored_repositories/GreatPlaces/lib
|
mirrored_repositories/GreatPlaces/lib/Helpers/LocationHerlper.dart
|
import 'dart:convert';
import 'package:places_app/APIKeys.dart';
import 'package:http/http.dart' as http;
class LocationHelper {
static String generateLocationPreview(
{required double latitude, required double longitude}) {
return "https://api.neshan.org/v2/static?key=$NESHAN_API_KEY&type=neshan&zoom=16¢er=$latitude,$longitude&width=600&height=300&marker=red";
// return "https://maps.googleapis.com/maps/api/staticmap?center=&$latitude,$longitude&zoom=13&size=600x300&maptype=roadmap&markers=color:red%7Clabel:A%7C$latitude,$longitude&key=$GOOGLE_API_KEY";
}
static Future<String> generateAddressWithLocation(
{required double latitude, required double longitude}) async {
final String url =
"https://api.neshan.org/v4/reverse?lat=$latitude&lng=$longitude";
final response =
await http.get(Uri.parse(url), headers: {"Api-Key": NESHAN_API_KEY});
print(response.body);
return json.decode(response.body)["formatted_address"];
}
}
| 0
|
mirrored_repositories/GreatPlaces/lib
|
mirrored_repositories/GreatPlaces/lib/Helpers/dbHelper.dart
|
import 'package:path/path.dart' as path;
import 'package:sqflite/sqflite.dart' as sqlite;
class DBHelper {
///opens or creates a dataBase and returns it
static Future<sqlite.Database> dataBase(String table) async {
//path to dataBase
final String sqlPath = await sqlite.getDatabasesPath();
//open dataBase
return sqlite.openDatabase(
//path
path.join(sqlPath, "palces.db"),
//when creating
onCreate: (db, version) {
print("Creating sqlite DataBase...");
return db.execute(
"CREATE TABLE $table (id TEXT PRIMARY KEY, title TEXT, details TEXT, imageUrl TEXT, address Text, latitude TEXT, longitude TEXT)",
);
},
version: 1,
);
}
static Future<void> insert(String table, Map<String, Object> values) async {
final dataBase = await DBHelper.dataBase(table);
print("value to insert: $values");
//insert data to dataBase
await dataBase.insert(table, values,
conflictAlgorithm: sqlite.ConflictAlgorithm.replace);
}
static Future<List<Map<String, dynamic>>> getData(String table) async {
final dataBase = await DBHelper.dataBase(table);
print("sqlite data: ${await dataBase.query(table)}");
//get data from dataBase
return dataBase.query(table);
}
static Future<void> deleteData(String table, String id) async {
final dataBase = await DBHelper.dataBase(table);
final result =
await dataBase.delete(table, where: "id = ?", whereArgs: [id]);
print("deleted id: $result");
}
static Future<void> updateData(
String table, Map<String, Object> values, String id) async {
final dataBase = await DBHelper.dataBase(table);
final result =
await dataBase.update(table, values, where: "id = ?", whereArgs: [id]);
print("updated id: $result");
}
static Future<void> resetData(String table) async {
final dataBase = await DBHelper.dataBase(table);
dataBase.execute("DELETE FROM $table");
await sqlite.deleteDatabase(dataBase.path);
print("DataBase has removed!");
}
}
| 0
|
mirrored_repositories/GreatPlaces
|
mirrored_repositories/GreatPlaces/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:places_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(PlacesApp());
// 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/Literaturamo
|
mirrored_repositories/Literaturamo/lib/api.dart
|
import 'dart:io';
import 'package:literaturamo/models/menus.dart';
import 'package:file_picker/file_picker.dart';
import 'package:literaturamo/models/dictionary.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/models/file_viewer.dart';
import 'package:literaturamo/models/text_parser.dart';
import 'package:literaturamo/constants.dart';
import 'package:flutter/material.dart';
import 'dart:developer' as developer;
void log(String msg) => developer.log(msg, name: "literaturamo.api");
typedef TextSelectionChanged = Future<OverlayEntry?> Function(
TextSelectionChange change);
/// A store for contributions that extend functionality into the App.
class ContributionPoint {
static final Map<String, LanguageDictionary> _langDictionaries = {};
static final Map<String, File> _definedWordsAssets = {};
static final Map<String, FileViewer> _fileViewers = {};
static final Map<String, TextParser> _textParsers = {};
static final List<ContextMenu> _selectionContextMenus = [];
static final Map<String, DocumentRegister> _documentRegisters = {};
static registerLanguageDictionary(LanguageDictionary provider) {
_langDictionaries.putIfAbsent(provider.language.code, () => provider);
log("Registered ${provider.language} language dictionary provider $provider.");
}
static registerFileViewer(DocumentType type, FileViewer provider) {
if (type == provider.supportedDocType) {
_fileViewers.putIfAbsent(type.extension, () => provider);
} else {
throw ("${provider.supportedDocType} does not match $type to register as file viewer.");
}
log("Registered $type document view provider $provider.");
}
static registerTextParser(TextParser provider) {
_textParsers.putIfAbsent(provider.supportedType.extension, () => provider);
log("Registered ${provider.supportedType} text parser $provider");
}
static registerSelectionContextMenu(ContextMenu provider) {
_selectionContextMenus.add(provider);
log("Registered selection context menu $provider.");
}
static registerDefinedWords(Language language, File asset) {
_definedWordsAssets.putIfAbsent(language.code, () => asset);
log("Registered $language language defined words asset $asset.");
}
static registerDocumentRegister(String ext, DocumentRegister register) {
_documentRegisters.putIfAbsent(ext, () => register);
log("Registered $ext extension document registerer $register.");
}
static List<ContextMenu> getSelectionContextMenus(Language language) =>
_selectionContextMenus;
static LanguageDictionary? getLanguageDictionary(Language language) =>
_getUnderlying(language.code, _langDictionaries);
static File? getDefinedWords(Language language) =>
_getUnderlying(language.code, _definedWordsAssets);
static DocumentRegister? getDocumentRegister(String ext) =>
_getUnderlying(ext, _documentRegisters);
static TextParser? getTextParser(DocumentType type) =>
_getUnderlying(type.extension, _textParsers);
static FileViewer getFileViewer(DocumentType type) =>
_getUnderlying(type.extension, _fileViewers);
static dynamic _getUnderlying(String key, Map<String, dynamic> store) =>
store.containsKey(key) ? store[key] : null;
}
/// A wrapper around global events that can be invoked and hooked.
class Events {
static final List<TextSelectionChanged> _textSelectionChangeListeners = [];
static final List<OverlayEntry> _disposables = [];
static final List<void Function(int pageNo)> _readNewPageListeners = [];
static final List<void Function(Document doc)> _openDocumentListeners = [];
static void onTextSelectionChanged(TextSelectionChanged listener) =>
_textSelectionChangeListeners.add(listener);
static void onOpenDocument(void Function(Document doc) listener) =>
_openDocumentListeners.add(listener);
static void onReadNewPage(void Function(int pageNo) listener) =>
_readNewPageListeners.add(listener);
static void openedDocument(Document doc) =>
_openDocumentListeners.map((element) => element(doc)).toList();
static Future<void> pageChanged(Document document, int lastReadPageNo) async {
document.lastReadPageNo = lastReadPageNo;
await document.save();
log("Event pageChanged triggered: '${document.canonicalName()}' lastReadPageNo set to $lastReadPageNo.");
for (final listener in _readNewPageListeners) {
listener(lastReadPageNo);
}
}
static void textSelectionChanged(
BuildContext context, TextSelectionChange change) {
if (change.text.isEmpty || _disposables.isNotEmpty) {
for (final element in _disposables) {
element.remove();
}
_disposables.clear();
} else {
_insertOverlays(Overlay.of(context), change);
}
}
static void _insertOverlays(
OverlayState state, TextSelectionChange change) async {
final List<OverlayEntry> tmpDisposes = [];
for (final listener in _textSelectionChangeListeners) {
final overlay = await listener(change);
if (overlay != null) {
tmpDisposes.add(overlay);
}
}
state.insertAll(tmpDisposes);
_disposables.addAll(tmpDisposes);
}
}
abstract class DocumentRegister {
Future<Document> getDocument(PlatformFile file);
}
abstract class ContextMenu {
final String label;
final Icon icon;
ContextMenu({required this.label, required this.icon});
}
class SettingBox {
SettingBox._();
static dynamic get(String option) => Hive.box(settingsBoxName).get(option);
static dynamic put(String option, dynamic value) =>
Hive.box(settingsBoxName).put(option, value);
}
| 0
|
mirrored_repositories/Literaturamo
|
mirrored_repositories/Literaturamo/lib/constants.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:collection/collection.dart';
import 'dart:developer' as developer;
void logMain(String msg) => developer.log(msg, name: "literaturamo.main");
/// Application Title for internal use
const String appTitle = "Literaturamo";
// Hive and HiveBox CONSTANTS
const String recentDocsBoxName = "recent50docs";
const String settingsBoxName = "settings";
const int docHiveTypeId = 0;
const int docTypeHiveTypeId = 1;
class SettingBoxOptions {
SettingBoxOptions._();
static const defaultPageIndex = "defaultPageIndex";
static const defaultFileViewerInversion = "defaultFileViewerInversion";
}
const appBarToolBarHeight = 48.0;
final supportedLocals = {
Locale(Language.english.code),
Locale(Language.myanmar.code)
};
// A constant global discord rich presence object
// late final DiscordRPC discordRPC;
double widthPercent(BuildContext ctx, int percent) =>
MediaQuery.of(ctx).size.width * (percent / 100);
double heightPercent(BuildContext ctx, int percent) =>
MediaQuery.of(ctx).size.height * (percent / 100);
Color saturate(Color original, int amount) {
final copy = original;
return copy
.withBlue(copy.blue + amount)
.withGreen(copy.green + amount)
.withRed(copy.red + amount);
}
/// A set of preconfigured library colors.
class LibColors {
LibColors._();
static const peach = Color.fromARGB(255, 246, 176, 146);
static const gray = Color(0xFF727779);
static const lightGray = Color(0xFF93A1A1);
static const darkGray = Color(0xFF5C5E5B);
static const hagueBlue = Color.fromARGB(255, 23, 27, 29);
static const lightHagueBlue = Color(0xFF262a2c);
static const lighterHagueBlue = Color(0xFF35393b);
static const solarizedBlue = Color(0xFF002B36);
static const solarizedLightBlue = Color(0xFF073642);
static const beige = Color(0xFFFDF6E3);
static const waterBlue = Color(0xFF268AD1);
static const indigo = Color(0xFF3F51B5);
static const slate = Color(0xFF607D8B);
}
/// A set of preconfigured library themes.
class LibThemes {
LibThemes._();
static ThemeData _makeTheme({
required bool isDarkThemed,
required Color accentColor,
required Color onAccent,
required Color primaryColor,
required Color onPrimary,
required Color backgroundColor,
required Color onBackground,
required Color lightBackgroundColor,
required Color onLighterBackground,
required Color lightestBackgroundColor,
required Color onLightestBackground,
required Color lighterBackgroundColor,
required TextStyle titleMedium,
required TextStyle titleSmall,
required TextStyle bodyMedium,
}) {
return ThemeData(
appBarTheme: AppBarTheme(
color: backgroundColor,
elevation: 0,
iconTheme: IconThemeData(
color: accentColor,
),
actionsIconTheme: IconThemeData(
color: onBackground,
),
shape: Border(
bottom: BorderSide(
color: accentColor,
width: 1,
),
),
titleTextStyle: GoogleFonts.playfairDisplay(
fontSize: 20,
color: onBackground,
fontWeight: FontWeight.bold,
),
),
dialogBackgroundColor: lightestBackgroundColor,
dialogTheme: DialogTheme(
titleTextStyle: GoogleFonts.playfairDisplay(
fontSize: 20,
color: onLightestBackground,
fontWeight: FontWeight.bold,
),
),
colorScheme: ColorScheme(
brightness: isDarkThemed ? Brightness.dark : Brightness.light,
primary: primaryColor,
onPrimary: onPrimary,
secondary: accentColor,
onSecondary: onAccent,
error: Colors.red,
onError: Colors.yellow,
background: backgroundColor,
onBackground: onBackground,
surface: lighterBackgroundColor,
onSurface: onLighterBackground,
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
elevation: 1,
backgroundColor: lightBackgroundColor,
selectedItemColor: accentColor,
selectedLabelStyle: TextStyle(
color: accentColor,
),
unselectedItemColor: lighterBackgroundColor,
unselectedLabelStyle: TextStyle(
color: lighterBackgroundColor,
),
),
scaffoldBackgroundColor: backgroundColor,
iconTheme: IconThemeData(color: accentColor),
textTheme: TextTheme(
bodyMedium: bodyMedium,
titleMedium: titleMedium,
titleSmall: titleSmall,
),
);
}
static final basicDark = _makeTheme(
isDarkThemed: true,
accentColor: LibColors.peach,
onAccent: Colors.white,
primaryColor: Colors.blue,
onPrimary: Colors.black,
backgroundColor: LibColors.hagueBlue,
onBackground: Colors.white,
lightBackgroundColor: const Color(0xFF262a2C),
lighterBackgroundColor: const Color(0xFF646768),
onLighterBackground: Colors.white,
lightestBackgroundColor: const Color(0xFF35393B),
onLightestBackground: Colors.white,
bodyMedium: GoogleFonts.playfairDisplay(
color: Colors.white,
),
titleMedium: GoogleFonts.playfairDisplay(color: Colors.white),
titleSmall: GoogleFonts.playfairDisplay(color: Colors.grey),
);
// static final solarizedDark = _makeTheme(
// appBarColor: LibColors.solarizedLightBlue,
// appBarElevation: 0,
// appBarBorderColor: LibColors.waterBlue,
// appBarIconColor: LibColors.waterBlue,
// appBarBorderWidth: 1,
// titleTextStyle: GoogleFonts.playfairDisplay(
// fontSize: 20,
// color: Colors.white,
// fontWeight: FontWeight.bold,
// ),
// bottomNavBarElevation: 1,
// bottomNavBarSelectedItemColor: LibColors.waterBlue,
// bottomNavBarUnselectedItemColor: LibColors.lightGray,
// bottomNavBarSelectedLabelStyle: const TextStyle(
// color: Colors.white,
// fontStyle: FontStyle.italic,
// ),
// bottomNavBarUnselectedLabelStyle: const TextStyle(
// color: LibColors.lightGray,
// ),
// backgroundColor: LibColors.solarizedBlue,
// primaryColor: LibColors.solarizedLightBlue,
// iconColor: LibColors.waterBlue,
// bodyMedium: GoogleFonts.playfairDisplay(
// color: Colors.white,
// ),
// titleMedium: GoogleFonts.playfairDisplay(
// color: Colors.white,
// ),
// titleSmall: GoogleFonts.playfairDisplay(
// color: Colors.grey,
// ),
// );
}
const langCode2Emojis = {
"af": "๐ฟ๐ฆ",
"sq": "๐ฆ๐ฑ",
"am": "๐ช๐น",
"ar": "๐ธ๐ฆ",
"hy": "๐ฆ๐ฒ",
"az": "๐ฆ๐ฟ",
"eu": "๐ช๐ธ",
"be": "๐ต๐ฑ",
"bn": "๐ง๐ฉ",
"bs": "๐ง๐ฆ",
"bg": "๐ง๐ฌ",
"ca": "๐ช๐ธ",
"ceb": "๐ต๐ญ",
"ny": "๐ฒ๐ผ",
"zh-cn": "๐จ๐ณ",
"zh-tw": "๐จ๐ณ",
"co": "๐ซ๐ท",
"hr": "๐ญ๐ท",
"cs": "๐จ๐ฟ",
"da": "๐ฉ๐ฐ",
"nl": "๐ณ๐ฑ",
"en": "๐ด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ",
"eo": "๐ฌ๐ง",
"et": "๐ช๐ช",
"tl": "๐ต๐ญ",
"fi": "๐ซ๐ฎ",
"fr": "๐ซ๐ท",
"fy": "๐ณ๐ฑ",
"gl": "๐ช๐ธ",
"ka": "๐ฌ๐ช",
"de": "๐ฉ๐ช",
"el": "๐ฌ๐ท",
"gu": "๐ฎ๐ณ",
"ht": "๐ญ๐น",
"ha": "๐จ๐ซ",
"haw": "๐บ๐ธ",
"iw": "๐ฎ๐ฑ",
"he": "๐ฎ๐ฑ",
"hi": "๐ฎ๐ณ",
"hmn": "๐ฑ๐ฆ",
"hu": "๐ญ๐บ",
"is": "๐ฎ๐ธ",
"ig": "๐ณ๐ฌ",
"id": "๐ฎ๐ฉ",
"ga": "๐ฎ๐ช",
"it": "๐ฎ๐น",
"ja": "๐ฏ๐ต",
"jw": "๐ฎ๐ฉ",
"kn": "๐ฎ๐ณ",
"kk": "๐ฐ๐ฟ",
"km": "๐ฐ๐ญ",
"ko": "๐ฐ๐ท",
"ku": "๐น๐ท",
"ky": "๐ฐ๐ฌ",
"lo": "๐ฑ๐ฆ",
"la": "๐ต๐น",
"lv": "๐ฑ๐ป",
"lt": "๐ฑ๐น",
"lb": "๐ฉ๐ช",
"mk": "๐ฒ๐ฐ",
"mg": "๐ฒ๐ฌ",
"ms": "๐ฒ๐พ",
"ml": "๐ฎ๐ณ",
"mt": "๐ฒ๐น",
"mi": "๐ณ๐ฟ",
"mr": "๐ฎ๐ณ",
"mn": "๐ฒ๐ณ",
"my": "๐ฒ๐ฒ",
"ne": "๐ณ๐ต",
"no": "๐ณ๐ด",
"or": "๐ฎ๐ณ",
"ps": "๐ฆ๐ซ",
"fa": "๐ฎ๐ท",
"pl": "๐ต๐ฑ",
"pt": "๐ต๐น",
"pa": "๐ฎ๐ณ",
"ro": "๐ท๐ด",
"ru": "๐ท๐บ",
"sm": "๐ฆ๐ธ",
"gd": "๐ด๓ ง๓ ข๓ ณ๓ ฃ๓ ด๓ ฟ",
"sr": "๐ท๐ธ",
"st": "๐ฑ๐ธ",
"sn": "๐ฟ๐ผ",
"sd": "๐ต๐ฐ",
"si": "๐ฑ๐ฐ",
"sk": "๐ธ๐ฐ",
"sl": "๐ฆ๐น",
"so": "๐ธ๐ด",
"es": "๐ช๐ธ",
"su": "๐ธ๐ฉ",
"sw": "๐บ๐ฌ",
"sv": "๐ธ๐ช",
"tg": "๐น๐ฏ",
"ta": "๐ฎ๐ณ",
"te": "๐ฎ๐ณ",
"th": "๐น๐ญ",
"tr": "๐น๐ท",
"uk": "๐บ๐ฆ",
"ug": "๐ต๐ฐ",
"uz": "๐บ๐ฟ",
"vi": "๐ป๐ณ",
"cy": "๐ด๓ ง๓ ข๓ ฅ๓ ฎ๓ ง๓ ฟ",
"xh": "๐ฟ๐ฆ",
"yi": "๐ฎ๐ฑ",
"yo": "๐ณ๐ฌ",
"zu": "๐ฟ๐ฆ",
};
enum Language {
afrikaans("af"),
albanian("sq"),
amharic("am"),
arabic("ar"),
armenian("hy"),
azerbaijani("az"),
basque("eu"),
belarusian("be"),
bengali("bn"),
bosnian("bs"),
bulgarian("bg"),
catalan("ca"),
cebuano("ceb"),
chichewa("ny"),
chineseSimplified("zh-cn"),
chineseTraditional("zh-tw"),
corsican("co"),
croatian("hr"),
czech("cs"),
danish("da"),
dutch("nl"),
english("en"),
esperanto("eo"),
estonian("et"),
filipino("tl"),
finnish("fi"),
french("fr"),
frisian("fy"),
galician("gl"),
georgian("ka"),
german("de"),
greek("el"),
gujarati("gu"),
haitianCreole("ht"),
hausa("ha"),
hawaiian("haw"),
hebrew("he"),
hindi("hi"),
hmong("hmn"),
hungarian("hu"),
icelandic("is"),
igbo("ig"),
indonesian("id"),
irish("ga"),
italian("it"),
japanese("ja"),
javanese("jw"),
kannada("kn"),
kazakh("kk"),
khmer("km"),
korean("ko"),
kurdishKurmanji("ku"),
kyrgyz("ky"),
lao("lo"),
latin("la"),
latvian("lv"),
lithuanian("lt"),
luxembourgish("lb"),
macedonian("mk"),
malagasy("mg"),
malay("ms"),
malayalam("ml"),
maltese("mt"),
maori("mi"),
marathi("mr"),
mongolian("mn"),
myanmar("my"),
burmese("my"),
nepali("ne"),
norwegian("no"),
odia("or"),
pashto("ps"),
persian("fa"),
polish("pl"),
portuguese("pt"),
punjabi("pa"),
romanian("ro"),
russian("ru"),
samoan("sm"),
scotsGaelic("gd"),
serbian("sr"),
sesotho("st"),
shona("sn"),
sindhi("sd"),
sinhala("si"),
slovak("sk"),
slovenian("sl"),
somali("so"),
spanish("es"),
sundanese("su"),
swahili("sw"),
swedish("sv"),
tajik("tg"),
tamil("ta"),
telugu("te"),
thai("th"),
turkish("tr"),
ukrainian("uk"),
urdu("ur"),
uyghur("ug"),
uzbek("uz"),
vietnamese("vi"),
welsh("cy"),
xhosa("xh"),
yiddish("yi"),
yoruba("yo"),
zulu("zu");
final String code;
String? get emoji {
return langCode2Emojis[code];
}
static Language? fromCode(String code) {
return Language.values.firstWhereOrNull((element) => element.code == code);
}
const Language(this.code);
}
class LabelledIcon {
final String label;
final IconData iconData;
LabelledIcon({required this.label, required this.iconData});
}
| 0
|
mirrored_repositories/Literaturamo
|
mirrored_repositories/Literaturamo/lib/main.dart
|
import 'package:flutter/foundation.dart';
import 'package:literaturamo/constants.dart';
import 'package:literaturamo/screens/home/home_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:literaturamo/lifecycle.dart' as lifecycle;
import 'package:flutter/services.dart';
import 'package:literaturamo/screens/home/components/lang_picker.dart';
import 'package:provider/provider.dart';
import 'dart:io' show Platform;
void main() async {
await lifecycle.startup();
runApp(const App());
}
class App extends StatelessWidget {
const App({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final theme = LibThemes.basicDark;
if (!kIsWeb && Platform.isAndroid) {
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
statusBarColor: theme.appBarTheme.backgroundColor,
),
);
}
return ChangeNotifierProvider(
create: (context) => LocalProvider(),
builder: (context, child) {
final provider = Provider.of<LocalProvider>(context);
return MaterialApp(
supportedLocales: AppLocalizations.supportedLocales,
localizationsDelegates: AppLocalizations.localizationsDelegates,
title: appTitle,
locale: provider.locale,
theme: theme,
home: const HomeScreen(),
);
},
);
}
}
| 0
|
mirrored_repositories/Literaturamo
|
mirrored_repositories/Literaturamo/lib/lifecycle.dart
|
import 'package:hive_flutter/hive_flutter.dart';
import 'package:literaturamo/constants.dart' as globs;
import 'dart:developer' as developer;
// Recognized library extensions
import 'package:literaturamo/extensions/dictionaries.dart' as dictionaries;
import 'package:literaturamo/extensions/epub.dart' as epub_ext;
import 'package:literaturamo/extensions/pdf.dart' as pdf_ext;
import 'package:literaturamo/extensions/txt.dart' as txt_ext;
import 'package:literaturamo/extensions/transcript.dart' as transcript_ext;
import 'package:literaturamo/extensions/menus.dart' as menus_ext;
import 'package:literaturamo/models/document.dart';
void log(String msg) => developer.log(msg, name: "literaturamo.lifecycle");
Future<void> startup() async {
log("Calling start-up functions and registerers.");
_loadExtensions();
// if (Platform.isWindows) {
// _initDiscordRPC();
// }
await _registerAdapters();
log("Finished calling start-up functions and registerers.");
}
void _initDiscordRPC() {
// DiscordRPC.initialize();
// globs.discordRPC = DiscordRPC(applicationId: "993126016476254220");
// globs.discordRPC.start(autoRegister: true);
}
/// Loads registered extensions, this should only be called once.
void _loadExtensions() {
log("Loading registered API extensions.");
dictionaries.main();
epub_ext.main();
pdf_ext.main();
txt_ext.main();
transcript_ext.main();
menus_ext.main();
log("Finished loading registered API extensions.");
}
Future<void> _registerAdapters() async {
log("Registering hive adapters.");
await Hive.initFlutter();
Hive.registerAdapter(DocumentAdapter());
Hive.registerAdapter(DocumentTypeAdapter());
final boxes = [];
await Hive.openBox<Document>(globs.recentDocsBoxName);
boxes.add(globs.recentDocsBoxName);
await Hive.openBox(globs.settingsBoxName);
boxes.add(globs.settingsBoxName);
log("Finished registering hive adapters, opened boxes $boxes.");
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/widgets/loading.dart
|
import 'package:flutter/material.dart';
import 'package:literaturamo/extensions/transcript.dart';
import 'package:literaturamo/constants.dart';
class Silhouette extends StatelessWidget {
final double? height, width;
const Silhouette({Key? key, required this.height, required this.width})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
height: height,
width: width,
padding: const EdgeInsets.all(8),
decoration: BoxDecoration(
color: saturate(Theme.of(context).textTheme.titleMedium!.color!, -10),
borderRadius: const BorderRadius.all(Radius.circular(16)),
),
);
}
}
class LoadingTextLine extends StatelessWidget {
const LoadingTextLine({
Key? key,
required this.height,
required this.width,
this.wordSpacing = 0.5,
this.words = 1,
}) : super(key: key);
final double height, width, wordSpacing;
final int words;
@override
Widget build(BuildContext context) {
final List<Widget> snippets = [
for (var i = 1; i <= words; i++)
Padding(
padding: EdgeInsets.symmetric(horizontal: wordSpacing),
child: Silhouette(height: height, width: width),
)
];
return Padding(
padding: const EdgeInsets.all(2),
child: Row(children: snippets),
);
}
}
class LoadingTextViewer extends StatelessWidget {
const LoadingTextViewer(
{Key? key,
required this.height,
required this.width,
required this.color,
required this.padding})
: super(key: key);
final double height, width;
final Color color;
final EdgeInsetsGeometry padding;
@override
Widget build(BuildContext context) {
return Container(
alignment: Alignment.topRight,
width: width,
height: height,
color: color,
padding: padding,
child: Column(
children: const [
LoadingTextLine(height: 10, width: 10),
LoadingTextLine(height: 10, width: 50, words: 4),
LoadingTextLine(height: 10, width: 50, words: 4),
LoadingTextLine(height: 10, width: 50, words: 4),
],
));
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/models/menus.dart
|
import 'dart:ui';
class TextSelectionChange {
final String text;
final Rect? region;
TextSelectionChange({required this.text, this.region});
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/models/dictionary.dart
|
import 'package:literaturamo/constants.dart';
typedef StrMap = Map<String, String>;
/// An abstract class that identifies a LanguageDictionary.
///
/// Implemented classes of [LanguageDictionary] can be registered into to
/// [ContributionPoints] at runtime into the associated store for
/// a specific [Language] notated by the `language` field
/// of the class.
///
/// ```dart
/// ContributionPoints.registerLanguageDictionary(Dictionary());
/// ```
abstract class LanguageDictionary {
abstract Language language;
Future<DictionaryEntry?> getDictionaryEntry(String word);
}
/// A resultant dictionary entry when a word is queried for meaning.
class DictionaryEntry {
final String query;
final String? origin;
final Language language;
final List<PhoneticRecord> phonetics;
final List<WordMeaning> meanings;
bool _isValid = true;
DictionaryEntry(
{required this.language,
required this.query,
required this.phonetics,
this.origin,
required this.meanings});
factory DictionaryEntry.fromJson(
String word, Language lang, Map<String, dynamic> json) {
return DictionaryEntry(
language: lang,
query: word,
phonetics: (json["phonetics"] as List<dynamic>)
.map(
(phonetic) => PhoneticRecord.fromJson(phonetic),
)
.toList(),
origin: json["origin"],
meanings: (json["meanings"] as List<dynamic>)
.map(
(meaning) => WordMeaning.fromJson(meaning),
)
.toList(),
);
}
}
/// A phonetic sampling of a word in the International Phonetic Alphabet
/// and an optional audio URL that vocalizes it.
class PhoneticRecord {
final String? text;
final String? audioUrl;
PhoneticRecord({required this.text, required this.audioUrl});
factory PhoneticRecord.fromJson(json) {
return PhoneticRecord(
text: json["text"],
audioUrl: json["audio"],
);
}
}
class WordMeaning {
final String partOfSpeech;
final List<WordDefinition> definitions;
WordMeaning({
required this.partOfSpeech,
required this.definitions,
});
factory WordMeaning.fromJson(json) {
return WordMeaning(
partOfSpeech: json["partOfSpeech"]!,
definitions: (json["definitions"] as List<dynamic>)
.map(
(def) => WordDefinition.fromJson(def),
)
.toList());
}
}
class WordDefinition {
final String definition;
final String? example;
final List<dynamic> synonyms;
final List<dynamic> antonyms;
WordDefinition({
required this.definition,
this.example,
required this.synonyms,
required this.antonyms,
});
factory WordDefinition.fromJson(json) {
return WordDefinition(
definition: json["definition"]!,
example: json["example"],
synonyms: json["synonyms"],
antonyms: json["antonyms"],
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/models/text_parser.dart
|
import 'package:literaturamo/models/document.dart';
abstract class TextParser {
abstract DocumentType supportedType;
Future<String> parse(Document doc, int startPageNo);
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/models/document.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'document.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class DocumentAdapter extends TypeAdapter<Document> {
@override
final int typeId = 0;
@override
Document read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Document(
fields[0] as String,
fields[7] as String?,
fields[1] as String,
fields[2] as int,
fields[3] as DocumentType,
fields[4] as String,
programmingLang: fields[5] as String?,
)..lastReadPageNo = fields[6] as int;
}
@override
void write(BinaryWriter writer, Document obj) {
writer
..writeByte(8)
..writeByte(0)
..write(obj.title)
..writeByte(1)
..write(obj.date)
..writeByte(2)
..write(obj.totalPageNum)
..writeByte(3)
..write(obj.type)
..writeByte(4)
..write(obj.uri)
..writeByte(5)
..write(obj.programmingLang)
..writeByte(6)
..write(obj.lastReadPageNo)
..writeByte(7)
..write(obj.authorName);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is DocumentAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
class DocumentTypeAdapter extends TypeAdapter<DocumentType> {
@override
final int typeId = 1;
@override
DocumentType read(BinaryReader reader) {
switch (reader.readByte()) {
case 0:
return DocumentType.pdf;
case 1:
return DocumentType.epub;
case 2:
return DocumentType.txt;
default:
return DocumentType.pdf;
}
}
@override
void write(BinaryWriter writer, DocumentType obj) {
switch (obj) {
case DocumentType.pdf:
writer.writeByte(0);
break;
case DocumentType.epub:
writer.writeByte(1);
break;
case DocumentType.txt:
writer.writeByte(2);
break;
}
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is DocumentTypeAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/models/file_viewer.dart
|
import 'package:literaturamo/models/document.dart';
import 'package:flutter/material.dart';
import 'package:literaturamo/api.dart';
/// An abstract class that identifies a FileViewer.
///
/// Implemented classes of [FileViewer] can be registered into to
/// [ContributionPoint] at runtime into the associated store for
/// a specific [DocumentType] notated by the `supportedType` field
/// of the class.
///
/// ```dart
/// ContributionPoints.registerFileViewer(Viewer());
/// ```
abstract class FileViewer {
late List<FileViewerAction> secondaryActions;
late final DocumentType supportedDocType;
FileViewerController? controller;
FileViewer(
{this.secondaryActions = const [], required this.supportedDocType});
Widget viewDocument(BuildContext context, Document document,
{bool invert = false, int? defaultPage, void Function()? onTap});
void load(Document document) {
Events.openedDocument(document);
}
}
class FileViewerController {
final int defaultPage;
final void Function(int page) gotoPage;
int currentPage;
FileViewerController({required this.defaultPage, required this.gotoPage})
: currentPage = defaultPage;
}
class FileViewerAction {
final Icon icon;
final Text? label;
final Function(BuildContext context, Document doc) onCall;
FileViewerAction({required this.icon, this.label, required this.onCall});
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/models/document.dart
|
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'package:literaturamo/constants.dart';
part 'document.g.dart';
@HiveType(typeId: docTypeHiveTypeId)
enum DocumentType {
@HiveField(0)
pdf("pdf"),
@HiveField(1)
epub("epub"),
@HiveField(2)
txt("txt"),
/// A transcript is not a real document, but a cached transcribed document.
transcript("transcript");
factory DocumentType.from(String code) {
final DocumentType type;
if (code == pdf.extension) {
type = pdf;
} else if (code == epub.extension) {
type = epub;
} else {
type = txt;
}
return type;
}
final String extension;
const DocumentType(this.extension);
}
/// A representation model of any potentially readable document of a specified
/// [DocumentType].
@HiveType(typeId: docHiveTypeId)
class Document extends HiveObject {
@HiveField(0)
final String title;
@HiveField(1)
String date;
@HiveField(2)
final int totalPageNum;
@HiveField(3)
final DocumentType type;
@HiveField(4)
final String uri;
@HiveField(5)
final String? programmingLang;
@HiveField(6)
int lastReadPageNo = 0;
@HiveField(7)
final String? authorName;
Future<String>? data;
Uint8List? uintData;
bool get isExternal {
return uri.startsWith("http://") || uri.startsWith("https://");
}
Document(this.title, this.authorName, this.date, this.totalPageNum, this.type,
this.uri,
{this.programmingLang, this.uintData});
Document withData(Future<String> data) {
return Document(title, authorName, date, totalPageNum, type, uri,
programmingLang: programmingLang)
..data = data;
}
Document withType(DocumentType type) {
return Document(title, authorName, date, totalPageNum, type, uri,
programmingLang: programmingLang);
}
@override
String toString() {
return "<Document $type '$title' ($date) @$uri@>";
}
String canonicalName() {
// does not involve the URI to be web compatible
return "$type-$title-$date";
}
static int compare(Document a, Document b) {
if (a.date == b.date) {
return 0;
} else if (DateTime.parse(a.date)
.difference(DateTime.parse(b.date))
.inMicroseconds >=
0) {
return -1;
} else {
return 1;
}
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/extensions/pdf.dart
|
import 'package:file_picker/file_picker.dart';
import 'package:literaturamo/extensions/pdf/cached_pdfviewer.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/api.dart';
void main() {
ContributionPoint.registerDocumentRegister(
DocumentType.pdf.extension, _PdfFileRegister());
// ContributionPoint.registerFileViewer(DocumentType.pdf, SyncFusionPdfViewer());
ContributionPoint.registerFileViewer(DocumentType.pdf, CachedPdfView());
// ContributionPoints.registerTextParser(_PdfTextParser());
}
class _PdfFileRegister implements DocumentRegister {
@override
Future<Document> getDocument(PlatformFile file) async {
return Document(
file.name,
"",
DateTime.now().toIso8601String(),
0,
DocumentType.pdf,
file.path!,
uintData: file.bytes,
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/extensions/menus.dart
|
import 'package:literaturamo/models/menus.dart';
import 'package:literaturamo/models/dictionary.dart';
import 'package:literaturamo/screens/viewer/components/dictionary.dart';
import 'package:literaturamo/constants.dart';
import 'package:literaturamo/api.dart';
import 'package:flutter/material.dart';
void main() {
Events.onTextSelectionChanged(_showDictionaryOverlay);
}
Future<OverlayEntry?> _showDictionaryOverlay(TextSelectionChange change) async {
final query = change.text;
// dictionary will only work for single word selections
if (query.isEmpty || query.contains(" ")) return null;
debugPrint("Show dictionary called on $query");
final dict = ContributionPoint.getLanguageDictionary(Language.english);
if (dict == null) return null;
final DictionaryEntry? entry;
entry = await dict.getDictionaryEntry(change.text);
if (entry == null) return null;
return OverlayEntry(
builder: (context) => Positioned(
bottom: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.black.withAlpha(200),
borderRadius: BorderRadius.circular(20),
),
child: DefinitionWidget(entry: entry!),
),
),
);
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/extensions/epub.dart
|
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/models/file_viewer.dart';
import 'package:literaturamo/api.dart';
import 'package:flutter/material.dart';
void main() {}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/extensions/transcript.dart
|
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/models/file_viewer.dart';
import 'package:literaturamo/models/text_parser.dart';
import 'package:literaturamo/api.dart';
import 'package:flutter/material.dart';
import 'package:literaturamo/constants.dart';
void main() {
ContributionPoint.registerFileViewer(
DocumentType.transcript, _TranscriptViewer());
}
/// A tarnscript viewer parses a document into text if the document type
/// has a TextParser supported, and displays the parsed text in TextViewer.
class _TranscriptViewer extends FileViewer {
_TranscriptViewer()
: super(
supportedDocType: DocumentType.transcript,
);
final FileViewer txtViewer =
ContributionPoint.getFileViewer(DocumentType.txt);
late TextParser txtParser;
@override
void load(Document document) {
txtParser = ContributionPoint.getTextParser(document.type)!;
}
@override
Widget viewDocument(BuildContext context, Document doc,
{bool invert = false, int? defaultPage, void Function()? onTap}) {
debugPrint("Transcribing print as ${doc.title}");
return PageView.builder(
itemBuilder: (context, int no) {
final document =
doc.withData(txtParser.parse(doc, (defaultPage ?? 0) + no + 1));
txtViewer.load(document);
return Container(
width: MediaQuery.of(context).size.width,
color: invert ? Colors.black : Colors.white,
padding: EdgeInsets.fromLTRB(
widthPercent(context, 2), 0, widthPercent(context, 2), 10),
child: txtViewer.viewDocument(context, document, invert: invert));
},
itemCount: doc.totalPageNum,
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/extensions/txt.dart
|
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:literaturamo/models/menus.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/models/file_viewer.dart';
import 'package:literaturamo/api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_highlight/flutter_highlight.dart';
import 'package:flutter_highlight/themes/obsidian.dart';
void main() {
ContributionPoint.registerFileViewer(DocumentType.txt, _TxtViewer());
}
/// A text viewer loads a text file at a specified destination and
/// serves data procedurally.
class _TxtViewer extends FileViewer {
_TxtViewer()
: super(
supportedDocType: DocumentType.txt,
);
Future<String>? data;
bool? invert;
@override
void load(Document document) {
if (document.data == null) {
data = kIsWeb
? Future<String>.value(document.uintData.toString())
: File(document.uri!).readAsString();
} else {
data = document.data;
}
}
@override
Widget viewDocument(BuildContext context, Document doc,
{bool invert = false, int? defaultPage, void Function()? onTap}) {
this.invert = invert;
Widget Function(
Document doc, BuildContext context, AsyncSnapshot<String> snapshot)
builder;
builder =
doc.programmingLang == null ? _documentWidget : _syntaticDocumentWidget;
return FutureBuilder(
future: data,
builder: (context, AsyncSnapshot<String> snapshot) =>
builder(doc, context, snapshot),
);
}
Widget _syntaticDocumentWidget(
Document doc, BuildContext context, AsyncSnapshot<String> snapshot) {
debugPrint("${doc.programmingLang} is the language.");
return Container(
margin: EdgeInsets.fromLTRB(
15, MediaQuery.of(context).padding.top + kToolbarHeight - 15, 15, 0),
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: HighlightView(
snapshot.data ?? "Err",
language: doc.programmingLang!,
theme: obsidianTheme,
),
);
}
Widget _documentWidget(
Document doc, BuildContext context, AsyncSnapshot<String> snapshot) {
return Container(
color: invert == true ? Colors.black : Colors.white,
padding: EdgeInsets.fromLTRB(
15, MediaQuery.of(context).padding.top + kToolbarHeight, 0, 15),
child: SelectableText(
snapshot.data ?? "Loading..",
toolbarOptions: const ToolbarOptions(),
style: GoogleFonts.notoSansGeorgian(
color: invert == true ? Colors.white : Colors.black,
fontSize: 20,
),
onSelectionChanged: (selection, cause) => Events.textSelectionChanged(
context,
TextSelectionChange(
text: snapshot.data!.substring(selection.start, selection.end),
region: Rect.fromPoints(
const Offset(100, 200),
const Offset(100, 200),
),
),
),
),
);
// SkeletonLoader(
// builder: LoadingTextViewer(
// width: MediaQuery.of(context).size.width,
// height: MediaQuery.of(context).size.height,
// color: saturate(Theme.of(context).scaffoldBackgroundColor, 10),
// padding: EdgeInsets.fromLTRB(15,
// kToolbarHeight - MediaQuery.of(context).padding.top, 0, 15),
// ),
// items: 1,
// period: const Duration(seconds: 2),
// highlightColor: Colors.lightBlue,
// direction: SkeletonDirection.ltr,
// )
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/extensions/dictionaries.dart
|
import 'dart:convert';
import 'package:literaturamo/models/dictionary.dart';
import 'package:literaturamo/constants.dart';
import 'package:literaturamo/api.dart';
import 'package:http/http.dart' as http;
void main() {
ContributionPoint.registerLanguageDictionary(EnglishLanguageDictionary());
}
const api = "https://api.dictionaryapi.dev/api/v2/entries";
class EnglishLanguageDictionary implements LanguageDictionary {
@override
Language language = Language.english;
@override
Future<DictionaryEntry?> getDictionaryEntry(String word) async {
final endpoint = Uri.parse("$api/${language.code}/$word");
late final http.Response res;
try {
res = await http.get(endpoint);
} catch (e) {
return null;
}
if (res.statusCode != 200) {
return null;
}
final resp = jsonDecode(res.body);
return DictionaryEntry.fromJson(word, language, resp[0]);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/extensions
|
mirrored_repositories/Literaturamo/lib/extensions/pdf/pdf_textparser.dart
|
// import 'package:literaturamo/models/text_parser.dart';
// import 'package:pdf_text/pdf_text.dart' as pdf_text;
// class _PdfTextParser implements TextParser {
// @override
// DocumentType supportedType = DocumentType.pdf;
// pdf_text.PDFDoc? _pdfDoc;
// String? lastOpenedUri;
// int? lastOpenedPage;
// final Map<int, String> _textCache = {};
// Future<String> text(Document doc) async {
// _pdfDoc =
// _pdfDoc == null ? await pdf_text.PDFDoc.fromPath(doc.uri) : _pdfDoc!;
// return await _pdfDoc!.text;
// }
// Future<String> pageText(Document doc, int page) async {
// _pdfDoc = _pdfDoc == null || lastOpenedUri != doc.uri
// ? await pdf_text.PDFDoc.fromPath(doc.uri)
// : _pdfDoc!;
// lastOpenedPage = page;
// lastOpenedUri = doc.uri;
// final text = await _pdfDoc!.pageAt(page).text;
// _textCache.putIfAbsent(page, () => text);
// return text;
// }
// @override
// Future<String> parse(Document doc, int page) async {
// if (_textCache.containsKey(page)) {
// return _textCache[page]!;
// }
// if (_textCache.length > 5) {
// _textCache.remove(_textCache.keys.first);
// }
// pageText(doc, page + 2);
// pageText(doc, page + 1);
// return pageText(doc, page);
// }
// }
| 0
|
mirrored_repositories/Literaturamo/lib/extensions
|
mirrored_repositories/Literaturamo/lib/extensions/pdf/cached_pdfviewer.dart
|
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/models/file_viewer.dart';
import 'package:flutter_cached_pdfview/flutter_cached_pdfview.dart'
as cached_pdf;
import 'package:flutter/material.dart';
import 'package:literaturamo/api.dart';
class CustomTapGestureRecognizer extends OneSequenceGestureRecognizer {
int? _selectedPointer;
// Initial Position of selected pointer
Offset? _initialPos;
// Timestamp of first pointer (selected) update
Duration? _first;
// Timestamp of latest pointer (selected) updatek
Duration? _last;
// Signifies that the event is potentially a tap
bool _isPotentiallyTap = false;
// For future taps
bool _isGoingToFire = false;
late Function onTap;
CustomTapGestureRecognizer()
: _isGoingToFire = false,
_isPotentiallyTap = false,
_selectedPointer = null,
_initialPos = null,
_first = null,
_last = null;
// Reset everything for a new session
void _resetState() {
_isGoingToFire = false;
_isPotentiallyTap = false;
_selectedPointer = null;
_initialPos = null;
_first = null;
_last = null;
}
@override
void addPointer(PointerDownEvent event) {
startTrackingPointer(event.pointer);
if (_selectedPointer == null) {
// Select the first pointer that comes through
_selectedPointer = event.pointer;
_isPotentiallyTap = true;
} else {
// Multiple pointers on the screen which means it's not a tap
_selectedPointer = null;
_isPotentiallyTap = false;
}
// Accept all. Rejecting might lead to other gestures not working
resolve(GestureDisposition.accepted);
// If previous pointer was going to fire [onTap], stop it.
// Used to prevent onTap being fired on multi-tap.
if (_isGoingToFire) {
_resetState();
}
}
@override
String get debugDescription => 'only one pointer recognizer';
@override
void didStopTrackingLastPointer(int pointer) {}
@override
void handleEvent(PointerEvent event) {
// onPointerUp, see if it moved and see the duration of its
// interaction on the screen. If it moved, it's not a tap.
// If its duration is more than 125 milliseconds (default
// Android tapTimeout), it's not a tap.
if (!event.down && event.pointer == _selectedPointer) {
_last = event.timeStamp;
if (event.localPosition.distanceSquared ==
(_initialPos?.distanceSquared ??
event.localPosition.distanceSquared) &&
(_last!.inMilliseconds - _first!.inMilliseconds) <= 125) {
_isGoingToFire = true;
// Presenting a slight delay to consider multi-tap case
Future.delayed(const Duration(milliseconds: 250), () {
if (_isPotentiallyTap) {
onTap();
}
_resetState();
});
} else {
_resetState();
}
} else if (_initialPos == null) {
// Get initialPos and time
_initialPos = event.localPosition;
_first = event.timeStamp;
}
}
}
class CachedPdfView extends FileViewer {
late int defaultPage;
Document? doc;
CachedPdfView()
: super(
supportedDocType: DocumentType.pdf,
) {
secondaryActions = [
FileViewerAction(
label: const Text("Copy Page Text"),
icon: const Icon(Icons.copy_rounded),
onCall: (context, doc) {
if (controller != null) {
job() async => Clipboard.setData(
ClipboardData(
text: await ContributionPoint.getTextParser(doc.type)!
.parse(doc, controller!.currentPage),
),
);
job();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Copied Text!'),
),
);
}
},
),
FileViewerAction(
label: const Text("Goto Page"),
icon: const Icon(Icons.directions_rounded),
onCall: (context, doc) {
showDialog(
context: context,
builder: (context) => SimpleDialog(
alignment: Alignment.center,
title: const Text("Page Number"),
children: [
TextField(
textInputAction: TextInputAction.go,
onSubmitted: (text) {
if (controller != null) {
controller!.gotoPage(int.parse(text));
}
},
decoration: InputDecoration(
filled: true,
hintText: "100..",
fillColor:
Theme.of(context).navigationBarTheme.backgroundColor,
),
autocorrect: true,
),
],
),
);
},
),
];
}
@override
Widget viewDocument(BuildContext context, Document document,
{bool invert = false, int? defaultPage, void Function()? onTap}) {
Widget viewer;
doc = document;
this.defaultPage = defaultPage ?? document.lastReadPageNo ?? 0;
debugPrint("Rendering view document at inversion $invert");
final pdf = cached_pdf.PDF(
onViewCreated: _onViewCreated,
onRender: _onRender,
onPageChanged: _onPageChanged,
onError: _onError,
swipeHorizontal: true,
enableSwipe: true,
gestureRecognizers: {
if (onTap != null)
Factory<CustomTapGestureRecognizer>(
() => CustomTapGestureRecognizer()..onTap = onTap,
)
},
defaultPage: this.defaultPage,
fitPolicy: cached_pdf.FitPolicy.BOTH,
nightMode: invert,
);
if (document.isExternal) {
viewer = pdf.fromUrl(
document.uri,
placeholder: (double progress) => Center(child: Text('$progress %')),
errorWidget: (dynamic error) => Center(child: Text(error.toString())),
);
} else {
viewer = pdf.fromPath(document.uri);
}
return viewer;
}
void _onViewCreated(cached_pdf.PDFViewController controller) {
debugPrint("Create view with controller $controller");
this.controller = FileViewerController(
defaultPage: defaultPage,
gotoPage: (page) => controller.setPage(page),
);
}
static void _onRender(int? no) {
debugPrint("Rendered page number $no");
}
void _onPageChanged(int? page, int? total) {
debugPrint("Page changed to $page ");
if (page != null) {
controller!.currentPage = page;
Events.pageChanged(doc!, page);
}
}
static void _onError(dynamic err) {
debugPrint("PDF View error $err");
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/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);
}
/// `English`
String get language {
return Intl.message(
'English',
name: 'language',
desc: 'The current language',
args: [],
);
}
/// `Recent`
String get recent {
return Intl.message(
'Recent',
name: 'recent',
desc: 'A page category',
args: [],
);
}
/// `Library`
String get library {
return Intl.message(
'Library',
name: 'library',
desc: 'A page category',
args: [],
);
}
/// `Discover`
String get discover {
return Intl.message(
'Discover',
name: 'discover',
desc: 'A page category',
args: [],
);
}
/// `Recently Opened`
String get recentlyOpened {
return Intl.message(
'Recently Opened',
name: 'recentlyOpened',
desc: 'A text',
args: [],
);
}
}
class AppLocalizationDelegate extends LocalizationsDelegate<S> {
const AppLocalizationDelegate();
List<Locale> get supportedLocales {
return const <Locale>[
Locale.fromSubtags(languageCode: 'en'),
Locale.fromSubtags(languageCode: 'my'),
];
}
@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/Literaturamo/lib/generated
|
mirrored_repositories/Literaturamo/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';
final messages = _notInlinedMessages(_notInlinedMessages);
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
"discover": MessageLookupByLibrary.simpleMessage("Discover"),
"language": MessageLookupByLibrary.simpleMessage("English"),
"library": MessageLookupByLibrary.simpleMessage("Library"),
"recent": MessageLookupByLibrary.simpleMessage("Recent"),
"recentlyOpened":
MessageLookupByLibrary.simpleMessage("Recently Opened")
};
}
| 0
|
mirrored_repositories/Literaturamo/lib/generated
|
mirrored_repositories/Literaturamo/lib/generated/intl/messages_my.dart
|
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart
// This is a library that provides messages for a my 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 => 'my';
final messages = _notInlinedMessages(_notInlinedMessages);
static Map<String, Function> _notInlinedMessages(_) => <String, Function>{
"discover": MessageLookupByLibrary.simpleMessage("แแพแฌแแฝแฑ"),
"language": MessageLookupByLibrary.simpleMessage("แแผแแบแแฌ"),
"library": MessageLookupByLibrary.simpleMessage("แ
แฌแแผแแทแบแแญแฏแแบ"),
"recent": MessageLookupByLibrary.simpleMessage("แแแแบแ
แฌแกแฏแแบแแปแฌแธ"),
"recentlyOpened": MessageLookupByLibrary.simpleMessage(
"แแแแบแแฝแแทแบแแพแ
แบแแฒแทแแฑแฌแ
แฌแกแฏแแบแแปแฌแธ")
};
}
| 0
|
mirrored_repositories/Literaturamo/lib/generated
|
mirrored_repositories/Literaturamo/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: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_my.dart' as messages_my;
typedef Future<dynamic> LibraryLoader();
Map<String, LibraryLoader> _deferredLibraries = {
'en': () => new Future.value(null),
'my': () => new Future.value(null),
};
MessageLookupByLibrary? _findExact(String localeName) {
switch (localeName) {
case 'en':
return messages_en.messages;
case 'my':
return messages_my.messages;
default:
return null;
}
}
/// User programs should call this before using [localeName] for messages.
Future<bool> initializeMessages(String localeName) async {
var availableLocale = Intl.verifiedLocale(
localeName, (locale) => _deferredLibraries[locale] != null,
onFailure: (_) => null);
if (availableLocale == null) {
return new Future.value(false);
}
var lib = _deferredLibraries[availableLocale];
await (lib == null ? new Future.value(false) : lib());
initializeInternalMessageLookup(() => new CompositeMessageLookup());
messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor);
return new Future.value(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/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/utils/skeleton_loader.dart
|
import 'package:flutter/material.dart';
import 'package:shimmer/shimmer.dart';
class SkeletonLoader extends StatefulWidget {
/// Number of skeleton items to show
/// Default is 1
final int items;
/// A layout of how you want your skeleton to look like
final Widget builder;
/// Base Color of the skeleton list item
/// Defaults to Colors.grey[300]
final Color baseColor;
/// Highlight Color of the skeleton list item
/// Defaults to Colors.grey[100]
final Color highlightColor;
/// Highlight Color of the skeleton list item
/// Defaults to ShimmerDirection.rtl
final ShimmerDirection direction;
/// Duration in which the transition takes place
/// Defaults to Duration(seconds: 2)
final Duration period;
const SkeletonLoader({
Key? key,
this.items = 1,
required this.builder,
this.baseColor = const Color(0xFFE0E0E0),
this.highlightColor = const Color(0xFFF5F5F5),
this.direction = ShimmerDirection.ltr,
this.period = const Duration(seconds: 2),
}) : super(key: key);
@override
State<SkeletonLoader> createState() => _SkeletonLoaderState();
}
class _SkeletonLoaderState extends State<SkeletonLoader> {
@override
Widget build(BuildContext context) {
ShimmerDirection direction = widget.direction;
return Column(
children: [
Shimmer.fromColors(
baseColor: widget.baseColor,
highlightColor: widget.highlightColor,
direction: direction,
period: widget.period,
child: ListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (_, __) => Container(
child: widget.builder,
),
itemCount: widget.items,
),
),
],
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/utils/responsive.dart
|
import 'package:flutter/material.dart';
class Responsive extends StatelessWidget {
final Widget mobile;
final Widget? tablet;
final Widget desktop;
const Responsive({
Key? key,
required this.mobile,
this.tablet,
required this.desktop,
}) : super(key: key);
static bool isMobile(BuildContext context) =>
MediaQuery.of(context).size.width < 850;
static bool isTablet(BuildContext context) =>
MediaQuery.of(context).size.width < 1100 &&
MediaQuery.of(context).size.width >= 850;
static bool isDesktop(BuildContext context) =>
MediaQuery.of(context).size.width >= 1100;
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
if (size.width >= 1100) {
return desktop;
} else if (size.width >= 850 && tablet != null) {
return tablet!;
} else {
return mobile;
}
}
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/utils/predictor.dart
|
// import 'package:fuzzy/fuzzy.dart';
import 'package:literaturamo/api.dart';
import 'package:literaturamo/constants.dart';
Future<List<String>> findClosest(Language language) async {
final List<String> words =
await ContributionPoint.getDefinedWords(language)!.readAsLines();
return [];
}
| 0
|
mirrored_repositories/Literaturamo/lib
|
mirrored_repositories/Literaturamo/lib/screens/settings.dart
|
import 'package:flutter/material.dart';
import 'package:literaturamo/constants.dart';
import 'package:settings_ui/settings_ui.dart';
class SettingScreen extends StatefulWidget {
const SettingScreen({Key? key}) : super(key: key);
@override
State<SettingScreen> createState() => _SettingScreenState();
}
class _SettingScreenState extends State<SettingScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"$appTitle Settings",
),
),
body: SettingsList(
sections: [
SettingsSection(
title: Text('Preferences'),
tiles: <SettingsTile>[
SettingsTile.navigation(
leading: Icon(Icons.language),
title: Text('Language'),
value: Text('English'),
),
SettingsTile.switchTile(
onToggle: (value) {},
initialValue: true,
leading: Icon(Icons.format_paint),
title: Text('Enable custom theme'),
),
],
),
SettingsSection(
title: Text('Common'),
tiles: <SettingsTile>[
SettingsTile.navigation(
leading: Icon(Icons.language),
title: Text('Language'),
value: Text('English'),
),
SettingsTile.switchTile(
onToggle: (value) {},
initialValue: true,
leading: Icon(Icons.format_paint),
title: Text('Enable custom theme'),
),
],
),
SettingsSection(
title: Text('Common'),
tiles: <SettingsTile>[
SettingsTile.navigation(
leading: Icon(Icons.language),
title: Text('Language'),
value: Text('English'),
),
SettingsTile.switchTile(
onToggle: (value) {},
initialValue: true,
leading: Icon(Icons.format_paint),
title: Text('Enable custom theme'),
),
],
),
SettingsSection(
title: Text('Help & Support'),
tiles: <SettingsTile>[
SettingsTile.navigation(
leading: Icon(Icons.help_center_rounded),
title: Text('Help'),
value: Text('English'),
),
SettingsTile.switchTile(
onToggle: (value) {},
initialValue: true,
leading: Icon(Icons.format_paint),
title: Text('Enable custom theme'),
),
],
),
],
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens
|
mirrored_repositories/Literaturamo/lib/screens/editor/editor_screen.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:literaturamo/screens/editor/components/ribbon.dart';
import 'package:literaturamo/screens/editor/components/sideview.dart';
import 'package:literaturamo/screens/editor/components/text_field.dart';
import 'package:literaturamo/constants.dart';
class EditorScreen extends StatefulWidget {
const EditorScreen({super.key});
@override
State<EditorScreen> createState() => _EditorScreenState();
}
class _EditorScreenState extends State<EditorScreen> {
bool enableSideview = true;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Row(
children: [
Column(
children: const [
EditorRibbon(),
EditorTextField(),
],
),
if (enableSideview) const EditorSideview(),
],
),
appBar: AppBar(
toolbarHeight: appBarToolBarHeight, // add this line
title: Row(children: [
const Text(
appTitle,
),
Padding(
padding: const EdgeInsets.only(left: 5),
child: Text(
"Writer's",
style: GoogleFonts.passionsConflict(),
),
)
]),
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/editor
|
mirrored_repositories/Literaturamo/lib/screens/editor/components/text_field.dart
|
import 'package:flutter/material.dart';
class EditorTextField extends StatelessWidget {
const EditorTextField({
super.key,
});
@override
Widget build(BuildContext context) {
return const TextField(
maxLines: null,
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/editor
|
mirrored_repositories/Literaturamo/lib/screens/editor/components/ribbon.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
class EditorRibbon extends StatelessWidget {
const EditorRibbon({super.key});
@override
Widget build(BuildContext context) {
return SizedBox(
width: MediaQuery.of(context).size.width,
height: 30,
child: Container(
color: Theme.of(context).bottomNavigationBarTheme.backgroundColor,
child: const Text("Ribbon"),
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/editor
|
mirrored_repositories/Literaturamo/lib/screens/editor/components/sideview.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
class EditorSideview extends StatefulWidget {
const EditorSideview({super.key});
@override
State<EditorSideview> createState() => _EditorSideviewState();
}
class _EditorSideviewState extends State<EditorSideview> {
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens
|
mirrored_repositories/Literaturamo/lib/screens/viewer/viewer_screen.dart
|
import 'package:flutter/services.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/models/file_viewer.dart';
import 'package:flutter/material.dart';
import 'package:literaturamo/screens/viewer/components/bottom_drawer.dart';
import 'package:literaturamo/api.dart';
import 'package:literaturamo/constants.dart';
import 'package:literaturamo/screens/viewer/components/dictionary.dart';
class ViewerScreen extends StatefulWidget {
final Document document;
final int? defaultPage;
final FileViewer? fileViewer;
const ViewerScreen(
{required this.document, this.defaultPage, this.fileViewer, Key? key})
: super(key: key);
@override
State<ViewerScreen> createState() => _ViewerScreenState();
}
class _ViewerScreenState extends State<ViewerScreen> {
late final FileViewer fileViewer;
late final bool hasTxtParser;
late bool invert;
bool inspect = true;
bool drawerOpened = false;
@override
void initState() {
super.initState();
fileViewer = widget.fileViewer ??
ContributionPoint.getFileViewer(widget.document.type);
fileViewer.load(widget.document);
invert =
SettingBox.get(SettingBoxOptions.defaultFileViewerInversion) ?? false;
hasTxtParser =
ContributionPoint.getTextParser(fileViewer.supportedDocType) != null;
}
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
extendBodyBehindAppBar: true,
extendBody: true,
appBar: inspect
? AppBar(
title: Text(widget.document.title),
actions: _actions(),
)
: null,
body: Stack(
children: [
fileViewer.viewDocument(
context,
widget.document,
invert: invert,
defaultPage: widget.defaultPage,
onTap: () {
setState(() {
inspect = !inspect;
drawerOpened = false;
});
if (!inspect) {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersive);
} else {
SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);
}
},
),
if (drawerOpened)
const Positioned(
left: 0,
bottom: 0,
child: BottomDrawer(
child: DictionaryDialog(
language: Language.english,
)),
)
],
),
);
}
List<Widget> _conditionalActions() {
return [
if (hasTxtParser)
IconButton(
tooltip: "Extract Text",
icon: const Icon(Icons.text_fields),
onPressed: _transcribe,
)
];
}
List<Widget> _secondaryActions() {
return [
if (fileViewer.secondaryActions.isNotEmpty)
PopupMenuButton(
icon: Icon(
Icons.more_vert_rounded,
color: Theme.of(context).colorScheme.onBackground,
),
tooltip: "Other Options",
color: Theme.of(context).scaffoldBackgroundColor,
itemBuilder: (context) {
return [
for (var i = 0; i < fileViewer.secondaryActions.length; i++)
PopupMenuItem<int>(
value: i,
child: Row(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(0, 0, 10, 0),
child: fileViewer.secondaryActions[i].icon),
fileViewer.secondaryActions[i].label!,
],
),
)
];
},
onSelected: (int value) {
fileViewer.secondaryActions
.elementAt(value)
.onCall(context, widget.document);
},
)
];
}
_actions() {
return [
IconButton(
tooltip: "Invert Color",
icon: const Icon(Icons.brightness_high),
onPressed: _invertColor,
),
IconButton(
tooltip: "Dictionary",
icon: const Icon(Icons.menu_book_rounded),
onPressed: () => setState(() {
drawerOpened = !drawerOpened;
}),
),
..._conditionalActions(),
..._secondaryActions(),
];
}
void _invertColor() {
SettingBox.put(SettingBoxOptions.defaultFileViewerInversion, !invert);
setState(() => invert = !invert);
}
void _transcribe() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return ViewerScreen(
document: widget.document,
fileViewer:
ContributionPoint.getFileViewer(DocumentType.transcript),
defaultPage: fileViewer.controller!
.currentPage, // CONTROLLER MAY BE NULL SOMETIMES SO FIX THIS
);
},
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/viewer
|
mirrored_repositories/Literaturamo/lib/screens/viewer/components/bottom_drawer.dart
|
import 'package:flutter/material.dart';
class BottomDrawer extends StatefulWidget {
final Widget child;
const BottomDrawer({required this.child, super.key});
@override
State<BottomDrawer> createState() => _BottomDrawerState();
}
class _BottomDrawerState extends State<BottomDrawer> {
@override
Widget build(BuildContext context) {
final double width = MediaQuery.of(context).size.width;
const double height = 193;
return Container(
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.brightness == Brightness.dark
? Colors.black
: Colors.white,
borderRadius: const BorderRadius.vertical(
top: Radius.circular(8),
),
),
width: width,
height: height,
child: Column(
children: [
Container(
margin: const EdgeInsets.only(left: 100, right: 100, top: 4),
width: 93,
height: 3,
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.secondary,
borderRadius: const BorderRadius.all(
Radius.circular(2),
),
),
),
widget.child
],
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/viewer
|
mirrored_repositories/Literaturamo/lib/screens/viewer/components/dictionary.dart
|
import 'package:google_fonts/google_fonts.dart';
import 'package:literaturamo/models/dictionary.dart';
import 'package:flutter/material.dart';
import 'package:literaturamo/api.dart';
import 'package:literaturamo/constants.dart';
/// A floating dialog box to display dictionary related content.
class DictionaryDialog extends StatefulWidget {
final Language language;
const DictionaryDialog({
Key? key,
required this.language,
}) : super(key: key);
@override
State<DictionaryDialog> createState() => _DictionaryDialogState();
}
class _DictionaryDialogState extends State<DictionaryDialog> {
DictionaryEntry? definition;
late final LanguageDictionary dictionary;
bool searching = false;
final TextEditingController _controller = TextEditingController();
@override
void initState() {
super.initState();
dictionary = ContributionPoint.getLanguageDictionary(widget.language)!;
}
void _setDefinition(String query) async {
if (query.length < 3 || query.contains(" ")) return;
query = query.toLowerCase().trim();
setState(() => searching = true);
final queryDefinition = await dictionary.getDictionaryEntry(query);
setState(() {
definition = queryDefinition;
searching = false;
});
_controller.clear();
}
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.fromLTRB(12, 19, 12, 0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(3),
),
child: Column(
children: [
Row(
children: [
Icon(
Icons.menu_book_rounded,
color:
Theme.of(context).colorScheme.brightness == Brightness.dark
? Colors.white
: Colors.black,
),
Container(
padding: const EdgeInsets.only(left: 6),
child:
Text(definition == null ? "Dictionary" : definition!.query),
),
if (definition != null)
Text(
definition!.phonetics.first.text!,
style: GoogleFonts.notoSans(
color: Theme.of(context).colorScheme.onBackground,
fontStyle: FontStyle.italic,
fontSize: 15,
decoration: TextDecoration.none,
),
)
],
),
if (searching)
const Text("Searching...")
else
Text(
definition == null
? "Text in something to find."
: definition!.meanings.first.definitions.first.definition,
softWrap: true,
maxLines: 2,
style: GoogleFonts.playfairDisplay(
color: Theme.of(context).colorScheme.onBackground,
fontSize: 13,
decoration: TextDecoration.none,
),
),
Container(
margin: const EdgeInsets.symmetric(vertical: 30),
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(25)),
color: Theme.of(context).bottomNavigationBarTheme.backgroundColor,
),
child: TextField(
textInputAction: TextInputAction.search,
onSubmitted: _setDefinition,
controller: _controller,
decoration: InputDecoration(
border: InputBorder.none,
suffixIcon: IconButton(
onPressed: () => _setDefinition(_controller.text),
icon: const Icon(Icons.search_rounded),
),
),
autocorrect: true,
),
),
],
),
);
}
}
/// A widget to display dictionary definitions.
class DefinitionWidget extends StatelessWidget {
final DictionaryEntry entry;
const DefinitionWidget({Key? key, required this.entry}) : super(key: key);
@override
Widget build(BuildContext context) {
final header = Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
entry.query,
style: GoogleFonts.playfairDisplay(
color: Theme.of(context).colorScheme.onBackground,
fontSize: 20,
decoration: TextDecoration.none,
),
),
if (entry.phonetics.isNotEmpty && entry.phonetics[0].text != null)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10,
),
child: Text(
entry.phonetics[0].text!,
style: GoogleFonts.notoSans(
color: Theme.of(context).colorScheme.onBackground,
fontStyle: FontStyle.italic,
fontSize: 15,
decoration: TextDecoration.none,
),
),
),
],
);
final definition = Column(
children:
entry.meanings.map((means) => DefintionMeaningWidget(means)).toList(),
);
return Container(
padding: const EdgeInsets.all(10),
child: Column(
children: [header, definition],
),
);
}
}
class DefintionMeaningWidget extends StatelessWidget {
const DefintionMeaningWidget(
this.means, {
super.key,
});
final WordMeaning means;
static Widget _buildDefinition(BuildContext context, WordDefinition defined) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
defined.definition,
softWrap: true,
maxLines: 2,
style: GoogleFonts.playfairDisplay(
color: Theme.of(context).colorScheme.onBackground,
fontSize: 13,
decoration: TextDecoration.none,
),
),
if (defined.example != null)
Text(
"E.g. ${defined.example!}",
softWrap: true,
maxLines: 2,
style: GoogleFonts.playfairDisplay(
color: saturate(Theme.of(context).colorScheme.onBackground, -30),
fontStyle: FontStyle.italic,
fontSize: 12,
decoration: TextDecoration.none,
),
)
],
);
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text(
means.partOfSpeech,
style: GoogleFonts.playfairDisplay(
color: Theme.of(context).colorScheme.secondary,
fontStyle: FontStyle.italic,
fontSize: 15,
decoration: TextDecoration.none,
),
),
Column(
children: means.definitions
.getRange(0, 1)
.map(
(defined) => _buildDefinition(context, defined),
)
.toList(),
),
],
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens
|
mirrored_repositories/Literaturamo/lib/screens/home/home_screen.dart
|
import 'package:file_picker/file_picker.dart';
import 'package:literaturamo/utils/responsive.dart';
import 'package:literaturamo/screens/home/views/discover.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:literaturamo/screens/home/components/sidebar.dart';
import 'package:literaturamo/screens/home/views/library.dart';
import 'package:literaturamo/screens/home/views/recents.dart';
import 'package:literaturamo/screens/viewer/viewer_screen.dart';
import 'package:literaturamo/api.dart';
import 'package:literaturamo/constants.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/screens/settings.dart';
import 'package:flutter/material.dart';
import 'package:collection/collection.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
Document? lastOpened;
late Box<Document> recentDocuments;
late int currentPageIndex;
late PageController pageController;
static const desktopSidebarWidth = 230.0;
static const mobilePageChangeDuration = 500;
static const desktopPageChangeDuration = 1;
@override
void initState() {
super.initState();
currentPageIndex = SettingBox.get(SettingBoxOptions.defaultPageIndex) ?? 0;
recentDocuments = Hive.box<Document>(recentDocsBoxName);
pageController = PageController(initialPage: currentPageIndex);
}
@override
Widget build(BuildContext context) {
final subpages = getSubpages(context);
return Scaffold(
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
appBar: AppBar(
toolbarHeight: appBarToolBarHeight, // add this line
title: const Text(
appTitle,
),
actions: [
IconButton(
icon: const Icon(Icons.note_add_rounded),
onPressed: _loadNewDocument,
),
IconButton(
icon: const Icon(Icons.settings_rounded),
tooltip: "Settings",
onPressed: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const SettingScreen(),
),
),
),
],
),
body: SafeArea(
child: Row(
children: [
if (Responsive.isDesktop(context))
HomeScreenSidebar(
desktopSidebarWidth: desktopSidebarWidth,
subpages: subpages,
desktopPageChangeDuration: desktopPageChangeDuration,
animateToSubPage: _animateToSubPage,
),
Expanded(
child: PageView(
controller: pageController,
onPageChanged: (idx) {
setState(() => currentPageIndex = idx);
logMain("Setting homepage default page to index $idx.");
Hive.box(settingsBoxName)
.put(SettingBoxOptions.defaultPageIndex, idx);
},
scrollDirection: Axis.horizontal,
children: const [RecentsView(), LibraryView(), DiscoverView()],
),
),
],
),
),
bottomNavigationBar: Responsive.isMobile(context)
? BottomNavigationBar(
currentIndex: currentPageIndex,
type: BottomNavigationBarType.fixed,
items: getSubpages(context)
.map((e) => BottomNavigationBarItem(
icon: Icon(e.iconData),
label: e.label,
))
.toList(),
onTap: (idx) => _animateToSubPage(idx, mobilePageChangeDuration),
)
: null,
floatingActionButton: !Responsive.isDesktop(context) &&
(lastOpened != null || recentDocuments.values.toList().isNotEmpty)
? FloatingActionButton(
onPressed: _openLastDocument,
backgroundColor: Theme.of(context).colorScheme.secondary,
child: Icon(
Icons.local_library_rounded,
color: Theme.of(context).colorScheme.onSecondary,
),
)
: null,
);
}
void _openLastDocument() {
if (lastOpened == null) {
final recentDocumentsOrdered = recentDocuments.values.toList();
recentDocumentsOrdered.sort((a, b) => Document.compare(a, b));
lastOpened = recentDocumentsOrdered.first;
}
_openDocument(lastOpened!, fromRecentDocs: true);
}
/// An ordered list of labelled icons for available subpages.
static List<LabelledIcon> getSubpages(BuildContext context) => [
LabelledIcon(
iconData: Icons.account_balance_rounded,
label: AppLocalizations.of(context)!.recent,
),
LabelledIcon(
iconData: Icons.import_contacts_rounded,
label: AppLocalizations.of(context)!.library,
),
LabelledIcon(
iconData: Icons.explore_rounded,
label: AppLocalizations.of(context)!.discover,
),
];
void _animateToSubPage(int index, int duration) {
currentPageIndex = index;
pageController.animateToPage(
index,
duration: Duration(milliseconds: duration),
curve: Curves.ease,
);
}
Future<void> _loadNewDocument() async {
final picked = await FilePicker.platform.pickFiles(
dialogTitle: "Open a Document",
type: FileType.custom,
allowedExtensions: ["pdf", "txt"],
allowMultiple: false,
);
if (picked == null ||
picked.files.isEmpty ||
picked.files[0].extension == null) return;
final file = picked.files[0];
final preExisting = recentDocuments.values
.firstWhereOrNull((element) => element.uri == file.path!);
final document =
await ContributionPoint.getDocumentRegister(picked.files[0].extension!)!
.getDocument(picked.files[0]);
if (preExisting != null) {
recentDocuments.put(
recentDocuments.values.toList().indexOf(preExisting),
document,
);
}
_openDocument(
document,
fromRecentDocs: preExisting != null,
);
}
void _openDocument(Document doc, {bool fromRecentDocs = false}) {
logMain("Opening new document at ${doc.uri}.");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ViewerScreen(document: doc),
),
);
if (fromRecentDocs == false &&
recentDocuments.values
.firstWhereOrNull((element) => element.uri == doc.uri) ==
null) {
recentDocuments.add(doc);
} else {
setState(() {
doc.date = DateTime.now().toIso8601String();
lastOpened = doc;
});
}
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/home
|
mirrored_repositories/Literaturamo/lib/screens/home/views/library.dart
|
import 'package:flutter/material.dart';
import 'package:literaturamo/constants.dart';
class LibraryView extends StatefulWidget {
const LibraryView({Key? key}) : super(key: key);
@override
State<LibraryView> createState() => _LibraryViewState();
}
class _LibraryViewState extends State<LibraryView> {
@override
Widget build(BuildContext context) {
return const Center(
child: Text(
"$appTitle Library",
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/home
|
mirrored_repositories/Literaturamo/lib/screens/home/views/recents.dart
|
import 'package:google_fonts/google_fonts.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:flutter/material.dart';
import 'package:literaturamo/models/document.dart';
import 'package:literaturamo/screens/viewer/viewer_screen.dart';
import 'package:literaturamo/constants.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:literaturamo/screens/home/components/document_tile.dart';
class RecentsView extends StatefulWidget {
const RecentsView({Key? key}) : super(key: key);
@override
State<RecentsView> createState() => _RecentsViewState();
}
class _RecentsViewState extends State<RecentsView> {
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
padding: const EdgeInsets.fromLTRB(15, 10, 15, 3),
alignment: Alignment.topLeft,
child: Text(
AppLocalizations.of(context)!.recentlyOpened,
style: GoogleFonts.playfairDisplay(
fontSize: 20,
),
),
),
Expanded(
child: ValueListenableBuilder(
valueListenable: Hive.box<Document>(recentDocsBoxName).listenable(),
builder: (context, Box<Document> box, _) {
if (box.values.isEmpty) {
return const Center(child: Text("No Recent Docs"));
}
final orderedBox = box.values.toList();
orderedBox.sort((a, b) => Document.compare(a, b));
return ListView.builder(
itemCount: orderedBox.length,
itemBuilder: (context, listIndex) => RecentDocumentListTile(
document: orderedBox.elementAt(listIndex),
onTap: (doc) => _openDocument(doc),
),
);
},
),
),
],
);
}
void _openDocument(Document doc) {
logMain("Opening recent document ${doc.uri} at ${doc.lastReadPageNo}");
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ViewerScreen(
document: doc,
defaultPage: doc.lastReadPageNo ?? 0,
),
),
);
doc.date = DateTime.now().toIso8601String();
doc.save();
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/home
|
mirrored_repositories/Literaturamo/lib/screens/home/views/discover.dart
|
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/material.dart';
class DiscoverView extends StatefulWidget {
const DiscoverView({Key? key}) : super(key: key);
@override
State<DiscoverView> createState() => _DiscoverViewState();
}
class _DiscoverViewState extends State<DiscoverView> {
@override
Widget build(BuildContext context) {
return const Center(child: Text("Discover"));
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/home
|
mirrored_repositories/Literaturamo/lib/screens/home/components/sidebar.dart
|
import 'package:flutter/material.dart';
import 'package:literaturamo/constants.dart';
class HomeScreenSidebar extends StatelessWidget {
const HomeScreenSidebar({
super.key,
required this.desktopSidebarWidth,
required this.subpages,
required this.desktopPageChangeDuration,
required this.animateToSubPage,
});
final double desktopSidebarWidth;
final List<LabelledIcon> subpages;
final int desktopPageChangeDuration;
final void Function(int, int) animateToSubPage;
@override
Widget build(BuildContext context) {
return SizedBox(
width: desktopSidebarWidth,
child: Container(
color: Theme.of(context).bottomNavigationBarTheme.backgroundColor,
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 30, 0, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: subpages
.map(
(e) => TextButton.icon(
onPressed: () => animateToSubPage(
subpages.indexOf(e), desktopPageChangeDuration),
icon: Icon(
e.iconData,
color: Theme.of(context)
.bottomNavigationBarTheme
.selectedItemColor,
),
label: Text(
e.label,
style: Theme.of(context)
.bottomNavigationBarTheme
.selectedLabelStyle,
),
),
)
.toList(),
),
),
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/home
|
mirrored_repositories/Literaturamo/lib/screens/home/components/document_tile.dart
|
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:literaturamo/models/document.dart';
/// A stateless rectangular tile to display a recent document.
class RecentDocumentListTile extends StatelessWidget {
final Document document;
final void Function(Document doc) onTap;
const RecentDocumentListTile(
{Key? key, required this.document, required this.onTap})
: super(key: key);
@override
Widget build(BuildContext context) {
final openedAt = DateTime.parse(document.date);
final openedSince = DateTime.now().difference(openedAt);
final String formatStr;
final String leading;
if (openedSince.inDays <= 5) {
if (openedSince.inDays <= 2) {
leading = openedSince.inDays == 0 ? 'Today' : 'Yesterday';
} else {
leading = "${openedSince.inDays} days ago";
}
formatStr = "kk:mm";
} else {
leading = "";
formatStr = "yyyy-MM-dd โ kk:mm";
}
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Card(
color: Theme.of(context).dialogBackgroundColor,
child: ListTile(
onTap: () => onTap(document),
title: Text(
document.title.trim(),
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleMedium,
),
leading: Icon(
Icons.book_online_rounded,
color: Theme.of(context).iconTheme.color,
),
subtitle: Text(
"${document.totalPageNum} Pages",
style: Theme.of(context).textTheme.titleSmall,
),
trailing: Text(
"$leading ${DateFormat(formatStr).format(openedAt)}",
),
),
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo/lib/screens/home
|
mirrored_repositories/Literaturamo/lib/screens/home/components/lang_picker.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:literaturamo/constants.dart';
import 'package:provider/provider.dart';
class LocalProvider extends ChangeNotifier {
Locale _locale = Locale(Language.english.code);
Locale get locale => _locale;
void setLocale(Locale locale) {
if (!AppLocalizations.supportedLocales.contains(locale)) return;
_locale = locale;
notifyListeners();
}
void clearLocale() {
_locale = Locale(Language.english.code);
notifyListeners();
}
}
class LanguagePicker extends StatelessWidget {
const LanguagePicker({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final provider = Provider.of<LocalProvider>(context);
return DropdownButtonHideUnderline(
child: DropdownButton(
dropdownColor:
Theme.of(context).bottomNavigationBarTheme.backgroundColor,
value: provider.locale,
icon: Container(width: 12),
items: AppLocalizations.supportedLocales
.map(
(locale) => DropdownMenuItem(
value: locale,
child: Center(
child: Text(Language.fromCode(locale.languageCode)
?.code
.toUpperCase() ??
""),
),
onTap: () => provider.setLocale(locale),
),
)
.toList(),
onChanged: (_) {},
),
);
}
}
| 0
|
mirrored_repositories/Literaturamo
|
mirrored_repositories/Literaturamo/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:literaturamo/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/Flutter_Clock
|
mirrored_repositories/Flutter_Clock/lib/digital_clock.dart
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_clock_helper/model.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
enum _Element {
background,
text,
shadow,
}
final _lightTheme = {
_Element.background: Color(0xFF81B3FE),
_Element.text: Colors.white,
_Element.shadow: Colors.black,
};
final _darkTheme = {
_Element.background: Colors.black,
_Element.text: Colors.white,
_Element.shadow: Color(0xFF174EA6),
};
/// A basic digital clock.
///
/// You can do better than this!
class DigitalClock extends StatefulWidget {
const DigitalClock(this.model);
final ClockModel model;
@override
_DigitalClockState createState() => _DigitalClockState();
}
class _DigitalClockState extends State<DigitalClock> {
DateTime _dateTime = DateTime.now();
Timer _timer;
@override
void initState() {
super.initState();
widget.model.addListener(_updateModel);
_updateTime();
_updateModel();
}
@override
void didUpdateWidget(DigitalClock oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.model != oldWidget.model) {
oldWidget.model.removeListener(_updateModel);
widget.model.addListener(_updateModel);
}
}
@override
void dispose() {
_timer?.cancel();
widget.model.removeListener(_updateModel);
widget.model.dispose();
super.dispose();
}
void _updateModel() {
setState(() {
// Cause the clock to rebuild when the model changes.
});
}
void _updateTime() {
setState(() {
_dateTime = DateTime.now();
// Update once per minute. If you want to update every second, use the
// following code.
_timer = Timer(
Duration(minutes: 1) -
Duration(seconds: _dateTime.second) -
Duration(milliseconds: _dateTime.millisecond),
_updateTime,
);
// Update once per second, but make sure to do it at the beginning of each
// new second, so that the clock is accurate.
// _timer = Timer(
// Duration(seconds: 1) - Duration(milliseconds: _dateTime.millisecond),
// _updateTime,
// );
});
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft,
]);
}
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).brightness == Brightness.light
? _lightTheme
: _darkTheme;
final hour =
DateFormat(widget.model.is24HourFormat ? 'HH' : 'hh').format(_dateTime);
final minute = DateFormat('mm').format(_dateTime);
final defaultStyle = TextStyle(
color: colors[_Element.text],
fontFamily: 'PressStart2P',
);
return Container(
decoration: new BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
gradient: new LinearGradient(colors: [
Colors.red,
Colors.red[300],
Colors.red[200],
Colors.red[400],
Colors.red[300]
]),
border: Border.all(width: 36, color: Colors.white),
boxShadow: [
new BoxShadow(
color: Colors.grey[500],
blurRadius: 20.0,
spreadRadius: 1.0,
)
]),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"55ยฐ",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
fontWeight: FontWeight.w500),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
hour,
style: TextStyle(
color: Colors.white,
fontSize: 130.0,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 20.0,
),
Text(
":",
style: TextStyle(
color: Colors.white,
fontSize: 130.0,
fontWeight: FontWeight.bold),
),
SizedBox(
width: 20.0,
),
Text(
minute,
style: TextStyle(
color: Colors.white,
fontSize: 120.0,
fontWeight: FontWeight.bold),
)
],
),
Text(
"SAT,JAN 1",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
fontWeight: FontWeight.w500),
),
],
),
);
}
}
| 0
|
mirrored_repositories/Flutter_Clock
|
mirrored_repositories/Flutter_Clock/lib/main.dart
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:io';
import 'package:flutter_clock_helper/customizer.dart';
import 'package:flutter_clock_helper/model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'digital_clock.dart';
void main() {
// A temporary measure until Platform supports web and TargetPlatform supports
// macOS.
if (!kIsWeb && Platform.isMacOS) {
// TODO(gspencergoog): Update this when TargetPlatform includes macOS.
// https://github.com/flutter/flutter/issues/31366
// See https://github.com/flutter/flutter/wiki/Desktop-shells#target-platform-override.
debugDefaultTargetPlatformOverride = TargetPlatform.fuchsia;
}
// This creates a clock that enables you to customize it.
//
// The [ClockCustomizer] takes in a [ClockBuilder] that consists of:
// - A clock widget (in this case, [DigitalClock])
// - A model (provided to you by [ClockModel])
// For more information, see the flutter_clock_helper package.
//
// Your job is to edit [DigitalClock], or replace it with your
// own clock widget. (Look in digital_clock.dart for more details!)
runApp(ClockCustomizer((ClockModel model) => DigitalClock(model)));
}
| 0
|
mirrored_repositories/Flutter_Clock
|
mirrored_repositories/Flutter_Clock/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:digital_clock/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/mobile-app-barbershop-ui-preview
|
mirrored_repositories/mobile-app-barbershop-ui-preview/lib/main.dart
|
import 'dart:html';
void main() => Text("ะฅะพัะตัั ัะฒะธะดะตัั ะธัะบะพะดะฝัะน ะบะพะด? ะทะฐะฟัะพัะธ ั ะฐะฒัะพัะฐ");
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/example3_a.dart
|
// Avoid
void main() {
String? girlFriend = null;
if (girlFriend != null) {
String newGirlFriend = girlFriend;
}
}
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/example3_issue.dart
|
// Issue
void main() {
String? girlFriend = null;
String newGirlFriend = girlFriend!;
}
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/example1.dart
|
void main() {
setGirlFriend(null);
}
void setGirlFriend(String? girlFriend) {
if (girlFriend == null) return;
girlFriend.toUpperCase();
}
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/example3_c.dart
|
// Logical
void main() {
bool isSingle = true;
String? girlFriend = null;
if (!isSingle) {
String newGirlFriend = girlFriend!;
}
}
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/example3_b.dart
|
// Default Value
void main() {
String? girlFriend = null;
String newGirlFriend = girlFriend ?? 'Sarah Abs';
}
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/main.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
static final String title = 'Null Safety';
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: title,
theme: ThemeData(primarySwatch: Colors.blue),
home: MainPage(),
);
}
class MainPage extends StatefulWidget {
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
late String girlFriend;
@override
void initState() {
super.initState();
girlFriend = 'Sarah Abs';
}
@override
Widget build(BuildContext context) => Scaffold(
backgroundColor: Colors.indigoAccent.withOpacity(0.4),
appBar: AppBar(
title: Text(MyApp.title),
centerTitle: true,
),
body: Container(
padding: EdgeInsets.all(16),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
FlutterLogo(size: 150),
RichText(
textAlign: TextAlign.center,
text: TextSpan(
style: TextStyle(
fontSize: 36,
height: 1.3,
fontWeight: FontWeight.bold,
color: Colors.black,
),
children: [
TextSpan(
text: 'Null Safety\n',
style: TextStyle(
color: Colors.lightBlue.shade300,
fontWeight: FontWeight.w400,
height: 3,
),
),
TextSpan(
text: 'In 5 Minutes',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
),
),
);
}
| 0
|
mirrored_repositories/null_safety_ii_example
|
mirrored_repositories/null_safety_ii_example/lib/example2.dart
|
// โ Works: Pass String --> String?
// โ Works: Pass Not Nullable Variable to a Nullable Field
void main() {
String girlFriend = 'Sarah Abs';
String? newGirlFriend = girlFriend;
}
| 0
|
mirrored_repositories/GoogleFonts
|
mirrored_repositories/GoogleFonts/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:fonts/screens/HomePage.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
}
| 0
|
mirrored_repositories/GoogleFonts/lib
|
mirrored_repositories/GoogleFonts/lib/screens/HomePage.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
"Hello World",
style: GoogleFonts.pacifico(
textStyle: TextStyle(
color: Colors.blue,
fontSize: 35,
),
),
),
Text(
"Hello World",
style: GoogleFonts.lobster(
textStyle: TextStyle(
color: Colors.blue,
fontSize: 35,
),
),
),
Text(
"Hello World",
style: GoogleFonts.playfairDisplay(
textStyle: TextStyle(
color: Colors.blue,
fontSize: 35,
),
),
),
Text(
"Hello World",
style: GoogleFonts.combo(
textStyle: TextStyle(
color: Colors.blue,
fontSize: 35,
),
),
),
Text(
"Hello World",
style: GoogleFonts.aBeeZee(
textStyle: TextStyle(
color: Colors.blue,
fontSize: 35,
),
),
),
Text(
"Hello World",
style: GoogleFonts.comingSoon(
textStyle: TextStyle(
color: Colors.blue,
fontSize: 35,
),
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/GoogleFonts
|
mirrored_repositories/GoogleFonts/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:fonts/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/currency-convertor
|
mirrored_repositories/currency-convertor/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
void main() {
runApp(MaterialApp(home: Converter()));
}
class Converter extends StatefulWidget {
@override
_ConverterState createState() => _ConverterState();
}
class _ConverterState extends State<Converter> {
final fromTextController = TextEditingController();
List<String> currencies;
String fromCurrency = "USD";
String toCurrency = "INR";
String results;
@override
void initState() {
// TODO: implement initState
super.initState();
_loadCurrencies();
}
Future<String> _loadCurrencies() async {
String url = 'https://api.exchangeratesapi.io/latest?base=INR';
var response = await http.get(Uri.encodeFull(url));
var responseBody = jsonDecode(response.body); //response body is a map
//rates is a key in response body which is itself a map
Map curMap = responseBody['rates']; // map is exactly like a dictionary
currencies = curMap.keys.toList(); //currencies is a list which has all the map's keys as its elements :)
setState(() {
});
print(currencies);
return ("Syccess");
}
Future<String> _doConversion() async{
String uri = 'https://api.exchangeratesapi.io/latest?base=$fromCurrency&symbols=$toCurrency';
var response = await http.get(Uri.encodeFull(uri));
var responseBody = jsonDecode(response.body); //response body is a map
setState(() {
results = (double.parse(fromTextController.text) * (responseBody['rates'][toCurrency])).toString(); //making the input which was given in fromcontroller text to double and multiplying it by rate
});
print(results);
return "Success!";
}
_onFromChanged(String value) {
setState(() {
fromCurrency = value; //update value of fromcurrency and update the value of drop down button
});
}
_onToChanged(String value) {
setState(() {
toCurrency = value; //update value of TO_currency and update the value of drop down button
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green[600],
title: Text('Currency Converter'),
centerTitle: true,
),
body: currencies == null
? Center(child: CircularProgressIndicator())
: Container(
color: Colors.black,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
color: Colors.white,
elevation: 3.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
ListTile(
title: TextField(
controller: fromTextController,
keyboardType:
TextInputType.numberWithOptions(decimal: true),
),
trailing: _buildDropDownButton(fromCurrency),
),
IconButton(
icon: Icon(Icons.arrow_downward),
onPressed: () {
_doConversion();
},
),
ListTile(
title: Chip(
backgroundColor: Colors.white70,
label: results != null ?
Text(
results,
style: Theme.of(context).textTheme.headline4,
)
:Text(""),
),
trailing: _buildDropDownButton(toCurrency),
),
],
),
),
),
),
);
}
Widget _buildDropDownButton(String currencyCategory) {
return DropdownButton(
value: currencyCategory,
items: currencies.map((String value) => DropdownMenuItem(
value: value,
child: Row(
children: <Widget>[
Text(value),
],
),
))
.toList(),
onChanged: (String value) {
if(currencyCategory == fromCurrency) {
_onFromChanged(value);
}
else {
_onToChanged(value);
}
},
);
}
}
| 0
|
mirrored_repositories/currency-convertor
|
mirrored_repositories/currency-convertor/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:api1/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/Flutter-Task-App
|
mirrored_repositories/Flutter-Task-App/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:task_app/screens/home.dart';
void main() => runApp(App());
class App extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Task App',
theme: ThemeData(
primarySwatch: Colors.blue,
splashColor: Colors.transparent,
highlightColor: Colors.transparent),
home: Home(),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/heading.dart
|
import 'package:flutter/material.dart';
class Heading extends StatelessWidget {
final Text text;
final button;
Heading({Key key, @required this.button, @required this.text})
: super(key: key);
@override
Widget build(BuildContext context) {
return Container(
child: ListTile(
leading: text,
trailing: Container(
height: 40,
width: 40,
child: button,
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/project_card_tile.dart
|
import 'package:task_app/widgets/progress_indicator.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
class ProjectCardTile extends StatelessWidget {
final List title = [
"HathTech",
"Automotive Shop",
"HathTech Innovations",
];
final List colors = [Colors.blue, Colors.black, Colors.green];
@override
Widget build(BuildContext context) {
var rng = new math.Random.secure();
return Padding(
padding: EdgeInsets.only(left: 8.0, right: 8.0, top: 4.0, bottom: 4.0),
child: Card(
elevation: 1.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
child: Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8),
child: ListTile(
leading: Container(
child: Center(
child: Text(
title[rng.nextInt(3)].split(" ")[0][0],
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
fontSize: 24),
),
),
decoration: BoxDecoration(
borderRadius: new BorderRadius.circular(8.0),
color: colors[rng.nextInt(3)]),
width: 70.0,
height: 80.0,
),
title: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title[rng.nextInt(3)],
style: TextStyle(
color: Colors.black54,
fontWeight: FontWeight.w700,
fontSize: 18,
fontFamily: "SF"),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"${rng.nextInt(40)} tasks",
style: TextStyle(
color: Colors.blueAccent,
fontSize: 12,
fontWeight: FontWeight.bold),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
Text(
"${rng.nextInt(10)} members",
style: TextStyle(
fontSize: 12,
color: Colors.grey,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
SizedBox(
height: 10,
),
FAProgressBar(
size: 4,
currentValue: 75,
progressColor: Colors.green,
backgroundColor: Color(0xffF0F0F0),
),
SizedBox(
height: 2,
),
],
),
),
),
));
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/progress_indicator.dart
|
import 'package:flutter/animation.dart';
import 'package:flutter/widgets.dart';
class FAProgressBar extends StatefulWidget {
FAProgressBar(
{Key key,
this.currentValue = 0,
this.maxValue = 100,
this.size = 12,
this.animatedDuration = const Duration(milliseconds: 300),
this.direction = Axis.horizontal,
this.verticalDirection = VerticalDirection.down,
this.borderRadius = 12,
this.backgroundColor = const Color(0x00FFFFFF),
this.progressColor = const Color(0xFFFA7268),
this.changeColorValue,
this.changeProgressColor = const Color(0xFF5F4B8B),
this.displayText})
: super(key: key);
final int currentValue;
final int maxValue;
final double size;
final Duration animatedDuration;
final Axis direction;
final VerticalDirection verticalDirection;
final double borderRadius;
final Color backgroundColor;
final Color progressColor;
final int changeColorValue;
final Color changeProgressColor;
final String displayText;
@override
_FAProgressBarState createState() => _FAProgressBarState();
}
class _FAProgressBarState extends State<FAProgressBar>
with SingleTickerProviderStateMixin {
Animation<double> _animation;
AnimationController _controller;
double _currentBegin = 0;
double _currentEnd = 0;
@override
void initState() {
_controller =
AnimationController(duration: widget.animatedDuration, vsync: this);
_animation = Tween<double>(begin: _currentBegin, end: _currentEnd)
.animate(_controller);
triggerAnimation();
super.initState();
}
@override
void didUpdateWidget(FAProgressBar old) {
triggerAnimation();
super.didUpdateWidget(old);
}
void triggerAnimation() {
setState(() {
_currentBegin = _animation.value;
_currentEnd = widget.currentValue / widget.maxValue;
_animation = Tween<double>(begin: _currentBegin, end: _currentEnd)
.animate(_controller);
});
_controller.reset();
_controller.forward();
}
@override
Widget build(BuildContext context) => AnimatedProgressBar(
animation: _animation,
widget: widget,
);
@override
void dispose() {
_controller.dispose();
super.dispose();
}
}
class AnimatedProgressBar extends AnimatedWidget {
AnimatedProgressBar({
Key key,
Animation<double> animation,
this.widget,
}) : super(key: key, listenable: animation);
final widget;
double transformValue(x, begin, end, before) {
double y = (end * x - (begin - before)) * (1 / before);
return y < 0 ? 0 : ((y > 1) ? 1 : y);
}
Widget build(BuildContext context) {
final Animation<double> animation = listenable;
Color progressColor = widget.progressColor;
if (widget.changeColorValue != null) {
final _colorTween = ColorTween(
begin: widget.progressColor, end: widget.changeProgressColor);
progressColor = _colorTween.transform(transformValue(
animation.value, widget.changeColorValue, widget.maxValue, 5));
}
List<Widget> progressWidgets = [];
Widget progressWidget = new Container(
decoration: BoxDecoration(
color: progressColor,
borderRadius: BorderRadius.circular(widget.borderRadius),
));
progressWidgets.add(progressWidget);
if (widget.displayText != null) {
Widget textProgress = new Container(
alignment: widget.direction == Axis.horizontal
? FractionalOffset(0.95, 0.5)
: (widget.verticalDirection == VerticalDirection.up
? FractionalOffset(0.5, 0.05)
: FractionalOffset(0.5, 0.95)),
child: Text(
(animation.value * widget.maxValue).toInt().toString() +
widget.displayText,
softWrap: false,
style: TextStyle(color: const Color(0xFFFFFFFF), fontSize: 8)));
progressWidgets.add(textProgress);
}
return Directionality(
textDirection: TextDirection.ltr,
child: Container(
width: widget.direction == Axis.vertical ? widget.size : null,
height: widget.direction == Axis.horizontal ? widget.size : null,
decoration: BoxDecoration(
color: widget.backgroundColor,
borderRadius: BorderRadius.circular(widget.borderRadius),
border: Border.all(color: widget.progressColor, width: 0.2),
),
child: Flex(
direction: widget.direction,
verticalDirection: widget.verticalDirection,
children: <Widget>[
Expanded(
flex: (animation.value * 100).toInt(),
child: Stack(children: progressWidgets)),
Expanded(
flex: 100 - (animation.value * 100).toInt(), child: Container())
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/project_card.dart
|
import 'package:task_app/widgets/progress_indicator.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
class ProjectCard extends StatelessWidget {
final List colors = [Colors.redAccent, Colors.blue, Colors.green];
@override
Widget build(BuildContext context) {
var rng = new math.Random.secure();
return Padding(
padding: EdgeInsets.only(top: 8.0, bottom: 8.0, right: 16),
child: Card(
color: colors[rng.nextInt(3)],
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
elevation: 0.0,
child: Container(
padding: EdgeInsets.all(32.0),
height: MediaQuery.of(context).size.height * 0.3,
// width: 260,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"Branding Studio",
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 10,
),
Expanded(
child: Text(
"Homepage design",
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w700,
fontSize: 24,
),
),
),
SizedBox(
height: 10,
),
Text(
"43%",
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w900),
),
SizedBox(
height: 4,
),
FAProgressBar(
size: 4,
borderRadius: 2,
currentValue: 43,
progressColor: Colors.blueAccent,
backgroundColor: Color(0xffF0F0F0),
),
SizedBox(
height: 2,
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/filter.dart
|
import "package:flutter/material.dart";
class FiltersWidget extends StatefulWidget {
FiltersWidget({Key key, @required this.updateFilter}) : super(key: key);
final Function updateFilter;
@override
State<StatefulWidget> createState() {
return FiltersWidgetState();
}
}
class FiltersWidgetState extends State<FiltersWidget> {
Widget _buildBadge(title) {
return Padding(
padding: const EdgeInsets.only(left: 8.0),
child: GestureDetector(
onTap: () {
selectedFilter = title.toLowerCase();
widget.updateFilter(title.toLowerCase());
},
child: RawChip(
padding: EdgeInsets.all(16),
label: Text(
title,
style: TextStyle(
fontFamily: "Montserrat", fontWeight: FontWeight.bold),
),
labelStyle: TextStyle(
color: selectedFilter == title.toLowerCase()
? Colors.white
: Colors.black,
fontSize: 14.0),
backgroundColor: selectedFilter == title.toLowerCase()
? Colors.redAccent
: Colors.grey[300],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(8.0),
),
),
),
),
);
}
String selectedFilter = "all";
final List filters = [
"All",
"Open",
"Closed",
"Expired",
];
@override
Widget build(BuildContext context) {
return Container(
height: 60.0,
padding: EdgeInsets.only(left: 8.0, top: 8, bottom: 8),
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: filters.length,
itemBuilder: (BuildContext context, int index) {
return _buildBadge(filters[index]);
},
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/carousel_slider.dart
|
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CarouselSlider extends StatefulWidget {
CarouselSlider(
{@required this.items,
this.height,
this.aspectRatio: 16 / 9,
this.viewportFraction: 0.8,
this.initialPage: 0,
int realPage: 10000,
this.enableInfiniteScroll: true,
this.reverse: false,
this.autoPlay: false,
this.autoPlayInterval: const Duration(seconds: 4),
this.autoPlayAnimationDuration = const Duration(milliseconds: 800),
this.autoPlayCurve: Curves.fastOutSlowIn,
this.pauseAutoPlayOnTouch,
this.enlargeCenterPage = false,
this.onPageChanged,
this.scrollPhysics,
this.scrollDirection: Axis.horizontal})
: this.realPage =
enableInfiniteScroll ? realPage + initialPage : initialPage,
this.pageController = PageController(
viewportFraction: viewportFraction,
initialPage:
enableInfiniteScroll ? realPage + initialPage : initialPage,
);
/// The widgets to be shown in the carousel.
final List<Widget> items;
/// Set carousel height and overrides any existing [aspectRatio].
final double height;
/// Aspect ratio is used if no height have been declared.
///
/// Defaults to 16:9 aspect ratio.
final double aspectRatio;
/// The fraction of the viewport that each page should occupy.
///
/// Defaults to 0.8, which means each page fills 80% of the carousel.
final num viewportFraction;
/// The initial page to show when first creating the [CarouselSlider].
///
/// Defaults to 0.
final num initialPage;
/// The actual index of the [PageView].
///
/// This value can be ignored unless you know the carousel will be scrolled
/// backwards more then 10000 pages.
/// Defaults to 10000 to simulate infinite backwards scrolling.
final num realPage;
///Determines if carousel should loop infinitely or be limited to item length.
///
///Defaults to true, i.e. infinite loop.
final bool enableInfiniteScroll;
/// Reverse the order of items if set to true.
///
/// Defaults to false.
final bool reverse;
/// Enables auto play, sliding one page at a time.
///
/// Use [autoPlayInterval] to determent the frequency of slides.
/// Defaults to false.
final bool autoPlay;
/// Sets Duration to determent the frequency of slides when
///
/// [autoPlay] is set to true.
/// Defaults to 4 seconds.
final Duration autoPlayInterval;
/// The animation duration between two transitioning pages while in auto playback.
///
/// Defaults to 800 ms.
final Duration autoPlayAnimationDuration;
/// Determines the animation curve physics.
///
/// Defaults to [Curves.fastOutSlowIn].
final Curve autoPlayCurve;
/// Sets a timer on touch detected that pause the auto play with
/// the given [Duration].
///
/// Touch Detection is only active if [autoPlay] is true.
final Duration pauseAutoPlayOnTouch;
/// Determines if current page should be larger then the side images,
/// creating a feeling of depth in the carousel.
///
/// Defaults to false.
final bool enlargeCenterPage;
/// The axis along which the page view scrolls.
///
/// Defaults to [Axis.horizontal].
final Axis scrollDirection;
/// Called whenever the page in the center of the viewport changes.
final Function(int index) onPageChanged;
/// How the carousel should respond to user input.
///
/// For example, determines how the items continues to animate after the
/// user stops dragging the page view.
///
/// The physics are modified to snap to page boundaries using
/// [PageScrollPhysics] prior to being used.
///
/// Defaults to matching platform conventions.
final ScrollPhysics scrollPhysics;
/// [pageController] is created using the properties passed to the constructor
/// and can be used to control the [PageView] it is passed to.
final PageController pageController;
/// Animates the controlled [CarouselSlider] to the next page.
///
/// The animation lasts for the given duration and follows the given curve.
/// The returned [Future] resolves when the animation completes.
Future<void> nextPage({Duration duration, Curve curve}) {
return pageController.nextPage(duration: duration, curve: curve);
}
/// Animates the controlled [CarouselSlider] to the previous page.
///
/// The animation lasts for the given duration and follows the given curve.
/// The returned [Future] resolves when the animation completes.
Future<void> previousPage({Duration duration, Curve curve}) {
return pageController.previousPage(duration: duration, curve: curve);
}
/// Changes which page is displayed in the controlled [CarouselSlider].
///
/// Jumps the page position from its current value to the given value,
/// without animation, and without checking if the new value is in range.
void jumpToPage(int page) {
final index =
_getRealIndex(pageController.page.toInt(), realPage, items.length);
return pageController
.jumpToPage(pageController.page.toInt() + page - index);
}
/// Animates the controlled [CarouselSlider] from the current page to the given page.
///
/// The animation lasts for the given duration and follows the given curve.
/// The returned [Future] resolves when the animation completes.
Future<void> animateToPage(int page, {Duration duration, Curve curve}) {
final index =
_getRealIndex(pageController.page.toInt(), realPage, items.length);
return pageController.animateToPage(
pageController.page.toInt() + page - index,
duration: duration,
curve: curve);
}
@override
_CarouselSliderState createState() => _CarouselSliderState();
}
class _CarouselSliderState extends State<CarouselSlider>
with TickerProviderStateMixin {
Timer timer;
@override
void initState() {
super.initState();
timer = getTimer();
}
Timer getTimer() {
return Timer.periodic(widget.autoPlayInterval, (_) {
if (widget.autoPlay) {
widget.pageController.nextPage(
duration: widget.autoPlayAnimationDuration,
curve: widget.autoPlayCurve);
}
});
}
void pauseOnTouch() {
timer.cancel();
timer = Timer(widget.pauseAutoPlayOnTouch, () {
timer = getTimer();
});
}
Widget getWrapper(Widget child) {
if (widget.height != null) {
final Widget wrapper = Container(height: widget.height, child: child);
return widget.autoPlay && widget.pauseAutoPlayOnTouch != null
? addGestureDetection(wrapper)
: wrapper;
} else {
final Widget wrapper =
AspectRatio(aspectRatio: widget.aspectRatio, child: child);
return widget.autoPlay && widget.pauseAutoPlayOnTouch != null
? addGestureDetection(wrapper)
: wrapper;
}
}
Widget addGestureDetection(Widget child) =>
GestureDetector(onPanDown: (_) => pauseOnTouch(), child: child);
@override
void dispose() {
super.dispose();
timer?.cancel();
}
@override
Widget build(BuildContext context) {
return getWrapper(PageView.builder(
physics: widget.scrollPhysics,
scrollDirection: widget.scrollDirection,
controller: widget.pageController,
reverse: widget.reverse,
itemCount: widget.enableInfiniteScroll ? null : widget.items.length,
onPageChanged: (int index) {
int currentPage = _getRealIndex(
index + widget.initialPage, widget.realPage, widget.items.length);
if (widget.onPageChanged != null) {
widget.onPageChanged(currentPage);
}
},
itemBuilder: (BuildContext context, int i) {
final int index = _getRealIndex(
i + widget.initialPage, widget.realPage, widget.items.length);
return AnimatedBuilder(
animation: widget.pageController,
child: widget.items[index],
builder: (BuildContext context, child) {
// on the first render, the pageController.page is null,
// this is a dirty hack
if (widget.pageController.position.minScrollExtent == null ||
widget.pageController.position.maxScrollExtent == null) {
Future.delayed(Duration(microseconds: 1), () {
setState(() {});
});
return Container();
}
double value = widget.pageController.page - i;
value = (1 - (value.abs() * 0.3)).clamp(0.0, 1.0);
final double height = widget.height ??
MediaQuery.of(context).size.width * (1 / widget.aspectRatio);
final double distortionValue = widget.enlargeCenterPage
? Curves.easeOut.transform(value)
: 1.0;
if (widget.scrollDirection == Axis.horizontal) {
return Center(
child:
SizedBox(height: distortionValue * height, child: child));
} else {
return Center(
child: SizedBox(
width:
distortionValue * MediaQuery.of(context).size.width,
child: child));
}
},
);
},
));
}
}
/// Converts an index of a set size to the corresponding index of a collection of another size
/// as if they were circular.
///
/// Takes a [position] from collection Foo, a [base] from where Foo's index originated
/// and the [length] of a second collection Baa, for which the correlating index is sought.
///
/// For example; We have a Carousel of 10000(simulating infinity) but only 6 images.
/// We need to repeat the images to give the illusion of a never ending stream.
/// By calling _getRealIndex with position and base we get an offset.
/// This offset modulo our length, 6, will return a number between 0 and 5, which represent the image
/// to be placed in the given position.
int _getRealIndex(int position, int base, int length) {
final int offset = position - base;
return _remainder(offset, length);
}
/// Returns the remainder of the modulo operation [input] % [source], and adjust it for
/// negative values.
int _remainder(int input, int source) {
final int result = input % source;
return result < 0 ? source + result : result;
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/project_detail_card.dart
|
import 'package:task_app/widgets/progress_indicator.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
class ProjectDetailCard extends StatelessWidget {
final List title = [
"HathTech",
"Automotive Shop",
"HathTech Innovations",
];
final List colors = [Colors.blue, Colors.black, Colors.green];
@override
Widget build(BuildContext context) {
var rng = new math.Random.secure();
return Padding(
padding: EdgeInsets.only(left: 8.0, right: 8.0, top: 4.0, bottom: 4.0),
child: Card(
elevation: 1.0,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),
child: Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 8),
child: ListTile(
leading: Container(
child: Center(
child: Text(
title[rng.nextInt(3)].split(" ")[0][0],
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
fontSize: 24),
),
),
decoration: BoxDecoration(
borderRadius: new BorderRadius.circular(8.0),
color: colors[rng.nextInt(3)]),
width: 70.0,
height: 80.0,
),
title: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
title[rng.nextInt(3)],
style: TextStyle(
color: Colors.black54,
fontWeight: FontWeight.w700,
fontSize: 18,
fontFamily: "SF"),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
"${rng.nextInt(40)} tasks",
style: TextStyle(
color: Colors.blueAccent,
fontSize: 12,
fontWeight: FontWeight.bold),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
SizedBox(
width: 8,
),
Container(
width: 2.0,
color: Colors.orange.withOpacity(0.3),
height: 15,
),
SizedBox(
width: 8,
),
Text(
"${rng.nextInt(30)} sep 19",
style: TextStyle(
fontSize: 12,
color: Colors.red,
),
),
],
),
SizedBox(
height: 18,
),
Text(
"Members",
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: Colors.grey[500],
),
),
Container(
width: MediaQuery.of(context).size.width * 0.7,
child: Row(
children: <Widget>[
Container(
decoration: BoxDecoration(
borderRadius: new BorderRadius.circular(8.0),
image: DecorationImage(
image: AssetImage("assets/user.jpeg"))),
width: 40.0,
height: 40.0,
),
Container(
margin: EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: new BorderRadius.circular(8.0),
image: DecorationImage(
image: AssetImage("assets/user.jpeg"))),
width: 40.0,
height: 40.0,
),
Container(
margin: EdgeInsets.all(8),
decoration: BoxDecoration(
borderRadius: new BorderRadius.circular(8.0),
image: DecorationImage(
image: AssetImage("assets/user.jpeg"))),
width: 40.0,
height: 40.0,
),
],
),
),
SizedBox(
height: 14,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"Progress",
style: TextStyle(
color: Colors.grey[500],
fontSize: 12,
fontWeight: FontWeight.bold),
),
Text(
"43%",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 12,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
SizedBox(
height: 12,
),
FAProgressBar(
size: 4,
currentValue: 75,
progressColor: Colors.green,
backgroundColor: Color(0xffF0F0F0),
),
SizedBox(
height: 2,
),
],
),
),
),
));
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/bottom_nav.dart
|
import "package:flutter/material.dart";
class CustomBottomNav extends StatefulWidget {
final Function updateIndex;
CustomBottomNav(this.updateIndex);
@override
State<StatefulWidget> createState() {
return _CustomBottomNav();
}
}
class _CustomBottomNav extends State<CustomBottomNav> {
int _selectedIndex = 0;
@override
Widget build(BuildContext context) {
double myHeight = 80.0;
return Material(
elevation: 24.0,
color: Color(0xff17181a),
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(8.0),
),
child: Container(
height: myHeight,
width: double.infinity,
margin: EdgeInsets.only(top: 0.0, bottom: 2.0),
child: Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 32.0),
child: Container(
height: myHeight,
width: MediaQuery.of(context).size.width * 0.2,
child: Row(
children: <Widget>[
Icon(
Icons.wrap_text,
size: 32,
color: Colors.white,
),
SizedBox(
width: 24,
),
Container(
width: 2.0,
color: Colors.orange.withOpacity(0.3),
height: 30,
),
],
),
),
),
Container(
width: MediaQuery.of(context).size.width * 0.53,
child: TabBar(
tabs: [
Tab(
icon: Icon(
Icons.home,
size: 28.0,
),
),
Tab(
icon: Icon(
Icons.list,
size: 28.0,
),
),
Tab(
icon: Icon(
Icons.search,
size: 28.0,
),
),
],
onTap: (int index) {
setState(() {
_selectedIndex = index;
});
widget.updateIndex(index);
},
indicatorColor: Colors.transparent,
indicatorSize: TabBarIndicatorSize.label,
labelColor: Colors.orange.withOpacity(0.8),
unselectedLabelColor: Colors.white,
),
),
SizedBox(
width: 6,
),
Container(
width: 65,
height: 55,
child: RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(8.0),
),
color: Color(0xff1e43f9),
child: Icon(
Icons.add,
color: Colors.white,
),
onPressed: () {},
),
)
],
)),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/projects_slider.dart
|
import 'package:flutter/material.dart';
import 'package:task_app/widgets/project_card.dart';
import 'carousel_slider.dart';
class ProjectSlider extends StatefulWidget {
ProjectSlider({@required this.projects}) : super();
final List projects;
@override
_ProjectSliderState createState() => _ProjectSliderState();
}
class _ProjectSliderState extends State<ProjectSlider> {
int _current = 0;
buildList(context, store) {
return ProjectCard();
}
buildIndicator(context, index, project, demoSlider) {
return GestureDetector(
onTap: () {
setState(() {
demoSlider.jumpToPage(index);
});
},
child: Container(
width: 6.0,
height: 6.0,
margin: EdgeInsets.symmetric(vertical: 24.0, horizontal: 3.0),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
borderRadius: BorderRadius.all(Radius.circular(8.0)),
color: _current == index
? Colors.black
: Colors.grey.withOpacity(0.8)),
),
);
}
Widget sliderDemo() {
final demoSlider = CarouselSlider(
aspectRatio: 2.0,
enableInfiniteScroll: true,
viewportFraction: 0.7,
scrollPhysics: BouncingScrollPhysics(),
height: MediaQuery.of(context).size.height * 0.3,
items: widget.projects
.map<Widget>((project) => buildList(context, project))
.toList(),
autoPlay: true,
enlargeCenterPage: true,
onPageChanged: (index) {
setState(() {
_current = index;
});
},
);
return Column(children: [
demoSlider,
Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: widget.projects
.map<Widget>((store) => buildIndicator(
context, widget.projects.indexOf(store), store, demoSlider))
.toList()),
),
]);
}
@override
Widget build(BuildContext context) {
return sliderDemo();
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/widgets/dashed_rect.dart
|
import 'package:flutter/material.dart';
import 'package:path_drawing/path_drawing.dart';
/// Add a dotted border around any [child] widget. The [strokeWidth] property
/// defines the width of the dashed border and [color] determines the stroke
/// paint color. [CircularIntervalList] is populated with the [dashPattern] to
/// render the appropriate pattern. The [radius] property is taken into account
/// only if the [borderType] is [BorderType.RRect]. A [customPath] can be passed in
/// as a parameter if you want to draw a custom shaped border.
class DottedBorder extends StatelessWidget {
final Widget child;
final EdgeInsets padding;
final double strokeWidth;
final Color color;
final List<double> dashPattern;
final BorderType borderType;
final Radius radius;
final Path customPath;
DottedBorder({
@required this.child,
this.color = Colors.black,
this.strokeWidth = 1,
this.borderType = BorderType.Rect,
this.dashPattern = const <double>[3, 1],
this.padding = const EdgeInsets.all(2),
this.radius = const Radius.circular(0),
this.customPath,
}) {
assert(child != null);
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Positioned.fill(
child: CustomPaint(
painter: _DashPainter(
strokeWidth: strokeWidth,
radius: radius,
color: color,
borderType: borderType,
dashPattern: dashPattern,
customPath: customPath,
),
),
),
Padding(
padding: padding,
child: child,
),
],
);
}
}
enum BorderType { Circle, RRect, Rect, Oval }
class _DashPainter extends CustomPainter {
final double strokeWidth;
final List<double> dashPattern;
final Color color;
final BorderType borderType;
final Radius radius;
final Path customPath;
_DashPainter({
this.strokeWidth = 2,
this.dashPattern = const <double>[3, 1],
this.color = Colors.black,
this.borderType = BorderType.Rect,
this.radius = const Radius.circular(0),
this.customPath,
}) {
assert(dashPattern.isNotEmpty, 'Dash Pattern cannot be empty');
}
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..strokeWidth = strokeWidth
..color = color
..style = PaintingStyle.stroke;
Path _path;
if (customPath != null) {
_path =
dashPath(customPath, dashArray: CircularIntervalList(dashPattern));
} else {
_path = _getPath(size);
}
canvas.drawPath(_path, paint);
}
Path _getPath(Size size) {
Path path;
switch (borderType) {
case BorderType.Circle:
path = _getCirclePath(size);
break;
case BorderType.RRect:
path = _getRRectPath(size, radius);
break;
case BorderType.Rect:
path = _getRectPath(size);
break;
case BorderType.Oval:
path = _getOvalPath(size);
break;
}
return dashPath(path, dashArray: CircularIntervalList(dashPattern));
}
Path _getCirclePath(Size size) {
double w = size.width;
double h = size.height;
double s = size.shortestSide;
return Path()
..addRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(
w > s ? (w - s) / 2 : 0,
h > s ? (h - s / 2) : 0,
s,
s,
),
Radius.circular(s / 2),
),
);
}
Path _getRRectPath(Size size, Radius radius) {
return Path()
..addRRect(
RRect.fromRectAndRadius(
Rect.fromLTWH(
0,
0,
size.width,
size.height,
),
radius,
),
);
}
Path _getRectPath(Size size) {
return Path()
..addRect(
Rect.fromLTWH(
0,
0,
size.width,
size.height,
),
);
}
Path _getOvalPath(Size size) {
return Path()
..addOval(
Rect.fromLTWH(
0,
0,
size.width,
size.height,
),
);
}
@override
bool shouldRepaint(_DashPainter oldDelegate) {
return oldDelegate.strokeWidth != this.strokeWidth ||
oldDelegate.color != this.color ||
oldDelegate.dashPattern != this.dashPattern ||
oldDelegate.borderType != this.borderType;
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/screens/dashboad.dart
|
import 'package:flutter/material.dart';
import 'package:task_app/widgets/dashed_rect.dart';
import 'package:task_app/widgets/heading.dart';
import 'package:task_app/widgets/project_card_tile.dart';
import 'package:task_app/widgets/projects_slider.dart';
class Dashboard extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: ConstrainedBox(
constraints:
BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(children: [
SizedBox(
height: 22,
),
Heading(
text: Text(
"Today's tasks",
style: TextStyle(fontSize: 32, fontWeight: FontWeight.w600),
),
button: DottedBorder(
borderType: BorderType.RRect,
radius: Radius.circular(8),
color: Colors.grey,
child: Center(
child: Icon(
Icons.navigate_next,
size: 28,
color: Colors.orange,
),
),
strokeWidth: 1,
dashPattern: [3, 4]),
),
SizedBox(
height: 22,
),
ProjectSlider(
projects: [1, 2, 3, 4, 5],
),
SizedBox(
height: 12,
),
Heading(
text: Text(
"Open projects",
style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600),
),
button: DottedBorder(
borderType: BorderType.RRect,
radius: Radius.circular(8),
color: Colors.grey,
child: Center(
child: Icon(
Icons.navigate_next,
size: 28,
color: Colors.orange,
),
),
strokeWidth: 1,
dashPattern: [3, 4]),
),
SizedBox(
height: 12.0,
),
Container(
child: ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: 5,
itemBuilder: (BuildContext context, int index) {
return ProjectCardTile();
},
),
)
]),
),
);
},
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/screens/projects.dart
|
import 'package:flutter/material.dart';
import 'package:task_app/widgets/dashed_rect.dart';
import 'package:task_app/widgets/filter.dart';
import 'package:task_app/widgets/heading.dart';
import 'package:task_app/widgets/project_card_tile.dart';
import 'package:task_app/widgets/project_detail_card.dart';
class Projects extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
scrollDirection: Axis.vertical,
child: ConstrainedBox(
constraints:
BoxConstraints(minHeight: viewportConstraints.maxHeight),
child: Column(children: [
SizedBox(
height: 22,
),
Heading(
text: Text(
"My projects",
style: TextStyle(fontSize: 32, fontWeight: FontWeight.w600),
),
button: DottedBorder(
borderType: BorderType.RRect,
radius: Radius.circular(8),
color: Colors.grey,
child: Center(
child: Icon(
Icons.filter_list,
size: 28,
color: Colors.orange,
),
),
strokeWidth: 1,
dashPattern: [3, 4]),
),
SizedBox(
height: 12,
),
FiltersWidget(
updateFilter: () {},
),
SizedBox(
height: 12,
),
Heading(
text: Text(
"You have 11 projects",
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
color: Colors.grey[500]),
),
button: SizedBox(),
),
Container(
child: ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemCount: 5,
itemBuilder: (BuildContext context, int index) {
return ProjectDetailCard();
},
),
)
]),
),
);
},
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App/lib
|
mirrored_repositories/Flutter-Task-App/lib/screens/home.dart
|
import 'package:flutter/material.dart';
import 'package:task_app/screens/dashboad.dart';
import 'package:task_app/screens/projects.dart';
import 'package:task_app/widgets/bottom_nav.dart';
class Home extends StatefulWidget {
const Home({Key key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return HomeState();
}
}
class HomeState extends State<Home> {
int selectedIndex = 0;
updateIndex(index) {
print(index);
setState(() {
selectedIndex = index;
});
}
Widget accountTab() {
return Container(
padding: EdgeInsets.only(top: 32, left: 8.0, right: 6.0),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[],
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 0.0,
automaticallyImplyLeading: true,
backgroundColor: Color(0xfff0f0f0),
centerTitle: false,
title: Padding(
padding: const EdgeInsets.only(left: 6.0, top: 5.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Text(
selectedIndex == 0 ? 'Dashboard' : 'Projects',
style: new TextStyle(
color: Colors.black87,
fontFamily: 'Montserrat',
fontWeight: FontWeight.bold,
fontSize: 23.0),
),
new Text(
'CoreTeam',
style: new TextStyle(color: Colors.grey, fontSize: 16.0),
),
],
),
),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 18.0, top: 8.0),
child: Container(
decoration: BoxDecoration(
borderRadius: new BorderRadius.circular(8.0),
image:
DecorationImage(image: AssetImage("assets/user.jpeg"))),
width: 40.0,
height: 40.0,
),
),
],
), //AppBar ,
body: DefaultTabController(
initialIndex: 0,
length: 3,
child: Scaffold(
//AppBar ,
body:
TabBarView(physics: NeverScrollableScrollPhysics(), children: [
Dashboard(),
Projects(),
accountTab(),
]),
bottomNavigationBar: Padding(
padding: const EdgeInsets.only(bottom: 0.0),
child: CustomBottomNav(updateIndex),
),
backgroundColor: Color(0xfff0f0f0),
)),
);
}
}
| 0
|
mirrored_repositories/Flutter-Task-App
|
mirrored_repositories/Flutter-Task-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 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:task_app/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(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/flip_flutter
|
mirrored_repositories/flip_flutter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flip_flutter/splashwidget.dart';
import 'package:pigment/pigment.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
// This widget is the root of your application.
@override
MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp>{
ThemeData _appTheme = new ThemeData(
primarySwatch: Colors.amber,
primaryColor: Colors.amber.shade700,
accentColor: Colors.amberAccent.shade400,
brightness: Brightness.light,
scaffoldBackgroundColor: Pigment.fromString("#FAFAFA"),
dialogBackgroundColor: Pigment.fromString("#FFFFFF"),
bottomAppBarColor: Pigment.fromString("#FAFAFA"),
dividerColor: Pigment.fromString("#0000000F"),
);
initPrefs() async{
bool useDarkTheme = false;
SharedPreferences.getInstance().then((SharedPreferences value) {
if (value.getBool("use_dark_theme") == null){
useDarkTheme = false;
} else if (value.getBool("use_dark_theme") == null){
useDarkTheme = false;
} else{
useDarkTheme = value.getBool("use_dark_theme");
}
updateTheme(useDarkTheme);
});
}
void updateTheme(bool isDark) {
setState(() {
if (isDark == true){ //use the Dark theme
_appTheme = new ThemeData(
primarySwatch: Colors.amber,
primaryColor: Colors.amber.shade700,
accentColor: Colors.amberAccent.shade400,
brightness: Brightness.dark,
scaffoldBackgroundColor: Pigment.fromString("#212121"),
dialogBackgroundColor: Pigment.fromString("#303030"),
bottomAppBarColor: Pigment.fromString("#212121"),
dividerColor: Pigment.fromString("#FFFFFF0F"),
);
} else { //use the default Light theme
_appTheme = new ThemeData(
primarySwatch: Colors.amber,
primaryColor: Colors.amber.shade700,
accentColor: Colors.amberAccent.shade400,
brightness: Brightness.light,
scaffoldBackgroundColor: Pigment.fromString("#FAFAFA"),
dialogBackgroundColor: Pigment.fromString("#FFFFFF"),
bottomAppBarColor: Pigment.fromString("#FAFAFA"),
dividerColor: Pigment.fromString("#0000000F"),
);
}
});
}
@override
void initState() {
super.initState();
initPrefs();
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flip',
theme: _appTheme,
home: new MyHomePage(title: 'Flip'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
enum AppMode{ die, coin, list, ndie}
class _MyHomePageState extends State<MyHomePage>
with TickerProviderStateMixin {
AppMode index = AppMode.die;
double appbarElevationScale = 0.0;
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: new Text(widget.title, style: Theme.of(context).textTheme.title,),
backgroundColor: Theme.of(context).scaffoldBackgroundColor,
elevation: appbarElevationScale * 4,
actions: <Widget>[
new IconButton(icon: new Icon(Icons.settings, color: Theme.of(context).textTheme.title.color,), tooltip: 'Settings', onPressed: (){
Navigator.push(
context,
new MaterialPageRoute(builder: (BuildContext context) => new SettingsPage())
);
}),
],
),
bottomNavigationBar: new BottomAppBar(
elevation: appbarElevationScale * 8,
hasNotch: false,
color: Theme.of(context).bottomAppBarColor,
child: new BottomNavigationBar(
type: BottomNavigationBarType.fixed,
items: <BottomNavigationBarItem>[
const BottomNavigationBarItem(icon: const Icon(Icons.casino), title: const Text('Dice'),),
const BottomNavigationBarItem(icon: const Icon(Icons.account_circle), title: const Text('Coin')),
const BottomNavigationBarItem(icon: const Icon(Icons.format_list_bulleted), title: const Text('List')),
const BottomNavigationBarItem(icon: const Icon(Icons.assistant), title: const Text('Custom dice')),
], currentIndex: index.index, onTap: (int index) {
switch(index){
case 0:
setState(() {
this.index = AppMode.die;
this.appbarElevationScale = 0.0;
});
break;
case 1:
setState(() {
this.index = AppMode.coin;
this.appbarElevationScale = 0.0;
});
break;
case 2:
setState(() {
this.index = AppMode.list;
this.appbarElevationScale = 1.0;
});
break;
case 3:
setState(() {
this.index = AppMode.ndie;
this.appbarElevationScale = 0.0;
});
break;
default:
setState(() {
//this.index = AppMode.die;
this.appbarElevationScale = 0.0;
});
}
},
),
),
body: new Stack(
children: <Widget>[
new Offstage(
offstage: index != AppMode.die,
child: new DicePage(),
),
new Offstage(
offstage: index != AppMode.coin,
child: new CoinPage()
),
new Offstage(
offstage: index != AppMode.list,
child: new ListPage(),
),
new Offstage(
offstage: index != AppMode.ndie,
child: new D20Page(),
),
],
),
);
}
}
class DicePage extends StatefulWidget {
const DicePage();
@override
_DicePageState createState() => new _DicePageState();
}
class _DicePageState extends State<DicePage> {
int diceNumber = randomize();
GlobalKey<SplashWidgetState> splashWidgetKey = new GlobalKey<SplashWidgetState>();
@override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: new Align(
alignment: new FractionalOffset(0.5,0.30),
child: new SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 80.0),
child: new SplashWidget(
key: splashWidgetKey,
size: 150.0,
child: new Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Text('You rolled a', style: Theme.of(context).textTheme.title.copyWith(color: Theme.of(context).textTheme.display1.color, fontFamily: 'ProductSans')),
const SizedBox(height:8.0),
new Text(diceNumber.toString(), style: Theme.of(context).textTheme.display2.copyWith(color: Theme.of(context).primaryColor, fontFamily: 'ProductSans')),
]
),
),
),
),
floatingActionButton: new FloatingActionButton.extended(
onPressed: onPressed,
icon: const Icon(Icons.casino,),
label: const Text('Roll'),
elevation: 4.0,
highlightElevation: 8.0,
),
);
}
static int randomize(){
final random = new Random();
return 1 + random.nextInt(6);
}
void onPressed(){
splashWidgetKey.currentState.splash();
setState((){
diceNumber = randomize();
});
}
}
class CoinPage extends StatefulWidget {
const CoinPage();
@override
_CoinPageState createState() => new _CoinPageState();
}
class _CoinPageState extends State<CoinPage> {
int coinNumber = 0;
String coinString = 'Nothing';
GlobalKey<SplashWidgetState> splashWidgetKey = new GlobalKey<SplashWidgetState>();
@override
Widget build(BuildContext context) {
return new Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
body: new Align(
alignment: new FractionalOffset(0.5,0.30),
child: new SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 80.0),
child: new SplashWidget(
key: splashWidgetKey,
size: 200.0,
child: new Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Text('You flipped', style: Theme.of(context).textTheme.title.copyWith(color: Theme.of(context).textTheme.display1.color, fontFamily: 'ProductSans')),
const SizedBox(height:8.0),
new Text(coinString, style: Theme.of(context).textTheme.display2.copyWith(color: Theme.of(context).primaryColor, fontFamily: 'ProductSans')),
]
),
),
),
),
floatingActionButton: new FloatingActionButton.extended(
onPressed: _onPressed,
icon: const Icon(Icons.casino,),
label: const Text('Flip'),
elevation: 4.0,
highlightElevation: 8.0,
),
);
}
static int _randomize(){
final random = new Random();
return random.nextInt(2);
}
void _onPressed(){
splashWidgetKey.currentState.splash();
setState((){
coinNumber = _randomize();
switch (coinNumber){
case 0:
coinString = 'Heads';
break;
case 1:
coinString = 'Tails';
break;
default:
coinString = 'error';
break;
}
});
}
}
class ListPage extends StatefulWidget {
const ListPage();
@override
_ListPageState createState() => new _ListPageState();
}
class _ListPageState extends State<ListPage> {
List<String> _itemsList;
SharedPreferences _prefs;
GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
@override
void initState() {
super.initState();
initList();
initPrefs();
}
initPrefs() async{
SharedPreferences.getInstance().then((SharedPreferences value) {
_prefs = value;
if (_prefs.getStringList("itemsList") != null){
setState(() {
_itemsList = _prefs.getStringList("itemsList");
});
}
});
}
void initList(){
_itemsList = [
"NewThing",
"MyThing",
"HelloThing",
"if you see this text, something went wrong"
];
}
void dialogNewItem(BuildContext context){
String text = "Blank Thing";
TextField textField = new TextField(
autofocus: true,
decoration: const InputDecoration(
hintText: "Name your Thing",
),
onChanged: (String value){
text = value;
},
onSubmitted: (String value){ addNewItem(value); },
);
showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context){
return new AlertDialog(
title: const Text("Add a Thing"),
content: textField,
actions: <Widget>[
new FlatButton(
child: const Text("Cancel"),
textColor: Theme.of(context).primaryColor,
onPressed: (){
Navigator.of(context).pop();
},
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(6.0)),
),
new RaisedButton(
child: const Text("Add"),
textColor: Theme.of(context).dialogBackgroundColor,
color: Theme.of(context).primaryColor,
elevation: 0.0,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(6.0)),
onPressed: (){ addNewItem(text); },
),
],
);
},
);
}
void addNewItem(String text) {
setState((){
_itemsList.insert(_itemsList.length - 1, text);
_prefs.setStringList("itemsList", _itemsList);
});
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
if (_itemsList == null){
initList();
}
return new Scaffold(
key: _scaffoldKey,
body: new Stack(children: <Widget>[
new Offstage( //Show this if there are no items in the list
offstage: _itemsList.length > 1,
child: new TickerMode(
enabled: _itemsList.length == 1,
child: new Align(
alignment: new FractionalOffset(0.5,0.40),
child: new Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text("There's nothing here", style: Theme.of(context).textTheme.headline.copyWith(fontSize: 20.0, color: Theme.of(context).textTheme.display1.color, fontFamily: 'ProductSans')),
const SizedBox(height:16.0),
new RaisedButton.icon(
onPressed: (){ dialogNewItem(context); },
icon: const Icon(Icons.add),
label: const Text("Add a Thing"),
color: Theme.of(context).accentColor,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(6.0)),
)
]
),
),
),
),
new Offstage( //show this if there are items in the list
offstage: _itemsList.length == 1,
child: new TickerMode(
enabled: _itemsList.length > 1,
child: new Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: new FloatingActionButton.extended(
onPressed: (){
if (_itemsList.length > 0){
showDialog(context: context, barrierDismissible: true, builder: (BuildContext context) {
return new AlertDialog(
title: const Text('Item selected from the list'),
content: new Text(
_itemsList[new Random().nextInt(_itemsList.length - 1)]),
actions: <
Widget>[ //AlertDialog with no buttons makes me nut but that's bad ux so i gotta abstain
new FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(6.0)),
child: const Text("OK"),
textColor: Theme.of(context).primaryColor,
),
],
);}
);
} else {
Scaffold.of(context).showSnackBar(const SnackBar(content: const Text("There's nothing to pick from!")));
}
},
icon: const Icon(Icons.casino,),
label: const Text('Pick'),
elevation: 4.0,
highlightElevation: 8.0,
),
body: new Scrollbar(child:
new ListView.builder(
padding: const EdgeInsets.only(top: 8.0, bottom: 80.0),
itemCount: _itemsList.length,
itemBuilder: (context, index){
Color shadeColor;
if (!index.isEven){
//shadeColor = const Color(0x11000000);
shadeColor = Theme.of(context).dividerColor;
}
String _label = _itemsList[index];
int _rememberIndex = index;
return new ListItem(
label: _label,
index: index,
shadeColor: shadeColor,
listLength: _itemsList.length,
actionCallback: index != _itemsList.length - 1
? (){ //this is a regular list item
setState((){ _itemsList.removeAt(index); });
_prefs.setStringList("itemsList", _itemsList);
//show a Snackbar with an Undo button
_scaffoldKey.currentState.showSnackBar(
new SnackBar(
content: new Text(_label + " removed"),
action: new SnackBarAction(
label: "Undo",
onPressed: (){
setState(() {
_itemsList.insert(_rememberIndex, _label);
});
_prefs.setStringList("itemsList", _itemsList);
}
),
)
);
}
: (){ //this is the end item, prompt to add an item
dialogNewItem(context);
},
);
},
)
),
),
),
),
],
)
);
}
}
class ListItem extends StatefulWidget {
ListItem({this.label, this.shadeColor, this.index, this.listLength, this.actionCallback})
: assert(label != null), assert(index != null);
final String label;
final int index;
final int listLength;
final Color shadeColor;
final VoidCallback actionCallback;
@override
_ListItemState createState() => new _ListItemState();
}
class _ListItemState extends State<ListItem> {
@override
Widget build(BuildContext context){
return new Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0), //Padding for outside the item
child: widget.index == widget.listLength - 1
? new Padding(
padding: const EdgeInsets.symmetric(vertical: 8.0),
child: new OutlineButton.icon(
onPressed: widget.actionCallback,
icon: const Icon(Icons.add),
label: const Text("Add a Thing"),
textColor: Theme.of(context).primaryColor,
highlightElevation: 0.0,
shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(6.0)),
)
)
: new DecoratedBox(
decoration: new BoxDecoration(color: widget.shadeColor, borderRadius: new BorderRadius.circular(6.0)),
child: new Padding(
padding: const EdgeInsets.only(left: 16.0, top: 8.0, right: 8.0, bottom: 8.0), //Padding for the label and button
child: new Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Expanded(
child: new Text(widget.label, style: Theme.of(context).textTheme.subhead.copyWith(color: Theme.of(context).textTheme.display1.color)),
),
new IconButton(
icon: new Icon(Icons.close, color: Theme.of(context).textTheme.display1.color,),
tooltip: 'Remove this Thing',
onPressed: (){widget.actionCallback();}
)
],
),
),
)
);
}
}
//Custom Dice page widget
class D20Page extends StatefulWidget {
const D20Page();
@override
D20PageState createState() => new D20PageState();
}
class D20PageState extends State<D20Page> {
int min = 1;
int max = 20;
int diceNumber = randomize(1, 20);
/* Create a Key for the Form that controls the TextFields. We're gonna need
this to validate the form when the FAB is clicked. */
final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
/* Create a Key for the Scaffold that holds everything. The Snackbar we show
if there's an error needs to be shown on this Widget's Scaffold so it can
move the FAB out of the way. */
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
final GlobalKey<SplashWidgetState> _splashWidgetKey = new GlobalKey<SplashWidgetState>();
//These functions validate the TextFields that control Min and Max variables.
String validateMin(String value){
if (value.isEmpty){
return "Please enter a number!";
}
try {
int intValue = int.parse(value);
if (intValue.isNegative){
return "Number can't be negative!";
}
if (intValue > 4294967296){
return "Number must be less than 4294967296!";
}
min = intValue;
return null;
} catch (FormatException){
return "That's not a number!";
}
}
String validateMax(String value){
if (value.isEmpty){
return "Please enter a number!";
}
try {
int intValue = int.parse(value);
if (intValue.isNegative){
return "Number can't be negative!";
}
if (intValue > 4294967296){
return "Number must be less than 4294967296!";
}
max = intValue;
return null;
} catch (FormatException){
return "That's not a number!";
}
}
@override
Widget build(BuildContext context) {
return new Scaffold(
key: _scaffoldKey,
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: new FloatingActionButton.extended(
icon: const Icon(Icons.casino),
label: const Text("Roll"),
elevation: 4.0,
highlightElevation: 8.0,
onPressed: (){ onPressed(); },
),
body: new Scrollbar(
child: new SingleChildScrollView(
padding: const EdgeInsets.only(left: 32.0, top: 16.0, right: 32.0, bottom: 80.0),
child: new Form(
key: _formKey,
autovalidate: true,
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
new Row(mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[new Column(
children: <Widget>[
new SplashWidget(
key: _splashWidgetKey,
size: 150.0,
child: new Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
new Text('You rolled', style: Theme.of(context).textTheme.title.copyWith(color: Theme.of(context).textTheme.display1.color, fontFamily: 'ProductSans')),
const SizedBox(height:8.0),
new Text(diceNumber.toString(), style: Theme.of(context).textTheme.display2.copyWith(color: Theme.of(context).primaryColor, fontFamily: 'ProductSans')),
]
),
),
],),],),
const SizedBox(height: 32.0),
new Text('From', style: Theme.of(context).textTheme.subhead.copyWith(color: Theme.of(context).textTheme.display1.color, fontFamily: 'ProductSans')),
new TextFormField(
decoration: new InputDecoration(hintText: "Small number"),
keyboardType: TextInputType.number,
//controller: new TextEditingController(text: min.toString()),
validator: validateMin,
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
initialValue: min.toString(),
),
const SizedBox(height: 8.0),
new Text('to', style: Theme.of(context).textTheme.subhead.copyWith(color: Theme.of(context).textTheme.display1.color, fontFamily: 'ProductSans')),
new TextFormField(
decoration: new InputDecoration(hintText: "Big number"),
keyboardType: TextInputType.number,
//controller: new TextEditingController(text: max.toString()),
validator: validateMax,
inputFormatters: [WhitelistingTextInputFormatter.digitsOnly],
initialValue: max.toString(),
),
],
),
)
),
),
);
}
static int randomize(int min, int max){
final random = new Random();
return min > max ? max + random.nextInt(min) : min + random.nextInt(max);
}
void onPressed(){
if (_formKey.currentState.validate()){
_splashWidgetKey.currentState.splash();
setState(() {
diceNumber = randomize(min, max);
});
} else {
_scaffoldKey.currentState.showSnackBar(new SnackBar(content: const Text("Something's wrong with your numbers!"), backgroundColor: Colors.red.shade800, duration: new Duration(seconds:3),));
}
}
}
//here's the Settings page from the gear on the toolbar
class SettingsPage extends StatefulWidget {
const SettingsPage();
@override
_SettingsPageState createState() => new _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
bool useDarkTheme = false;
GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
SharedPreferences _prefs;
bool _wasDark = false;
initPrefs() async{
useDarkTheme = false;
SharedPreferences.getInstance().then((SharedPreferences value) {
_prefs = value;
setState(() {
if (value.getBool("use_dark_theme") == null){
useDarkTheme = false;
} else if (value.getBool("use_dark_theme") == null){
useDarkTheme = false;
} else{
useDarkTheme = value.getBool("use_dark_theme");
}
});
});
}
@override
void initState() {
super.initState();
initPrefs();
}
@override
Widget build(BuildContext context) {
if (Theme.of(context).brightness == Brightness.dark){ _wasDark = true; }
return new Scaffold(
key: _scaffoldKey,
appBar: new AppBar(
title: new Text('Settings', style: new TextStyle(color: Theme.of(context).primaryColor),),
elevation: 0.0,
backgroundColor: Colors.transparent,
leading: new IconButton(
icon: new Icon(Icons.arrow_back, color: Theme.of(context).primaryColor,),
onPressed: (){ Navigator.pop(context); },
),
),
body: new ListTile(
leading: new Icon(Icons.brightness_3, color: Theme.of(context).textTheme.title.color,),
title: const Text('Dark theme (requires restart)'),
subtitle: new Text(useDarkTheme ? "App will use a dark theme next time you open it" : "App will use a light theme next time you open it"),
trailing: new Switch(
value: useDarkTheme,
onChanged: (bool value){
switchTheme(value);
}
),
onTap: (){ switchTheme(!useDarkTheme); },
),
);
}
void switchTheme(bool isDark){
setState(() {
useDarkTheme = isDark;
});
_prefs.setBool('use_dark_theme', isDark);
_scaffoldKey.currentState.hideCurrentSnackBar();
if (_wasDark != isDark){
_scaffoldKey.currentState.showSnackBar(new SnackBar(content: new Text(useDarkTheme
? "Close and reopen Flip to apply the dark theme!"
: "Close and reopen Flip to apply the light theme!"
)) );
}
}
}
| 0
|
mirrored_repositories/flip_flutter
|
mirrored_repositories/flip_flutter/lib/splashwidget.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
class SplashWidget extends StatefulWidget {
SplashWidget({Key key, this.size, this.child}) : assert(size != null), super(key: key);
final double size;
final Widget child;
@override
SplashWidgetState createState() => new SplashWidgetState();
}
class SplashWidgetState extends State<SplashWidget>
with TickerProviderStateMixin {
Animation<double> sizeAnimation;
Animation<double> opacityAnimation;
AnimationController controller;
CurvedAnimation curvedAnimation;
@override
initState() {
super.initState();
controller = new AnimationController(
duration: const Duration(milliseconds: 250), vsync: this);
sizeAnimation = new Tween(begin: 0.0, end: widget.size).chain(
new CurveTween(
curve: Curves.easeInOut,
)
).animate(controller)
..addListener((){
setState(() {
});
})
;
opacityAnimation = new CurvedAnimation(parent: controller, curve: Curves.easeIn);
controller.value = controller.upperBound;
}
void splash(){
controller.reset();
controller.forward();
}
@override
void dispose() {
super.dispose();
controller.dispose();
}
@override
Widget build(BuildContext context){
return new Container(
width:widget.size,
height: widget.size,
child: new Stack(children: <Widget>[
new Container(
width:widget.size,
height: widget.size,
child: new Opacity(
opacity: 1 -opacityAnimation.value,
child: new DecoratedBox(decoration: new BoxDecoration(
color: Theme.of(context).accentColor,
shape: BoxShape.circle,
),),
)
),
new Center(child: widget.child),
],)
);
}
}
| 0
|
mirrored_repositories/flip_flutter
|
mirrored_repositories/flip_flutter/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 '../lib/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(new 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/flutter-myshop
|
mirrored_repositories/flutter-myshop/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:myshop/helpers/custom_route.dart';
import 'package:myshop/providers/auth.dart';
import 'package:myshop/providers/cart.dart';
import 'package:myshop/providers/orders.dart';
import 'package:myshop/providers/product_provider.dart';
import 'package:myshop/screens/auth/auth_screen.dart';
import 'package:myshop/screens/cart/cart_screen.dart';
import 'package:myshop/screens/order/order_screen.dart';
import 'package:myshop/screens/product/edit_product_screen.dart';
import 'package:myshop/screens/product/product_detail_screen.dart';
import 'package:myshop/screens/product/product_overview_screen.dart';
import 'package:myshop/screens/product/user_product_screen.dart';
import 'package:myshop/screens/splash_screen.dart';
import 'package:myshop/widgets/utils/tabs_screen.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
create: (context) => Auth(),
),
ChangeNotifierProxyProvider<Auth, ProductProvider>(
create: null,
update: (context, authData, productProvider) => ProductProvider(
authData.getToken,
authData.userId,
productProvider == null ? [] : productProvider.items),
),
ChangeNotifierProvider(
create: (context) => CartProvider(),
),
ChangeNotifierProxyProvider<Auth, Orders>(
create: null,
update: (context, authData, previewsOrders) => Orders(
authData.getToken,
authData.userId,
previewsOrders == null ? [] : previewsOrders.order),
),
],
child: Consumer<Auth>(
builder: (context, authData, _) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
primaryColor: Color.fromRGBO(31, 52, 76, 1),
accentColor: Color.fromRGBO(72, 66, 109, 1),
textTheme: GoogleFonts.latoTextTheme(
Theme.of(context).textTheme,
).copyWith(
// ignore: deprecated_member_use
title: GoogleFonts.lato(
// ignore: deprecated_member_use
textStyle: Theme.of(context).textTheme.title,
color: Colors.black,
fontSize: 17,
),
),
pageTransitionsTheme: PageTransitionsTheme(
builders: ({
TargetPlatform.android: CustomPageTransitionBuilder(),
TargetPlatform.iOS: CustomPageTransitionBuilder(),
})),
appBarTheme: AppBarTheme(
textTheme: TextTheme(
// ignore: deprecated_member_use
title: TextStyle(
color: Colors.black,
fontSize: 18,
),
),
),
),
home: authData.isAuth
? TabsScreen()
: FutureBuilder(
future: authData.tryAutoLogin(),
builder: (context, snapshot) =>
snapshot.connectionState == ConnectionState.waiting
? SplashScreen()
: AuthScreen(),
),
routes: {
ProductOverviewScreen.routeName: (context) =>
ProductOverviewScreen(),
ProductDetailScreen.routeName: (context) => ProductDetailScreen(),
CartScreen.routeName: (context) => CartScreen(),
OrderScreen.routeName: (contex) => OrderScreen(),
UserProduct.routeName: (context) => UserProduct(),
EditProductScreen.routeName: (context) => EditProductScreen(),
},
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/cart/cart_item.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/widgets/utils/alert.dart';
import 'package:provider/provider.dart';
import 'package:myshop/providers/cart.dart';
class CartItem extends StatelessWidget {
final String id;
final String productId;
final String title;
final int quantity;
final double price;
CartItem(this.id, this.productId, this.title, this.quantity, this.price);
@override
Widget build(BuildContext context) {
return Dismissible(
key: ValueKey(id),
direction: DismissDirection.endToStart,
onDismissed: (direction) {
Provider.of<CartProvider>(context, listen: false)
.removeItems(productId);
},
confirmDismiss: (direction) {
return showDialog(
context: context,
builder: (context) {
return Alert('Do you want to remove this item from cart?', false);
},
);
},
background: Container(
color: Theme.of(context).errorColor,
child: const Icon(
Icons.delete_sweep_rounded,
size: 40,
color: Colors.white,
),
alignment: Alignment.centerRight,
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 10),
padding: const EdgeInsets.only(right: 10),
),
child: Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
child: Padding(
padding: const EdgeInsets.all(10),
child: ListTile(
leading: CircleAvatar(
radius: 23,
backgroundColor: Theme.of(context).accentColor,
child: Padding(
padding: const EdgeInsets.all(1),
child: FittedBox(
fit: BoxFit.contain,
child: Text(
'\$$price',
style: TextStyle(
color: Colors.white,
),
),
),
),
),
title: Text(title),
subtitle: Text('Total : ${(price * quantity)}'),
trailing: Text('$quantity x'),
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/order/order_item.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:myshop/providers/orders.dart' as ord;
import 'package:intl/intl.dart';
import 'package:myshop/providers/orders.dart';
import 'package:provider/provider.dart';
class OrderItem extends StatefulWidget {
final ord.OrderItem order;
OrderItem(this.order);
@override
_OrderItemState createState() => _OrderItemState();
}
class _OrderItemState extends State<OrderItem> {
var _expanded = false;
@override
Widget build(BuildContext context) {
return Consumer<Orders>(
builder: (context, orders, _) => AnimatedContainer(
duration: Duration(milliseconds: 300),
height: _expanded
? min(widget.order.cartItems.length * 25.0 + 110, 250)
: 85,
child: Card(
elevation: 3,
child: Column(
children: [
ListTile(
title: Text('\$${widget.order.amount.toStringAsFixed(2)}'),
subtitle: Text(DateFormat('dd/MM/yyyy hh:mm')
.format(widget.order.dateTime)),
trailing: IconButton(
icon: Icon(_expanded ? Icons.expand_less : Icons.expand_more),
onPressed: () {
setState(() {
_expanded = !_expanded;
});
},
),
),
AnimatedContainer(
duration: const Duration(milliseconds: 300),
padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
height: _expanded
? min(widget.order.cartItems.length * 25.0 + 30, 120)
: 0,
child: ListView(
children: widget.order.cartItems
.map((cartItems) => Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(top: 5),
child: Text(
cartItems.title,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
Text(
'${cartItems.quantity}pcs x \$${cartItems.price}',
style: TextStyle(
fontSize: 18,
color: Colors.grey,
),
),
],
))
.toList(),
),
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/product/product_grid.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/product_provider.dart';
import 'package:provider/provider.dart';
import 'product_items.dart';
class ProductGrid extends StatelessWidget {
final bool showOnlyFavorite;
ProductGrid(this.showOnlyFavorite);
@override
Widget build(BuildContext context) {
final productProviderData = Provider.of<ProductProvider>(context);
final product = showOnlyFavorite
? productProviderData.favoriteItems
: productProviderData.items;
return ListView.builder(
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) => ChangeNotifierProvider.value(
value: product[index],
child: ProductItem(),
),
padding: const EdgeInsets.all(10),
itemCount: product.length,
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/product/product_items.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/product.dart';
import 'package:myshop/screens/product/product_detail_screen.dart';
import 'package:provider/provider.dart';
class ProductItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
final product = Provider.of<Product>(context, listen: false);
final deviceSize = MediaQuery.of(context).size;
return ClipRRect(
borderRadius: BorderRadius.circular(15),
child: GestureDetector(
onTap: () {
Navigator.of(context)
.pushNamed(ProductDetailScreen.routeName, arguments: product.id);
},
child: Column(
children: [
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Card(
borderOnForeground: true,
child: Row(
children: [
Container(
height: deviceSize.height * 0.23,
width: deviceSize.width * 0.25,
margin: const EdgeInsets.symmetric(
horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(Radius.circular(10))),
child: Column(
children: [
Container(
child: Hero(
tag: product.id,
child: FadeInImage(
placeholder: AssetImage(
'assets/images/product-placeholder.png'),
image: NetworkImage(
product.imageUrl,
),
fit: BoxFit.contain,
height: 120,
),
),
),
Spacer(),
Text(
product.title,
textAlign: TextAlign.center,
style: TextStyle(
color: Color(0xff676767),
fontSize: 14,
),
),
],
),
),
],
),
),
),
],
),
),
);
}
}
// Consumer<CartProvider>(
// builder: (context, cart, _) => IconButton(
// icon: Icon(Icons.shopping_cart,
// color: Colors.deepOrange),
// onPressed: () {
// cart.addItems(
// product.id, product.title, product.price);
// Scaffold.of(context).hideCurrentSnackBar();
// Scaffold.of(context).showSnackBar(
// SnackBar(
// content: Text('Sucessfully added to cart!'),
// action: SnackBarAction(
// label: 'UNDO',
// textColor: Colors.white,
// onPressed: () {
// cart.removeSingleItem(product.id);
// },
// ),
// ),
// );
// },
// ),
// ),
// Consumer<Product>(
// builder: (context, product, _) {
// return IconButton(
// icon: Icon(
// product.isFavorite
// ? Icons.favorite
// : Icons.favorite_border,
// color: Colors.deepOrange,
// ),
// onPressed: () {
// product.toogleFavorite(
// authToken.getToken, authToken.userId);
// },
// );
// },
// ),
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/product/user_product_item.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/product_provider.dart';
import 'package:myshop/screens/product/edit_product_screen.dart';
import 'package:provider/provider.dart';
class UserProductItem extends StatelessWidget {
final String id;
final String title;
final String imageUrl;
final double price;
UserProductItem(this.id, this.title, this.imageUrl, this.price);
Future<void> _refreshProduct(BuildContext context) async {
await Provider.of<ProductProvider>(context, listen: false)
.fetchAndSetProducts();
}
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
return RefreshIndicator(
onRefresh: () => _refreshProduct(context),
child: Padding(
padding: const EdgeInsets.all(5),
child: Card(
elevation: 3,
child: ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(imageUrl),
),
title: Text(title),
subtitle: Text('\$$price'),
trailing: Container(
width: mediaQuery.size.width * 0.3,
child: Row(
children: [
IconButton(
onPressed: () async {
try {
await Provider.of<ProductProvider>(context,
listen: false)
.removeProduct(id);
} catch (error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Deleting failed!'),
),
);
}
},
icon: Icon(
Icons.delete_outline_outlined,
color: Theme.of(context).errorColor,
),
),
IconButton(
onPressed: () {
Navigator.of(context).pushNamed(
EditProductScreen.routeName,
arguments: id);
},
icon: Icon(
Icons.edit_sharp,
color: Theme.of(context).accentColor,
),
),
],
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/auth/auth_card.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/models/http_exception.dart';
import 'package:myshop/providers/auth.dart';
import 'package:myshop/widgets/utils/alert.dart';
import 'package:provider/provider.dart';
class AuthCard extends StatefulWidget {
const AuthCard({
Key key,
}) : super(key: key);
@override
_AuthCardState createState() => _AuthCardState();
}
enum AuthMode { Signup, Login }
class _AuthCardState extends State<AuthCard>
with SingleTickerProviderStateMixin {
final GlobalKey<FormState> _formKey = GlobalKey();
AuthMode _authMode = AuthMode.Login;
Map<String, String> _authData = {
'email': '',
'password': '',
};
var _isLoading = false;
final _passwordController = TextEditingController();
AnimationController _animationController;
Animation<double> _animationOpacity;
Animation<Offset> _animationSlide;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(
milliseconds: 500,
));
_animationOpacity = Tween(begin: 0.0, end: 1.0).animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.fastOutSlowIn,
),
);
_animationSlide =
Tween<Offset>(begin: Offset(0.0, -1.5), end: Offset(0, 0)).animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.linear,
),
);
}
@override
void dispose() {
super.dispose();
_animationController.dispose();
}
void showErrorDialog(String message) {
showDialog(context: context, builder: (context) => Alert(message, true));
}
void _submit() async {
if (!_formKey.currentState.validate()) {
// Invalid!
return;
}
_formKey.currentState.save();
setState(() {
_isLoading = true;
});
try {
if (_authMode == AuthMode.Login) {
// Log user in
await Provider.of<Auth>(context, listen: false)
.signin(_authData['email'], _authData['password']);
} else {
// Sign user up
await Provider.of<Auth>(context, listen: false)
.signup(_authData['email'], _authData['password']);
}
} on HttpException catch (e) {
var errorMessage = 'Authentication failed';
if (e.message.contains('EMAIL_EXISTS')) {
errorMessage = 'This email address already exists.';
} else if (e.message.contains('INVALID_EMAIL')) {
errorMessage = 'This email address is invalid.';
} else if (e.message.contains('WEAK_PASSWORD')) {
errorMessage = 'This email address is to weak.';
} else if (e.message.contains('EMAIL_NOT_FOUND')) {
errorMessage = 'This email address not found.';
} else if (e.message.contains('INVALID_PASSWORD')) {
errorMessage = 'Invalid password.';
}
showErrorDialog(errorMessage);
} catch (e) {
print(e);
var errorMessage = 'Could not authenticate you. Please try again later';
showErrorDialog(errorMessage);
}
setState(() {
_isLoading = false;
});
}
void _switchAuthMode() {
if (_authMode == AuthMode.Login) {
setState(() {
_authMode = AuthMode.Signup;
_animationController.forward();
});
} else {
setState(() {
_authMode = AuthMode.Login;
_animationController.reverse();
});
}
}
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
elevation: 8.0,
child: AnimatedContainer(
duration: Duration(milliseconds: 300),
curve: Curves.bounceIn,
height: _authMode == AuthMode.Signup ? 320 : 260,
constraints:
BoxConstraints(minHeight: _authMode == AuthMode.Signup ? 320 : 260),
width: deviceSize.width * 0.75,
padding: const EdgeInsets.all(16.0),
child: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(labelText: 'E-Mail'),
keyboardType: TextInputType.emailAddress,
validator: (value) {
if (value.isEmpty || !value.contains('@')) {
return 'Invalid email!';
}
return null;
},
onSaved: (value) {
_authData['email'] = value;
},
),
TextFormField(
decoration: InputDecoration(labelText: 'Password'),
obscureText: true,
controller: _passwordController,
// ignore: missing_return
validator: (value) {
if (value.isEmpty || value.length < 5) {
return 'Password is too short!';
}
},
onSaved: (value) {
_authData['password'] = value;
},
),
AnimatedContainer(
duration: const Duration(milliseconds: 300),
constraints: BoxConstraints(
minHeight: _authMode == AuthMode.Signup ? 60 : 0,
maxHeight: _authMode == AuthMode.Signup ? 120 : 0,
),
child: FadeTransition(
opacity: _animationOpacity,
child: SlideTransition(
position: _animationSlide,
child: TextFormField(
enabled: _authMode == AuthMode.Signup,
decoration:
InputDecoration(labelText: 'Confirm Password'),
obscureText: true,
validator: _authMode == AuthMode.Signup
// ignore: missing_return
? (value) {
if (value != _passwordController.text) {
return 'Passwords do not match!';
}
}
: null,
),
),
),
),
SizedBox(
height: 20,
),
if (_isLoading)
CircularProgressIndicator()
else
ElevatedButton(
child:
Text(_authMode == AuthMode.Login ? 'LOGIN' : 'SIGN UP'),
onPressed: _submit,
style: ElevatedButton.styleFrom(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
padding: const EdgeInsets.symmetric(
horizontal: 30.0, vertical: 8.0),
primary: Theme.of(context).primaryColor,
textStyle: TextStyle(
color:
Theme.of(context).primaryTextTheme.button.color),
),
),
TextButton(
child: Text(
'${_authMode == AuthMode.Login ? 'SIGNUP' : 'LOGIN'}',
style: TextStyle(color: Colors.black),
),
onPressed: _switchAuthMode,
style: TextButton.styleFrom(
padding: const EdgeInsets.symmetric(
horizontal: 30.0, vertical: 4),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
textStyle: TextStyle(color: Theme.of(context).primaryColor),
),
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/container_title.dart
|
import 'package:flutter/material.dart';
class ContainerTitle extends StatelessWidget {
final String _title;
ContainerTitle(this._title);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(
left: 20,
right: 20,
top: 10,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
_title,
style: TextStyle(
color: Colors.black, fontSize: 16, fontWeight: FontWeight.bold),
),
Text(
'Show More',
style: TextStyle(
color: Colors.red[700],
fontSize: 11,
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/alert.dart
|
import 'package:flutter/material.dart';
class Alert extends StatelessWidget {
final String textContent;
final bool _isError;
Alert(this.textContent, this._isError);
Widget _ifError(BuildContext context) {
if (!_isError) {
return Row(
children: [
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: const Text('NO'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('YES'),
),
],
);
} else {
return TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('YES'),
);
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text(
'Alert from Tokoku!',
style: TextStyle(color: Colors.black),
),
content: Text(textContent),
actions: [_ifError(context)],
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/tabs_screen.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/auth.dart';
import 'package:myshop/screens/order/order_screen.dart';
import 'package:myshop/screens/product/product_overview_screen.dart';
import 'package:myshop/screens/product/user_product_screen.dart';
import 'package:provider/provider.dart';
class TabsScreen extends StatefulWidget {
@override
_TabsScreenState createState() => _TabsScreenState();
}
class _TabsScreenState extends State<TabsScreen> {
List<Map<String, Object>> _pages;
int _selectedPagesIndex = 0;
void _selectedPages(int index) {
setState(() {
_selectedPagesIndex = index;
});
}
@override
void initState() {
super.initState();
_pages = [
{'pages': ProductOverviewScreen()},
{'pages': OrderScreen()},
{'pages': UserProduct()},
];
}
@override
Widget build(BuildContext context) {
final deviceSize = MediaQuery.of(context).size;
return Scaffold(
body: _pages[_selectedPagesIndex]['pages'],
bottomNavigationBar: Container(
height: deviceSize.height * 0.13,
child: ClipRRect(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(25),
topRight: Radius.circular(25),
),
child: BottomNavigationBar(
elevation: 5,
backgroundColor: Theme.of(context).primaryColor,
onTap: _selectedPages,
iconSize: 20,
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.yellow[900],
unselectedItemColor: Colors.white,
currentIndex: _selectedPagesIndex,
items: [
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: const Icon(Icons.shop),
label: 'Shop',
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: const Icon(Icons.payment),
label: 'Orders',
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: const Icon(Icons.shopping_bag),
label: 'Products',
),
BottomNavigationBarItem(
backgroundColor: Theme.of(context).primaryColor,
icon: TextButton(
style: TextButton.styleFrom(
padding: const EdgeInsets.only(top: 16),
),
child: Column(
children: const [
Icon(
Icons.exit_to_app,
color: Colors.white,
),
Text(
'Logout',
style: TextStyle(
color: Colors.white,
fontSize: 13,
),
),
],
),
onPressed: () {
Navigator.of(context).pushReplacementNamed('/');
Provider.of<Auth>(context, listen: false).logout();
},
),
label: '',
),
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/search.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/product.dart';
import 'package:myshop/screens/product/product_detail_screen.dart';
class CustomSearch extends SearchDelegate<String> {
final List<Product> items;
CustomSearch(this.items);
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
)
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
close(context, null);
},
);
}
@override
Widget buildResults(BuildContext context) {
return null;
}
@override
Widget buildSuggestions(BuildContext context) {
final suggestionList = items
.where(
(i) => i.title.toLowerCase().startsWith(
query.toLowerCase(),
),
)
.toList();
return ListView.builder(
itemCount: suggestionList.length,
itemBuilder: (context, index) => ListTile(
leading: CircleAvatar(
backgroundImage: NetworkImage(suggestionList[index].imageUrl),
),
onTap: () {
Navigator.of(context).popAndPushNamed(ProductDetailScreen.routeName,
arguments: suggestionList[index].id);
},
title: RichText(
text: TextSpan(
text: suggestionList[index].title.substring(0, query.length),
style: TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
children: [
TextSpan(
text: suggestionList[index].title.substring(query.length),
style: TextStyle(color: Colors.grey))
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/badge.dart
|
import 'package:flutter/material.dart';
class Badge extends StatelessWidget {
const Badge({
Key key,
@required this.child,
@required this.value,
this.color = Colors.deepOrange,
}) : super(key: key);
final Widget child;
final String value;
final Color color;
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: [
child,
Positioned(
right: 8,
top: 8,
child: Container(
padding: const EdgeInsets.all(2.0),
// color: Theme.of(context).accentColor,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
color: color,
),
constraints: BoxConstraints(
minWidth: 16,
minHeight: 16,
),
child: Text(
value,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 10,
),
),
),
)
],
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/categories_item.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:myshop/widgets/utils/container_title.dart';
class CategoriesItem extends StatelessWidget {
const CategoriesItem({
Key key,
@required this.deviceSize,
}) : super(key: key);
final Size deviceSize;
@override
Widget build(BuildContext context) {
return Column(
children: [
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(width: 10),
Container(
margin: const EdgeInsets.only(top: 4),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: const Text(
'Discount up to 50%',
style: TextStyle(color: Colors.white),
),
),
SizedBox(width: 10),
Container(
margin: const EdgeInsets.only(top: 4),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: const Text(
'Sale Everyday!',
style: TextStyle(color: Colors.white),
),
),
SizedBox(width: 10),
Container(
margin: const EdgeInsets.only(top: 4),
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.green[900],
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Text(
'100% Original Item',
style: TextStyle(color: Colors.white),
),
),
SizedBox(width: 10),
],
),
),
SizedBox(height: 15),
Container(
width: double.infinity,
margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 15),
padding: const EdgeInsets.all(15),
decoration: BoxDecoration(
color: Colors.cyan[900],
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: const [
Icon(
Icons.confirmation_num,
color: Colors.white,
size: 30,
),
Text(
'Coupon',
style: TextStyle(color: Colors.white),
),
],
),
Column(
children: const [
Icon(
Icons.account_box_rounded,
color: Colors.white,
size: 30,
),
Text(
'Account',
style: TextStyle(color: Colors.white),
),
],
),
Column(
children: const [
Icon(
Icons.account_balance_wallet_rounded,
color: Colors.white,
size: 30,
),
Text(
'Wallet',
style: TextStyle(color: Colors.white),
),
],
),
],
),
),
ContainerTitle('Categories'),
SizedBox(height: 5),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
Container(
height: deviceSize.height * 0.15,
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(
'assets/images/image-banner1.png',
fit: BoxFit.cover,
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'Electronic',
textAlign: TextAlign.right,
style: GoogleFonts.muli(
color: Colors.white,
backgroundColor: Colors.black45,
fontSize: 18,
),
),
),
],
),
),
Container(
height: deviceSize.height * 0.15,
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: Image.asset(
'assets/images/image-banner2.png',
fit: BoxFit.cover,
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Text(
'Fashion',
textAlign: TextAlign.right,
style: GoogleFonts.muli(
color: Colors.white,
backgroundColor: Colors.black45,
fontSize: 18,
),
),
),
],
),
),
],
),
),
],
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/widgets
|
mirrored_repositories/flutter-myshop/lib/widgets/utils/app_drawer.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/auth.dart';
import 'package:myshop/screens/order/order_screen.dart';
import 'package:myshop/screens/product/product_overview_screen.dart';
import 'package:myshop/screens/product/user_product_screen.dart';
import 'package:provider/provider.dart';
class AppDrawer extends StatelessWidget {
const AppDrawer({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
Widget listTile(String title, Icon icon, routeName) {
return ListTile(
leading: icon,
title: Text(title),
onTap: () {
Navigator.of(context).pushReplacementNamed(routeName);
},
);
}
return Drawer(
child: Column(
children: [
AppBar(
title: const Text('Welcome to Tokoku!'),
automaticallyImplyLeading: false,
),
const Divider(),
listTile('Shop', Icon(Icons.shop_rounded),
ProductOverviewScreen.routeName),
const Divider(),
listTile('Orders', Icon(Icons.payment), OrderScreen.routeName),
const Divider(),
listTile('Manage Products', Icon(Icons.shopping_bag),
UserProduct.routeName),
const Divider(),
ListTile(
leading: const Icon(Icons.exit_to_app),
title: const Text('Logout'),
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).pushReplacementNamed('/');
Provider.of<Auth>(context, listen: false).logout();
},
)
],
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib
|
mirrored_repositories/flutter-myshop/lib/models/http_exception.dart
|
class HttpException implements Exception {
String message;
HttpException(this.message);
@override
String toString() {
return message;
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib
|
mirrored_repositories/flutter-myshop/lib/helpers/custom_route.dart
|
import 'package:flutter/material.dart';
class CustomRoute<T> extends MaterialPageRoute<T> {
CustomRoute({
WidgetBuilder builder,
RouteSettings settings,
}) : super(
builder: builder,
settings: settings,
);
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (settings.name == '/') {
return child;
}
return FadeTransition(
opacity: animation,
child: child,
);
}
}
class CustomPageTransitionBuilder implements PageTransitionsBuilder {
@override
Widget buildTransitions<T>(
PageRoute<T> route,
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
if (route.settings.name == '/') {
return child;
}
return FadeTransition(
opacity: animation,
child: child,
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib
|
mirrored_repositories/flutter-myshop/lib/screens/splash_screen.dart
|
import 'package:flutter/material.dart';
class SplashScreen extends StatelessWidget {
const SplashScreen({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: const Text('Loading...'),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/screens
|
mirrored_repositories/flutter-myshop/lib/screens/cart/cart_screen.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/cart.dart' show CartProvider;
import 'package:myshop/providers/orders.dart';
import 'package:myshop/widgets/cart/cart_item.dart';
import 'package:provider/provider.dart';
class CartScreen extends StatelessWidget {
static const routeName = '/cart';
@override
Widget build(BuildContext context) {
final mediaQuery = MediaQuery.of(context);
final cart = Provider.of<CartProvider>(context);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
iconTheme: const IconThemeData(color: Colors.black),
title: const Text('Cart Screen'),
),
body: Column(
children: [
Card(
elevation: 3,
margin: const EdgeInsets.all(15),
child: Padding(
padding: const EdgeInsets.all(10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Total :',
style: TextStyle(fontSize: 20),
),
Spacer(),
SizedBox(
width: mediaQuery.size.width * 0.1,
),
Consumer<CartProvider>(
builder: (_, cart, child) => Chip(
label: Text(
'\$${cart.totalAmount.toStringAsFixed(2)}',
style: TextStyle(color: Colors.white),
),
backgroundColor: Theme.of(context).accentColor,
),
),
OrdersButton(cart: cart),
],
),
),
),
Expanded(
child: ListView.builder(
itemBuilder: (context, index) => CartItem(
cart.items.values.toList()[index].id,
cart.items.keys.toList()[index],
cart.items.values.toList()[index].title,
cart.items.values.toList()[index].quantity,
cart.items.values.toList()[index].price,
),
itemCount: cart.items.length,
))
],
),
);
}
}
class OrdersButton extends StatefulWidget {
const OrdersButton({
Key key,
@required this.cart,
}) : super(key: key);
final CartProvider cart;
@override
_OrdersButtonState createState() => _OrdersButtonState();
}
class _OrdersButtonState extends State<OrdersButton> {
var _isLoading = false;
@override
Widget build(BuildContext context) {
return TextButton(
onPressed: (widget.cart.totalAmount <= 0 || _isLoading)
? null
: () async {
setState(() {
_isLoading = true;
});
await Provider.of<Orders>(context, listen: false).addOrder(
widget.cart.items.values.toList(), widget.cart.totalAmount);
setState(() {
_isLoading = false;
});
widget.cart.clearCart();
},
child: _isLoading
? CircularProgressIndicator()
: const Text(
'ORDER NOW!',
style: TextStyle(fontSize: 17, fontWeight: FontWeight.bold),
),
);
}
}
| 0
|
mirrored_repositories/flutter-myshop/lib/screens
|
mirrored_repositories/flutter-myshop/lib/screens/order/order_screen.dart
|
import 'package:flutter/material.dart';
import 'package:myshop/providers/orders.dart' show Orders;
import 'package:myshop/widgets/order/order_item.dart';
import 'package:provider/provider.dart';
class OrderScreen extends StatelessWidget {
static const routeName = '/order';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
'Order History',
style: TextStyle(color: Colors.black),
),
backgroundColor: Colors.transparent,
elevation: 0,
),
body: Column(
children: [
Expanded(
child: FutureBuilder(
future: Provider.of<Orders>(context, listen: false)
.fetchAndSetOrders(),
builder: (context, dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.waiting) {
return Center(
child: const CircularProgressIndicator(),
);
} else {
if (dataSnapshot.error != null) {
return Center(
child: const Text('Error occured!'),
);
} else {
return Consumer<Orders>(
builder: (context, orderData, child) {
return ListView.builder(
itemCount: orderData.order.length,
itemBuilder: (context, index) =>
OrderItem(orderData.order[index]),
);
},
);
}
}
},
),
),
],
),
);
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.