repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib/src/popover.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:appflowy_popover/src/layout.dart';
import 'mask.dart';
import 'mutex.dart';
class PopoverController {
PopoverState? _state;
void close() {
_state?.close();
}
void show() {
_state?.showOverlay();
}
}
class PopoverTriggerFlags {
static const int none = 0x00;
static const int click = 0x01;
static const int hover = 0x02;
}
enum PopoverDirection {
// Corner aligned with a corner of the SourceWidget
topLeft,
topRight,
bottomLeft,
bottomRight,
center,
// Edge aligned with a edge of the SourceWidget
topWithLeftAligned,
topWithCenterAligned,
topWithRightAligned,
rightWithTopAligned,
rightWithCenterAligned,
rightWithBottomAligned,
bottomWithLeftAligned,
bottomWithCenterAligned,
bottomWithRightAligned,
leftWithTopAligned,
leftWithCenterAligned,
leftWithBottomAligned,
custom,
}
enum PopoverClickHandler {
listener,
gestureDetector,
}
class Popover extends StatefulWidget {
final PopoverController? controller;
/// The offset from the [child] where the popover will be drawn
final Offset? offset;
/// Amount of padding between the edges of the window and the popover
final EdgeInsets? windowPadding;
final Decoration? maskDecoration;
/// The function used to build the popover.
final Widget? Function(BuildContext context) popupBuilder;
/// Specify how the popover can be triggered when interacting with the child
/// by supplying a bitwise-OR combination of one or more [PopoverTriggerFlags]
final int triggerActions;
/// If multiple popovers are exclusive,
/// pass the same mutex to them.
final PopoverMutex? mutex;
/// The direction of the popover
final PopoverDirection direction;
final VoidCallback? onOpen;
final VoidCallback? onClose;
final Future<bool> Function()? canClose;
final bool asBarrier;
/// The widget that will be used to trigger the popover.
///
/// Why do we need this?
/// Because if the parent widget of the popover is GestureDetector,
/// the conflict won't be resolve by using Listener, we want these two gestures exclusive.
final PopoverClickHandler clickHandler;
final bool skipTraversal;
/// The content area of the popover.
final Widget child;
const Popover({
super.key,
required this.child,
required this.popupBuilder,
this.controller,
this.offset,
this.maskDecoration = const BoxDecoration(
color: Color.fromARGB(0, 244, 67, 54),
),
this.triggerActions = 0,
this.direction = PopoverDirection.rightWithTopAligned,
this.mutex,
this.windowPadding,
this.onOpen,
this.onClose,
this.canClose,
this.asBarrier = false,
this.clickHandler = PopoverClickHandler.listener,
this.skipTraversal = false,
});
@override
State<Popover> createState() => PopoverState();
}
class PopoverState extends State<Popover> {
static final RootOverlayEntry _rootEntry = RootOverlayEntry();
final PopoverLink popoverLink = PopoverLink();
@override
void initState() {
super.initState();
widget.controller?._state = this;
}
void showOverlay() {
close();
if (widget.mutex != null) {
widget.mutex?.state = this;
}
final shouldAddMask = _rootEntry.isEmpty;
final newEntry = OverlayEntry(builder: (context) {
final children = <Widget>[];
if (shouldAddMask) {
children.add(
PopoverMask(
decoration: widget.maskDecoration,
onTap: () async {
if (!(await widget.canClose?.call() ?? true)) {
return;
}
_removeRootOverlay();
},
),
);
}
children.add(
PopoverContainer(
direction: widget.direction,
popoverLink: popoverLink,
offset: widget.offset ?? Offset.zero,
windowPadding: widget.windowPadding ?? EdgeInsets.zero,
popupBuilder: widget.popupBuilder,
onClose: close,
onCloseAll: _removeRootOverlay,
skipTraversal: widget.skipTraversal,
),
);
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.escape): _removeRootOverlay,
},
child: FocusScope(child: Stack(children: children)),
);
});
_rootEntry.addEntry(context, this, newEntry, widget.asBarrier);
}
void close({
bool notify = true,
}) {
if (_rootEntry.contains(this)) {
_rootEntry.removeEntry(this);
if (notify) {
widget.onClose?.call();
}
}
}
void _removeRootOverlay() {
_rootEntry.popEntry();
if (widget.mutex?.state == this) {
widget.mutex?.removeState();
}
}
@override
void deactivate() {
close(notify: false);
super.deactivate();
}
@override
Widget build(BuildContext context) {
return PopoverTarget(
link: popoverLink,
child: _buildChild(context),
);
}
Widget _buildChild(BuildContext context) {
if (widget.triggerActions == 0) {
return widget.child;
}
return MouseRegion(
onEnter: (event) {
if (widget.triggerActions & PopoverTriggerFlags.hover != 0) {
showOverlay();
}
},
child: _buildClickHandler(
widget.child,
() {
widget.onOpen?.call();
if (widget.triggerActions & PopoverTriggerFlags.click != 0) {
showOverlay();
}
},
),
);
}
Widget _buildClickHandler(Widget child, VoidCallback handler) {
switch (widget.clickHandler) {
case PopoverClickHandler.listener:
return Listener(
onPointerDown: (_) => _callHandler(handler),
child: child,
);
case PopoverClickHandler.gestureDetector:
return GestureDetector(
onTap: () => _callHandler(handler),
child: child,
);
}
}
void _callHandler(VoidCallback handler) {
if (_rootEntry.contains(this)) {
close();
} else {
handler();
}
}
}
class PopoverContainer extends StatefulWidget {
final Widget? Function(BuildContext context) popupBuilder;
final PopoverDirection direction;
final PopoverLink popoverLink;
final Offset offset;
final EdgeInsets windowPadding;
final void Function() onClose;
final void Function() onCloseAll;
final bool skipTraversal;
const PopoverContainer({
super.key,
required this.popupBuilder,
required this.direction,
required this.popoverLink,
required this.offset,
required this.windowPadding,
required this.onClose,
required this.onCloseAll,
required this.skipTraversal,
});
@override
State<StatefulWidget> createState() => PopoverContainerState();
static PopoverContainerState of(BuildContext context) {
if (context is StatefulElement && context.state is PopoverContainerState) {
return context.state as PopoverContainerState;
}
final PopoverContainerState? result =
context.findAncestorStateOfType<PopoverContainerState>();
return result!;
}
}
class PopoverContainerState extends State<PopoverContainer> {
@override
Widget build(BuildContext context) {
return Focus(
autofocus: true,
skipTraversal: widget.skipTraversal,
child: CustomSingleChildLayout(
delegate: PopoverLayoutDelegate(
direction: widget.direction,
link: widget.popoverLink,
offset: widget.offset,
windowPadding: widget.windowPadding,
),
child: widget.popupBuilder(context),
),
);
}
void close() => widget.onClose();
void closeAll() => widget.onCloseAll();
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib/src/follower.dart | import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
class PopoverCompositedTransformFollower extends CompositedTransformFollower {
const PopoverCompositedTransformFollower({
super.key,
required super.link,
super.showWhenUnlinked = true,
super.offset = Offset.zero,
super.targetAnchor = Alignment.topLeft,
super.followerAnchor = Alignment.topLeft,
super.child,
});
@override
PopoverRenderFollowerLayer createRenderObject(BuildContext context) {
final screenSize = MediaQuery.of(context).size;
return PopoverRenderFollowerLayer(
screenSize: screenSize,
link: link,
showWhenUnlinked: showWhenUnlinked,
offset: offset,
leaderAnchor: targetAnchor,
followerAnchor: followerAnchor,
);
}
@override
void updateRenderObject(
BuildContext context, PopoverRenderFollowerLayer renderObject) {
final screenSize = MediaQuery.of(context).size;
renderObject
..screenSize = screenSize
..link = link
..showWhenUnlinked = showWhenUnlinked
..offset = offset
..leaderAnchor = targetAnchor
..followerAnchor = followerAnchor;
}
}
class PopoverRenderFollowerLayer extends RenderFollowerLayer {
Size screenSize;
PopoverRenderFollowerLayer({
required super.link,
super.showWhenUnlinked = true,
super.offset = Offset.zero,
super.leaderAnchor = Alignment.topLeft,
super.followerAnchor = Alignment.topLeft,
super.child,
required this.screenSize,
});
@override
void paint(PaintingContext context, Offset offset) {
super.paint(context, offset);
if (link.leader == null) {
return;
}
if (link.leader!.offset.dx + link.leaderSize!.width + size.width >
screenSize.width) {
debugPrint("over flow");
}
debugPrint(
"right: ${link.leader!.offset.dx + link.leaderSize!.width + size.width}, screen with: ${screenSize.width}");
}
}
class EdgeFollowerLayer extends FollowerLayer {
EdgeFollowerLayer({
required super.link,
super.showWhenUnlinked = true,
super.unlinkedOffset = Offset.zero,
super.linkedOffset = Offset.zero,
});
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib/src/layout.dart | import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import './popover.dart';
class PopoverLayoutDelegate extends SingleChildLayoutDelegate {
PopoverLink link;
PopoverDirection direction;
final Offset offset;
final EdgeInsets windowPadding;
PopoverLayoutDelegate({
required this.link,
required this.direction,
required this.offset,
required this.windowPadding,
});
@override
bool shouldRelayout(PopoverLayoutDelegate oldDelegate) {
if (direction != oldDelegate.direction) {
return true;
}
if (link != oldDelegate.link) {
return true;
}
if (link.leaderOffset != oldDelegate.link.leaderOffset) {
return true;
}
if (link.leaderSize != oldDelegate.link.leaderSize) {
return true;
}
return false;
}
@override
Size getSize(BoxConstraints constraints) {
return Size(
constraints.maxWidth - windowPadding.left - windowPadding.right,
constraints.maxHeight - windowPadding.top - windowPadding.bottom,
);
}
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return BoxConstraints(
maxWidth: constraints.maxWidth - windowPadding.left - windowPadding.right,
maxHeight:
constraints.maxHeight - windowPadding.top - windowPadding.bottom,
);
// assert(link.leaderSize != null);
// // if (link.leaderSize == null) {
// // return constraints.loosen();
// // }
// final anchorRect = Rect.fromLTWH(
// link.leaderOffset!.dx,
// link.leaderOffset!.dy,
// link.leaderSize!.width,
// link.leaderSize!.height,
// );
// BoxConstraints childConstraints;
// switch (direction) {
// case PopoverDirection.topLeft:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.left,
// anchorRect.top,
// ));
// break;
// case PopoverDirection.topRight:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth - anchorRect.right,
// anchorRect.top,
// ));
// break;
// case PopoverDirection.bottomLeft:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.left,
// constraints.maxHeight - anchorRect.bottom,
// ));
// break;
// case PopoverDirection.bottomRight:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth - anchorRect.right,
// constraints.maxHeight - anchorRect.bottom,
// ));
// break;
// case PopoverDirection.center:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth,
// constraints.maxHeight,
// ));
// break;
// case PopoverDirection.topWithLeftAligned:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth - anchorRect.left,
// anchorRect.top,
// ));
// break;
// case PopoverDirection.topWithCenterAligned:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth,
// anchorRect.top,
// ));
// break;
// case PopoverDirection.topWithRightAligned:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.right,
// anchorRect.top,
// ));
// break;
// case PopoverDirection.rightWithTopAligned:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth - anchorRect.right,
// constraints.maxHeight - anchorRect.top,
// ));
// break;
// case PopoverDirection.rightWithCenterAligned:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth - anchorRect.right,
// constraints.maxHeight,
// ));
// break;
// case PopoverDirection.rightWithBottomAligned:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth - anchorRect.right,
// anchorRect.bottom,
// ));
// break;
// case PopoverDirection.bottomWithLeftAligned:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.left,
// constraints.maxHeight - anchorRect.bottom,
// ));
// break;
// case PopoverDirection.bottomWithCenterAligned:
// childConstraints = BoxConstraints.loose(Size(
// constraints.maxWidth,
// constraints.maxHeight - anchorRect.bottom,
// ));
// break;
// case PopoverDirection.bottomWithRightAligned:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.right,
// constraints.maxHeight - anchorRect.bottom,
// ));
// break;
// case PopoverDirection.leftWithTopAligned:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.left,
// constraints.maxHeight - anchorRect.top,
// ));
// break;
// case PopoverDirection.leftWithCenterAligned:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.left,
// constraints.maxHeight,
// ));
// break;
// case PopoverDirection.leftWithBottomAligned:
// childConstraints = BoxConstraints.loose(Size(
// anchorRect.left,
// anchorRect.bottom,
// ));
// break;
// case PopoverDirection.custom:
// childConstraints = constraints.loosen();
// break;
// default:
// throw UnimplementedError();
// }
// return childConstraints;
}
@override
Offset getPositionForChild(Size size, Size childSize) {
if (link.leaderSize == null) {
return Offset.zero;
}
final anchorRect = Rect.fromLTWH(
link.leaderOffset!.dx + offset.dx,
link.leaderOffset!.dy + offset.dy,
link.leaderSize!.width,
link.leaderSize!.height,
);
Offset position;
switch (direction) {
case PopoverDirection.topLeft:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top - childSize.height,
);
break;
case PopoverDirection.topRight:
position = Offset(
anchorRect.right,
anchorRect.top - childSize.height,
);
break;
case PopoverDirection.bottomLeft:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.bottom,
);
break;
case PopoverDirection.bottomRight:
position = Offset(
anchorRect.right,
anchorRect.bottom,
);
break;
case PopoverDirection.center:
position = anchorRect.center;
break;
case PopoverDirection.topWithLeftAligned:
position = Offset(
anchorRect.left,
anchorRect.top - childSize.height,
);
break;
case PopoverDirection.topWithCenterAligned:
position = Offset(
anchorRect.left + anchorRect.width / 2.0 - childSize.width / 2.0,
anchorRect.top - childSize.height,
);
break;
case PopoverDirection.topWithRightAligned:
position = Offset(
anchorRect.right - childSize.width,
anchorRect.top - childSize.height,
);
break;
case PopoverDirection.rightWithTopAligned:
position = Offset(anchorRect.right, anchorRect.top);
break;
case PopoverDirection.rightWithCenterAligned:
position = Offset(
anchorRect.right,
anchorRect.top + anchorRect.height / 2.0 - childSize.height / 2.0,
);
break;
case PopoverDirection.rightWithBottomAligned:
position = Offset(
anchorRect.right,
anchorRect.bottom - childSize.height,
);
break;
case PopoverDirection.bottomWithLeftAligned:
position = Offset(
anchorRect.left,
anchorRect.bottom,
);
break;
case PopoverDirection.bottomWithCenterAligned:
position = Offset(
anchorRect.left + anchorRect.width / 2.0 - childSize.width / 2.0,
anchorRect.bottom,
);
break;
case PopoverDirection.bottomWithRightAligned:
position = Offset(
anchorRect.right - childSize.width,
anchorRect.bottom,
);
break;
case PopoverDirection.leftWithTopAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top,
);
break;
case PopoverDirection.leftWithCenterAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.top + anchorRect.height / 2.0 - childSize.height / 2.0,
);
break;
case PopoverDirection.leftWithBottomAligned:
position = Offset(
anchorRect.left - childSize.width,
anchorRect.bottom - childSize.height,
);
break;
default:
throw UnimplementedError();
}
return Offset(
math.max(
windowPadding.left,
math.min(
windowPadding.left + size.width - childSize.width, position.dx)),
math.max(
windowPadding.top,
math.min(
windowPadding.top + size.height - childSize.height, position.dy)),
);
}
}
class PopoverTarget extends SingleChildRenderObjectWidget {
final PopoverLink link;
const PopoverTarget({
super.key,
super.child,
required this.link,
});
@override
PopoverTargetRenderBox createRenderObject(BuildContext context) {
return PopoverTargetRenderBox(
link: link,
);
}
@override
void updateRenderObject(
BuildContext context, PopoverTargetRenderBox renderObject) {
renderObject.link = link;
}
}
class PopoverTargetRenderBox extends RenderProxyBox {
PopoverLink link;
PopoverTargetRenderBox({required this.link, RenderBox? child}) : super(child);
@override
bool get alwaysNeedsCompositing => true;
@override
void performLayout() {
super.performLayout();
link.leaderSize = size;
}
@override
void paint(PaintingContext context, Offset offset) {
link.leaderOffset = localToGlobal(Offset.zero);
super.paint(context, offset);
}
@override
void detach() {
super.detach();
link.leaderOffset = null;
link.leaderSize = null;
}
@override
void attach(covariant PipelineOwner owner) {
super.attach(owner);
if (hasSize) {
// The leaderSize was set after [performLayout], but was
// set to null when [detach] get called.
//
// set the leaderSize when attach get called
link.leaderSize = size;
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<PopoverLink>('link', link));
}
}
class PopoverLink {
Offset? leaderOffset;
Size? leaderSize;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib/src/mask.dart | import 'dart:collection';
import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flutter/material.dart';
typedef EntryMap = LinkedHashMap<PopoverState, OverlayEntryContext>;
class RootOverlayEntry {
final EntryMap _entries = EntryMap();
RootOverlayEntry();
void addEntry(
BuildContext context,
PopoverState newState,
OverlayEntry entry,
bool asBarrier,
) {
_entries[newState] = OverlayEntryContext(entry, newState, asBarrier);
Overlay.of(context).insert(entry);
}
bool contains(PopoverState oldState) {
return _entries.containsKey(oldState);
}
void removeEntry(PopoverState oldState) {
if (_entries.isEmpty) return;
final removedEntry = _entries.remove(oldState);
removedEntry?.overlayEntry.remove();
}
bool get isEmpty => _entries.isEmpty;
bool get isNotEmpty => _entries.isNotEmpty;
bool hasEntry() {
return _entries.isNotEmpty;
}
PopoverState? popEntry() {
if (_entries.isEmpty) return null;
final lastEntry = _entries.values.last;
_entries.remove(lastEntry.popoverState);
lastEntry.overlayEntry.remove();
lastEntry.popoverState.widget.onClose?.call();
if (lastEntry.asBarrier) {
return lastEntry.popoverState;
} else {
return popEntry();
}
}
}
class OverlayEntryContext {
final bool asBarrier;
final PopoverState popoverState;
final OverlayEntry overlayEntry;
OverlayEntryContext(
this.overlayEntry,
this.popoverState,
this.asBarrier,
);
}
class PopoverMask extends StatelessWidget {
final void Function() onTap;
final Decoration? decoration;
const PopoverMask({super.key, required this.onTap, this.decoration});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: Container(
decoration: decoration,
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/lib/src/mutex.dart | import 'package:flutter/material.dart';
import 'popover.dart';
/// If multiple popovers are exclusive,
/// pass the same mutex to them.
class PopoverMutex {
final _PopoverStateNotifier _stateNotifier = _PopoverStateNotifier();
PopoverMutex();
void removePopoverListener(VoidCallback listener) {
_stateNotifier.removeListener(listener);
}
VoidCallback listenOnPopoverChanged(VoidCallback callback) {
listenerCallback() {
callback();
}
_stateNotifier.addListener(listenerCallback);
return listenerCallback;
}
void close() => _stateNotifier.state?.close();
PopoverState? get state => _stateNotifier.state;
set state(PopoverState? newState) => _stateNotifier.state = newState;
void removeState() {
_stateNotifier.state = null;
}
void dispose() {
_stateNotifier.dispose();
}
}
class _PopoverStateNotifier extends ChangeNotifier {
PopoverState? _state;
PopoverState? get state => _state;
set state(PopoverState? newState) {
if (_state != null && _state != newState) {
_state?.close();
}
_state = newState;
notifyListeners();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/test/popover_test.dart | import 'package:flutter_test/flutter_test.dart';
void main() {
test('adds one to input values', () {
// final calculator = Calculator();
// expect(calculator.addOne(2), 3);
// expect(calculator.addOne(-7), -6);
// expect(calculator.addOne(0), 1);
});
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/example | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/example/lib/example_button.dart | import 'package:flutter/material.dart';
import 'package:appflowy_popover/appflowy_popover.dart';
class PopoverMenu extends StatefulWidget {
const PopoverMenu({super.key});
@override
State<StatefulWidget> createState() => _PopoverMenuState();
}
class _PopoverMenuState extends State<PopoverMenu> {
final PopoverMutex popOverMutex = PopoverMutex();
@override
Widget build(BuildContext context) {
return Material(
type: MaterialType.transparency,
child: Container(
width: 200,
height: 200,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: const BorderRadius.all(Radius.circular(8)),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 5,
blurRadius: 7,
offset: const Offset(0, 3), // changes position of shadow
),
],
),
child: ListView(children: [
Container(
margin: const EdgeInsets.all(8),
child: const Text("Popover",
style: TextStyle(
fontSize: 14,
color: Colors.black,
fontStyle: null,
decoration: null)),
),
Popover(
triggerActions:
PopoverTriggerFlags.hover | PopoverTriggerFlags.click,
mutex: popOverMutex,
offset: const Offset(10, 0),
popupBuilder: (BuildContext context) {
return const PopoverMenu();
},
child: TextButton(
onPressed: () {},
child: const Text("First"),
),
),
Popover(
triggerActions:
PopoverTriggerFlags.hover | PopoverTriggerFlags.click,
mutex: popOverMutex,
offset: const Offset(10, 0),
popupBuilder: (BuildContext context) {
return const PopoverMenu();
},
child: TextButton(
onPressed: () {},
child: const Text("Second"),
),
),
]),
));
}
}
class ExampleButton extends StatelessWidget {
final String label;
final Offset? offset;
final PopoverDirection? direction;
const ExampleButton({
super.key,
required this.label,
this.direction,
this.offset = Offset.zero,
});
@override
Widget build(BuildContext context) {
return Popover(
triggerActions: PopoverTriggerFlags.click,
offset: offset,
direction: direction ?? PopoverDirection.rightWithTopAligned,
child: TextButton(child: Text(label), onPressed: () {}),
popupBuilder: (BuildContext context) {
return const PopoverMenu();
},
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/example | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/appflowy_popover/example/lib/main.dart | import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:flutter/material.dart';
import "./example_button.dart";
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'AppFlowy Popover Example'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// 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
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@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 Scaffold(
appBar: 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: Text(widget.title),
),
body: const Row(
children: [
Column(children: [
ExampleButton(
label: "Left top",
offset: Offset(0, 10),
direction: PopoverDirection.bottomWithLeftAligned,
),
Expanded(child: SizedBox.shrink()),
ExampleButton(
label: "Left bottom",
offset: Offset(0, -10),
direction: PopoverDirection.topWithLeftAligned,
),
]),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ExampleButton(
label: "Top",
offset: Offset(0, 10),
direction: PopoverDirection.bottomWithCenterAligned,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ExampleButton(
label: "Central",
offset: Offset(0, 10),
direction: PopoverDirection.bottomWithCenterAligned,
),
],
),
),
ExampleButton(
label: "Bottom",
offset: Offset(0, -10),
direction: PopoverDirection.topWithCenterAligned,
),
],
),
),
Column(
children: [
ExampleButton(
label: "Right top",
offset: Offset(0, 10),
direction: PopoverDirection.bottomWithRightAligned,
),
Expanded(child: SizedBox.shrink()),
ExampleButton(
label: "Right bottom",
offset: Offset(0, -10),
direction: PopoverDirection.topWithRightAligned,
),
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg/lib/flowy_svg.dart | /// A Flutter package to generate Dart code for SVG files.
library flowy_svg;
export 'src/flowy_svg.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg/lib/src/flowy_svg.dart | import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
/// The class for FlowySvgData that the code generator will implement
class FlowySvgData {
/// The svg data
const FlowySvgData(
this.path,
);
/// The path to the svg data in appflowy assets/images
final String path;
}
/// For icon that needs to change color when it is on hovered
///
/// Get the hover color from ThemeData
class FlowySvg extends StatelessWidget {
/// Construct a FlowySvg Widget
const FlowySvg(
this.svg, {
super.key,
this.size,
this.color,
this.blendMode = BlendMode.srcIn,
});
/// The data for the flowy svg. Will be generated by the generator in this
/// package within bin/flowy_svg.dart
final FlowySvgData svg;
/// The size of the svg
final Size? size;
/// The color of the svg.
///
/// This property will not be applied to the underlying svg widget if the
/// blend mode is null, but the blend mode defaults to [BlendMode.srcIn]
/// if it is not explicitly set to null.
final Color? color;
/// The blend mode applied to the svg.
///
/// If the blend mode is null then the icon color will not be applied.
/// Set both the icon color and blendMode in order to apply color to the
/// svg widget.
final BlendMode? blendMode;
@override
Widget build(BuildContext context) {
final iconColor = color ?? Theme.of(context).iconTheme.color;
final textScaleFactor = MediaQuery.textScalerOf(context).scale(1);
return Transform.scale(
scale: textScaleFactor,
child: SizedBox(
width: size?.width,
height: size?.height,
child: SvgPicture.asset(
_normalized(),
width: size?.width,
height: size?.height,
colorFilter: iconColor != null && blendMode != null
? ColorFilter.mode(
iconColor,
blendMode!,
)
: null,
),
),
);
}
/// If the SVG's path does not start with `assets/`, it is
/// normalized and directed to `assets/images/`
///
/// If the SVG does not end with `.svg`, then we append the file extension
///
String _normalized() {
var path = svg.path;
if (!path.toLowerCase().startsWith('assets/')) {
path = 'assets/images/$path';
}
if (!path.toLowerCase().endsWith('.svg')) {
path = '$path.svg';
}
return path;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg/bin/options.dart | /// The options for the command line tool
class Options {
/// The source directory which the tool will use to generate the output file
String? sourceDir;
/// The output directory which the tool will use to output the file(s)
String? outputDir;
/// The name of the file that will be generated
String? outputFile;
@override
String toString() {
return '''
Options:
sourceDir: $sourceDir
outputDir: $outputDir
name: $outputFile
''';
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/packages/flowy_svg/bin/flowy_svg.dart | import 'dart:async';
import 'dart:developer';
import 'dart:io';
import 'package:args/args.dart';
import 'package:path/path.dart' as path;
import 'options.dart';
const languageKeywords = [
'abstract',
'else',
'import',
'show',
'as',
'enum',
'static',
'assert',
'export',
'interface',
'super',
'async',
'extends',
'is',
'switch',
'await',
'extension',
'late',
'sync',
'base',
'external',
'library',
'this',
'break',
'factory',
'mixin',
'throw',
'case',
'false',
'new',
'true',
'catch',
'final',
'variable',
'null',
'try',
'class',
'final',
'class',
'on',
'typedef',
'const',
'finally',
'operator',
'var',
'continue',
'for',
'part',
'void',
'covariant',
'Function',
'required',
'when',
'default',
'get',
'rethrow',
'while',
'deferred',
'hide',
'return',
'with',
'do',
'if',
'sealed',
'yield',
'dynamic',
'implements',
'set',
];
void main(List<String> args) {
if (_isHelpCommand(args)) {
_printHelperDisplay();
} else {
generateSvgData(_generateOption(args));
}
}
bool _isHelpCommand(List<String> args) {
return args.length == 1 && (args[0] == '--help' || args[0] == '-h');
}
void _printHelperDisplay() {
final parser = _generateArgParser(null);
log(parser.usage);
}
Options _generateOption(List<String> args) {
final generateOptions = Options();
_generateArgParser(generateOptions).parse(args);
return generateOptions;
}
ArgParser _generateArgParser(Options? generateOptions) {
final parser = ArgParser()
..addOption(
'source-dir',
abbr: 'S',
defaultsTo: '/assets/flowy_icons',
callback: (String? x) => generateOptions!.sourceDir = x,
help: 'Folder containing localization files',
)
..addOption(
'output-dir',
abbr: 'O',
defaultsTo: '/lib/generated',
callback: (String? x) => generateOptions!.outputDir = x,
help: 'Output folder stores for the generated file',
)
..addOption(
'name',
abbr: 'N',
defaultsTo: 'flowy_svgs.g.dart',
callback: (String? x) => generateOptions!.outputFile = x,
help: 'The name of the output file that this tool will generate',
);
return parser;
}
Directory source(Options options) => Directory(
[
Directory.current.path,
Directory.fromUri(
Uri.file(
options.sourceDir!,
windows: Platform.isWindows,
),
).path,
].join(),
);
File output(Options options) => File(
[
Directory.current.path,
Directory.fromUri(
Uri.file(options.outputDir!, windows: Platform.isWindows),
).path,
Platform.pathSeparator,
File.fromUri(
Uri.file(
options.outputFile!,
windows: Platform.isWindows,
),
).path,
].join(),
);
/// generates the svg data
Future<void> generateSvgData(Options options) async {
// the source directory that this is targeting
final src = source(options);
// the output directory that this is targeting
final out = output(options);
var files = await dirContents(src);
files = files.where((f) => f.path.contains('.svg')).toList();
await generate(files, out, options);
}
/// List the contents of the directory
Future<List<FileSystemEntity>> dirContents(Directory dir) {
final files = <FileSystemEntity>[];
final completer = Completer<List<FileSystemEntity>>();
dir.list(recursive: true).listen(
files.add,
onDone: () => completer.complete(files),
);
return completer.future;
}
/// Generate the abstract class for the FlowySvg data.
Future<void> generate(
List<FileSystemEntity> files,
File output,
Options options,
) async {
final generated = File(output.path);
// create the output file if it doesn't exist
if (!generated.existsSync()) {
generated.createSync(recursive: true);
}
// content of the generated file
final builder = StringBuffer()..writeln(prelude);
files.whereType<File>().forEach(
(element) => builder.writeln(lineFor(element, options)),
);
builder.writeln(postlude);
generated.writeAsStringSync(builder.toString());
}
String lineFor(File file, Options options) {
final name = varNameFor(file, options);
return " static const $name = FlowySvgData('${pathFor(file)}');";
}
String pathFor(File file) {
final relative = path.relative(file.path, from: Directory.current.path);
final uri = Uri.file(relative);
return uri.toFilePath(windows: false);
}
String varNameFor(File file, Options options) {
final from = source(options).path;
final relative = Uri.file(path.relative(file.path, from: from));
final parts = relative.pathSegments;
final cleaned = parts.map(clean).toList();
var simplified = cleaned.reversed
// join all cleaned path segments with an underscore
.join('_')
// there are some cases where the segment contains a dart reserved keyword
// in this case, the path will be suffixed with an underscore which means
// there will be a double underscore, so we have to replace the double
// underscore with one underscore
.replaceAll(RegExp('_+'), '_');
// rename icon based on relative path folder name (16x, 24x, etc.)
for (final key in sizeMap.keys) {
simplified = simplified.replaceAll(key, sizeMap[key]!);
}
return simplified;
}
const sizeMap = {r'$16x': 's', r'$24x': 'm', r'$32x': 'lg', r'$40x': 'xl'};
/// cleans the path segment before rejoining the path into a variable name
String clean(String segment) {
final cleaned = segment
// replace all dashes with underscores (dash is invalid in
// a variable name)
.replaceAll('-', '_')
// replace all spaces with an underscore
.replaceAll(RegExp(r'\s+'), '_')
// replace all file extensions with an empty string
.replaceAll(RegExp(r'\.[^.]*$'), '')
// convert everything to lower case
.toLowerCase();
if (languageKeywords.contains(cleaned)) {
return '${cleaned}_';
} else if (cleaned.startsWith(RegExp('[0-9]'))) {
return '\$$cleaned';
}
return cleaned;
}
/// The prelude for the generated file
const prelude = '''
// DO NOT EDIT. This code is generated by the flowy_svg script
// import the widget with from this package
import 'package:flowy_svg/flowy_svg.dart';
// export as convenience to the programmer
export 'package:flowy_svg/flowy_svg.dart';
/// A class to easily list all the svgs in the app
class FlowySvgs {''';
/// The postlude for the generated file
const postlude = '''
}
''';
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/generated_plugin_registrant.dart | //
// Generated file. Do not edit.
//
// ignore_for_file: directives_ordering
// ignore_for_file: lines_longer_than_80_chars
// ignore_for_file: depend_on_referenced_packages
import 'package:geolocator_web/geolocator_web.dart';
import 'package:shared_preferences_web/shared_preferences_web.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
// ignore: public_member_api_docs
void registerPlugins(Registrar registrar) {
GeolocatorPlugin.registerWith(registrar);
SharedPreferencesPlugin.registerWith(registrar);
registrar.registerMessageHandler();
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/main.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:vishal_mega_mart_app/screens/constant.dart';
import 'package:vishal_mega_mart_app/screens/home.dart';
import 'package:vishal_mega_mart_app/screens/model/token.dart';
import 'package:vishal_mega_mart_app/screens/sharedpref.dart';
import 'package:vishal_mega_mart_app/screens/splashscreen.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
var TOKEN;
var firstLogin;
Future<TokenModel> Token() async {
// ignore: avoid_print
print(
"======= API CALLING =========",
);
// const token = tokens.TOKEN;
var headers = {
'Authorization':
'Basic OTgwNGY4YjQtZTQzMS00OTUwLWE3NDMtYmRhMjJmMDllYmI4OlZNTU1vYmlsZUFwcDIwMjAj',
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie':
'route=1660200976.763.118.455900|b4b9366450a28a63ee5f72b7d8464f5c'
};
var request = http.Request('POST',
Uri.parse('https://account.demandware.com/dwsso/oauth2/access_token'));
request.bodyFields = {'grant_type': 'client_credentials'};
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
final res = await response.stream.bytesToString();
Map valueMap = json.decode(res);
dynamic Token = valueMap.remove('access_token');
TokenValue.mytoken = Token;
TOKEN = Token;
final jwt = Token;
await appPreferences.saveStringPreference("my_token", jwt);
print("+++++777jwt7777+++++${jwt}+++++++++++++");
if (response.statusCode == 200) {
//print("=======Product====== ${res}");
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
// print("======= Failed to load posts =========");
}
return TokenModel.fromJson(jsonDecode(res));
}
void updatevalue() {
TokenValue.mytoken = TOKEN;
print("+++++ TTTTTTTTTT+++++${firstLogin}+++++++++++++");
}
@override
void initState() {
// TODO: implement initState
super.initState();
print("+++++Token in init state+++++${firstLogin}+++++++++++++");
updatevalue();
Token();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SplashScreen(),
);
}
}
class TokenValue {
static var mytoken;
}
// addStringToSF() async {
// SharedPreferences prefs = await SharedPreferences.getInstance();
// prefs.setString('stringValue', TokenValue.mytoken);
// }
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/sharedpref.dart | import 'package:shared_preferences/shared_preferences.dart';
class AppPreferences {
AppPreferences._internal();
factory AppPreferences() {
return _appPreferences;
}
final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
saveStringPreference(String key, String value) async {
final SharedPreferences prefs = await _prefs;
await prefs.setString(key, value);
}
saveBoolPreference(String key, bool value) async {
final SharedPreferences prefs = await _prefs;
await prefs.setBool(key, value);
}
saveIntPreference(String key, int value) async {
final SharedPreferences prefs = await _prefs;
await prefs.setInt(key, value);
}
saveDoublePreference(String key, double value) async {
final SharedPreferences prefs = await _prefs;
await prefs.setDouble(key, value);
}
saveListPreference(String key, List<String> value) async {
final SharedPreferences prefs = await _prefs;
await prefs.setStringList(key, value);
}
getStringPreference(String key) async {
final SharedPreferences prefs = await _prefs;
return prefs.getString(key) ?? '';
}
getBoolPreference(String key) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getBool(key) ?? false;
}
getIntPreference(String key) async {
final SharedPreferences prefs = await _prefs;
return prefs.getInt(key) ?? -1;
}
getDoublePreference(String key) async {
final SharedPreferences prefs = await _prefs;
return prefs.getDouble(key) ?? -1;
}
getListPreference(String key) async {
final SharedPreferences prefs = await _prefs;
return prefs.getStringList(key) ?? '';
}
// void clearPreferences() async {
// final SharedPreferences prefs = await _prefs;
// prefs.setString(Constants.userName, '');
// prefs.setString(Constants.firstName, '');
// prefs.setString(Constants.lastName, '');
// prefs.setString(Constants.contactNumber, '');
// prefs.setString(Constants.accessToken, '');
// prefs.setBool(Constants.rememberMe, false);
// prefs.setBool(Constants.doneOnBoarding, false);
// prefs.setBool(Constants.firstLogin, false);
// prefs.setInt(Constants.userId, -1);
// prefs.setString(Constants.userEmail, '');
// prefs.setString(Constants.userRole, '');
// prefs.setString(Constants.profileImage, '');
// }
// Future savePreferences(String token, String id, String firstname, String lastname, String userName,
// String email, String contact, String? loginTime, String profileImage) async {
// appPreferences.saveBoolPreference(Constants.rememberMe, true);
// appPreferences.saveBoolPreference(Constants.firstLogin, loginTime!=null);
// appPreferences.saveStringPreference(Constants.userId, id);
// appPreferences.saveStringPreference(Constants.accessToken, token);
// appPreferences.saveStringPreference(Constants.firstName, firstname);
// appPreferences.saveStringPreference(Constants.lastName, lastname);
// appPreferences.saveStringPreference(Constants.userName, userName);
// appPreferences.saveStringPreference(Constants.userEmail, email);
// appPreferences.saveStringPreference(Constants.contactNumber, contact);
// appPreferences.saveStringPreference(Constants.profileImage, profileImage);
// }
static final AppPreferences _appPreferences = AppPreferences._internal();
}
AppPreferences appPreferences = AppPreferences();
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/api.dart | import 'package:flutter/material.dart';
class Commonwidgets extends StatelessWidget {
String? imglink;
final String discription;
final String brand;
String? price;
Commonwidgets(
{required this.brand,
this.price,
required this.discription,
this.imglink});
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(left: 10),
//color: Colors.red[200],
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.only(
top: 10.0,
),
height: 130.0,
width: 130.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(imglink.toString()),
),
),
),
const SizedBox(
height: 2,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
brand,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
const SizedBox(
height: 3,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
discription,
),
),
const SizedBox(
height: 2,
),
// Align(
// alignment: Alignment.centerLeft,
// child: Text(
// price.toString(),
// style: const TextStyle(fontWeight: FontWeight.bold),
// ),
// ),
],
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/productDetails.dart | import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vishal_mega_mart_app/screens/bloc/productbloc.dart';
import 'package:vishal_mega_mart_app/screens/productdetailsapipage.dart';
import 'package:vishal_mega_mart_app/screens/themes/app_fonts.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
class ProductDetails extends StatefulWidget {
const ProductDetails({Key? key}) : super(key: key);
@override
State<ProductDetails> createState() => _ProductDetailsState();
}
class _ProductDetailsState extends State<ProductDetails> {
@override
Widget build(BuildContext context) {
bloc.fetchallproduct();
return Scaffold(
appBar:PreferredSize(
preferredSize: Size.fromHeight(80.0), // here the desired height
child: AppBar(
backgroundColor: AppTheme.appThemeColor,
automaticallyImplyLeading: false,
toolbarHeight: 70,
elevation: 0,
titleSpacing: 0,
title: Container(
width: MediaQuery.of(context).size.width,
height: 55,
child: Padding(
padding: EdgeInsets.only(left: 12, right: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image.asset(
"assets/location.png",
height: 25,
color: AppTheme.whitColor,
),
Expanded(
child: Container(
child: Padding(
padding: EdgeInsets.only(left: 14, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"Noida Sector 1",
style: GoogleFonts.poppins(
color: AppTheme.whitColor,
fontSize: AppFonts.subtitle1),
),
],
),
],
),
),
)),
Image.asset(
"assets/like.png",
height: 25,
color: AppTheme.whitColor,
),
SizedBox(
width: 12,
),
Image.asset(
"assets/shopping-cart.png",
height: 25,
color: AppTheme.whitColor,
),
]),
),
),
),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: SizedBox(
height: 1700,
child:SearchProduct()
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/lastapi.dart | import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/bloc/lastbloc.dart';
import 'package:vishal_mega_mart_app/screens/category.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'package:vishal_mega_mart_app/screens/model/lastmodel.dart';
import 'model/category_section.dart';
class list extends StatelessWidget {
@override
Widget build(BuildContext context) {
bloc.fetchalllast();
return Scaffold(
body: StreamBuilder(
stream: bloc.alllastapi,
builder: (context, AsyncSnapshot<LastModel> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: 7,
itemBuilder: (BuildContext context, int index) => CategoriesItem(
categoryName: snapshot.data!.categories![index].pageDescription!.pageDefault.toString(),
image: snapshot.data?.categories?[index].thumbnail,
),
);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/lastscrenn.dart | import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vishal_mega_mart_app/screens/lastapi.dart';
import 'package:vishal_mega_mart_app/screens/lastpagescreen.dart';
import 'package:vishal_mega_mart_app/screens/themes/app_fonts.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
class LatScreen extends StatefulWidget {
const LatScreen({Key? key}) : super(key: key);
@override
State<LatScreen> createState() => _LatScreenState();
}
class _LatScreenState extends State<LatScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar:PreferredSize(
preferredSize: Size.fromHeight(80.0), // here the desired height
child: AppBar(
backgroundColor: AppTheme.appThemeColor,
automaticallyImplyLeading: false,
toolbarHeight: 70,
elevation: 0,
titleSpacing: 0,
title: Container(
width: MediaQuery.of(context).size.width,
height: 55,
child: Padding(
padding: EdgeInsets.only(left: 12, right: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image.asset(
"assets/location.png",
height: 25,
color: AppTheme.whitColor,
),
Expanded(
child: Container(
child: Padding(
padding: EdgeInsets.only(left: 14, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"Noida Sector 1",
style: GoogleFonts.poppins(
color: AppTheme.whitColor,
fontSize: AppFonts.subtitle1),
),
],
),
],
),
),
)),
Image.asset(
"assets/like.png",
height: 25,
color: AppTheme.whitColor,
),
SizedBox(
width: 12,
),
Image.asset(
"assets/shopping-cart.png",
height: 25,
color: AppTheme.whitColor,
),
]),
),
),
),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
margin: EdgeInsets.all(10),
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height * .14,
width: double.infinity,
child: list()),
Container(height: 3000, child: LastPage()),
// LastPage(),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/categoryss.dart | import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/bloc/categorybloc.dart';
import 'package:vishal_mega_mart_app/screens/category.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'model/category_section.dart';
class MovieList extends StatelessWidget {
@override
Widget build(BuildContext context) {
bloc.fetchallcategory();
return Scaffold(
body: StreamBuilder(
stream: bloc.allcategory,
builder: (context, AsyncSnapshot<CategorySection> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: 9,
itemBuilder: (BuildContext context, int index) => CategoriesItem(
categoryName: snapshot.data!.categories![index].name!.descriptionDefault,
image: snapshot.data?.categories?[index].thumbnail,
),
);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/category.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vishal_mega_mart_app/screens/productDetails.dart';
import 'package:vishal_mega_mart_app/screens/subcat.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
class CategoriesItem extends StatelessWidget {
final String? image;
final String? categoryName;
CategoriesItem({
Key? key,
this.image,
this.categoryName = '',
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SubcatScreen(),
),
);
},
child: Container(
height: MediaQuery.of(context).size.height * .11,
width: MediaQuery.of(context).size.height * .14,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Container(
height: MediaQuery.of(context).size.height * .1,
width: MediaQuery.of(context).size.height * .1,
decoration: const BoxDecoration(
color: AppTheme.whitColor, shape: BoxShape.circle),
child: ClipRRect(
borderRadius: BorderRadius.circular(100),
child: image != null && image!.isNotEmpty
? Image.network(
image.toString(),
fit: BoxFit.contain,
)
: Image.asset(image.toString()),
),
),
Text(
categoryName.toString(),
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
color: AppTheme.blackText,
fontSize: 10,
fontWeight: FontWeight.normal,
wordSpacing: 0.3,
letterSpacing: 0.3,
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/page.dart |
import 'package:flutter/material.dart';
import 'package:flutter/src/foundation/key.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:vishal_mega_mart_app/screens/searchwidget.dart';
class Search extends StatefulWidget {
const Search({Key? key}) : super(key: key);
@override
State<Search> createState() => _SearchState();
}
class _SearchState extends State<Search> {
@override
Widget build(BuildContext context) {
return Scaffold(body: Random(),);
}
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/lastpagescreen.dart | import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/bloc/productlistbloc.dart';
import 'package:vishal_mega_mart_app/screens/lastpagewidget.dart';
import 'package:vishal_mega_mart_app/screens/model/lastmodel.dart';
import 'package:vishal_mega_mart_app/screens/model/productlist.dart';
import 'bloc/productlistbloc.dart';
class LastPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
bloc.fetchallproductlist();
return Scaffold(
// appBar: AppBar(
// backgroundColor: Colors.transparent,
// ),
body: StreamBuilder(
stream: bloc.allproductlist,
builder: (context, AsyncSnapshot<ProductListModel> snapshot) {
if (snapshot.hasData) {
return buildList(snapshot);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
);
}
Widget buildList(AsyncSnapshot<ProductListModel> snapshot) {
return GridView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: snapshot.data!.hits!.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return Commonwidget(
brand: snapshot.data!.hits![index].cBrand.toString(),
discription: snapshot.data!.hits![index].productName.toString(),
price: snapshot.data!.hits![index].cListprice.toString(),
imglink: snapshot.data!.hits![index].image!.link.toString());
},
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/subcategorywidget.dart | import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/lastpagescreen.dart';
import 'package:vishal_mega_mart_app/screens/lastscrenn.dart';
import 'package:vishal_mega_mart_app/screens/productDetails.dart';
class SubCat extends StatelessWidget {
final String text;
final String image;
SubCat({required this.image, required this.text});
@override
Widget build(BuildContext context) {
return Container(
height: 50.0,
margin: EdgeInsets.all(10),
child: Center(
child: Row(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(50),
child: image != null && image.isNotEmpty
? Image.network(
image,
fit: BoxFit.contain,
)
: Image.asset("assets/p.jpeg"),
),
ElevatedButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => LatScreen(),
),
);
},
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(80.0)),
// padding: EdgeInsets.all(0.0),
child: Ink(
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [
Color.fromARGB(255, 235, 120, 178),
Color.fromARGB(255, 166, 110, 152)
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
borderRadius: BorderRadius.circular(30.0)),
child: Container(
constraints: BoxConstraints(maxWidth: 250.0, minHeight: 50.0),
alignment: Alignment.center,
child: Text(
text,
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontSize: 15),
),
),
),
),
],
)),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/lastpagewidget.dart | import 'package:flutter/material.dart';
class Commonwidget extends StatelessWidget {
String? imglink;
final String discription;
final String brand;
String? price;
Commonwidget(
{required this.brand,
this.price,
required this.discription,
this.imglink});
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.only(left: 10),
//color: Colors.red[200],
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
margin: const EdgeInsets.only(
top: 10.0,
),
height: 130.0,
width: 130.0,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
image: DecorationImage(
fit: BoxFit.fill,
image: NetworkImage(imglink.toString()),
),
),
),
const SizedBox(
height: 2,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
brand,
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
const SizedBox(
height: 3,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
discription,
),
),
const SizedBox(
height: 2,
),
Align(
alignment: Alignment.centerLeft,
child: Text(
price.toString(),
style: const TextStyle(fontWeight: FontWeight.bold),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/splashscreen.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vishal_mega_mart_app/screens/home.dart';
import 'package:vishal_mega_mart_app/screens/themes/app_fonts.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
class SplashScreen extends StatefulWidget {
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
reDricet();
super.initState();
}
reDricet(){
Timer(Duration(seconds: 2), (() {
Navigator.of(context).push(MaterialPageRoute(builder: (_)=> Home()));
}));
}
@override
Widget build(BuildContext context) {
AppFonts(context);
return Scaffold(
backgroundColor: AppTheme.whitColor,
body: Center(
child: Container(
height: 100.0,
decoration: BoxDecoration(
color: AppTheme.whitColor,
borderRadius: BorderRadius.circular(0.0),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(10.0),
child: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
fit: BoxFit.cover,
height: 50,
width: 200,
),
Text(
"Welcome To Vishal Megamart",
style:GoogleFonts.poppins(
color:AppTheme.blackText,
fontSize: AppFonts.subtitle1,
fontWeight: FontWeight.w500
)
)
],
),
),
),
),
),
);
}
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/extra.dart |
import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
final outlineBorder = OutlineInputBorder(
borderSide: BorderSide(
color: AppTheme.scaffoldBackgroundColor, style: BorderStyle.solid, width: 1.2),
borderRadius: BorderRadius.circular(30),
);
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/constant.dart | import 'package:vishal_mega_mart_app/screens/model/token.dart';
class tokens {
static var TOKEN ;
}
class mytoken extends TokenModel {
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/home.dart | import 'dart:convert';
import 'dart:developer';
import 'package:carousel_pro/carousel_pro.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:http/http.dart' as http;
import 'package:vishal_mega_mart_app/screens/apis/tokenapi.dart';
import 'package:vishal_mega_mart_app/screens/bloc/categorybloc.dart';
import 'package:vishal_mega_mart_app/screens/categoryss.dart';
import 'package:vishal_mega_mart_app/screens/constant.dart';
import 'package:vishal_mega_mart_app/screens/extra.dart';
import 'package:vishal_mega_mart_app/screens/lastapi.dart';
import 'package:vishal_mega_mart_app/screens/model/token.dart';
import 'package:vishal_mega_mart_app/screens/page.dart';
import 'package:vishal_mega_mart_app/screens/productdetailsapipage.dart';
import 'package:vishal_mega_mart_app/screens/searchwidget.dart';
import 'package:vishal_mega_mart_app/screens/themes/app_fonts.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
final myController = TextEditingController();
@override
void dispose() {
// Clean up the controller when the widget is disposed.
print("++++++++++${myController.text}+++++++++++++");
myController.dispose();
super.dispose();
}
// Future<TokenModel> Token() async {
// // ignore: avoid_print
// print(
// "======= API CALLING =========",
// );
// // const token = tokens.TOKEN;
// var headers = {
// 'Authorization':
// 'Basic OTgwNGY4YjQtZTQzMS00OTUwLWE3NDMtYmRhMjJmMDllYmI4OlZNTU1vYmlsZUFwcDIwMjAj',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Cookie':
// 'route=1660200976.763.118.455900|b4b9366450a28a63ee5f72b7d8464f5c'
// };
// var request = http.Request('POST',
// Uri.parse('https://account.demandware.com/dwsso/oauth2/access_token'));
// request.bodyFields = {'grant_type': 'client_credentials'};
// request.headers.addAll(headers);
// http.StreamedResponse response = await request.send();
// final res = await response.stream.bytesToString();
// Map valueMap = json.decode(res);
// // print("=== VALUE MAP ==========");
// // print("=== VALUE MAP ===== ${valueMap}=====");
// dynamic Token = valueMap.remove('access_token');
// print('Value popped from the Map ${Token}');
// // tokens.TOKEN =Token;
// TokenValue.mytoken = Token;
// print("+++++7777777+++++${TokenValue.mytoken}+++++++++++++");
// if (response.statusCode == 200) {
// print("=======Product====== ${res}");
// print(await response.stream.bytesToString());
// } else {
// print(response.reasonPhrase);
// // print("======= Failed to load posts =========");
// }
// return TokenModel.fromJson(jsonDecode(res));
// }
void text() {
Searchtext.searchelemnt = myController.text;
print("++++++++++${myController.text}+++++++++++++");
print("++++++++++${Searchtext.searchelemnt}+++++++++++++");
}
@override
void initState() {
// TODO: implement initState
super.initState();
text();
// Token();
}
var category = [
{"name": "Women", "url": "assets/images.jpeg"},
{"name": "Men's Fashion", "url": "assets/men.webp"},
{"name": "Kids & Infants", "url": "assets/kid.webp"},
{"name": "Home & Kitchen", "url": "assets/home.jpeg"},
{"name": "Application", "url": "assets/electronic.jpeg"},
];
@override
Widget build(BuildContext context) {
bloc.fetchallcategory();
return Scaffold(
backgroundColor: Colors.white,
appBar: PreferredSize(
preferredSize: Size.fromHeight(80.0), // here the desired height
child: AppBar(
backgroundColor: AppTheme.appThemeColor,
automaticallyImplyLeading: false,
toolbarHeight: 70,
elevation: 0,
titleSpacing: 0,
title: Container(
width: MediaQuery.of(context).size.width,
height: 55,
child: Padding(
padding: EdgeInsets.only(left: 12, right: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image.asset(
"assets/location.png",
height: 25,
color: AppTheme.whitColor,
),
Expanded(
child: Container(
child: Padding(
padding: EdgeInsets.only(left: 14, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"Noida Sector 1",
style: GoogleFonts.poppins(
color: AppTheme.whitColor, fontSize: 17),
),
],
),
],
),
),
)),
Image.asset(
"assets/like.png",
height: 25,
color: AppTheme.whitColor,
),
SizedBox(
width: 12,
),
Image.asset(
"assets/shopping-cart.png",
height: 25,
color: AppTheme.whitColor,
),
]),
),
),
),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Container(
margin: EdgeInsets.all(10),
child: Column(
children: [
Padding(
padding: EdgeInsets.only(top: 10, right: 10, left: 10),
child: Container(
decoration: BoxDecoration(
color: AppTheme.whitColor,
borderRadius: BorderRadius.circular(30),
),
child: TextFormField(
keyboardType: TextInputType.text,
textInputAction: TextInputAction.next,
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w400,
letterSpacing: .5,
),
cursorColor: AppTheme.buttonThemeColor,
// cursorHeight: scaler.scalerV(20),
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
contentPadding:
const EdgeInsets.fromLTRB(10.0, 10.0, 20.0, 10.0),
counterStyle: const TextStyle(
color: AppTheme.hintText,
),
hintText: "Search for Product",
enabledBorder: outlineBorder,
hintStyle: GoogleFonts.poppins(
fontWeight: FontWeight.w400,
height: 1.5,
letterSpacing: .5,
fontSize: AppFonts.subtitle1,
color: AppTheme.hintText,
),
focusedBorder: outlineBorder,
focusedErrorBorder: outlineBorder,
errorBorder: outlineBorder,
prefixIcon: Icon(
Icons.search,
color: AppTheme.hintText,
),
// contentPadding: EdgeInsets.only(
// left: 10, right: 5, bottom: 12,top: 12),
border: InputBorder.none),
),
),
),
const SizedBox(height: 10),
// const SizedBox(height: 15),
const Align(
alignment: Alignment.centerLeft,
child: Text(
"Shop by category",
style: TextStyle(fontSize: 20),
),
),
const SizedBox(height: 10),
//Expanded(child: MovieList()),
Container(
height: MediaQuery.of(context).size.height * .14,
width: double.infinity,
child: MovieList()),
const SizedBox(height: 15),
const Align(
alignment: Alignment.centerLeft,
child: Text(
"Popular Products",
style: TextStyle(fontSize: 20),
),
),
const SizedBox(height: 10),
// CarouselSlider(
// options: CarouselOptions(
// height: 200.0,
// viewportFraction: 1,
// autoPlay: true,
// ),
// items: [1, 2, 3, 4, 5].map((i) {
// return Builder(
// builder: (BuildContext context) {
// return Container(
// width: MediaQuery.of(context).size.width,
// margin: EdgeInsets.symmetric(horizontal: 1.0),
// // decoration: BoxDecoration(color: Colors.red[100]),
// child: ClipRRect(
// child: Image.asset("assets/img.png"),
// ),
// );
// },
// );
// }).toList(),
// ),
Padding(
padding: EdgeInsets.only(
top: 8,
),
child: SizedBox(
height: 200.0,
width: MediaQuery.of(context).size.width,
child: Carousel(
images: [
Image.asset(
"assets/ss1.webp",
fit: BoxFit.fitWidth,
),
Image.asset(
"assets/ss2.webp",
fit: BoxFit.fitWidth,
),
Image.asset(
"assets/ss3.jpeg",
fit: BoxFit.fitWidth,
),
Image.asset(
"assets/ss4.jpeg",
fit: BoxFit.fitWidth,
),
Image.asset(
"assets/ss5.jpeg",
fit: BoxFit.fitWidth,
),
],
dotSize: 4.0,
dotSpacing: 15.0,
dotColor: Colors.lightGreenAccent,
indicatorBgPadding: 5.0,
dotBgColor: Colors.transparent,
borderRadius: true,
),
),
),
const SizedBox(height: 15),
const Align(
alignment: Alignment.centerLeft,
child: Text(
"Best Deals",
style: TextStyle(fontSize: 20),
),
),
const SizedBox(height: 10),
GridView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
mainAxisExtent: 300),
itemCount: category.length,
itemBuilder: (BuildContext context, int index) {
return Container(
// color: AppTheme.appThemeColor,
child: Image.asset(
"${category[index]["url"]}",
height: 200,
fit: BoxFit.cover,
),
);
},
),
],
),
),
),
);
}
}
class Searchtext {
static var searchelemnt;
}
// class TokenValue {
// static var mytoken;
// }
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/productdetailsapipage.dart | import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/bloc/productbloc.dart';
import 'package:vishal_mega_mart_app/screens/model/product.dart';
class SearchProduct extends StatelessWidget {
@override
Widget build(BuildContext context) {
bloc.fetchallproduct();
return Scaffold(
body: StreamBuilder(
stream: bloc.allproduct,
builder: (context, AsyncSnapshot<ProductModel> snapshot) {
if (snapshot.hasData) {
return GridView.builder(
physics: const NeverScrollableScrollPhysics(),
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
),
itemCount: 40,
itemBuilder: (BuildContext context, int index) {
index++;
return Card(
//color: Colors.lightBlueAccent,
child: Column(
children:const [
// Expanded(
// // child:snapshot.data!.hits![index].cVmmSizeChart!.path.toString().isNotEmpty
// // ? Image.asset(
// // snapshot.data!.hits![index].cVmmSizeChart!.path.toString(),
// // //fit: BoxFit.fill,
// // ): assets/t.jpg
// child: NetworkImage(imglink),
// ),
Align(
alignment: Alignment.centerLeft,
child: Text(
"some",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Align(
alignment: Alignment.centerLeft,
child: Text(
"someeeeeee",
style: TextStyle(fontSize: 20, color: Colors.grey),
),
),
const Align(
alignment: Alignment.centerLeft,
child: Text(
"\$ 229.00",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
},);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}
// class MovieListss extends StatelessWidget {
// @override
// Widget build(BuildContext context) {
// bloc.fetchallproduct();
// return Scaffold(
// body: StreamBuilder(
// stream: bloc.allproduct,
// builder: (context, AsyncSnapshot<ProductModel> snapshot) {
// if (snapshot.hasData) {
// return GridView.builder(
// physics: const NeverScrollableScrollPhysics(),
// shrinkWrap: true,
// gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
// crossAxisCount: 2,
// ),
// itemCount: 10,
// itemBuilder: (BuildContext context, int index) {
// return Card(
// //color: Colors.lightBlueAccent,
// child: Column(
// children: [
// Expanded(
// child: Image.asset(
// snapshot.data!.hits[index].cVmmSizeChart!.path.toString(),
// fit: BoxFit.fill,
// ),
// ),
// const Align(
// alignment: Alignment.centerLeft,
// child: Text(
// "Brink",
// style: TextStyle(
// fontSize: 20,
// fontWeight: FontWeight.bold,
// ),
// ),
// ),
// const Align(
// alignment: Alignment.centerLeft,
// child: Text(
// "Solid Polo Shirt",
// style: TextStyle(fontSize: 20, color: Colors.grey),
// ),
// ),
// const Align(
// alignment: Alignment.centerLeft,
// child: Text(
// "\$ 229.00",
// style: TextStyle(
// fontSize: 20,
// fontWeight: FontWeight.bold,
// ),
// ),
// ),
// ],
// ),
// );
// },);
// } else if (snapshot.hasError) {
// return Text(snapshot.error.toString());
// }
// return Center(child: CircularProgressIndicator());
// },
// ),
// );
// }
// Widget buildList(AsyncSnapshot<ProductModel> snapshot) {
// return
// }
// } | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/searchwidget.dart | // import 'package:flutter/material.dart';
// import 'package:vishal_mega_mart_app/screens/bloc/productbloc.dart';
// import 'package:vishal_mega_mart_app/screens/lastpagewidget.dart';
// import 'package:vishal_mega_mart_app/screens/model/product.dart';
// class SearchPage extends StatelessWidget {
// @override
// Widget build(BuildContext context) {
// bloc.fetchallproduct;
// return Scaffold(
// appBar: AppBar(
// backgroundColor: Colors.transparent,
// ),
// body: StreamBuilder(
// stream: bloc.allproduct,
// builder: (context, AsyncSnapshot<ProductModel> snapshot) {
// if (snapshot.hasData) {
// return buildList(snapshot);
// } else if (snapshot.hasError) {
// print("==== ERROR ${snapshot.error.toString()}");
// return Text(snapshot.error.toString());
// }
// return Center(child: CircularProgressIndicator());
// },
// ),
// );
// }
// Widget buildList(AsyncSnapshot<ProductModel> snapshot) {
// return GridView.builder(
// physics: const NeverScrollableScrollPhysics(),
// shrinkWrap: true,
// itemCount: 2,
// gridDelegate:
// new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
// itemBuilder: (BuildContext context, int index) {
// return Commonwidget(
// brand: snapshot.data!.hits![index].brand.toString(),
// discription: snapshot.data!.hits![index].name!.cVmmBrandDefault.toString(),
// //price: snapshot.data!.hits![index].cListprice.toString(),
// imglink: snapshot.data!.hits![index].cVmmSizeChart!.path.toString());
// },
// );
// }
// }
import 'package:flutter/material.dart';
import 'package:vishal_mega_mart_app/screens/api.dart';
import 'package:vishal_mega_mart_app/screens/bloc/productbloc.dart';
import 'package:vishal_mega_mart_app/screens/lastpagewidget.dart';
import 'package:vishal_mega_mart_app/screens/model/product.dart';
class Random extends StatelessWidget {
@override
Widget build(BuildContext context) {
bloc.fetchallproduct();
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
),
body: StreamBuilder(
stream: bloc.allproduct,
builder: (context, AsyncSnapshot<ProductModel> snapshot) {
if (snapshot.hasData) {
return buildList(snapshot);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
);
}
Widget buildList(AsyncSnapshot<ProductModel> snapshot) {
return GridView.builder(
itemCount: snapshot.data!.hits!.length,
gridDelegate:
new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
itemBuilder: (BuildContext context, int index) {
return Commonwidgets(
brand: snapshot.data!.hits![index].brand.toString(),
discription: snapshot.data!.hits![index].name!.cVmmBrandDefault.toString(),
//price: snapshot.data!.hits![index].cListprice.toString(),
imglink: snapshot.data!.hits![index].cVmmSizeChart!.path.toString()
);
});
}
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/subcat.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vishal_mega_mart_app/screens/bloc/subcatbloc.dart';
import 'package:vishal_mega_mart_app/screens/model/subcatmodel.dart';
import 'package:vishal_mega_mart_app/screens/subcategorywidget.dart';
import 'package:vishal_mega_mart_app/screens/themes/app_fonts.dart';
import 'package:vishal_mega_mart_app/screens/themes/apptheme.dart';
class SubcatScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
bloc.fetchallSubcategory();
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(80.0), // here the desired height
child: AppBar(
backgroundColor: AppTheme.appThemeColor,
automaticallyImplyLeading: false,
toolbarHeight: 70,
elevation: 0,
titleSpacing: 0,
title: Container(
width: MediaQuery.of(context).size.width,
height: 55,
child: Padding(
padding: EdgeInsets.only(left: 12, right: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Image.asset(
"assets/location.png",
height: 25,
color: AppTheme.whitColor,
),
Expanded(
child: Container(
child: Padding(
padding: EdgeInsets.only(left: 14, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text(
"Noida Sector 1",
style: GoogleFonts.poppins(
color: AppTheme.whitColor,
fontSize: AppFonts.subtitle1),
),
],
),
],
),
),
)),
Image.asset(
"assets/like.png",
height: 25,
color: AppTheme.whitColor,
),
SizedBox(
width: 12,
),
Image.asset(
"assets/shopping-cart.png",
height: 25,
color: AppTheme.whitColor,
),
]),
),
),
),
),
// backgroundColor: Color.fromARGB(255, 204, 246, 255),
body: Center(
child: Container(
margin: EdgeInsets.only(left: 40),
child: StreamBuilder(
stream: bloc.allsubcategory,
builder: (context, AsyncSnapshot<SubCatModel> snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.vertical,
itemCount: 6,
itemBuilder: (BuildContext context, int index) => SubCat(
image: snapshot.data!.categories![index].thumbnail
.toString(),
text: snapshot
.data!.categories![index].name!.nameDefault
.toString()));
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/categoryapi.dart | import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' show Client;
import 'package:vishal_mega_mart_app/main.dart';
import 'package:vishal_mega_mart_app/screens/model/token.dart';
import 'package:vishal_mega_mart_app/screens/sharedpref.dart';
import '../model/category_section.dart';
class CategoryProvider {
Client client = Client();
Future<CategorySection> getcategory() async {
const url =
"https://www.vishalmegamart.com/s/-/dw/data/v20_10/catalogs/vmm-storefront-catalog/categories/root";
//var token = tokens.TOKEN;
// Read token value
final mytoken = await appPreferences.getStringPreference("my_token");
String token = mytoken;
print("===TOKEN IN API=========");
print("===TOKEN IN API=====${token}====");
var response = await client.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
final jsondata = jsonDecode(response.body.toString());
// print("=========${jsondata.length}");
//return CategorySection.fromJson(jsonDecode(response.body));
//print("=========++++====${response.body.toString()}+++++++++++++++++++");
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return CategorySection.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('=====Failed to load post');
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/tokenapi.dart | // import 'dart:convert';
// import 'package:http/http.dart' as http;
// import 'package:vishal_mega_mart_app/screens/constant.dart';
// import 'package:vishal_mega_mart_app/screens/model/token.dart';
// class TokenProvider {
// //Client client = Client();
// Future<TokenModel> Token() async {
// // ignore: avoid_print
// print(
// "======= API CALLING =========",
// );
// var headers = {
// 'Authorization':
// 'Basic OTgwNGY4YjQtZTQzMS00OTUwLWE3NDMtYmRhMjJmMDllYmI4OlZNTU1vYmlsZUFwcDIwMjAj',
// 'Content-Type': 'application/x-www-form-urlencoded',
// 'Cookie':
// 'route=1660200976.763.118.455900|b4b9366450a28a63ee5f72b7d8464f5c'
// };
// var request = http.Request('POST',
// Uri.parse('https://account.demandware.com/dwsso/oauth2/access_token'));
// request.bodyFields = {'grant_type': 'client_credentials'};
// request.headers.addAll(headers);
// http.StreamedResponse response = await request.send();
// final res = await response.stream.bytesToString();
// if (response.statusCode == 200) {
// print(await response.stream.bytesToString());
// } else {
// print(response.reasonPhrase);
// }
// print("=======Product====== ${res}");
// if (response.statusCode == 200) {
// print("=======Product====== ${res}");
// // print("============= ${await response.stream.bytesToString()}");
// } else {
// print("======= Failed to load posts =========");
// }
// return TokenModel.fromJson(jsonDecode(res));
// }
// }
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/lastapi.dart | import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' show Client;
import 'package:vishal_mega_mart_app/screens/constant.dart';
import 'package:vishal_mega_mart_app/screens/model/lastmodel.dart';
import 'package:vishal_mega_mart_app/screens/sharedpref.dart';
import '../model/category_section.dart';
class LatProvider {
Client client = Client();
Future<LastModel> getlastapi() async {
const url =
"https://www.vishalmegamart.com/s/-/dw/data/v20_10/catalogs/vmm-storefront-catalog/categories/1003001";
final mytoken = await appPreferences.getStringPreference("my_token");
String token = mytoken;
print("===TOKEN IN API=========");
print("===TOKEN IN API=====${token}====");
var response = await client.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
final jsondata = jsonDecode(response.body.toString());
// print("=========${jsondata.length}");
//return CategorySection.fromJson(jsonDecode(response.body));
print("=========++++====${response.body.toString()}+++++++++++++++++++");
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return LastModel.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('=====Failed to load post');
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/subcatapi.dart | import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' show Client;
import 'package:vishal_mega_mart_app/screens/constant.dart';
import 'package:vishal_mega_mart_app/screens/model/subcatmodel.dart';
import 'package:vishal_mega_mart_app/screens/sharedpref.dart';
import '../model/category_section.dart';
class SUbcatProvider {
Client client = Client();
Future<SubCatModel> getsubcat() async {
const url =
"https://www.vishalmegamart.com/s/-/dw/data/v20_10/catalogs/vmm-storefront-catalog/categories/1003";
final mytoken = await appPreferences.getStringPreference("my_token");
String token = mytoken;
print("===TOKEN IN API=========");
print("===TOKEN IN API=====${token}====");
var response = await client.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
final jsondata = jsonDecode(response.body.toString());
// print("=========${jsondata.length}");
//return CategorySection.fromJson(jsonDecode(response.body));
print("=========++++====${response.body.toString()}+++++++++++++++++++");
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return SubCatModel.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('=====Failed to load post');
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/profuct.dart | import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:vishal_mega_mart_app/screens/constant.dart';
import 'package:vishal_mega_mart_app/screens/home.dart';
import 'package:vishal_mega_mart_app/screens/model/product.dart';
import 'package:vishal_mega_mart_app/screens/sharedpref.dart';
class ProductProvider {
//Client client = Client();
Future<ProductModel> product() async {
// ignore: avoid_print
print("======= API CALLING =========",);
final mytoken = await appPreferences.getStringPreference("my_token");
String token = mytoken;
print("===TOKEN IN API=========");
print("===TOKEN IN API=====${token}====");
var headers = {
'Content-Type': 'application/json',
'Authorization':
'Bearer token',
};
var request = http.Request(
'POST',
Uri.parse(
'https://www.vishalmegamart.com/s/-/dw/data/v20_10/product_search'));
//var elemnt = Searchtext();
var value = Searchtext.searchelemnt;
print("========= VALUE======= ${value}+++++++++++");
request.body = json.encode({
"query": {
"text_query": {
"fields": ["name"],
"search_phrase": value
}
},
"expand": ["prices"],
"select": "(**)"
});
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
final res = await response.stream.bytesToString();
print("=======Product====== ${res}");
if (response.statusCode == 200) {
print("=======Product====== ${res}");
// print("============= ${await response.stream.bytesToString()}");
} else {
print("======= Failed to load posts =========");
}
return ProductModel.fromJson(jsonDecode(res));
// const url =
// "https://www.vishalmegamart.com/s/-/dw/data/v20_10/product_search";
// const token =
// "eyJ0eXAiOiJKV1QiLCJraWQiOiJEMWhPUDdEODN4TjBqZWlqaTI3WWFvZFRjL0E9IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiI5ODA0ZjhiNC1lNDMxLTQ5NTAtYTc0My1iZGEyMmYwOWViYjgiLCJjdHMiOiJPQVVUSDJfU1RBVEVMRVNTX0dSQU5UIiwiYXVkaXRUcmFja2luZ0lkIjoiZjBkY2U0OTEtNjBjMi00NDlhLWJkMWYtZDYyMTVjNDIwN2ZjLTQwOTE3MDIxNSIsInN1Ym5hbWUiOiI5ODA0ZjhiNC1lNDMxLTQ5NTAtYTc0My1iZGEyMmYwOWViYjgiLCJpc3MiOiJodHRwczovL2FjY291bnQuZGVtYW5kd2FyZS5jb206NDQzL2R3c3NvL29hdXRoMiIsInRva2VuTmFtZSI6ImFjY2Vzc190b2tlbiIsInRva2VuX3R5cGUiOiJCZWFyZXIiLCJhdXRoR3JhbnRJZCI6IjdVTEpQVFNGbUZLbVpSQ0xuR2RfczMtWER3WSIsImF1ZCI6Ijk4MDRmOGI0LWU0MzEtNDk1MC1hNzQzLWJkYTIyZjA5ZWJiOCIsIm5iZiI6MTY1OTUwOTQ5MCwiZ3JhbnRfdHlwZSI6ImNsaWVudF9jcmVkZW50aWFscyIsInNjb3BlIjpbIm1haWwiXSwiYXV0aF90aW1lIjoxNjU5NTA5NDkwLCJyZWFsbSI6Ii8iLCJleHAiOjE2NTk1MTEyOTAsImlhdCI6MTY1OTUwOTQ5MCwiZXhwaXJlc19pbiI6MTgwMCwianRpIjoiUWVRMGNTWG52OHpJZ2ZIaHY4LUYxOFF2eHpBIiwiY2xpZW50X2lkIjoiOTgwNGY4YjQtZTQzMS00OTUwLWE3NDMtYmRhMjJmMDllYmI4In0.ffWR2QMSpW34yobnU_8_U3-tdVFJvqgDrzg6Q32ab8FPRRM5NyFqCQbyw2nwfX8K8D_mbwlU3fbSSSsK-aRagfhw6fYwxLi0cCMxsJISSR-XaZzE9w8wp5mRsBPReoUC-BW5C2H7tXIGuKAUOn9bUF3_bd99e3u4TEAJj6-U6CXfRq_lbSdshvs3aneIPf6v-dtte5ehpRBKrUlmj_1T0kxsaNbJItaxrDECOFEfaJwhBnvKeAKHjkTOufd5cB9R69j8bJSi1RNYYGYnjZ05FuujXYsXusTf4alppqOd2WWUsnrJRTHJKRkQNu8I8w9gZk4ELnmFZ28LKXkP-LXvVw";
// final queryParams = {
// 'fields': 'name',
// 'search_phrase': 'jeans',
// 'expand': 'prices',
// 'select': '(**)'
// };
// final uri = Uri.parse(url).replace(queryParameters: {
// 'fields': 'name',
// 'search_phrase': 'jeans',
// 'expand': 'prices',
// 'select': '(**)'
// });
// // String urll = Uri.parse("https://www.vishalmegamart.com/s/-/dw/data/v20_10");
// // Uri urls = Uri.http(
// // urll,
// // '/product_search',
// // {
// // 'mapData': jsonEncode(queryParams),
// // },
// // );
// // Uri url = Uri.http(
// // 'domain.com',
// // '/endpoint',
// // {
// // 'mapData': jsonEncode(queryParams),
// // },
// // );
// // {
// // 'mapData': jsonEncode(queryParams),
// // },
// var response = await client.post(uri, headers: {
// 'Content-Type': 'application/json',
// 'Accept': 'application/json',
// 'Authorization': 'Bearer $token',
// });
// final jsondata = jsonDecode(response.body.toString());
// //return CategorySection.fromJson(jsonDecode(response.body));
// print(
// "\n\n=========PRODUCT====${response.statusCode}+++++++++++++++++++\n\n");
// print(
// "\n\n=========PRODUCT====${response.body.toString()}+++++++++++++++++++\n\n");
// if (response.statusCode == 200) {
// // If the call to the server was successful, parse the JSON
// return ProductModel.fromJson(json.decode(response.body));
// } else {
// // If that call was not successful, throw an error.
// throw Exception('=====Failed to load post');
// }
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/repository.dart | import 'package:vishal_mega_mart_app/screens/apis/categoryapi.dart';
import 'package:vishal_mega_mart_app/screens/apis/lastapi.dart';
import 'package:vishal_mega_mart_app/screens/apis/productlistapi.dart';
import 'package:vishal_mega_mart_app/screens/apis/profuct.dart';
import 'package:vishal_mega_mart_app/screens/apis/subcatapi.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'package:vishal_mega_mart_app/screens/model/lastmodel.dart';
import 'package:vishal_mega_mart_app/screens/model/product.dart';
import 'package:vishal_mega_mart_app/screens/model/productlist.dart';
import 'package:vishal_mega_mart_app/screens/model/subcatmodel.dart';
class Repository {
final categoryprovider = CategoryProvider();
Future<CategorySection> getallcategory() => categoryprovider.getcategory();
final productprovider = ProductProvider();
Future<ProductModel> getallproducts() => productprovider.product();
final subcatprovider = SUbcatProvider();
Future<SubCatModel> getallsubcat() => subcatprovider.getsubcat();
final lastprovider = LatProvider();
Future<LastModel> getalllast() => lastprovider.getlastapi();
final productlistprovider = ProductlistyProvider();
Future<ProductListModel> getallproductlist() => productlistprovider.getallproductlist();
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/apis/productlistapi.dart | import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' show Client;
import 'package:vishal_mega_mart_app/screens/constant.dart';
import 'package:vishal_mega_mart_app/screens/model/productlist.dart';
import 'package:vishal_mega_mart_app/screens/sharedpref.dart';
import '../model/category_section.dart';
class ProductlistyProvider {
Client client = Client();
Future<ProductListModel> getallproductlist() async {
const url ="https://www.vishalmegamart.com/dw/shop/v20_10/product_search?refine_2=cgid=1003001&refine_1=price=(0.01..99999)&start=0&count=35&inventory_ids=HH15_Inventory&expand=images&client_id=9804f8b4-e431-4950-a743-bda22f09ebb8&storeID=HH15&locale=en-IN";
final mytoken = await appPreferences.getStringPreference("my_token");
String token = mytoken;
print("===TOKEN IN API=========");
print("===TOKEN IN API=====${token}====");
var response = await client.get(Uri.parse(url), headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token',
});
final jsondata = jsonDecode(response.body.toString());
// print("=========${jsondata.length}");
//return CategorySection.fromJson(jsonDecode(response.body));
print("=========++++====${response.body.toString()}+++++++++++++++++++");
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return ProductListModel.fromJson(json.decode(response.body));
} else {
// If that call was not successful, throw an error.
throw Exception('=====Failed to load post');
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/bloc/productlistbloc.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';
import 'package:vishal_mega_mart_app/screens/apis/repository.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'package:vishal_mega_mart_app/screens/model/productlist.dart';
class ProductListBloc {
final _repository = Repository();
final _productlistfetcher = PublishSubject<ProductListModel>();
Stream<ProductListModel> get allproductlist => _productlistfetcher.stream;
fetchallproductlist() async {
ProductListModel productListModel = await _repository.getallproductlist();
_productlistfetcher.sink.add(productListModel);
}
dispose() {
_productlistfetcher.close();
}
}
final bloc = ProductListBloc();
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/bloc/productbloc.dart |
import 'package:rxdart/subjects.dart';
import 'package:vishal_mega_mart_app/screens/apis/repository.dart';
import 'package:vishal_mega_mart_app/screens/model/product.dart';
class ProductBloc {
final _repository = Repository();
final _productfetcher = PublishSubject<ProductModel>();
Stream<ProductModel> get allproduct => _productfetcher.stream;
fetchallproduct() async {
ProductModel productModel = await _repository.getallproducts();
_productfetcher.sink.add(productModel);
}
dispose(){
_productfetcher.close();
}
}
final bloc = ProductBloc(); | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/bloc/lastbloc.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';
import 'package:vishal_mega_mart_app/screens/apis/repository.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'package:vishal_mega_mart_app/screens/model/lastmodel.dart';
import 'package:vishal_mega_mart_app/screens/model/subcatmodel.dart';
class LastBloc {
final _repository = Repository();
final _lastfetcher = PublishSubject<LastModel>();
Stream<LastModel> get alllastapi => _lastfetcher.stream;
fetchalllast() async {
LastModel lastModel = await _repository.getalllast();
_lastfetcher.sink.add(lastModel);
}
dispose() {
_lastfetcher.close();
}
}
final bloc = LastBloc();
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/bloc/subcatbloc.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';
import 'package:vishal_mega_mart_app/screens/apis/repository.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
import 'package:vishal_mega_mart_app/screens/model/subcatmodel.dart';
class SubCatBloc {
final _repository = Repository();
final _Subcategoryfetcher = PublishSubject<SubCatModel>();
Stream<SubCatModel> get allsubcategory => _Subcategoryfetcher.stream;
fetchallSubcategory() async {
SubCatModel subCatModel = await _repository.getallsubcat();
_Subcategoryfetcher.sink.add(subCatModel);
}
dispose() {
_Subcategoryfetcher.close();
}
}
final bloc = SubCatBloc();
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/bloc/categorybloc.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';
import 'package:vishal_mega_mart_app/screens/apis/repository.dart';
import 'package:vishal_mega_mart_app/screens/model/category_section.dart';
class CategoryBloc {
final _repository = Repository();
final _categoryfetcher = PublishSubject<CategorySection>();
Stream<CategorySection> get allcategory => _categoryfetcher.stream;
fetchallcategory() async {
CategorySection categorySection = await _repository.getallcategory();
_categoryfetcher.sink.add(categorySection);
}
dispose() {
_categoryfetcher.close();
}
}
final bloc = CategoryBloc();
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/lastmodel.dart | // To parse this JSON data, do
//
// final lastModel = lastModelFromJson(jsonString);
import 'dart:convert';
LastModel lastModelFromJson(String str) => LastModel.fromJson(json.decode(str));
String lastModelToJson(LastModel data) => json.encode(data.toJson());
class LastModel {
LastModel({
this.v,
this.type,
this.resourceState,
this.catalogId,
this.categories,
this.creationDate,
this.id,
this.lastModified,
this.link,
this.name,
this.online,
this.pageDescription,
this.pageKeywords,
this.pageTitle,
this.parentCategoryId,
this.thumbnail,
this.cEnableCompare,
this.cShowInMenu,
});
String? v;
String? type;
String? resourceState;
String? catalogId;
List<LastModel>? categories;
DateTime? creationDate;
String? id;
DateTime? lastModified;
String? link;
Name? name;
bool? online;
Page? pageDescription;
Page? pageKeywords;
Page? pageTitle;
String? parentCategoryId;
String? thumbnail;
bool? cEnableCompare;
bool? cShowInMenu;
factory LastModel.fromJson(Map<String, dynamic> json) => LastModel(
v: json["_v"] == null ? null : json["_v"],
type: json["_type"],
resourceState: json["_resource_state"] == null ? null : json["_resource_state"],
catalogId: json["catalog_id"],
categories: json["categories"] == null ? null : List<LastModel>.from(json["categories"].map((x) => LastModel.fromJson(x))),
creationDate: DateTime.parse(json["creation_date"]),
id: json["id"],
lastModified: DateTime.parse(json["last_modified"]),
link: json["link"],
name: Name.fromJson(json["name"]),
online: json["online"],
pageDescription: Page.fromJson(json["page_description"]),
pageKeywords: Page.fromJson(json["page_keywords"]),
pageTitle: Page.fromJson(json["page_title"]),
parentCategoryId: json["parent_category_id"],
thumbnail: json["thumbnail"],
cEnableCompare: json["c_enableCompare"],
cShowInMenu: json["c_showInMenu"],
);
Map<String, dynamic> toJson() => {
"_v": v == null ? null : v,
"_type": type,
"_resource_state": resourceState == null ? null : resourceState,
"catalog_id": catalogId,
"categories": categories == null ? null : List<dynamic>.from(categories!.map((x) => x.toJson())),
"creation_date": creationDate!.toIso8601String(),
"id": id,
"last_modified": lastModified!.toIso8601String(),
"link": link,
"name": name!.toJson(),
"online": online,
"page_description": pageDescription!.toJson(),
"page_keywords": pageKeywords!.toJson(),
"page_title": pageTitle!.toJson(),
"parent_category_id": parentCategoryId,
"thumbnail": thumbnail,
"c_enableCompare": cEnableCompare,
"c_showInMenu": cShowInMenu,
};
}
class Name {
Name({
this.nameDefault,
this.hiIn,
});
String? nameDefault;
String? hiIn;
factory Name.fromJson(Map<String, dynamic> json) => Name(
nameDefault: json["default"],
hiIn: json["hi-IN"],
);
Map<String, dynamic> toJson() => {
"default": nameDefault,
"hi-IN": hiIn,
};
}
class Page {
Page({
this.pageDefault,
});
String? pageDefault;
factory Page.fromJson(Map<String, dynamic> json) => Page(
pageDefault: json["default"],
);
Map<String, dynamic> toJson() => {
"default": pageDefault,
};
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/productlist.dart | // To parse this JSON data, do
//
// final productListModel = productListModelFromJson(jsonString);
import 'dart:convert';
ProductListModel productListModelFromJson(String str) =>
ProductListModel.fromJson(json.decode(str));
String productListModelToJson(ProductListModel data) =>
json.encode(data.toJson());
class ProductListModel {
ProductListModel({
this.v,
this.type,
this.count,
this.hits,
this.next,
this.refinements,
this.searchPhraseSuggestions,
this.selectedRefinements,
this.sortingOptions,
this.start,
this.total,
});
String? v;
String? type;
int? count;
List<Hit>? hits;
String? next;
List<Refinement>? refinements;
SearchPhraseSuggestions? searchPhraseSuggestions;
SelectedRefinements? selectedRefinements;
List<SortingOption>? sortingOptions;
int? start;
int? total;
factory ProductListModel.fromJson(Map<String, dynamic> json) =>
ProductListModel(
v: json["_v"],
type: json["_type"],
count: json["count"],
hits: List<Hit>.from(json["hits"].map((x) => Hit.fromJson(x))),
next: json["next"],
refinements: List<Refinement>.from(
json["refinements"].map((x) => Refinement.fromJson(x))),
searchPhraseSuggestions:
SearchPhraseSuggestions.fromJson(json["search_phrase_suggestions"]),
selectedRefinements:
SelectedRefinements.fromJson(json["selected_refinements"]),
sortingOptions: List<SortingOption>.from(
json["sorting_options"].map((x) => SortingOption.fromJson(x))),
start: json["start"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"_v": v,
"_type": type,
"count": count,
"hits": List<dynamic>.from(hits!.map((x) => x.toJson())),
"next": next,
"refinements": List<dynamic>.from(refinements!.map((x) => x.toJson())),
"search_phrase_suggestions": searchPhraseSuggestions!.toJson(),
"selected_refinements": selectedRefinements!.toJson(),
"sorting_options":
List<dynamic>.from(sortingOptions!.map((x) => x.toJson())),
"start": start,
"total": total,
};
}
class Hit {
Hit({
this.type,
this.hitType,
this.image,
this.link,
this.productId,
this.productName,
this.productType,
this.representedProduct,
this.cAvailability,
this.cBrand,
this.cVmmProductType,
this.cIsPromoAvailable,
this.cPromoMessage,
this.cPriceRange,
this.cListprice,
this.cSaleprice,
this.cDiscount,
});
HitType? type;
HitTypeEnum? hitType;
Image? image;
String? link;
String? productId;
String? productName;
ProductType? productType;
RepresentedProduct? representedProduct;
CAvailability? cAvailability;
CBrand? cBrand;
CVmmProductType? cVmmProductType;
bool? cIsPromoAvailable;
CPromoMessage? cPromoMessage;
bool? cPriceRange;
double? cListprice;
double? cSaleprice;
double? cDiscount;
factory Hit.fromJson(Map<String, dynamic> json) => Hit(
type: hitTypeValues.map![json["_type"]],
hitType: hitTypeEnumValues.map![json["hit_type"]],
image: Image.fromJson(json["image"]),
link: json["link"],
productId: json["product_id"],
productName: json["product_name"],
productType: ProductType.fromJson(json["product_type"]),
representedProduct:
RepresentedProduct.fromJson(json["represented_product"]),
cAvailability: cAvailabilityValues.map![json["c_availability"]],
cBrand: cBrandValues.map![json["c_brand"]],
cVmmProductType: cVmmProductTypeValues.map![json["c_vmmProductType"]],
cIsPromoAvailable: json["c_isPromoAvailable"],
cPromoMessage: cPromoMessageValues.map![json["c_promoMessage"]],
cPriceRange: json["c_priceRange"],
cListprice: json["c_listprice"],
cSaleprice: json["c_saleprice"],
cDiscount: json["c_discount"] == null ? null : json["c_discount"],
);
Map<String, dynamic> toJson() => {
"_type": hitTypeValues.reverse![type],
"hit_type": hitTypeEnumValues.reverse![hitType],
"image": image!.toJson(),
"link": link,
"product_id": productId,
"product_name": productName,
"product_type": productType!.toJson(),
"represented_product": representedProduct!.toJson(),
"c_availability": cAvailabilityValues.reverse![cAvailability],
"c_brand": cBrandValues.reverse![cBrand],
"c_vmmProductType": cVmmProductTypeValues.reverse![cVmmProductType],
"c_isPromoAvailable": cIsPromoAvailable,
"c_promoMessage": cPromoMessageValues.reverse![cPromoMessage],
"c_priceRange": cPriceRange,
"c_listprice": cListprice,
"c_saleprice": cSaleprice,
"c_discount": cDiscount == null ? null : cDiscount,
};
}
enum CAvailability { IN_STOCK }
final cAvailabilityValues = EnumValues({"IN_STOCK": CAvailability.IN_STOCK});
enum CBrand { BRINK, DRIFTWOOD }
final cBrandValues =
EnumValues({"Brink": CBrand.BRINK, "Driftwood": CBrand.DRIFTWOOD});
enum CPromoMessage {
GET_50_OFF,
EMPTY,
BUY_2_ABOVE_GET_20_OFF,
BUY_1_GET_1_FREE
}
final cPromoMessageValues = EnumValues({
"Buy 1 Get 1 Free": CPromoMessage.BUY_1_GET_1_FREE,
"Buy 2 & Above Get 20 % Off": CPromoMessage.BUY_2_ABOVE_GET_20_OFF,
"": CPromoMessage.EMPTY,
"Get ₹50 off": CPromoMessage.GET_50_OFF
});
enum CVmmProductType { APPAREL }
final cVmmProductTypeValues = EnumValues({"Apparel": CVmmProductType.APPAREL});
enum HitTypeEnum { VARIATION_GROUP }
final hitTypeEnumValues =
EnumValues({"variation_group": HitTypeEnum.VARIATION_GROUP});
class Image {
Image({
this.type,
this.alt,
this.disBaseLink,
this.link,
this.title,
});
ImageType? type;
String? alt;
String? disBaseLink;
String? link;
String? title;
factory Image.fromJson(Map<String, dynamic> json) => Image(
type: imageTypeValues.map![json["_type"]],
alt: json["alt"],
disBaseLink: json["dis_base_link"],
link: json["link"],
title: json["title"],
);
Map<String, dynamic> toJson() => {
"_type": imageTypeValues.reverse![type],
"alt": alt,
"dis_base_link": disBaseLink,
"link": link,
"title": title,
};
}
enum ImageType { IMAGE }
final imageTypeValues = EnumValues({"image": ImageType.IMAGE});
class ProductType {
ProductType({
this.type,
this.variationGroup,
});
ProductTypeType? type;
bool? variationGroup;
factory ProductType.fromJson(Map<String, dynamic> json) => ProductType(
type: productTypeTypeValues.map![json["_type"]],
variationGroup: json["variation_group"],
);
Map<String, dynamic> toJson() => {
"_type": productTypeTypeValues.reverse![type],
"variation_group": variationGroup,
};
}
enum ProductTypeType { PRODUCT_TYPE }
final productTypeTypeValues =
EnumValues({"product_type": ProductTypeType.PRODUCT_TYPE});
class RepresentedProduct {
RepresentedProduct({
this.type,
this.id,
this.link,
});
RepresentedProductType? type;
String? id;
String? link;
factory RepresentedProduct.fromJson(Map<String, dynamic> json) =>
RepresentedProduct(
type: representedProductTypeValues.map![json["_type"]],
id: json["id"],
link: json["link"],
);
Map<String, dynamic> toJson() => {
"_type": representedProductTypeValues.reverse![type],
"id": id,
"link": link,
};
}
enum RepresentedProductType { PRODUCT_REF }
final representedProductTypeValues =
EnumValues({"product_ref": RepresentedProductType.PRODUCT_REF});
enum HitType { PRODUCT_SEARCH_HIT }
final hitTypeValues =
EnumValues({"product_search_hit": HitType.PRODUCT_SEARCH_HIT});
class Refinement {
Refinement({
this.type,
this.attributeId,
this.label,
this.values,
});
RefinementType? type;
String? attributeId;
String? label;
List<Value>? values;
factory Refinement.fromJson(Map<String, dynamic> json) => Refinement(
type: refinementTypeValues.map![json["_type"]],
attributeId: json["attribute_id"],
label: json["label"],
values: json["values"] == null
? null
: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"_type": refinementTypeValues.reverse![type],
"attribute_id": attributeId,
"label": label,
"values": values == null
? null
: List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
enum RefinementType { PRODUCT_SEARCH_REFINEMENT }
final refinementTypeValues = EnumValues(
{"product_search_refinement": RefinementType.PRODUCT_SEARCH_REFINEMENT});
class Value {
Value({
this.type,
this.hitCount,
this.label,
this.value,
this.values,
});
ValueType? type;
int? hitCount;
String? label;
String? value;
List<Value>? values;
factory Value.fromJson(Map<String, dynamic> json) => Value(
type: valueTypeValues.map![json["_type"]],
hitCount: json["hit_count"],
label: json["label"],
value: json["value"],
values: json["values"] == null
? null
: List<Value>.from(json["values"].map((x) => Value.fromJson(x))),
);
Map<String, dynamic> toJson() => {
"_type": valueTypeValues.reverse![type],
"hit_count": hitCount,
"label": label,
"value": value,
"values": values == null
? null
: List<dynamic>.from(values!.map((x) => x.toJson())),
};
}
enum ValueType { PRODUCT_SEARCH_REFINEMENT_VALUE }
final valueTypeValues = EnumValues({
"product_search_refinement_value": ValueType.PRODUCT_SEARCH_REFINEMENT_VALUE
});
class SearchPhraseSuggestions {
SearchPhraseSuggestions({
this.type,
});
String? type;
factory SearchPhraseSuggestions.fromJson(Map<String, dynamic> json) =>
SearchPhraseSuggestions(
type: json["_type"],
);
Map<String, dynamic> toJson() => {
"_type": type,
};
}
class SelectedRefinements {
SelectedRefinements({
this.cgid,
this.price,
});
String? cgid;
String? price;
factory SelectedRefinements.fromJson(Map<String, dynamic> json) =>
SelectedRefinements(
cgid: json["cgid"],
price: json["price"],
);
Map<String, dynamic> toJson() => {
"cgid": cgid,
"price": price,
};
}
class SortingOption {
SortingOption({
this.type,
this.id,
this.label,
});
String? type;
String? id;
String? label;
factory SortingOption.fromJson(Map<String, dynamic> json) => SortingOption(
type: json["_type"],
id: json["id"],
label: json["label"],
);
Map<String, dynamic> toJson() => {
"_type": type,
"id": id,
"label": label,
};
}
class EnumValues<T> {
Map<String, T>? map;
Map<T, String>? reverseMap;
EnumValues(this.map);
Map<T, String>? get reverse {
if (reverseMap == null) {
reverseMap = map!.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/category_section.g.dart | // // GENERATED CODE - DO NOT MODIFY BY HAND
// part of 'category_section.dart';
// // **************************************************************************
// // JsonSerializableGenerator
// // **************************************************************************
// CategorySection _$CategorySectionFromJson(Map<String, dynamic> json) =>
// CategorySection(
// V: json['_v'] as String?,
// Type: json['_type'] as String?,
// ResourceState: json['_resource_state'] as String?,
// catalogId: json['catalog_id'] as String?,
// categories: (json['categories'] as List<dynamic>?)
// ?.map((e) => Categorie.fromJson(e as Map<String, dynamic>))
// .toList(),
// creationDate: json['creation_date'] as String?,
// id: json['id'] as String?,
// lastModified: json['last_modified'] as String?,
// link: json['link'] as String?,
// online: json['online'] as bool?,
// pageDescription: json['page_description'] == null
// ? null
// : PageDescription.fromJson(
// json['page_description'] as Map<String, dynamic>),
// pageKeywords: json['page_keywords'] == null
// ? null
// : PageKeywords.fromJson(
// json['page_keywords'] as Map<String, dynamic>),
// pageTitle: json['page_title'] == null
// ? null
// : PageTitle.fromJson(json['page_title'] as Map<String, dynamic>),
// cEnableCompare: json['c_enableCompare'] as bool?,
// cShowInMenu: json['c_showInMenu'] as bool?,
// );
// Map<String, dynamic> _$CategorySectionToJson(CategorySection instance) =>
// <String, dynamic>{
// '_v': instance.V,
// '_type': instance.Type,
// '_resource_state': instance.ResourceState,
// 'catalog_id': instance.catalogId,
// 'categories': instance.categories,
// 'creation_date': instance.creationDate,
// 'id': instance.id,
// 'last_modified': instance.lastModified,
// 'link': instance.link,
// 'online': instance.online,
// 'page_description': instance.pageDescription,
// 'page_keywords': instance.pageKeywords,
// 'page_title': instance.pageTitle,
// 'c_enableCompare': instance.cEnableCompare,
// 'c_showInMenu': instance.cShowInMenu,
// };
// Categorie _$CategorieFromJson(Map<String, dynamic> json) => Categorie(
// Type: json['_type'] as String?,
// catalogId: json['catalog_id'] as String?,
// creationDate: json['creation_date'] as String?,
// description: json['description'] == null
// ? null
// : Description.fromJson(json['description'] as Map<String, dynamic>),
// id: json['id'] as String?,
// lastModified: json['last_modified'] as String?,
// link: json['link'] as String?,
// name: json['name'] == null
// ? null
// : Name.fromJson(json['name'] as Map<String, dynamic>),
// online: json['online'] as bool?,
// pageDescription: json['page_description'] == null
// ? null
// : PageDescription.fromJson(
// json['page_description'] as Map<String, dynamic>),
// pageKeywords: json['page_keywords'] == null
// ? null
// : PageKeywords.fromJson(
// json['page_keywords'] as Map<String, dynamic>),
// pageTitle: json['page_title'] == null
// ? null
// : PageTitle.fromJson(json['page_title'] as Map<String, dynamic>),
// parentCategoryId: json['parent_category_id'] as String?,
// thumbnail: json['thumbnail'] as String?,
// cEnableCompare: json['c_enableCompare'] as bool?,
// cShowInMenu: json['c_showInMenu'] as bool?,
// );
// Map<String, dynamic> _$CategorieToJson(Categorie instance) => <String, dynamic>{
// '_type': instance.Type,
// 'catalog_id': instance.catalogId,
// 'creation_date': instance.creationDate,
// 'description': instance.description,
// 'id': instance.id,
// 'last_modified': instance.lastModified,
// 'link': instance.link,
// 'name': instance.name,
// 'online': instance.online,
// 'page_description': instance.pageDescription,
// 'page_keywords': instance.pageKeywords,
// 'page_title': instance.pageTitle,
// 'parent_category_id': instance.parentCategoryId,
// 'thumbnail': instance.thumbnail,
// 'c_enableCompare': instance.cEnableCompare,
// 'c_showInMenu': instance.cShowInMenu,
// };
// Description _$DescriptionFromJson(Map<String, dynamic> json) => Description(
// defaults: json['default'] as String?,
// );
// Map<String, dynamic> _$DescriptionToJson(Description instance) =>
// <String, dynamic>{
// 'default': instance.defaults,
// };
// Name _$NameFromJson(Map<String, dynamic> json) => Name(
// defaults: json['default'] as String?,
// hi_IN: json['hi-IN'] as String?,
// );
// Map<String, dynamic> _$NameToJson(Name instance) => <String, dynamic>{
// 'default': instance.defaults,
// 'hi-IN': instance.hi_IN,
// };
// PageDescription _$PageDescriptionFromJson(Map<String, dynamic> json) =>
// PageDescription(
// defaults: json['default'] as String?,
// );
// Map<String, dynamic> _$PageDescriptionToJson(PageDescription instance) =>
// <String, dynamic>{
// 'default': instance.defaults,
// };
// PageKeywords _$PageKeywordsFromJson(Map<String, dynamic> json) => PageKeywords(
// defaults: json['default'] as String?,
// );
// Map<String, dynamic> _$PageKeywordsToJson(PageKeywords instance) =>
// <String, dynamic>{
// 'default': instance.defaults,
// };
// PageTitle _$PageTitleFromJson(Map<String, dynamic> json) => PageTitle(
// defaults: json['default'] as String?,
// );
// Map<String, dynamic> _$PageTitleToJson(PageTitle instance) => <String, dynamic>{
// 'default': instance.defaults,
// };
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/token.dart | // To parse this JSON data, do
//
// final tokenModel = tokenModelFromJson(jsonString);
import 'dart:convert';
TokenModel tokenModelFromJson(String str) => TokenModel.fromJson(json.decode(str));
String tokenModelToJson(TokenModel data) => json.encode(data.toJson());
class TokenModel {
TokenModel({
this.accessToken,
this.scope,
this.tokenType,
this.expiresIn,
});
String? accessToken;
String? scope;
String? tokenType;
int? expiresIn;
factory TokenModel.fromJson(Map<String, dynamic> json) => TokenModel(
accessToken: json["access_token"],
scope: json["scope"],
tokenType: json["token_type"],
expiresIn: json["expires_in"],
);
Map<String, dynamic> toJson() => {
"access_token": accessToken,
"scope": scope,
"token_type": tokenType,
"expires_in": expiresIn,
};
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/product.dart | // To parse this JSON data, do
//
// final productModel = productModelFromJson(jsonString);
import 'dart:convert';
ProductModel productModelFromJson(String str) =>
ProductModel.fromJson(json.decode(str));
String productModelToJson(ProductModel data) => json.encode(data.toJson());
class ProductModel {
ProductModel({
this.v,
this.type,
this.count,
this.expand,
this.hits,
this.next,
this.query,
this.select,
this.start,
this.total,
});
String? v;
String? type;
int? count;
List<String>? expand;
List<Hit>? hits;
Next? next;
Query? query;
String? select;
int? start;
int? total;
factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel(
v: json["_v"],
type: json["_type"],
count: json["count"],
expand: List<String>.from(json["expand"].map((x) => x)),
hits: List<Hit>.from(json["hits"].map((x) => Hit.fromJson(x))),
next: Next.fromJson(json["next"]),
query: Query.fromJson(json["query"]),
select: json["select"],
start: json["start"],
total: json["total"],
);
Map<String, dynamic> toJson() => {
"_v": v,
"_type": type,
"count": count,
"expand": List<dynamic>.from(expand!.map((x) => x)),
"hits": List<dynamic>.from(hits!.map((x) => x.toJson())),
"next": next!.toJson(),
"query": query!.toJson(),
"select": select,
"start": start,
"total": total,
};
}
class Hit {
Hit({
this.type,
this.resourceState,
this.brand,
this.creationDate,
this.id,
this.lastModified,
this.link,
this.name,
this.onlineFlag,
this.owningCatalogId,
this.searchable,
this.shortDescription,
this.hitType,
this.unitQuantity,
this.cVmmBrand,
this.cVmmProductType,
this.taxClassId,
this.cColor,
this.cSize,
this.cVmmColor,
this.cVmmDesign,
this.cVmmFabric,
this.cVmmFit,
this.cVmmGender,
this.cVmmMerchandiseCategory,
this.cVmmPattern,
this.cVmmProduct,
this.cVmmQualityAssuranceId,
this.cVmmReturnWindow,
this.cVmmReturnWindowId,
this.cVmmSize,
this.cVmmSizeChart,
this.cVmmSleeve,
this.cVmmStyle,
});
HitType? type;
String? resourceState;
Brand? brand;
DateTime? creationDate;
String? id;
DateTime? lastModified;
String? link;
CVmmBrand? name;
OnlineFlag? onlineFlag;
OwningCatalogId? owningCatalogId;
OnlineFlag? searchable;
ShortDescription? shortDescription;
Type? hitType;
int? unitQuantity;
CVmmBrand? cVmmBrand;
CVmmBrand? cVmmProductType;
TaxClassId? taxClassId;
CColor? cColor;
String? cSize;
CVmmBrand? cVmmColor;
CVmmBrand? cVmmDesign;
CVmmBrand? cVmmFabric;
CVmmBrand? cVmmFit;
CVmmBrand? cVmmGender;
CVmmMerchandiseCategory? cVmmMerchandiseCategory;
CVmm? cVmmPattern;
CVmmBrand? cVmmProduct;
CVmmQualityAssuranceId? cVmmQualityAssuranceId;
CVmmBrand? cVmmReturnWindow;
CVmmReturnWindowId? cVmmReturnWindowId;
CVmmBrand? cVmmSize;
CVmmSizeChart? cVmmSizeChart;
CVmm? cVmmSleeve;
CVmmBrand? cVmmStyle;
factory Hit.fromJson(Map<String, dynamic> json) => Hit(
type: hitTypeValues.map![json["_type"]],
resourceState: json["_resource_state"],
brand: brandValues.map![json["brand"]],
creationDate: DateTime.parse(json["creation_date"]),
id: json["id"],
lastModified: DateTime.parse(json["last_modified"]),
link: json["link"],
name: CVmmBrand.fromJson(json["name"]),
onlineFlag: OnlineFlag.fromJson(json["online_flag"]),
owningCatalogId: owningCatalogIdValues.map![json["owning_catalog_id"]],
searchable: OnlineFlag.fromJson(json["searchable"]),
shortDescription: ShortDescription.fromJson(json["short_description"]),
hitType: Type.fromJson(json["type"]),
unitQuantity: json["unit_quantity"],
cVmmBrand: CVmmBrand.fromJson(json["c_vmmBrand"]),
cVmmProductType: CVmmBrand.fromJson(json["c_vmmProductType"]),
taxClassId: json["tax_class_id"] == null
? null
: taxClassIdValues.map![json["tax_class_id"]],
cColor:
json["c_color"] == null ? null : cColorValues.map![json["c_color"]],
cSize: json["c_size"] == null ? null : json["c_size"],
cVmmColor: json["c_vmmColor"] == null
? null
: CVmmBrand.fromJson(json["c_vmmColor"]),
cVmmDesign: json["c_vmmDesign"] == null
? null
: CVmmBrand.fromJson(json["c_vmmDesign"]),
cVmmFabric: json["c_vmmFabric"] == null
? null
: CVmmBrand.fromJson(json["c_vmmFabric"]),
cVmmFit: json["c_vmmFit"] == null
? null
: CVmmBrand.fromJson(json["c_vmmFit"]),
cVmmGender: json["c_vmmGender"] == null
? null
: CVmmBrand.fromJson(json["c_vmmGender"]),
cVmmMerchandiseCategory: json["c_vmmMerchandiseCategory"] == null
? null
: cVmmMerchandiseCategoryValues
.map![json["c_vmmMerchandiseCategory"]],
cVmmPattern: json["c_vmmPattern"] == null
? null
: CVmm.fromJson(json["c_vmmPattern"]),
cVmmProduct: json["c_vmmProduct"] == null
? null
: CVmmBrand.fromJson(json["c_vmmProduct"]),
cVmmQualityAssuranceId: json["c_vmmQualityAssuranceId"] == null
? null
: cVmmQualityAssuranceIdValues
.map![json["c_vmmQualityAssuranceId"]],
cVmmReturnWindow: json["c_vmmReturnWindow"] == null
? null
: CVmmBrand.fromJson(json["c_vmmReturnWindow"]),
cVmmReturnWindowId: json["c_vmmReturnWindowId"] == null
? null
: cVmmReturnWindowIdValues.map![json["c_vmmReturnWindowId"]],
cVmmSize: json["c_vmmSize"] == null
? null
: CVmmBrand.fromJson(json["c_vmmSize"]),
cVmmSizeChart: json["c_vmmSizeChart"] == null
? null
: CVmmSizeChart.fromJson(json["c_vmmSizeChart"]),
cVmmSleeve: json["c_vmmSleeve"] == null
? null
: CVmm.fromJson(json["c_vmmSleeve"]),
cVmmStyle: json["c_vmmStyle"] == null
? null
: CVmmBrand.fromJson(json["c_vmmStyle"]),
);
Map<String, dynamic> toJson() => {
"_type": hitTypeValues.reverse![type],
"_resource_state": resourceState,
"brand": brandValues.reverse![brand],
"creation_date": creationDate!.toIso8601String(),
"id": id,
"last_modified": lastModified!.toIso8601String(),
"link": link,
"name": name!.toJson(),
"online_flag": onlineFlag!.toJson(),
"owning_catalog_id": owningCatalogIdValues.reverse![owningCatalogId],
"searchable": searchable!.toJson(),
"short_description": shortDescription!.toJson(),
"type": hitType!.toJson(),
"unit_quantity": unitQuantity,
"c_vmmBrand": cVmmBrand!.toJson(),
"c_vmmProductType": cVmmProductType!.toJson(),
"tax_class_id":
taxClassId == null ? null : taxClassIdValues.reverse![taxClassId],
"c_color": cColor == null ? null : cColorValues.reverse![cColor],
"c_size": cSize == null ? null : cSize,
"c_vmmColor": cVmmColor == null ? null : cVmmColor!.toJson(),
"c_vmmDesign": cVmmDesign == null ? null : cVmmDesign!.toJson(),
"c_vmmFabric": cVmmFabric == null ? null : cVmmFabric!.toJson(),
"c_vmmFit": cVmmFit == null ? null : cVmmFit!.toJson(),
"c_vmmGender": cVmmGender == null ? null : cVmmGender!.toJson(),
"c_vmmMerchandiseCategory": cVmmMerchandiseCategory == null
? null
: cVmmMerchandiseCategoryValues.reverse![cVmmMerchandiseCategory],
"c_vmmPattern": cVmmPattern == null ? null : cVmmPattern!.toJson(),
"c_vmmProduct": cVmmProduct == null ? null : cVmmProduct!.toJson(),
"c_vmmQualityAssuranceId": cVmmQualityAssuranceId == null
? null
: cVmmQualityAssuranceIdValues.reverse![cVmmQualityAssuranceId],
"c_vmmReturnWindow":
cVmmReturnWindow == null ? null : cVmmReturnWindow!.toJson(),
"c_vmmReturnWindowId": cVmmReturnWindowId == null
? null
: cVmmReturnWindowIdValues.reverse![cVmmReturnWindowId],
"c_vmmSize": cVmmSize == null ? null : cVmmSize!.toJson(),
"c_vmmSizeChart":
cVmmSizeChart == null ? null : cVmmSizeChart!.toJson(),
"c_vmmSleeve": cVmmSleeve == null ? null : cVmmSleeve!.toJson(),
"c_vmmStyle": cVmmStyle == null ? null : cVmmStyle!.toJson(),
};
}
enum Brand { DRIFTWOOD }
final brandValues = EnumValues({"Driftwood": Brand.DRIFTWOOD});
enum CColor { LIGHT_BLUE, DARK_BLUE, WHITE }
final cColorValues = EnumValues({
"Dark Blue": CColor.DARK_BLUE,
"Light Blue": CColor.LIGHT_BLUE,
"White": CColor.WHITE
});
class CVmmBrand {
CVmmBrand({
this.cVmmBrandDefault,
this.hiIn,
});
String? cVmmBrandDefault;
String? hiIn;
factory CVmmBrand.fromJson(Map<String, dynamic> json) => CVmmBrand(
cVmmBrandDefault: json["default"],
hiIn: json["hi-IN"],
);
Map<String, dynamic> toJson() => {
"default": cVmmBrandDefault,
"hi-IN": hiIn,
};
}
enum CVmmMerchandiseCategory { THE_111010007399, THE_111010012399 }
final cVmmMerchandiseCategoryValues = EnumValues({
"111010007-399": CVmmMerchandiseCategory.THE_111010007399,
"111010012-399": CVmmMerchandiseCategory.THE_111010012399
});
class CVmm {
CVmm({
this.cVmmDefault,
});
DefaultEnum? cVmmDefault;
factory CVmm.fromJson(Map<String, dynamic> json) => CVmm(
cVmmDefault: defaultEnumValues.map![json["default"]],
);
Map<String, dynamic> toJson() => {
"default": defaultEnumValues.reverse![cVmmDefault],
};
}
enum DefaultEnum { SOLID, PRINTED, FULL_SLEEVE, HALF_SLEEVE }
final defaultEnumValues = EnumValues({
"Full Sleeve": DefaultEnum.FULL_SLEEVE,
"Half Sleeve": DefaultEnum.HALF_SLEEVE,
"Printed": DefaultEnum.PRINTED,
"Solid": DefaultEnum.SOLID
});
enum CVmmQualityAssuranceId { ASSET_APPARELS_QUALITY_ASSURANCE }
final cVmmQualityAssuranceIdValues = EnumValues({
"Asset-Apparels-Quality-Assurance":
CVmmQualityAssuranceId.ASSET_APPARELS_QUALITY_ASSURANCE
});
enum CVmmReturnWindowId { ASSET_APPARELS_RETURN_POLICY }
final cVmmReturnWindowIdValues = EnumValues({
"asset-apparels-return-policy":
CVmmReturnWindowId.ASSET_APPARELS_RETURN_POLICY
});
class CVmmSizeChart {
CVmmSizeChart({
this.type,
this.absUrl,
this.disBaseUrl,
this.path,
});
CVmmSizeChartType? type;
String? absUrl;
String? disBaseUrl;
Path? path;
factory CVmmSizeChart.fromJson(Map<String, dynamic> json) => CVmmSizeChart(
type: cVmmSizeChartTypeValues.map![json["_type"]],
absUrl: json["abs_url"],
disBaseUrl: json["dis_base_url"],
path: pathValues.map![json["path"]],
);
Map<String, dynamic> toJson() => {
"_type": cVmmSizeChartTypeValues.reverse![type],
"abs_url": absUrl,
"dis_base_url": disBaseUrl,
"path": pathValues.reverse![path],
};
}
enum Path {
IMAGES_SIZECHART_CASUAL_SHIRT_FULL_SLEEVES_131010016_JPG,
IMAGES_SIZECHART_CASUAL_SHIRT_HALF_SLEEVES_131010017_JPG
}
final pathValues = EnumValues({
"images/sizechart/Casual_shirt_full_sleeves_131010016.jpg":
Path.IMAGES_SIZECHART_CASUAL_SHIRT_FULL_SLEEVES_131010016_JPG,
"images/sizechart/Casual_shirt_Half_sleeves_131010017.jpg":
Path.IMAGES_SIZECHART_CASUAL_SHIRT_HALF_SLEEVES_131010017_JPG
});
enum CVmmSizeChartType { MEDIA_FILE }
final cVmmSizeChartTypeValues =
EnumValues({"media_file": CVmmSizeChartType.MEDIA_FILE});
class Type {
Type({
this.type,
this.master,
this.variant,
});
TypeType? type;
bool? master;
bool? variant;
factory Type.fromJson(Map<String, dynamic> json) => Type(
type: typeTypeValues.map![json["_type"]],
master: json["master"] == null ? null : json["master"],
variant: json["variant"] == null ? null : json["variant"],
);
Map<String, dynamic> toJson() => {
"_type": typeTypeValues.reverse![type],
"master": master == null ? null : master,
"variant": variant == null ? null : variant,
};
}
enum TypeType { PRODUCT_TYPE }
final typeTypeValues = EnumValues({"product_type": TypeType.PRODUCT_TYPE});
class OnlineFlag {
OnlineFlag({
this.onlineFlagDefault,
this.defaultVishalmegamart,
});
bool? onlineFlagDefault;
bool? defaultVishalmegamart;
factory OnlineFlag.fromJson(Map<String, dynamic> json) => OnlineFlag(
onlineFlagDefault: json["default"],
defaultVishalmegamart: json["default@vishalmegamart"] == null
? null
: json["default@vishalmegamart"],
);
Map<String, dynamic> toJson() => {
"default": onlineFlagDefault,
"default@vishalmegamart":
defaultVishalmegamart == null ? null : defaultVishalmegamart,
};
}
enum OwningCatalogId { VMM_APPAREL_MASTER_CATALOG }
final owningCatalogIdValues = EnumValues(
{"vmm-apparel-master-catalog": OwningCatalogId.VMM_APPAREL_MASTER_CATALOG});
class ShortDescription {
ShortDescription({
this.shortDescriptionDefault,
this.hiIn,
});
DefaultClass? shortDescriptionDefault;
DefaultClass? hiIn;
factory ShortDescription.fromJson(Map<String, dynamic> json) =>
ShortDescription(
shortDescriptionDefault: DefaultClass.fromJson(json["default"]),
hiIn: DefaultClass.fromJson(json["hi-IN"]),
);
Map<String, dynamic> toJson() => {
"default": shortDescriptionDefault!.toJson(),
"hi-IN": hiIn!.toJson(),
};
}
class DefaultClass {
DefaultClass({
this.type,
this.markup,
this.source,
});
DefaultType? type;
Markup? markup;
Markup? source;
factory DefaultClass.fromJson(Map<String, dynamic> json) => DefaultClass(
type: defaultTypeValues.map![json["_type"]],
markup: markupValues.map![json["markup"]],
source: markupValues.map![json["source"]],
);
Map<String, dynamic> toJson() => {
"_type": defaultTypeValues.reverse![type],
"markup": markupValues.reverse![markup],
"source": markupValues.reverse![source],
};
}
enum Markup { SPECIFICATIONS, EMPTY }
final markupValues = EnumValues(
{"विशेष विवरण": Markup.EMPTY, "SPECIFICATIONS": Markup.SPECIFICATIONS});
enum DefaultType { MARKUP_TEXT }
final defaultTypeValues = EnumValues({"markup_text": DefaultType.MARKUP_TEXT});
enum TaxClassId { GST_TAX_3 }
final taxClassIdValues = EnumValues({"gst-tax-3": TaxClassId.GST_TAX_3});
enum HitType { PRODUCT }
final hitTypeValues = EnumValues({"product": HitType.PRODUCT});
class Next {
Next({
this.type,
this.count,
this.start,
});
String? type;
int? count;
int? start;
factory Next.fromJson(Map<String, dynamic> json) => Next(
type: json["_type"],
count: json["count"],
start: json["start"],
);
Map<String, dynamic> toJson() => {
"_type": type,
"count": count,
"start": start,
};
}
class Query {
Query({
this.textQuery,
});
TextQuery? textQuery;
factory Query.fromJson(Map<String, dynamic> json) => Query(
textQuery: TextQuery.fromJson(json["text_query"]),
);
Map<String, dynamic> toJson() => {
"text_query": textQuery!.toJson(),
};
}
class TextQuery {
TextQuery({
this.type,
this.fields,
this.searchPhrase,
});
String? type;
List<String>? fields;
String? searchPhrase;
factory TextQuery.fromJson(Map<String, dynamic> json) => TextQuery(
type: json["_type"],
fields: List<String>.from(json["fields"].map((x) => x)),
searchPhrase: json["search_phrase"],
);
Map<String, dynamic> toJson() => {
"_type": type,
"fields": List<dynamic>.from(fields!.map((x) => x)),
"search_phrase": searchPhrase,
};
}
class EnumValues<T> {
Map<String, T>? map;
Map<T, String>? reverseMap;
EnumValues(this.map);
Map<T, String>? get reverse {
if (reverseMap == null) {
reverseMap = map!.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/category_section.dart | // import 'package:json_annotation/json_annotation.dart';
// part 'category_section.g.dart';
// @JsonSerializable()
// class CategorySection {
// @JsonKey(name: '_v')
// String? V;
// @JsonKey(name: '_type')
// String? Type;
// @JsonKey(name: '_resource_state')
// String? ResourceState;
// @JsonKey(name: 'catalog_id')
// String? catalogId;
// @JsonKey(name: 'categories')
// List<Categorie>? categories;
// @JsonKey(name: 'creation_date')
// String? creationDate;
// @JsonKey(name: 'id')
// String? id;
// @JsonKey(name: 'last_modified')
// String? lastModified;
// @JsonKey(name: 'link')
// String? link;
// @JsonKey(name: 'online')
// bool? online;
// @JsonKey(name: 'page_description')
// PageDescription? pageDescription;
// @JsonKey(name: 'page_keywords')
// PageKeywords? pageKeywords;
// @JsonKey(name: 'page_title')
// PageTitle? pageTitle;
// @JsonKey(name: 'c_enableCompare')
// bool? cEnableCompare;
// @JsonKey(name: 'c_showInMenu')
// bool? cShowInMenu;
// CategorySection({
// this.V,
// this.Type,
// this.ResourceState,
// this.catalogId,
// this.categories,
// this.creationDate,
// this.id,
// this.lastModified,
// this.link,
// this.online,
// this.pageDescription,
// this.pageKeywords,
// this.pageTitle,
// this.cEnableCompare,
// this.cShowInMenu,
// });
// factory CategorySection.fromJson(Map<String, dynamic> json) =>
// _$CategorySectionFromJson(json);
// Map<String, dynamic> toJson() => _$CategorySectionToJson(this);
// }
// @JsonSerializable()
// class Categorie {
// @JsonKey(name: '_type')
// String? Type;
// @JsonKey(name: 'catalog_id')
// String? catalogId;
// @JsonKey(name: 'creation_date')
// String? creationDate;
// @JsonKey(name: 'description')
// Description? description;
// @JsonKey(name: 'id')
// String? id;
// @JsonKey(name: 'last_modified')
// String? lastModified;
// @JsonKey(name: 'link')
// String? link;
// @JsonKey(name: 'name')
// Name? name;
// @JsonKey(name: 'online')
// bool? online;
// @JsonKey(name: 'page_description')
// PageDescription? pageDescription;
// @JsonKey(name: 'page_keywords')
// PageKeywords? pageKeywords;
// @JsonKey(name: 'page_title')
// PageTitle? pageTitle;
// @JsonKey(name: 'parent_category_id')
// String? parentCategoryId;
// @JsonKey(name: 'thumbnail')
// String? thumbnail;
// @JsonKey(name: 'c_enableCompare')
// bool? cEnableCompare;
// @JsonKey(name: 'c_showInMenu')
// bool? cShowInMenu;
// Categorie(
// {this.Type,
// this.catalogId,
// this.creationDate,
// this.description,
// this.id,
// this.lastModified,
// this.link,
// this.name,
// this.online,
// this.pageDescription,
// this.pageKeywords,
// this.pageTitle,
// this.parentCategoryId,
// this.thumbnail,
// this.cEnableCompare,
// this.cShowInMenu});
// factory Categorie.fromJson(Map<String, dynamic> json) =>
// _$CategorieFromJson(json);
// Map<String, dynamic> toJson() => _$CategorieToJson(this);
// }
// @JsonSerializable()
// class Description {
// @JsonKey(name: 'default')
// String? defaults;
// Description({this.defaults});
// factory Description.fromJson(Map<String, dynamic> json) =>
// _$DescriptionFromJson(json);
// Map<String, dynamic> toJson() => _$DescriptionToJson(this);
// }
// @JsonSerializable()
// class Name {
// @JsonKey(name: 'default')
// String? defaults;
// @JsonKey(name: 'hi-IN')
// String? hi_IN;
// Name({this.defaults, this.hi_IN});
// factory Name.fromJson(Map<String, dynamic> json) => _$NameFromJson(json);
// Map<String, dynamic> toJson() => _$NameToJson(this);
// }
// @JsonSerializable()
// class PageDescription {
// @JsonKey(name: 'default')
// String? defaults;
// PageDescription({this.defaults});
// factory PageDescription.fromJson(Map<String, dynamic> json) =>
// _$PageDescriptionFromJson(json);
// Map<String, dynamic> toJson() => _$PageDescriptionToJson(this);
// }
// @JsonSerializable()
// class PageKeywords {
// @JsonKey(name: 'default')
// String? defaults;
// PageKeywords({this.defaults});
// factory PageKeywords.fromJson(Map<String, dynamic> json) =>
// _$PageKeywordsFromJson(json);
// Map<String, dynamic> toJson() => _$PageKeywordsToJson(this);
// }
// @JsonSerializable()
// class PageTitle {
// @JsonKey(name: 'default')
// String? defaults;
// PageTitle({this.defaults});
// factory PageTitle.fromJson(Map<String, dynamic> json) =>
// _$PageTitleFromJson(json);
// Map<String, dynamic> toJson() => _$PageTitleToJson(this);
// }
// To parse this JSON data, do
//
// final categorySection = categorySectionFromJson(jsonString);
import 'dart:convert';
CategorySection categorySectionFromJson(String str) => CategorySection.fromJson(json.decode(str));
String categorySectionToJson(CategorySection data) => json.encode(data.toJson());
class CategorySection {
CategorySection({
this.v,
this.type,
this.resourceState,
this.catalogId,
this.categories,
this.creationDate,
this.id,
this.lastModified,
this.link,
this.online,
this.pageDescription,
this.pageKeywords,
this.pageTitle,
this.cEnableCompare,
this.cShowInMenu,
this.description,
this.name,
this.parentCategoryId,
this.thumbnail,
});
String? v;
Type? type;
String? resourceState;
CatalogId? catalogId;
List<CategorySection>? categories;
DateTime? creationDate;
String? id;
DateTime? lastModified;
String? link;
bool? online;
Page? pageDescription;
Page? pageKeywords;
Page? pageTitle;
bool? cEnableCompare;
bool? cShowInMenu;
Description? description;
Description? name;
ParentCategoryId? parentCategoryId;
String? thumbnail;
factory CategorySection.fromJson(Map<String, dynamic> json) => CategorySection(
v: json["_v"] == null ? null : json["_v"],
type: typeValues.map[json["_type"]],
resourceState: json["_resource_state"] == null ? null : json["_resource_state"],
catalogId: catalogIdValues.map[json["catalog_id"]],
categories: json["categories"] == null ? null : List<CategorySection>.from(json["categories"].map((x) => CategorySection.fromJson(x))),
creationDate: DateTime.parse(json["creation_date"]),
id: json["id"],
lastModified: DateTime.parse(json["last_modified"]),
link: json["link"],
online: json["online"],
pageDescription: json["page_description"] == null ? null : Page.fromJson(json["page_description"]),
pageKeywords: json["page_keywords"] == null ? null : Page.fromJson(json["page_keywords"]),
pageTitle: json["page_title"] == null ? null : Page.fromJson(json["page_title"]),
cEnableCompare: json["c_enableCompare"] == null ? null : json["c_enableCompare"],
cShowInMenu: json["c_showInMenu"] == null ? null : json["c_showInMenu"],
description: json["description"] == null ? null : Description.fromJson(json["description"]),
name: json["name"] == null ? null : Description.fromJson(json["name"]),
parentCategoryId: json["parent_category_id"] == null ? null : parentCategoryIdValues.map[json["parent_category_id"]],
thumbnail: json["thumbnail"] == null ? null : json["thumbnail"],
);
Map<String, dynamic> toJson() => {
"_v": v == null ? null : v,
"_type": typeValues.reverse[type],
"_resource_state": resourceState == null ? null : resourceState,
"catalog_id": catalogIdValues.reverse[catalogId],
"categories": categories == null ? null : List<dynamic>.from(categories!.map((x) => x.toJson())),
"creation_date": creationDate!.toIso8601String(),
"id": id,
"last_modified": lastModified!.toIso8601String(),
"link": link,
"online": online,
"page_description": pageDescription == null ? null : pageDescription!.toJson(),
"page_keywords": pageKeywords == null ? null : pageKeywords!.toJson(),
"page_title": pageTitle == null ? null : pageTitle!.toJson(),
"c_enableCompare": cEnableCompare == null ? null : cEnableCompare,
"c_showInMenu": cShowInMenu == null ? null : cShowInMenu,
"description": description == null ? null : description!.toJson(),
"name": name == null ? null : name!.toJson(),
"parent_category_id": parentCategoryId == null ? null : parentCategoryIdValues.reverse[parentCategoryId],
"thumbnail": thumbnail == null ? null : thumbnail,
};
}
enum CatalogId { VMM_STOREFRONT_CATALOG }
final catalogIdValues = EnumValues({
"vmm-storefront-catalog": CatalogId.VMM_STOREFRONT_CATALOG
});
class Description {
Description({
this.descriptionDefault,
this.hiIn,
});
String? descriptionDefault;
String? hiIn;
factory Description.fromJson(Map<String, dynamic> json) => Description(
descriptionDefault: json["default"],
hiIn: json["hi-IN"] == null ? null : json["hi-IN"],
);
Map<String, dynamic> toJson() => {
"default": descriptionDefault,
"hi-IN": hiIn == null ? null : hiIn,
};
}
class Page {
Page({
this.pageDefault,
});
String? pageDefault;
factory Page.fromJson(Map<String, dynamic> json) => Page(
pageDefault: json["default"],
);
Map<String, dynamic> toJson() => {
"default": pageDefault,
};
}
enum ParentCategoryId { ROOT }
final parentCategoryIdValues = EnumValues({
"root": ParentCategoryId.ROOT
});
enum Type { CATEGORY }
final typeValues = EnumValues({
"category": Type.CATEGORY
});
class EnumValues<T> {
late Map<String, T> map;
late Map<T, String> reverseMap;
EnumValues(this.map);
Map<T, String> get reverse {
if (reverseMap == null) {
reverseMap = map.map((k, v) => new MapEntry(v, k));
}
return reverseMap;
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/model/subcatmodel.dart | // To parse this JSON data, do
//
// final subCatModel = subCatModelFromJson(jsonString);
import 'dart:convert';
SubCatModel subCatModelFromJson(String str) => SubCatModel.fromJson(json.decode(str));
String subCatModelToJson(SubCatModel data) => json.encode(data.toJson());
class SubCatModel {
SubCatModel({
this.v,
this.type,
this.resourceState,
this.catalogId,
this.categories,
this.creationDate,
this.id,
this.lastModified,
this.link,
this.name,
this.online,
this.pageDescription,
this.pageKeywords,
this.pageTitle,
this.parentCategoryId,
this.thumbnail,
this.cEnableCompare,
this.cShowInMenu,
});
String? v;
String? type;
String? resourceState;
String? catalogId;
List<SubCatModel>? categories;
DateTime? creationDate;
String? id;
DateTime? lastModified;
String? link;
Name? name;
bool? online;
Page? pageDescription;
Page? pageKeywords;
Page? pageTitle;
String? parentCategoryId;
String? thumbnail;
bool? cEnableCompare;
bool? cShowInMenu;
factory SubCatModel.fromJson(Map<String, dynamic> json) => SubCatModel(
v: json["_v"] == null ? null : json["_v"],
type: json["_type"],
resourceState: json["_resource_state"] == null ? null : json["_resource_state"],
catalogId: json["catalog_id"],
categories: json["categories"] == null ? null : List<SubCatModel>.from(json["categories"].map((x) => SubCatModel.fromJson(x))),
creationDate: DateTime.parse(json["creation_date"]),
id: json["id"],
lastModified: DateTime.parse(json["last_modified"]),
link: json["link"],
name: Name.fromJson(json["name"]),
online: json["online"],
pageDescription: Page.fromJson(json["page_description"]),
pageKeywords: Page.fromJson(json["page_keywords"]),
pageTitle: Page.fromJson(json["page_title"]),
parentCategoryId: json["parent_category_id"],
thumbnail: json["thumbnail"],
cEnableCompare: json["c_enableCompare"],
cShowInMenu: json["c_showInMenu"],
);
Map<String, dynamic> toJson() => {
"_v": v == null ? null : v,
"_type": type,
"_resource_state": resourceState == null ? null : resourceState,
"catalog_id": catalogId,
"categories": categories == null ? null : List<dynamic>.from(categories!.map((x) => x.toJson())),
"creation_date": creationDate!.toIso8601String(),
"id": id,
"last_modified": lastModified!.toIso8601String(),
"link": link,
"name": name!.toJson(),
"online": online,
"page_description": pageDescription!.toJson(),
"page_keywords": pageKeywords!.toJson(),
"page_title": pageTitle!.toJson(),
"parent_category_id": parentCategoryId,
"thumbnail": thumbnail,
"c_enableCompare": cEnableCompare,
"c_showInMenu": cShowInMenu,
};
}
class Name {
Name({
this.nameDefault,
this.hiIn,
});
String? nameDefault;
String? hiIn;
factory Name.fromJson(Map<String, dynamic> json) => Name(
nameDefault: json["default"],
hiIn: json["hi-IN"],
);
Map<String, dynamic> toJson() => {
"default": nameDefault,
"hi-IN": hiIn,
};
}
class Page {
Page({
this.pageDefault,
});
String? pageDefault;
factory Page.fromJson(Map<String, dynamic> json) => Page(
pageDefault: json["default"],
);
Map<String, dynamic> toJson() => {
"default": pageDefault,
};
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/themes/apptheme.dart | import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
class AppTheme {
static const Color appThemeColor = Color(0xff0068A9);
static const Color buttonThemeColor = Color(0xff1FA0BD);
static const Color hintText = Color(0xffAABCCC);
static const Color whitColor = Color(0xffffffff);
static const Color background = Color(0xffF7F7F7);
static const Color blackText = Color(0xFF000000);
static const Color scaffoldBackgroundColor = Color(0xffEEEEEE);
static const Color gobutton = Color(0xffF9E56F);
static const Color subscriptionColor = Colors.green;
static const Color discountColor = Colors.red;
static const Color toastColor = Color(0xff415841);
// #F9E56F
lightTheme() {
return ThemeData(
brightness: Brightness.light,
buttonTheme: const ButtonThemeData(
buttonColor: Color(0xff1FA0BD),
textTheme: ButtonTextTheme.primary,
disabledColor: Color(0x1a25a3bf),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
alignedDropdown: true),
appBarTheme: const AppBarTheme(
elevation: 0.2,
color: Colors.white,
iconTheme: IconThemeData(
color: Colors.black,
)),
primaryColor: const Color(0xff1FA0BD),
primaryColorLight: const Color(0x1a84FFFF),
scaffoldBackgroundColor: const Color(0xffFFFFFF),
bottomAppBarColor: const Color(0xffFFFFFF),
dividerColor: const Color(0x1f84FFFF),
textTheme: TextTheme(
headline1: GoogleFonts.abel(),
headline2: GoogleFonts.aBeeZee(),
bodyText1: GoogleFonts.aBeeZee(),
bodyText2: GoogleFonts.poppins()),
focusColor: const Color(0x1aF5E0C3),
colorScheme: ColorScheme.fromSwatch(
primarySwatch: const MaterialColor(
0xff1FA0BD,
<int, Color>{
50: Color(0xff000000),
100: Color(0xff000000),
200: Color(0xff000000),
300: Color(0xff000000),
400: Color(0xff000000),
500: Color(0xff000000),
600: Color(0xff000000),
700: Color(0xff000000),
800: Color(0xff000000)
},
)).copyWith(secondary: const Color(0xff1FA0BD)));
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/lib/screens/themes/app_fonts.dart | import 'package:flutter/material.dart';
class AppFonts {
static double pageviewHeader = 0.0;
static double registerHeader = 0.0;
static double bigSubtitle = 0.0;
static double buttomtext = 0.0;
static double headertitle = 0.0;
static double hinttextsize = 0.0;
static double iconsize = 0.0;
static double historysubtitlesize = 0.0;
static double historycouplesize = 0.0;
static double subtitle1 = 0.0;
AppFonts(context) {
var device = MediaQuery.of(context).size.width;
pageviewHeader = device > 600.0 ? 50 :38.0;
registerHeader = device > 600.0 ? 45 : 30.0;
bigSubtitle = device > 600 ? 24 : 18.0;
buttomtext = device > 600.0 ?24: 20.0;
headertitle = device > 600.0 ? 24 :20.0;
hinttextsize = device > 600.0 ? 20: 16.0;
iconsize = device > 600.0 ? 45 : 30.0;
historysubtitlesize = device > 600 ? 18 : 12.0;
historycouplesize = device > 600.0 ?18: 14.0;
subtitle1 = device > 600.0 ? 18: 12.0;
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/.dart_tool | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/.dart_tool/dartpad/web_plugin_registrant.dart | // Flutter web plugin registrant file.
//
// Generated file. Do not edit.
//
// @dart = 2.13
// ignore_for_file: type=lint
import 'package:geolocator_web/geolocator_web.dart';
import 'package:shared_preferences_web/shared_preferences_web.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
void registerPlugins([final Registrar? pluginRegistrar]) {
final Registrar registrar = pluginRegistrar ?? webPluginRegistrar;
GeolocatorPlugin.registerWith(registrar);
SharedPreferencesPlugin.registerWith(registrar);
registrar.registerMessageHandler();
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/.dart_tool | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/E-com app/.dart_tool/flutter_build/dart_plugin_registrant.dart | //
// Generated file. Do not edit.
// This file is generated from template in file `flutter_tools/lib/src/flutter_plugins.dart`.
//
// @dart = 2.12
import 'dart:io'; // flutter_ignore: dart_io_import.
import 'package:geolocator_android/geolocator_android.dart';
import 'package:path_provider_android/path_provider_android.dart';
import 'package:shared_preferences_android/shared_preferences_android.dart';
import 'package:geolocator_apple/geolocator_apple.dart';
import 'package:path_provider_ios/path_provider_ios.dart';
import 'package:shared_preferences_ios/shared_preferences_ios.dart';
import 'package:path_provider_linux/path_provider_linux.dart';
import 'package:shared_preferences_linux/shared_preferences_linux.dart';
import 'package:path_provider_macos/path_provider_macos.dart';
import 'package:shared_preferences_macos/shared_preferences_macos.dart';
import 'package:path_provider_windows/path_provider_windows.dart';
import 'package:shared_preferences_windows/shared_preferences_windows.dart';
@pragma('vm:entry-point')
class _PluginRegistrant {
@pragma('vm:entry-point')
static void register() {
if (Platform.isAndroid) {
try {
GeolocatorAndroid.registerWith();
} catch (err) {
print(
'`geolocator_android` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
PathProviderAndroid.registerWith();
} catch (err) {
print(
'`path_provider_android` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
SharedPreferencesAndroid.registerWith();
} catch (err) {
print(
'`shared_preferences_android` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
} else if (Platform.isIOS) {
try {
GeolocatorApple.registerWith();
} catch (err) {
print(
'`geolocator_apple` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
PathProviderIOS.registerWith();
} catch (err) {
print(
'`path_provider_ios` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
SharedPreferencesIOS.registerWith();
} catch (err) {
print(
'`shared_preferences_ios` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
} else if (Platform.isLinux) {
try {
PathProviderLinux.registerWith();
} catch (err) {
print(
'`path_provider_linux` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
SharedPreferencesLinux.registerWith();
} catch (err) {
print(
'`shared_preferences_linux` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
} else if (Platform.isMacOS) {
try {
PathProviderMacOS.registerWith();
} catch (err) {
print(
'`path_provider_macos` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
SharedPreferencesMacOS.registerWith();
} catch (err) {
print(
'`shared_preferences_macos` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
} else if (Platform.isWindows) {
try {
PathProviderWindows.registerWith();
} catch (err) {
print(
'`path_provider_windows` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
try {
SharedPreferencesWindows.registerWith();
} catch (err) {
print(
'`shared_preferences_windows` threw an error: $err. '
'The app may not function as expected until you remove this plugin from pubspec.yaml'
);
rethrow;
}
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/presentation/pages/home_page.dart';
import 'package:momento/utils/themes.dart';
void main() {
runApp(
ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
ThemeMode themeMode = watch(ThemeManagerProvider).currentThemeMode;
return MaterialApp(
title: 'Notes',
darkTheme: AppThemeDark,
theme: AppThemeLight,
themeMode: themeMode,
home: HomePage(),
debugShowCheckedModeBanner: false,
);
},
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/data | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/data/models/note.dart | import 'package:flutter/foundation.dart';
import 'package:momento/data/services/database_service.dart';
class Note extends ChangeNotifier {
int id;
String title;
String content;
int isPinned;
String date_created;
String last_updated;
bool _disposed = false;
Note({
this.id,
this.title,
this.content,
this.isPinned,
this.date_created,
this.last_updated,
});
factory Note.fromMap(Map<String, dynamic> map) {
return new Note(
id: map['id'],
title: map['title'],
content: map['content'],
isPinned: map['isPinned'],
date_created: map['date_created'],
last_updated: map['last_updated']);
}
Map<String, dynamic> toMap() {
Map<String, dynamic> map = {
'title': title,
'content': content,
'isPinned': isPinned,
'date_created': date_created,
'last_updated': last_updated
};
return map;
}
Future<int> update(Note note) async {
var result = await DatabaseService.instance.updateNote(note);
this.content = note.content;
this.date_created = note.date_created;
this.id = note.id;
this.isPinned = note.isPinned;
this.last_updated = note.last_updated;
this.last_updated = note.last_updated;
this.title = note.title;
notifyListeners();
return result;
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
@override
void notifyListeners() {
if (!_disposed) {
super.notifyListeners();
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/data | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/data/repositories/notes_repository.dart | import 'package:flutter/foundation.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/data/services/database_service.dart';
enum LayoutType { List, Grid }
class NotesRepository extends ChangeNotifier {
List<Note> notes_list;
LayoutType layout = LayoutType.Grid;
NotesRepository() {
this.notes_list = [];
}
Future<int> addNote(Note note) async {
var result = await DatabaseService.instance.addNote(note);
await getAllNotes();
// notifyListeners();
return result;
}
Future<void> getAllNotes() async {
notes_list = await DatabaseService.instance.getAllNotes();
notifyListeners(); // if(notes_list == null) return [];
}
Future<Note> getNote(int noteId) async {
return notes_list.map((element) {
if (element.id == noteId) {
return element;
}
}).first;
}
Future<int> deleteNote(int noteid) async {
var result = await DatabaseService.instance.deleteNote(noteid);
//await getAllNotes();
// notifyListeners();
return result;
}
Future<void> deleteMultipleNotes(List<int> noteids) async {
noteids.forEach((element) async {
await DatabaseService.instance.deleteNote(element);
});
await getAllNotes();
// notifyListeners();
}
setPin(List<Note> notelist) {
notelist.forEach((element) {
Note temp = element;
temp.isPinned = 1;
element.update(temp);
});
notifyListeners();
}
unsetPin(List<Note> notelist) {
notelist.forEach((element) {
Note temp = element;
temp.isPinned = 0;
element.update(temp);
});
notifyListeners();
}
// Future<void> updateNote(Note note) async {
// await DatabaseHelper.instance.updateNote(note);
// // await getAllNotes();
// notifyListeners();
// }
void toggleView() {
if (layout == LayoutType.Grid) {
layout = LayoutType.List;
} else {
layout = LayoutType.Grid;
}
notifyListeners();
}
// Future<int> updateNote(Note note) async {
// var result = await DatabaseHelper.instance.updateNote(note);
// // notes_list = await DatabaseHelper.instance.getAllNotes();
// int index= notes_list.indexWhere((element) => element.id == note.id);
// notes_list[index] = note;
// notifyListeners();
// return result;
// }
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/data | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/data/services/database_service.dart | import 'dart:io';
import 'package:momento/data/models/note.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
class DatabaseService {
static const String tableName = "notes_tb";
static const String columnId = "id";
static const String columnTitle = "title";
static const String columnContent = "content";
static const String columnIsPinned = "isPinned";
static const String columnDateCreated = "date_created";
static const String columnLastUpdated = "last_updated";
DatabaseService._();
static final DatabaseService instance = new DatabaseService._();
static Database _database;
Future<Database> get database async {
if (_database != null) {
return _database;
}
_database = await initDb();
return _database;
}
Future<Database> initDb() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = join(directory.path, "notes.db");
Database dbCreated =
await openDatabase(path, version: 1, onCreate: _onCreate);
return dbCreated;
}
void _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE $tableName(
$columnId INTEGER PRIMARY KEY AUTOINCREMENT,
$columnTitle TEXT,
$columnContent TEXT NOT NULL,
$columnIsPinned INTEGER NOT NULL,
$columnDateCreated TEXT,
$columnLastUpdated TEXT);
''');
}
Future<int> addNote(Note note) async {
var db = await database;
int result = await db.insert("$tableName", note.toMap());
return result;
}
Future<List<Note>> getAllNotes() async {
var db = await database;
var result = await db.query(
"$tableName",
orderBy: columnDateCreated + ' DESC',
);
if (result.isEmpty) return null;
return result.map((row) => Note.fromMap(row)).toList();
}
Future<Note> getNote(int noteId) async {
var db = await database;
var item = await db
.query("$tableName", where: "$columnId = ?", whereArgs: [noteId]);
if (item.length == 0) return null;
return new Note.fromMap(item.first);
}
Future<int> deleteNote(int noteid) async {
var db = await database;
int rowsDeleted = await db
.delete("$tableName", where: "$columnId = ?", whereArgs: [noteid]);
return rowsDeleted;
}
Future<int> updateNote(Note note) async {
var db = await database;
int rowsUpdated = await db.update("$tableName", note.toMap(),
where: "$columnId = ?", whereArgs: [note.id]);
return rowsUpdated;
}
Future close() async {
var db = await database;
db.close();
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic/providers/selected_notes.dart | import 'package:flutter/cupertino.dart';
import 'package:momento/data/models/note.dart';
// stores notes which are currrently selected and notifies it's listners when ever selection changes
class SelectedNotes extends ChangeNotifier{
List<Note> notes_list = [];
void add(Note note){
notes_list.add(note);
notifyListeners();
}
void remove(Note note){
notes_list.removeWhere((element) => element.id == note.id);
notifyListeners();
}
void clear(){
notes_list = [];
notifyListeners();
}
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic/providers/theme_manager.dart | import 'package:flutter/material.dart';
class ThemeManager extends ChangeNotifier {
ThemeManager() : _currentThemeMode = ThemeMode.dark;
ThemeMode _currentThemeMode;
get currentThemeMode => _currentThemeMode;
void changeTheme(ThemeMode newThemeMode) {
_currentThemeMode = newThemeMode;
notifyListeners();
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic/providers/search_result.dart | import 'package:flutter/cupertino.dart';
import 'package:momento/data/models/note.dart';
class SearchResult extends ChangeNotifier {
// ProviderReference ref;
// SearchResult(this.ref);
List<Note> notes;
String str;
SearchResult({this.notes,this.str}){
// get search results every time this constructor is called
// in order to fetch search results every time the value of
// [notes] or [str] changes.
_get();
}
List<Note> result_notes_list = [];
void _get() {
List<Note> notes_filtered = [];
str = str.trim();
if (str.isEmpty || notes == null) {
result_notes_list = [];
notifyListeners();
return;
}
List<String> searchwords = str.split(" ").toList();
notes.forEach((element) {
bool flag = searchwords.every((word) {
return (element.content.toLowerCase().contains(word) ||
element.title.toLowerCase().contains(word));
});
if (flag && !notes_filtered.contains(element))
notes_filtered.add(element);
});
// notes_filtered.forEach((element) {
// print('filtered note' + element.id.toString() + ' ' + element.title);
// });
result_notes_list = notes_filtered;
notifyListeners();
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/business_logic/providers/providers.dart | import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/theme_manager.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/business_logic/providers/search_result.dart';
import 'package:momento/data/repositories/notes_repository.dart';
import 'package:momento/business_logic/providers/selected_notes.dart';
// The [NotesRepositoryProvider] provides an instance of [NotesRepository] class.
final NotesRepositoryProvider =
ChangeNotifierProvider<NotesRepository>((ref) => NotesRepository());
// The [AllNotesProvider] fetches Notes List from [NotesRepository] class
// using the [NotesRepositoryProvider] and provides the Notes List.
// note: we use [FutureProvider] because =>
// 1. we need to await for getAllNotes() to be completed.
// 2. we get benifit of using .when() with [AsyncValue] , so we don't need [FutureBuilder]
final AllNotesProvider = FutureProvider<List<Note>>((ref) async {
await ref.watch(NotesRepositoryProvider).getAllNotes();
return ref.watch(NotesRepositoryProvider).notes_list ?? [];
});
final PinnedNotesProvider = FutureProvider<List<Note>>((ref) async {
var notes = ref.watch(AllNotesProvider)?.data?.value;
List<Note> pinnednotes = [];
notes?.forEach((e) {
if (e.isPinned == 1) pinnednotes.add(e);
});
return pinnednotes;
});
final UnPinnedNotesProvider = FutureProvider<List<Note>>((ref) async {
var notes = ref.watch(AllNotesProvider)?.data?.value;
List<Note> unpinnednotes = [];
notes?.forEach((e) {
if (e.isPinned == 0) unpinnednotes.add(e);
});
return unpinnednotes;
});
// The [NoteProvider] takes an index of the Note and fetches the Note
// from Note List Provided by [AllNotesProvider] class.
final NoteProvider = ChangeNotifierProvider.family<Note, int>((ref, id) {
var notelist = ref.watch(AllNotesProvider)?.data?.value;
ref.onDispose(() {
print('note with id: ' + id.toString() + ' disposed');
});
return notelist?.firstWhere((element) => element.id == id);
});
// The [SelectedNotesProvider] provides SelectedNotes ChangeNotifier
// which we can listen to in order to get currently selected notes
final SelectedNotesProvider =
ChangeNotifierProvider<SelectedNotes>((ref) => new SelectedNotes());
// The [SearchTextProvider] provides Search Text typed in the [SearchBar]
// which we can listen to in order to get current SearchText
final SearchTextProvider = StateProvider<String>((ref) {
return "";
});
// The [SearchResultClassProvider] provides [SearchResult] instance.
// It Takes List of Notes from [AllNotesProvider] and
// The Search Text From [SearchTextProvider]
final SearchResultClassProvider = ChangeNotifierProvider<SearchResult>((ref) {
var notelist = ref.watch(AllNotesProvider)?.data?.value;
String str = ref.watch(SearchTextProvider).state;
return SearchResult(notes: notelist, str: str);
});
// The [AllSearchResultProvider] provides List of Notes From [SearchResult]
final AllSearchResultProvider = FutureProvider<List<Note>>((ref) async {
return ref.watch(SearchResultClassProvider).result_notes_list;
});
//final isNoteSelected = Provider.family<bool, int>((ref, noteId) {
// return ref
// .watch(SelectedNotesProvider)
// .notes_list
// .any((element) => element.id == noteId);
//});
/// isNoteEdited
ValueNotifier<bool> a = ValueNotifier<bool>(false);
final ThemeManagerProvider = ChangeNotifierProvider<ThemeManager>((ref){
return ThemeManager();
});
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/note_pin.dart | import 'package:flutter/material.dart';
class NotePin extends StatefulWidget {
Function(int) onChanged;
int isPinned;
NotePin({this.onChanged, this.isPinned});
@override
_NotePinState createState() => _NotePinState();
}
class _NotePinState extends State<NotePin> {
@override
Widget build(BuildContext context) {
if (widget.isPinned == 1) {
return IconButton(
splashRadius: 25.0,
icon: Icon(Icons.push_pin),
onPressed: () {
setState(() {
widget.isPinned = 0;
});
widget.onChanged(widget.isPinned);
},
);
} else {
return IconButton(
splashRadius: 25.0,
icon: Icon(Icons.push_pin_outlined),
onPressed: () {
setState(() {
widget.isPinned = 1;
});
widget.onChanged(widget.isPinned);
},
);
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/custom_drawer.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:momento/presentation/widgets/custom_cupertino_switch.dart';
class CustomDrawer extends StatelessWidget {
const CustomDrawer({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
// color: kBackgroundColor,
color: Theme.of(context).backgroundColor,
width: 340,
height: double.infinity,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
height: 40.0,
),
ListTile(
title: Text(
'Momento',
style: TextStyle(
fontSize: 28.0,
fontFamily: 'Open Sans',
letterSpacing: 0.8,
fontWeight: FontWeight.bold,
// color: kAccentColor,
color: Theme.of(context).accentColor
),
),
),
// SizedBox(
// height: 25.0,
// ),
Image.asset(
'assets/light-illustration.png',
semanticLabel: 'Illustration',
width: 400,
scale: 1.0,
repeat: ImageRepeat.noRepeat,
),
Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'Settings',
maxLines: 1,
style: TextStyle(
fontFamily: 'Open Sans',
fontSize: 24.0,
fontWeight: FontWeight.w600,
// color: Color(0xEEFFFFFF),
color: Theme.of(context).textTheme.bodyText2.color
),
),
),
ListTile(
title: Text(
'Dark Mode',
style: TextStyle(
fontFamily: 'Open Sans',
fontSize: 20.0,
// color: Color(0xEEFFFFFF),
color: Theme.of(context).textTheme.bodyText2.color
),
),
trailing:CustomCupertinoSwitch(),
),
// SizedBox(
// height: 10.0,
// ),
// Container(
// padding: EdgeInsets.only(
// left: 20.0,
// ),
// child: Row(
// children: [
// Icon(Icons.info_outline, color: Color(0xEEFFFFFF)),
// SizedBox(
// width: 10.0,
// ),
// Text(
// 'About Us',
// style:
// TextStyle(fontSize: 19.0, color: Color(0xEEFFFFFF)),
// ),
// ],
// ),
// ),
// AboutListTile(
// applicationName: 'Momento',
// applicationVersion: '1.0.0',
// child: Text('About Us',style: TextStyle(
// fontSize: 21.0,
// color: Color(0xEEFFFFFF),
// ),),
// icon: Icon(Icons.info_outline),
// aboutBoxChildren: [
// ListTile(
// title: Text('Developer'),
// subtitle: Text('Abrar Malek'),
// trailing: CircleAvatar(
// backgroundColor: Color(0xFFe57373),
// ),
// ),
// ],
// ),
Divider(
indent: 16.0,
endIndent: 16.0,
),
Container(
padding: EdgeInsets.symmetric(horizontal: 16.0),
child: Text(
'About',
maxLines: 1,
style: TextStyle(
fontFamily: 'Open Sans',
fontSize: 24.0,
fontWeight: FontWeight.w600,
// color: Color(0xEEFFFFFF),
color: Theme.of(context).textTheme.bodyText2.color
),
),
),
ListTile(
title: Text(
'Abrar Malek',
style: TextStyle(
fontSize: 20.0,
fontFamily: 'Open Sans',
// color: Color(0xEEFFFFFF),
color: Theme.of(context).textTheme.bodyText2.color
),
),
subtitle: Text(
'Developer',
style: TextStyle(
fontSize: 15.0,
fontFamily: 'Open Sans',
),
),
trailing: CircleAvatar(
// backgroundColor: kAccentColor,
backgroundColor: Theme.of(context).accentColor,
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/notes_list.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/presentation/widgets/note_card.dart';
import 'package:momento/business_logic/providers/providers.dart';
class NotesList extends StatelessWidget {
final String page;
final String type;
NotesList({this.page,this.type});
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
AsyncValue<List<Note>> asyncnotelist;
if(page == 'home' && type=="pinned"){
asyncnotelist = watch(PinnedNotesProvider);
}
else if(page == 'home' && type=="unpinned"){
asyncnotelist = watch(UnPinnedNotesProvider);
}
else if(page == 'search'){
asyncnotelist = watch(AllSearchResultProvider);
}
return asyncnotelist.when(
data: (data) {
// This [Padding] affects the area between the edge of the screen and the [ListView]
return SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
sliver: SliverList(
delegate: SliverChildBuilderDelegate(
(contex, index) {
return NoteCard(
id: data[index].id,
page: page,
);
},
childCount: data?.length ?? 0,
),
),
);
},
loading: () {
return SliverFillRemaining(
child: Center(child: CircularProgressIndicator()));
},
error: (errr, stack) =>
SliverFillRemaining(child: const Text('error')),
);
},
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/contextual_appbar.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/data/models/note.dart';
class ContextualAppBar extends StatefulWidget {
@override
_ContextualAppBarState createState() => _ContextualAppBarState();
}
class _ContextualAppBarState extends State<ContextualAppBar> {
@override
Widget build(BuildContext context) {
return SliverAppBar(
elevation: 3,
forceElevated: true,
pinned: true,
automaticallyImplyLeading: false,
// backgroundColor: kAppBarColor,
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
leadingWidth: 100,
leading: Row(
children: [
IconButton(
icon: Icon(
Icons.clear,
),
onPressed: () {
context.read(SelectedNotesProvider).clear();
},
),
SizedBox(
width: 5.0,
),
Consumer(builder: (context, watch, child) {
final selectednotes = watch(SelectedNotesProvider);
final count = selectednotes.notes_list.length;
return Text(
'$count',
style: TextStyle(
fontSize: 23.0,
),
);
}),
],
),
// toolbarHeight: 71.0,
actions: [
Consumer(
builder: (context, watch, child) {
List<Note> selectednotes = watch(SelectedNotesProvider).notes_list;
var pinnedcount = 0, unpinnedcount = 0;
selectednotes.forEach((element) {
if (element.isPinned == 1) {
pinnedcount++;
} else {
unpinnedcount++;
}
});
if (pinnedcount > 0 && unpinnedcount > 0) {
// show a way to pin notes
return IconButton(
icon: Icon(Icons.push_pin_outlined),
onPressed: () {
context.read(NotesRepositoryProvider).setPin(selectednotes);
context.read(SelectedNotesProvider).clear();
},
);
} else if (pinnedcount > 0 && unpinnedcount == 0) {
// show a way to unpin notes
return IconButton(
icon: Icon(Icons.push_pin),
onPressed: () {
context.read(NotesRepositoryProvider).unsetPin(selectednotes);
context.read(SelectedNotesProvider).clear();
},
);
} else if (pinnedcount == 0 && unpinnedcount > 0) {
// show a way to pin notes
return IconButton(
icon: Icon(Icons.push_pin_outlined),
onPressed: () {
context.read(NotesRepositoryProvider).setPin(selectednotes);
context.read(SelectedNotesProvider).clear();
},
);
} else {
return Container();
}
},
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () {
context.read(NotesRepositoryProvider).deleteMultipleNotes(context
.read(SelectedNotesProvider)
.notes_list
.map((e) => e.id)
.toList());
context.read(SelectedNotesProvider).clear();
},
),
],
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/unPinnned_label.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/business_logic/providers/providers.dart';
class UnPinnedLable extends StatelessWidget {
const UnPinnedLable({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
AsyncValue<List<Note>> asyncnotelist = watch(AllNotesProvider);
return asyncnotelist.when(
data: (allnotes) {
var pinnedcount = 0,unpinnedcount = 0;
allnotes.forEach((element) {
if(element.isPinned == 1) {
pinnedcount++;
}
else{
unpinnedcount++;
}
});
if ( unpinnedcount > 0 && pinnedcount >0) {
return SliverPadding(
padding: EdgeInsets.only(top: 12.0, left: 20.0, bottom: 12.0),
sliver: SliverToBoxAdapter(
child: Text(
'OTHERS',
style: TextStyle(
fontSize: 12,
color: Theme.of(context).textTheme.overline.color,
),
),
),
);
} else {
return SliverToBoxAdapter(
child: SizedBox(
height: 5,
),
);
}
},
error: (Object error, StackTrace stackTrace) {
return SliverToBoxAdapter();
},
loading: () {
return SliverToBoxAdapter();
},
);
},
);
}
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/notes_grid.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/presentation/widgets/note_card.dart';
class NotesGrid extends StatelessWidget {
final String page;
final String type;
NotesGrid({this.page,this.type});
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
AsyncValue<List<Note>> asyncnotelist;
if(page == 'home' && type=="pinned"){
asyncnotelist = watch(PinnedNotesProvider);
}
else if(page == 'home' && type=="unpinned"){
asyncnotelist = watch(UnPinnedNotesProvider);
}
else if(page == 'search'){
asyncnotelist = watch(AllSearchResultProvider);
}
return asyncnotelist.when(
data: (data) {
print(asyncnotelist);
print(data?.length);
return SliverPadding(
// This [Padding] affects the area between the edge of the screen and the [StaggeredGridView]
padding: const EdgeInsets.symmetric(horizontal: 8.0),
sliver: SliverStaggeredGrid.countBuilder(
// The [crossAxisSpacing] and [mainAxisSpacing] affects the area the between Grid Items
crossAxisSpacing: 9.0,
mainAxisSpacing: 9.0,
itemCount: data?.length ?? 0,
staggeredTileBuilder: (index) {
return const StaggeredTile.fit(1);
},
crossAxisCount: 2,
itemBuilder: (context, index) {
return NoteCard(
id: data[index].id,
page: page,
);
},
),
);
},
loading: () {
return SliverFillRemaining(
child: Center(child: CircularProgressIndicator()));
},
error: (error, stack) =>
SliverFillRemaining(child: Text('$error')),
);
},
);
// AsyncValue<List<Note>> notelist = watch(AllNotesProvider);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/last_edited_label.dart | import 'package:flutter/material.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/utils/helper_functions.dart';
class LastEditedLabel extends StatefulWidget {
final String last_updated;
LastEditedLabel({this.last_updated});
@override
_LastEditedLabelState createState() => _LastEditedLabelState();
}
class _LastEditedLabelState extends State<LastEditedLabel> {
@override
Widget build(BuildContext context) {
return ValueListenableBuilder(
valueListenable: a,
builder: (context, isEdited, child) {
print(isEdited);
if (!isEdited) {
return Text(
getLastEdited(widget.last_updated),
style: TextStyle(
fontSize: 15.0,
),
);
}
return Container();
},
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/main_app_bar.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/presentation/pages/search_page.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/data/repositories/notes_repository.dart';
class MainAppBar extends StatefulWidget {
final VoidCallback onClick;
MainAppBar({this.onClick});
@override
_MainAppBarState createState() => _MainAppBarState();
}
class _MainAppBarState extends State<MainAppBar> {
@override
Widget build(BuildContext context) {
return SliverAppBar(
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(10.0),
// ),
floating: true,
snap: true,
primary: false,
elevation: 0.0,
toolbarHeight: 71.0,
// centerTitle: true,
// forceElevated: true,
automaticallyImplyLeading: false,
// backgroundColor: Color(0xFF354252),
backgroundColor: Colors.transparent,
title: Column(
children: [
SizedBox(
height: 5.0,
),
Card(
// elevation: 5.0,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
child: Ink(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
// color: Color(0xFF303440),
color: Theme.of(context).appBarTheme.backgroundColor,
),
child: InkWell(
borderRadius: BorderRadius.circular(10.0),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SearchPage(),
),
);
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 2),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
IconButton(
splashRadius: 25.0,
icon: Icon(
Icons.menu,
color: Theme.of(context).appBarTheme.iconTheme.color,
),
onPressed: () {
widget.onClick();
},
),
Expanded(
child: Hero(
tag: 'searchbar',
transitionOnUserGestures: true,
child: Material(
type: MaterialType.transparency,
child: Text(
'Search your notes',
style: TextStyle(
fontFamily: 'Open Sans',
fontSize: 18.0,
// color: Colors.grey.shade400,
color: Theme.of(context)
.appBarTheme
.titleTextStyle
.color),
),
),
),
),
Consumer(
builder: (context, watch, child) {
final viewModel = watch(NotesRepositoryProvider);
// layout variable is used to determine currently slected layout
LayoutType layout = viewModel.layout;
if (layout == LayoutType.Grid) {
return IconButton(
splashRadius: 25.0,
icon: Icon(
Icons.view_agenda_outlined,
// color: Colors.grey.shade400,
color: Theme.of(context)
.appBarTheme
.actionsIconTheme
.color,
),
onPressed: () {
viewModel.toggleView();
},
);
} else {
// if current layout is List then Show the Grid Icon
return IconButton(
splashRadius: 25.0,
icon: Icon(
Icons.grid_view,
// color: Colors.grey.shade400,
color: Theme.of(context)
.appBarTheme
.actionsIconTheme
.color,
),
onPressed: () {
viewModel.toggleView();
},
);
}
// }
},
),
],
),
),
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/pinnned_label.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/business_logic/providers/providers.dart';
class PinnedLable extends StatelessWidget {
const PinnedLable({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
AsyncValue<List<Note>> asyncnotelist = watch(AllNotesProvider);
return asyncnotelist.when(
data: (allnotes) {
var pinnedcount = 0,unpinnedcount = 0;
allnotes.forEach((element) {
if(element.isPinned == 1) {
pinnedcount++;
}
else{
unpinnedcount++;
}
});
if (pinnedcount > 0) {
return SliverPadding(
padding: EdgeInsets.only(top: 12.0, left: 20.0, bottom: 12.0),
sliver: SliverToBoxAdapter(
child: Text(
'PINNED',
style: TextStyle(
fontSize: 12,
color: Theme.of(context).textTheme.overline.color,
),
),
),
);
} else {
return SliverToBoxAdapter(
);
}
},
error: (Object error, StackTrace stackTrace) {
return SliverToBoxAdapter();
},
loading: () {
return SliverToBoxAdapter();
},
);
},
);
}
} | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/note_card.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/presentation/pages/edit_note_page.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/presentation/pages/search_page.dart';
import 'package:momento/utils/helper_functions.dart';
import 'package:momento/utils/themes.dart';
import 'package:momento/data/repositories/notes_repository.dart';
import 'package:momento/presentation/pages/home_page.dart';
class NoteCard extends StatefulWidget {
final int id;
final String page;
NoteCard({this.page, this.id});
@override
_NoteCardState createState() => _NoteCardState();
}
class _NoteCardState extends State<NoteCard> {
@override
Widget build(BuildContext context) {
// we use [Consumer] here in order to minimize the rebuild by only rebuilding this
// instance [NoteCard] when this Note changes, using the [NoteProvider] as oppose to
// rebuilding the whole listview or gridview which happens in the case where
// the current Note was provided from [AllNotesProvider] which causes the whole list rebuild
// whenever a single Note changes because [AllNotesProvider] provies the note list, not a single note.
return Consumer(
builder: (context, watch, child) {
// print('inside note card at index ${widget.index}');
Note note = watch(NoteProvider(widget.id));
final viewModel = watch(NotesRepositoryProvider);
LayoutType layout = viewModel.layout;
final selectednotes = watch(SelectedNotesProvider);
// [isSelected] will be true if current note is selected
bool isSelected = selectednotes.notes_list.contains(note);
return Hero(
tag: widget.id.toString() + widget.page.toString(),
transitionOnUserGestures: true,
child: Material(
type: MaterialType.transparency,
child: Container(
// use [margin] property only if using list layout , don't use it with grid layout
margin: layout == LayoutType.List
? const EdgeInsets.only(bottom: 9.0)
: null,
// the reason i used [foregroundDecoration] instead of simple [Decoration] property is that
// the [foregroundDecoration] property draws the decoration on top of the Container so
// it doesn't interfear with spacing and layout of the nearby [NoteCard] widgets in the grid or list
// if we used simple [Decoration] properrty then when ever we select the widget and the Container's
// border are drawn then the surrounding widgets get pushed by some pixels
foregroundDecoration: BoxDecoration(
border: isSelected
? Border.all(
width: 1.8,
color: Theme.of(context).selectedBorderColor,
)
: Border.all(
width: 1.2,
color: Theme.of(context).regularBorderColor,
),
borderRadius: BorderRadius.circular(10.0),
),
child: Ink(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10.0),
// color: kCardColor,
color: Theme.of(context).backgroundColor
),
child: InkWell(
borderRadius: BorderRadius.circular(10.0),
enableFeedback: true,
onTap: () async {
// check if current or any of the notes in the list is selected
// if current note is selected and user presses on it , then deselect it
// by removing it from the selectednotes list
if (isSelected) {
selectednotes.remove(note);
} else if (selectednotes.notes_list.isNotEmpty) {
// if current note is not selected but any of the other note is selected
// then select the current note when user presses on it by adding it to the selectednotes list
selectednotes.add(note);
} else {
bool shouldShowSnackBar = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditNotePage(
id: widget.id,
page: widget.page,
),
),
);
if (shouldShowSnackBar == true) {
if (widget.page == "search") {
emptyNoteDiscardedFlushbar
..show(searchPageScaffoldkey.currentContext);
} else {
emptyNoteDiscardedFlushbar
..show(homePageScaffoldkey.currentContext);
}
}
}
},
onLongPress: () {
// select the note on long press
if (isSelected) {
selectednotes.remove(note);
return;
}
selectednotes.add(note);
},
child: SingleChildScrollView(
physics: NeverScrollableScrollPhysics(),
child: Container(
padding: const EdgeInsets.only(
top: 15.0, right: 15.0, bottom: 0.0, left: 15.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: [
note.title.isNotEmpty
? Padding(
// padding:const EdgeInsets.fromLTRB(8.0, 2.0, 2.0, 7.0),
padding: const EdgeInsets.all(0.0),
child: Text(
"${note.title}",
overflow: TextOverflow.ellipsis,
maxLines: 1,
style: TextStyle(
// fontFamily: 'Open Sans',
// fontFamily: 'Roboto Mono',
// fontWeight: FontWeight.w500,
// wordSpacing: -5,
fontFamily: 'Roboto',
// fontFamily: 'Noto Sans',
fontSize: 18.0,
color: Theme.of(context).textTheme.bodyText1.color),
),
)
: Container(
height: 0.0,
width: 0.0,
),
_applySpacing(note.title, note.content),
note.content.isNotEmpty
? Padding(
// padding: const EdgeInsets.fromLTRB(8.0, 0.0, 2.0, 8.0),
padding: const EdgeInsets.only(bottom: 15.0),
child: Text(
"${note.content}",
overflow: TextOverflow.ellipsis,
maxLines: 10,
style: TextStyle(
fontSize: 16.0,
// fontFamily: 'Open Sans',
fontFamily: 'Roboto',
// fontFamily: 'Roboto Mono',
// wordSpacing: -5,
// fontFamily: 'Nato Sans'
color: Theme.of(context).textTheme.headline2.color,
),
),
)
: Container(),
],
),
),
),
),
),
),
),
);
},
);
}
}
Widget _applySpacing(String title, String content) {
if (title.isNotEmpty && content.isNotEmpty) {
return SizedBox(
height: 10.0,
);
} else if (title.isNotEmpty && content.isEmpty) {
return SizedBox(
height: 15.0,
);
} else {
return SizedBox(
height: 0.0,
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/fab.dart | import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:momento/utils/themes.dart';
class Fab extends StatelessWidget {
final VoidCallback onPressed;
Fab({this.onPressed});
@override
Widget build(BuildContext context) {
return FloatingActionButton(
onPressed: onPressed,
tooltip: 'Add Note',
child: Icon(
Icons.add,
color: Theme.of(context).fabTextColor,
),
backgroundColor: Theme.of(context).fabBackgroundColor,
elevation: 8.0,
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/custom_cupertino_switch.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
class CustomCupertinoSwitch extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer(
builder: (context, watch, child) {
ThemeMode themeMode = watch(ThemeManagerProvider).currentThemeMode;
return CupertinoSwitch(
value: themeMode == ThemeMode.dark,
onChanged: (isLight) {
context
.read(ThemeManagerProvider)
.changeTheme(isLight ? ThemeMode.dark : ThemeMode.light);
},
activeColor: Theme.of(context).accentColor,
);
},
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/widgets/search_bar.dart | import 'package:flutter/material.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class SearchBar extends StatefulWidget {
@override
_SearchBarState createState() => _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
TextEditingController t1;
@override
void initState() {
super.initState();
t1 = TextEditingController();
// update the state of [SearchTextProvider] every time text of
// [TextField] changes
t1.addListener(() {
context.read(SearchTextProvider).state = t1.text.toLowerCase();
});
}
@override
void dispose() {
t1.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return SliverAppBar(
leading: IconButton(
splashRadius: 25.0,
icon: Icon(Icons.arrow_back),
onPressed: () {
Navigator.pop(context);
}),
actions: [
Consumer(
builder: (context, watch, child) {
String txt = watch(SearchTextProvider).state;
if (txt.isNotEmpty) {
return IconButton(
splashRadius: 25.0,
icon: Icon(
Icons.clear,
color: Theme.of(context).appBarTheme.actionsIconTheme.color,
),
onPressed: () {
t1.clear();
},
);
} else {
return Container();
}
},
)
],
// backgroundColor: kAppBarColor,
backgroundColor: Theme.of(context).appBarTheme.backgroundColor,
forceElevated: true,
title: Hero(
tag: 'searchbar',
transitionOnUserGestures: true,
child: Material(
type: MaterialType.transparency,
child: TextField(
autofocus: true,
controller: t1,
toolbarOptions: ToolbarOptions(
copy: true, cut: true, paste: true, selectAll: true),
style: TextStyle(
color: Theme.of(context).textTheme.bodyText1.color,
fontSize: 18.0,
),
decoration: InputDecoration(
focusedBorder: InputBorder.none,
hintText: 'Search your notes',
hintStyle: TextStyle(
// color: Colors.grey.shade400,
color: Theme.of(context).appBarTheme.titleTextStyle.color,
fontFamily: 'Open Sans',
),
border: InputBorder.none),
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/pages/home_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/presentation/pages/add_note_page.dart';
import 'package:momento/presentation/widgets/custom_drawer.dart';
import 'package:momento/utils/helper_functions.dart';
import 'package:momento/data/repositories/notes_repository.dart';
import 'package:momento/presentation/widgets/contextual_appbar.dart';
import 'package:momento/presentation/widgets/fab.dart';
import 'package:momento/presentation/widgets/notes_grid.dart';
import 'package:momento/presentation/widgets/notes_list.dart';
import 'package:momento/presentation/widgets/main_app_bar.dart';
import 'package:momento/presentation/widgets/pinnned_label.dart';
import 'package:momento/presentation/widgets/unPinnned_label.dart';
import 'package:page_transition/page_transition.dart';
import 'package:sliver_tools/sliver_tools.dart';
final GlobalKey<ScaffoldState> homePageScaffoldkey = GlobalKey<ScaffoldState>();
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: CustomDrawer(),
key: homePageScaffoldkey,
// backgroundColor: kBackgroundColor,
backgroundColor: Theme.of(context).backgroundColor,
body: SafeArea(
child: CustomScrollView(
// physics: BouncingScrollPhysics(),
slivers: [
// there is a bug in flutter which causes app to crash if the first widget
// in [CustomScrollView] is not a sliver i.e. [Consumer] thats why here first
// widget is [SliverToBoxAdapter].
SliverToBoxAdapter(),
Consumer(
builder: (context, watch, child) {
final selectednotes = watch(SelectedNotesProvider);
// [isSelected] will be true if any notes are selected
bool isSelected = selectednotes.notes_list.isNotEmpty;
// return SliverAnimatedSwitcher(
// child: isSelected
// ? MultiSliver(children: [
// ContextualAppBar(),
// SizedBox(
// height: 15.0,
// ),
// ])
// : MainAppBar(),
// duration: Duration(milliseconds: 200));
return SliverStack(
children: [
SliverOffstage(
offstage: isSelected,
sliver: MainAppBar(onClick: () {
homePageScaffoldkey.currentState.openDrawer();
})),
if (isSelected)
MultiSliver(children: [
ContextualAppBar(),
SizedBox(
height: 15.0,
),
])
],
);
},
),
PinnedLable(),
// pinned notes
Consumer(
builder: (context, watch, child) {
LayoutType layout = watch(NotesRepositoryProvider).layout;
return layout == LayoutType.Grid
? NotesGrid(
page: 'home',
type: 'pinned',
)
: NotesList(
page: 'home',
type: 'pinned',
);
},
),
UnPinnedLable(),
// unpinned notes
Consumer(
builder: (context, watch, child) {
LayoutType layout = watch(NotesRepositoryProvider).layout;
return layout == LayoutType.Grid
? NotesGrid(
page: 'home',
type: 'unpinned',
)
: NotesList(
page: 'home',
type: 'unpinned',
);
},
),
SliverToBoxAdapter(
child: SizedBox(
height: 70.0,
),
),
],
),
),
floatingActionButton: Fab(
onPressed: () async {
context.read(SelectedNotesProvider).clear();
bool shouldShowSnackBar = await Navigator.push(
context,
PageTransition(
// type: PageTransitionType.scale,
// child: AddNotePage(),
// duration: Duration(milliseconds: 200),
// alignment: Alignment.bottomRight,
// curve: Curves.easeInOutCubic),
// type: PageTransitionType.rightToLeft,
// child: AddNotePage(),
// duration: Duration(milliseconds: 200),curve: Curves.easeInOutCubic
type: PageTransitionType.rightToLeft,
child: AddNotePage(),
duration: Duration(milliseconds: 200),
reverseDuration: Duration(milliseconds: 200),
// alignment: Alignment.bottomRight,
curve: Curves.easeInOutCubic),
);
if (shouldShowSnackBar == true) {
emptyNoteDiscardedFlushbar..show(context);
}
},
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/pages/add_note_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/presentation/widgets/note_pin.dart';
class AddNotePage extends StatefulWidget {
@override
_AddNotePageState createState() => _AddNotePageState();
}
class _AddNotePageState extends State<AddNotePage> {
TextEditingController t1;
TextEditingController t2;
int isPinned;
@override
void initState() {
super.initState();
isPinned = 0;
t1 = TextEditingController();
t2 = TextEditingController();
}
@override
void dispose() {
t1.dispose();
t2.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
title: const Text('Add note'),
centerTitle: true,
// backgroundColor: kBackgroundColor,
backgroundColor: Theme.of(context).backgroundColor,
actions: [
NotePin(
isPinned: isPinned,
onChanged: (val) {
isPinned = val;
},
),
],
leading: IconButton(
splashRadius: 25.0,
icon: const Icon(Icons.arrow_back),
onPressed: () async {
bool isDiscarded = false;
isDiscarded =
await _addOrDiscard(context, t1.text, t2.text, isPinned);
Navigator.pop(context, isDiscarded);
},
),
),
body: WillPopScope(
onWillPop: () async {
bool isDiscarded = false;
isDiscarded =
await _addOrDiscard(context, t1.text, t2.text, isPinned);
Navigator.pop(context, isDiscarded);
return false;
},
child: SingleChildScrollView(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Column(
children: [
const SizedBox(
height: 26.0,
),
TextField(
autofocus: true,
style: TextStyle(
fontSize: 25,
color: Theme.of(context).textTheme.bodyText1.color),
controller: t1,
maxLines: null,
decoration: InputDecoration(
focusedBorder: InputBorder.none,
hintText: 'Title',
// hintStyle: TextStyle(color: Colors.grey.shade400),
hintStyle: TextStyle(
color: Theme.of(context).textTheme.headline3.color),
border: InputBorder.none),
),
TextField(
maxLines: null,
controller: t2,
style: TextStyle(
color: Theme.of(context).textTheme.bodyText1.color),
decoration: InputDecoration(
focusedBorder: InputBorder.none,
hintText: 'Type Something',
// hintStyle: TextStyle(color: Colors.grey.shade400),
hintStyle: TextStyle(
color: Theme.of(context).textTheme.headline3.color),
border: InputBorder.none),
)
],
),
),
),
),
);
}
}
Future<bool> _addOrDiscard(
BuildContext context,
String title,
String content,
int isPinned,
) async {
bool isDiscarded = false;
// if only title or content is note empty then update the note
if (title.trim() != "" || content.trim() != "") {
await context.read(NotesRepositoryProvider).addNote(Note.fromMap({
'title': '$title',
'content': '$content',
'isPinned': isPinned,
'date_created': '${DateTime.now()}',
'last_updated': '${DateTime.now()}'
}));
}
// if both title and content are note empty then discard the note
else if (title.trim() == "" && content.trim() == "") {
isDiscarded = true;
}
return isDiscarded;
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/pages/search_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/data/repositories/notes_repository.dart';
import 'package:momento/presentation/widgets/contextual_appbar.dart';
import 'package:momento/presentation/widgets/notes_grid.dart';
import 'package:momento/presentation/widgets/notes_list.dart';
import 'package:momento/presentation/widgets/search_bar.dart';
import 'package:sliver_tools/sliver_tools.dart';
final GlobalKey<ScaffoldState> searchPageScaffoldkey =
GlobalKey<ScaffoldState>();
class SearchPage extends StatefulWidget {
@override
_SearchPageState createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
key: searchPageScaffoldkey,
// backgroundColor: kBackgroundColor,
backgroundColor: Theme.of(context).backgroundColor,
// appBar: AppBar(
// title: const Text('Notes'),
// centerTitle: true,
// ),
body: WillPopScope(
onWillPop: () async {
if (context.read(SelectedNotesProvider).notes_list.isEmpty) {
return true;
} else {
context.read(SelectedNotesProvider).clear();
return false;
}
},
child: SafeArea(
top: true,
child: CustomScrollView(
slivers: [
// there is a bug in flutter which causes app to crash if the first widget
// in [CustomScrollView] is not a sliver i.e. [Consumer] thats why here first
// widget is [SliverToBoxAdapter].
SliverToBoxAdapter(),
Consumer(
builder: (context, watch, child) {
final selectednotes = watch(SelectedNotesProvider);
// [isSelected] will be true if any notes are selected
bool isSelected = selectednotes.notes_list.isNotEmpty;
// return SliverAnimatedSwitcher(
// child: isSelected
// ? ContextualAppBar()
// : SearchBar(
// onTextChanged: (val) {
// setState(() {
// txt = val;
// });
// },
// ),
// duration: Duration(milliseconds: 200),
// );
return SliverStack(
children: [
SliverOffstage(
offstage: isSelected,
sliver: SearchBar(),
),
if (isSelected) ContextualAppBar()
],
);
},
),
SliverToBoxAdapter(
child: SizedBox(
height: 15,
),
),
Consumer(
builder: (context, watch, child) {
String txt = watch(SearchTextProvider).state;
if (txt.isNotEmpty) {
return context.read(NotesRepositoryProvider).layout ==
LayoutType.Grid
? NotesGrid(
page: 'search',
type: 'all',
)
: NotesList(
page: 'search',
type: 'all',
);
} else {
return SliverToBoxAdapter(
child: Container(),
);
}
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/presentation/pages/edit_note_page.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:momento/business_logic/providers/providers.dart';
import 'package:momento/data/models/note.dart';
import 'package:momento/presentation/widgets/last_edited_label.dart';
import 'package:momento/presentation/widgets/note_pin.dart';
import 'package:share_plus/share_plus.dart';
class EditNotePage extends StatefulWidget {
final String page;
final int id;
EditNotePage({this.page, this.id});
@override
_EditNotePageState createState() => _EditNotePageState();
}
class _EditNotePageState extends State<EditNotePage> {
TextEditingController t1;
TextEditingController t2;
Note currentNote;
int isPinned;
bool isEdited;
@override
void initState() {
super.initState();
currentNote = context.read(NoteProvider(widget.id));
isPinned = currentNote.isPinned;
t1 = TextEditingController(text: currentNote.title);
t2 = TextEditingController(text: currentNote.content);
isEdited = false;
t1.addListener(() {
if (t1.text.toLowerCase() != currentNote.title.toLowerCase()) {
isEdited = true;
a.value = true;
}
});
t2.addListener(() {
if (t2.text.toLowerCase() != currentNote.content.toLowerCase()) {
isEdited = true;
a.value = true;
}
});
}
@override
void dispose() {
t1.dispose();
t2.dispose();
a.value = false;
super.dispose();
}
@override
Widget build(BuildContext context) {
return Hero(
tag: widget.id.toString() + widget.page.toString(),
transitionOnUserGestures: true,
// flightShuttleBuilder: (
// BuildContext flightContext,
// Animation<double> animation,
// HeroFlightDirection flightDirection,
// BuildContext fromHeroContext,
// BuildContext toHeroContext,
// ) {
// // this fixes issue which causes yellow underline to apear when trasitioning back
// return DefaultTextStyle(
// style: DefaultTextStyle.of(fromHeroContext).style,
// child: toHeroContext.widget,
// );
// },
child: Scaffold(
// backgroundColor: kBackgroundColor,
backgroundColor: Theme.of(context).backgroundColor,
appBar: AppBar(
// backgroundColor: kBackgroundColor,
backgroundColor: Theme.of(context).backgroundColor,
leading: IconButton(
splashRadius: 25.0,
icon: const Icon(Icons.arrow_back),
onPressed: () async {
bool isDiscarded = false;
if (isEdited) {
isDiscarded = await _updateOrDiscard(
context, t1.text, t2.text, currentNote, isPinned);
}
Navigator.pop(context, isDiscarded);
}),
actions: [
// Consumer(
// builder: (context, watch, child) {
// Note note = watch(NoteProvider(currentNote.id));
// if (note == null) return Container();
// if (note.isPinned == 1) {
// return IconButton(
// icon: Icon(Icons.push_pin),
// onPressed: () {
// context.read(NoteListViewModelProvider).unsetPin([note]);
// },
// );
// } else {
// return IconButton(
// icon: Icon(Icons.push_pin_outlined),
// onPressed: () {
// context.read(NoteListViewModelProvider).setPin([note]);
// },
// );
// }
// },
// ),
NotePin(
isPinned: isPinned,
onChanged: (val) {
isPinned = val;
isEdited = true;
a.value = true;
},
),
IconButton(
splashRadius: 25.0,
icon: Icon(Icons.share),
onPressed: () {
Share.share(t1.text + '\n' + t2.text, subject: t1.text);
})
],
),
body: WillPopScope(
onWillPop: () async {
bool isDiscarded = false;
if (isEdited) {
isDiscarded = await _updateOrDiscard(
context, t1.text, t2.text, currentNote, isPinned);
}
Navigator.pop(context, isDiscarded);
return false;
},
child: SingleChildScrollView(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 15.0),
child: Column(
children: [
const SizedBox(
height: 26.0,
),
Column(
children: [
TextField(
style: TextStyle(
fontSize: 25,
color: Theme.of(context).textTheme.bodyText1.color,
),
controller: t1,
maxLines: null,
decoration: InputDecoration(
hintStyle: TextStyle(color: Colors.grey.shade400),
focusedBorder: InputBorder.none,
hintText: 'Title',
border: InputBorder.none),
),
TextField(
style: TextStyle(
color: Theme.of(context).textTheme.bodyText1.color),
maxLines: null,
controller: t2,
decoration: InputDecoration(
focusedBorder: InputBorder.none,
hintText: 'Type Something',
hintStyle: TextStyle(color: Colors.grey.shade400),
border: InputBorder.none),
)
],
)
],
),
),
),
),
bottomSheet: Container(
height: 50.0,
padding: EdgeInsets.only(
top: 5.0,
),
// color: kBackgroundColor,
color: Theme.of(context).backgroundColor,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
LastEditedLabel(
last_updated: currentNote.last_updated,
)
],
),
),
),
);
}
}
Future<bool> _updateOrDiscard(
BuildContext context,
String title,
String content,
Note currentNote,
int isPinned,
) async {
bool isDiscarded = false;
// if only title or content is note empty then update the note
if (title.trim() != "" || content.trim() != "") {
Note newNote = Note.fromMap(
{
'title': '$title',
'content': '$content',
'isPinned': isPinned,
'last_updated': '${DateTime.now()}'
},
);
newNote.id = currentNote.id;
// if isPinned is changed update the note and also update HomePage
bool _shouldUpdateHomePage = false;
if (currentNote.isPinned != isPinned) {
_shouldUpdateHomePage = true;
}
// update note
await context.read(NoteProvider(currentNote.id)).update(newNote);
// setPin() and unsetPin methods will update the homepage if it should be updated
if (_shouldUpdateHomePage && isPinned == 1) {
context.read(NotesRepositoryProvider).setPin([newNote]);
} else if (_shouldUpdateHomePage && isPinned == 0) {
context.read(NotesRepositoryProvider).unsetPin([newNote]);
}
}
// if both title and content are note empty then discard the note
else if (title.trim() == "" && content.trim() == "") {
await context
.read(NotesRepositoryProvider)
.deleteMultipleNotes([currentNote.id]);
isDiscarded = true;
}
return isDiscarded;
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/utils/themes.dart | import 'package:flutter/material.dart';
import 'package:momento/utils/app_colors.dart';
final ThemeData AppThemeDark = ThemeData(
brightness: Brightness.dark,
accentColor: kAccentColor,
backgroundColor: kBackgroundColorDark,
appBarTheme: AppBarTheme(
iconTheme: IconThemeData(color: Colors.white),
actionsIconTheme: IconThemeData(color: Colors.grey.shade400),
backgroundColor: kAppBarColorDark,
titleTextStyle: TextStyle(color: Colors.grey.shade400),
),
textTheme: TextTheme(
bodyText1: TextStyle(color: Colors.white),
bodyText2: TextStyle(color: Color(0xEEFFFFFF)),
headline2: TextStyle(color: Colors.white),
headline3: TextStyle(color: Colors.grey.shade400),
overline: TextStyle(color: Colors.grey.shade400),
),
iconTheme: IconThemeData(
color: Colors.white,
),
);
final ThemeData AppThemeLight = ThemeData(
brightness: Brightness.light,
accentColor: kAccentColor,
backgroundColor: kBackgroundColorLight,
// this is used to change the color of [TextSelectionToolBar]
// because it uses [TextButton] widgets under the hood.
textButtonTheme: TextButtonThemeData(
style: ButtonStyle(
backgroundColor: MaterialStateProperty.all(Colors.white),
)),
appBarTheme: AppBarTheme(
iconTheme: IconThemeData(color: Colors.black),
actionsIconTheme: IconThemeData(color: Colors.black54),
backgroundColor: kAppBarColorLight,
titleTextStyle: TextStyle(color: Colors.grey.shade700),
),
textTheme: TextTheme(
bodyText1: TextStyle(color: Colors.black),
bodyText2: TextStyle(color: Colors.black),
headline2: TextStyle(color: Colors.black54),
headline3: TextStyle(color: Colors.black54),
overline: TextStyle(color: Colors.grey.shade700),
),
iconTheme: IconThemeData(
color: Colors.black,
),
);
extension FabTheme on ThemeData {
Color get fabBackgroundColor {
if (this.brightness == Brightness.dark) {
return kFabColorDark;
} else {
return kFabColorLight;
}
}
Color get fabTextColor {
if (this.brightness == Brightness.dark) {
return Colors.white;
} else {
return Colors.white;
}
}
}
extension NoteCardTheme on ThemeData {
Color get regularBorderColor {
if (this.brightness == Brightness.dark) {
return Color(0xFF3f475a);
} else {
return Colors.grey.shade400.withOpacity(0.8);
}
}
Color get selectedBorderColor {
if (this.brightness == Brightness.dark) {
return Colors.white;
} else {
// return kFabColorLight;
return Colors.black;
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/utils/app_colors.dart | import 'package:flutter/material.dart';
// const Color kCardColor = Color(0xFF212936);
// const Color kCardColor = Color(0xFF242833);
// const Color kCardColor =Color(0xFF212736);
const Color kCardColorDark = Color(0xFF282c36);
// const Color kBackgroundColor = Color(0xFF293440);
// const Color kBackgroundColor = Color(0xFF252B34);
// const Color kBackgroundColor = Color(0xFF232834);
// const Color kBackgroundColor = Color(0xFF242833);
// const Color kBackgroundColor = Color(0xFF212736);
// const Color kBackgroundColor = Color(0xFF282c36);
// const Color kBackgroundColor = Color(0xFF212936);
// const Color kBackgroundColor = Color(0xFF242c38);
// const Color kBackgroundColor = Color(0xFF2a313c);
const Color kBackgroundColorDark = Color(0xFF282c36);
const Color kBackgroundColorLight = Colors.white;
// const Color kAppBarColor = Color(0xFF2a313c);
// const Color kAppBarColor = Color(0xFF303845);
// const Color kAppBarColor = Color(0xFF303645);
// const Color kAppBarColor = Color(0xFF2e3444);
const Color kAppBarColorDark = Color(0xFF303440);
const Color kAppBarColorLight = Colors.white;
const Color kSnackBarColorDark = Color(0xFF363c49);
const Color kSnackBarColorLight = Color(0xFF363c49);
// const Color kFabColor = Color(0xFF8aacc8);
const Color kFabColorDark = Color(0xFF363c49);
const Color kFabColorLight = Color(0xFFe57373);
const Color kAccentColor = Color(0xFFe57373); | 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/lib/utils/helper_functions.dart | import 'package:another_flushbar/flushbar.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:momento/utils/app_colors.dart';
Flushbar emptyNoteDiscardedFlushbar = Flushbar(
messageText: Text('Empty note discarded'),
flushbarStyle: FlushbarStyle.FLOATING,
dismissDirection: FlushbarDismissDirection.HORIZONTAL,
margin: EdgeInsets.only(bottom: 40.0, left: 15.0, right: 15.0),
backgroundColor: kSnackBarColorDark,
borderRadius: BorderRadius.circular(5.0),
leftBarIndicatorColor: Colors.redAccent,
duration: Duration(seconds: 2),
// animationDuration: Duration(seconds: 10),
forwardAnimationCurve: Curves.easeInOut,
reverseAnimationCurve: Curves.easeInOut,
);
String getLastEdited(String lastEdited) {
DateTime ledited = DateTime.parse(lastEdited);
String result = "";
DateTime now = DateTime.now();
if (ledited.year < now.year) {
result = "Edited ${DateFormat().add_d().add_MMM().add_y().format(ledited)}";
} else if (ledited.month < now.month) {
result = "Edited ${DateFormat().add_d().add_MMM().format(ledited)}";
} else if ((now.day - ledited.day) == 1) {
result = "Edited Yesterday, ${DateFormat().add_jm().format(ledited)}";
} else if (ledited.day < now.day) {
result = "Edited ${DateFormat().add_d().add_MMM().format(ledited)}";
} else if (ledited.hour < now.hour || ledited.second < now.second) {
result = "Edited ${DateFormat().add_jm().format(ledited)}";
}
else{
result = "Edited ${DateFormat().add_jm().format(ledited)}";
}
return result;
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/Momento/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:momento/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-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/route_generator.dart | import 'package:ecommerce_app_isaatech/models/product.dart';
import 'package:ecommerce_app_isaatech/screens/home/main_home.dart';
import 'package:ecommerce_app_isaatech/screens/login.dart';
import 'package:ecommerce_app_isaatech/screens/product_page.dart';
import 'package:ecommerce_app_isaatech/screens/signup.dart';
import 'package:ecommerce_app_isaatech/screens/splash_screen.dart';
import 'package:flutter/material.dart';
class RouteGenerator {
static Route<dynamic> generateRoute(RouteSettings settings) {
final args;
switch (settings.name) {
case SplashScreen.id:
return MaterialPageRoute(builder: (context) => const SplashScreen());
case LoginScreen.id:
return MaterialPageRoute(builder: (context) => const LoginScreen());
case SignUpScreen.id:
return MaterialPageRoute(builder: (context) => const SignUpScreen());
case ProductPage.id:
args = settings.arguments as Product;
return MaterialPageRoute(
builder: (context) => ProductPage(
product: args,
));
case UserDashboard.id:
return MaterialPageRoute(builder: (context) => UserDashboard());
default:
return MaterialPageRoute(builder: (context) => const SplashScreen());
}
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/main.dart | import 'package:ecommerce_app_isaatech/route_generator.dart';
import 'package:ecommerce_app_isaatech/screens/splash_screen.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const EcommerceAppIsaatech());
}
class EcommerceAppIsaatech extends StatelessWidget {
const EcommerceAppIsaatech({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Isaatech Ecommerce',
theme: ThemeData(
scaffoldBackgroundColor: Colors.white,
brightness: Brightness.light,
fontFamily: 'Gilroy',
primarySwatch: Colors.purple,
appBarTheme: AppBarTheme(
elevation: 0,
centerTitle: false,
titleTextStyle: Theme.of(context)
.textTheme
.headline5!
.copyWith(fontWeight: FontWeight.bold),
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: Theme.of(context).colorScheme.onSurface,
),
),
colorScheme: const ColorScheme(
brightness: Brightness.light,
primary: Color(0xFF0F1327),
primaryVariant: Color(0xFF0F0317),
secondary: Color(0xFFEFC3FE),
secondaryVariant: Color(0xFF9F83BE),
onPrimary: Colors.white,
surface: Colors.white,
onSecondary: Colors.white,
onSurface: Colors.black87,
background: Colors.white,
error: Colors.red,
onBackground: Colors.black87,
onError: Colors.white,
),
),
initialRoute: SplashScreen.id,
onGenerateRoute: RouteGenerator.generateRoute,
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/constants/images.dart | class Images {
Images._();
static const String logo = 'assets/icons/logo.png';
// anims
static const String splashAnim = 'assets/anims/splash_anim.json';
static const String proceed = 'assets/anims/proceed.json';
// images
static const String loginBg = 'assets/images/login_bg.png';
static const String sh1 = 'assets/images/sh1.png';
static const String sh2 = 'assets/images/sh2.png';
static const String sh3 = 'assets/images/sh3.png';
static const String sh4 = 'assets/images/sh4.png';
static const String sh5 = 'assets/images/sh5.png';
static const String sh6 = 'assets/images/sh6.png';
static const String sh7 = 'assets/images/sh7.png';
// icons
static const String cartIcon = 'assets/icons/cart.png';
static const String shoppingBag = 'assets/icons/shopping_bag.png';
static const String sneakers = 'assets/icons/sneakers.svg';
static const String avatar = 'assets/icons/avatar.png';
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/constants/dummy_data.dart | import 'package:flutter/material.dart';
import '/constants/images.dart';
import '../models/product.dart';
List<Product> products = [
Product(
name: 'Air Max Sequent 4 Shield',
brand: 'nike',
description:
'The Air Jordan 1 Mid shoe is inspired by the first AJ1, offering fans of Jordan retros a chance to follow in the footsteps of the greatness.',
price: 115,
rating: 5,
productColors: [
Colors.grey.shade600,
Colors.purple.shade400,
Colors.pink.shade300,
Colors.blue.shade400
],
productImages: [
Images.sh1,
Images.sh2,
Images.sh3,
Images.sh4,
Images.sh6,
]),
Product(
name: 'Nike High Run Pro',
brand: 'nike',
description:
'The Air Jordan 1 Mid shoe is inspired by the first AJ1, offering fans of Jordan retros a chance to follow in the footsteps of the greatness.',
price: 235,
rating: 5,
productColors: [
Colors.blue.shade200,
Colors.teal.shade400,
Colors.purple.shade400,
Colors.blue.shade400
],
productImages: [
Images.sh2,
Images.sh1,
Images.sh3,
Images.sh4,
Images.sh6,
]),
Product(
name: 'Random Color Shoe',
brand: 'adidas',
description:
'The Air Jordan 1 Mid shoe is inspired by the first AJ1, offering fans of Jordan retros a chance to follow in the footsteps of the greatness.',
price: 80,
rating: 4,
productColors: [
Colors.orange.shade300,
Colors.teal.shade400,
Colors.purple.shade400,
Colors.blue.shade400
],
productImages: [
Images.sh3,
Images.sh2,
Images.sh1,
Images.sh4,
Images.sh6,
]),
Product(
name: 'Air Max 270 Ultramarine',
brand: 'nike',
description:
'The Air Jordan 1 Mid shoe is inspired by the first AJ1, offering fans of Jordan retros a chance to follow in the footsteps of the greatness.',
price: 80,
rating: 4,
productColors: [
Colors.grey.shade600,
Colors.teal.shade400,
Colors.purple.shade400,
Colors.blue.shade400
],
productImages: [
Images.sh7,
Images.sh6,
Images.sh1,
Images.sh4,
Images.sh3,
]),
Product(
name: 'Runner Pro High Sole',
brand: 'adidas',
description:
'The Air Jordan 1 Mid shoe is inspired by the first AJ1, offering fans of Jordan retros a chance to follow in the footsteps of the greatness.',
price: 80,
rating: 4,
productColors: [
Colors.amber.shade600,
Colors.teal.shade400,
Colors.purple.shade400,
Colors.blue.shade400
],
productImages: [
Images.sh6,
Images.sh4,
Images.sh1,
Images.sh7,
Images.sh3,
]),
];
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/constants/colors.dart | import 'package:flutter/material.dart';
class CustomColors {
static const Color starColor = Color(0xFFFFCC66);
static const Color customGrey = Color(0xFF989ACF);
static const Color darkBlue = Color(0xFF0F1327);
static const Color halfWhite = Color(0xFFFAFAFA);
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/rating_widget.dart | import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
import '../constants/colors.dart';
class RatingWidget extends StatelessWidget {
const RatingWidget({Key? key, required this.rating}) : super(key: key);
final double rating;
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(Icons.star, size: 19, color: CustomColors.starColor),
4.widthBox,
'($rating)'.text.sm.softWrap(true).make(),
],
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/main_page_product_card.dart | import 'package:ecommerce_app_isaatech/components/buttons.dart';
import 'package:ecommerce_app_isaatech/components/rating_widget.dart';
import 'package:ecommerce_app_isaatech/models/product.dart';
import 'package:ecommerce_app_isaatech/screens/product_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:velocity_x/velocity_x.dart';
class HomeScreenProductCard extends StatefulWidget {
const HomeScreenProductCard(
{Key? key, required this.product, required this.isCurrentInView})
: super(key: key);
final Product product;
final bool isCurrentInView;
@override
_HomeScreenProductCardState createState() => _HomeScreenProductCardState();
}
class _HomeScreenProductCardState extends State<HomeScreenProductCard>
with SingleTickerProviderStateMixin {
late AnimationController _imageAnimationController;
@override
void initState() {
_imageAnimationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 600),
);
super.initState();
_imageAnimationController.addListener(() {
setState(() {});
});
_imageAnimationController.forward();
}
@override
void dispose() {
_imageAnimationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.bottomCenter,
children: [
Container(
padding: const EdgeInsets.only(left: 12, right: 12, bottom: 12),
margin:
const EdgeInsets.only(top: 110, left: 8, right: 8, bottom: 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(12),
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.12),
offset: const Offset(0, 12),
spreadRadius: 1,
blurRadius: 24),
]),
child: Container(
width: double.infinity,
)),
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
const Spacer(),
Flexible(
flex: 5,
child: GestureDetector(
onTap: () {
Navigator.of(context).pushNamed(
ProductPage.id,
arguments: widget.product,
);
},
child: Container(
decoration: BoxDecoration(
color: widget.product.productColors[0],
boxShadow: [
widget.isCurrentInView
? BoxShadow(
color: Colors.grey.shade200,
offset: const Offset(0, 8),
spreadRadius: 1,
blurRadius: 8)
: const BoxShadow(
color: Colors.transparent,
offset: Offset(0, 8),
),
],
borderRadius: BorderRadius.circular(24)),
// margin: const EdgeInsets.only(
// left: 25, right: 25, top: 24, bottom: 32),
child: Stack(
children: [
AspectRatio(
aspectRatio: 0.9,
child: Transform.rotate(
angle: widget.isCurrentInView
? (_imageAnimationController.value * -0.5)
: 0,
child: Image.asset(
widget.product.productImages[0],
).p(16)),
),
Positioned(
right: 12,
top: 12,
child: SizedBox(
height: _imageAnimationController.value * 27,
width: _imageAnimationController.value * 27,
child: FavouriteButton(
iconSize: _imageAnimationController.value * 17,
onPressed: () {},
)),
)
],
),
),
).p(20),
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: widget.product.name.text
.size(21)
.semiBold
.maxLines(2)
.softWrap(true)
.make(),
),
12.widthBox,
RatingWidget(rating: widget.product.rating),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
widget.product.brand
.toUpperCase()
.text
.semiBold
.color(Colors.grey)
.softWrap(true)
.make()
.py(4),
'\$${widget.product.price}'
.text
.size(15)
.semiBold
.softWrap(true)
.make(),
],
),
const Spacer(),
SizedBox(
height: _imageAnimationController.value * 30,
width: _imageAnimationController.value * 30,
child: RoundedAddButton(
onPressed: () {},
),
)
],
),
],
).px(24).pOnly(bottom: 28)
],
)
],
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/social_icon_buttons_row.dart | import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:velocity_x/velocity_x.dart';
class SocialIconButtonsRow extends StatelessWidget {
const SocialIconButtonsRow({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
const SizedBox(),
SocialButtonWithShadow(
icon: FontAwesomeIcons.facebookF,
color: const Color(0xFF4267B2),
onPressed: () {},
),
SocialButtonWithShadow(
icon: FontAwesomeIcons.twitter,
color: const Color(0xFF1DA1F2),
onPressed: () {},
),
SocialButtonWithShadow(
icon: FontAwesomeIcons.googlePlusG,
color: const Color(0xFFDB4437),
onPressed: () {},
),
const SizedBox(),
],
);
}
}
class SocialButtonWithShadow extends StatelessWidget {
const SocialButtonWithShadow(
{Key? key, required this.icon, required this.color, this.onPressed})
: super(key: key);
final Color color;
final IconData icon;
final Function()? onPressed;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 45,
height: 45,
child: TextButton(
onPressed: onPressed,
style: ButtonStyle(
padding: MaterialStateProperty.all(const EdgeInsets.all(0)),
elevation: MaterialStateProperty.resolveWith((states) {
if (states.contains(MaterialState.pressed)) {
return 0;
} else {
return 8;
}
}),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),
backgroundColor: MaterialStateProperty.all(color),
shadowColor: MaterialStateProperty.all(color),
),
child: Icon(
icon,
color: Colors.white,
).p(8),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/textfields.dart | import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
class PrimaryTextField extends StatefulWidget {
const PrimaryTextField({
this.hintText = '',
this.prefixIcon,
this.isObscure = false,
Key? key,
}) : super(key: key);
final IconData? prefixIcon;
final String hintText;
final bool isObscure;
@override
State<PrimaryTextField> createState() => _PrimaryTextFieldState();
}
class _PrimaryTextFieldState extends State<PrimaryTextField> {
@override
Widget build(BuildContext context) {
return Card(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
elevation: 16,
shadowColor: Colors.black54,
child: TextFormField(
validator: (v) {},
obscureText: widget.isObscure,
controller: null,
style: Theme.of(context)
.textTheme
.bodyText1!
.copyWith(fontWeight: FontWeight.bold, fontSize: 16),
decoration: InputDecoration(
contentPadding: const EdgeInsets.only(top: 14),
prefixIcon: widget.prefixIcon != null
? Icon(
widget.prefixIcon,
size: 20,
color: Theme.of(context).colorScheme.onBackground,
)
: const SizedBox.shrink(),
border: InputBorder.none,
hintText: widget.hintText,
hintStyle:
const TextStyle(fontSize: 17, fontWeight: FontWeight.normal)),
).px(12).py(2.5),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/bottom_bar_custom.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
class CustomNavigationBar extends StatefulWidget {
const CustomNavigationBar(
{Key? key, required this.updatePage, required this.currentHomeScreen})
: super(key: key);
final Function updatePage;
final int currentHomeScreen;
@override
_CustomNavigationBarState createState() => _CustomNavigationBarState();
}
class _CustomNavigationBarState extends State<CustomNavigationBar> {
@override
Widget build(BuildContext context) {
return SizedBox(
height: 85,
child: Stack(
children: [
Container(
margin: const EdgeInsets.only(top: 16),
padding: const EdgeInsets.only(bottom: 24, top: 6),
color: Colors.white,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
BottomBarButton(widget.currentHomeScreen, 0, Icons.home_filled,
widget.updatePage),
BottomBarButton(widget.currentHomeScreen, 1, Icons.favorite,
widget.updatePage),
const SizedBox(
width: 50,
),
BottomBarButton(widget.currentHomeScreen, 3,
CupertinoIcons.bell_fill, widget.updatePage),
BottomBarButton(widget.currentHomeScreen, 4,
CupertinoIcons.person_fill, widget.updatePage),
],
),
),
Align(
alignment: Alignment.center,
child: BottomBarMiddleButton(
widget.currentHomeScreen, widget.updatePage)
.pOnly(bottom: 32),
),
],
),
);
}
}
class BottomBarMiddleButton extends StatelessWidget {
const BottomBarMiddleButton(this.currentHomeScreen, this.updatePage,
{Key? key})
: super(key: key);
final int currentHomeScreen;
final Function updatePage;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 55,
height: 55,
child: TextButton(
onPressed: () => updatePage(2),
style: ButtonStyle(
padding: MaterialStateProperty.all(const EdgeInsets.all(0)),
elevation: MaterialStateProperty.all(8),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50))),
backgroundColor: MaterialStateProperty.all(Colors.transparent),
shadowColor: MaterialStateProperty.all(
Theme.of(context).colorScheme.onSurface),
),
child: Container(
width: 55,
height: 55,
margin: const EdgeInsets.all(0),
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: RadialGradient(
colors: [Colors.black.withOpacity(0.4), Colors.black87],
center: Alignment.topLeft,
radius: 1)),
child: Icon(
CupertinoIcons.cart_fill,
color: (currentHomeScreen == 2)
? Colors.purple.shade200
: Colors.white,
).p(8),
),
),
);
}
}
class BottomBarButton extends StatelessWidget {
const BottomBarButton(
this.currentPage, this.index, this.icon, this.updatePage,
{Key? key})
: super(key: key);
final IconData icon;
final int currentPage;
final int index;
final Function updatePage;
@override
Widget build(BuildContext context) {
return SizedBox(
width: 50,
height: 40,
child: MaterialButton(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
padding: const EdgeInsets.all(0),
onPressed: () => updatePage(index),
child: AnimatedContainer(
duration: const Duration(milliseconds: 500),
child: Icon(
icon,
color: index == currentPage
? Theme.of(context).colorScheme.onSurface
: Colors.grey,
),
)),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/blur_container.dart | import 'package:flutter/material.dart';
import 'dart:ui';
class BlurContainer extends StatelessWidget {
const BlurContainer({Key? key, this.value = 0}) : super(key: key);
final double value;
@override
Widget build(BuildContext context) {
return BackdropFilter(
filter: ImageFilter.blur(
sigmaX: value,
sigmaY: value,
),
child: Container(
color: Colors.transparent,
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/components/buttons.dart | import 'package:ecommerce_app_isaatech/constants/colors.dart';
import 'package:ecommerce_app_isaatech/constants/images.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:lottie/lottie.dart';
import 'package:velocity_x/velocity_x.dart';
class AuthButton extends StatelessWidget {
const AuthButton({Key? key, required this.text, required this.onPressed})
: super(key: key);
final String text;
final Function() onPressed;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(text,
style: Theme.of(context).textTheme.headline4!.copyWith(
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onBackground)),
SizedBox(
child: MaterialButton(
splashColor: CustomColors.customGrey,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(80)),
padding: const EdgeInsets.all(0),
onPressed: onPressed,
child: Transform.rotate(
angle: 4.71239,
child: LottieBuilder.asset(
Images.proceed,
height: 80,
frameRate: FrameRate(60),
)),
),
),
],
);
}
}
class PrimaryShadowedButton extends StatelessWidget {
const PrimaryShadowedButton(
{Key? key,
required this.child,
required this.onPressed,
required this.borderRadius,
required this.color})
: super(key: key);
final Widget child;
final double borderRadius;
final Color color;
final Function() onPressed;
@override
Widget build(BuildContext context) {
return Container(
margin: const EdgeInsets.all(0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(borderRadius),
gradient: const RadialGradient(
colors: [Colors.black54, Colors.black],
center: Alignment.topLeft,
radius: 2),
boxShadow: [
BoxShadow(
color: color.withOpacity(0.25),
offset: const Offset(3, 2),
spreadRadius: 1,
blurRadius: 8)
]),
child: MaterialButton(
padding: const EdgeInsets.all(0),
onPressed: onPressed,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(borderRadius)),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
child,
],
),
),
);
}
}
class FavouriteButton extends StatelessWidget {
const FavouriteButton(
{Key? key, required this.iconSize, required this.onPressed})
: super(key: key);
final double iconSize;
final Function() onPressed;
@override
Widget build(BuildContext context) {
return TextButton(
style: ButtonStyle(
padding: MaterialStateProperty.all(const EdgeInsets.all(0)),
shape: MaterialStateProperty.all(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(80))),
backgroundColor: MaterialStateProperty.all(Colors.pink),
elevation: MaterialStateProperty.all(4),
shadowColor: MaterialStateProperty.all(Colors.pink)),
child: Center(
child: Icon(
Icons.favorite,
size: iconSize,
color: Colors.white,
),
),
onPressed: onPressed,
);
}
}
class RoundedAddButton extends StatelessWidget {
const RoundedAddButton({
Key? key,
this.onPressed,
}) : super(key: key);
final Function()? onPressed;
@override
Widget build(BuildContext context) {
return MaterialButton(
elevation: 0,
padding: const EdgeInsets.all(0),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(100)),
child: Icon(
FontAwesomeIcons.plus,
size: 16,
color: Theme.of(context).colorScheme.surface,
).centered(),
onPressed: onPressed,
color: Colors.black);
}
}
class BagButton extends StatelessWidget {
const BagButton({Key? key, this.numberOfItemsPurchased = 0})
: super(key: key);
final int? numberOfItemsPurchased;
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.topRight,
children: [
IconButton(
icon: Image.asset(
Images.shoppingBag,
height: 28,
),
onPressed: () {},
),
if (numberOfItemsPurchased != 0)
Container(
margin: const EdgeInsets.only(right: 4, top: 8),
height: 20,
width: 20,
decoration: BoxDecoration(
color: CustomColors.darkBlue,
shape: BoxShape.circle,
border: Border.all(width: 1.5, color: Colors.white)),
child:
numberOfItemsPurchased.toString().text.sm.makeCentered().p(2),
),
],
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/models/category_model.dart | class Category {
String name;
String icon;
Category(this.icon, this.name);
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/models/product.dart | import 'package:flutter/material.dart';
class Product {
String name;
String brand;
String description;
double price;
double rating;
List<Color> productColors;
List<String> productImages;
Product(
{required this.name,
required this.brand,
required this.description,
required this.price,
required this.rating,
required this.productColors,
required this.productImages});
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/screens/profile_screen.dart | import 'package:ecommerce_app_isaatech/constants/images.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:velocity_x/velocity_x.dart';
class UserProfileScreen extends StatefulWidget {
const UserProfileScreen({Key? key}) : super(key: key);
static const String id = '/user-profile';
@override
_UserProfileScreenState createState() => _UserProfileScreenState();
}
class _UserProfileScreenState extends State<UserProfileScreen> {
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
children: [
Card(
margin: const EdgeInsets.all(0),
elevation: 10,
shadowColor: Colors.grey.shade100,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Row(
children: [
const CircleAvatar(
radius: 33,
backgroundImage: AssetImage(Images.avatar),
),
12.widthBox,
Column(
children: [
'Rashid Wassan'.text.xl2.semiBold.make(),
'[email protected]'.text.sm.make(),
],
),
],
).p(8),
),
24.heightBox,
ProfileScreenCardView(
title: 'Purchases',
accentColor: Colors.blue.shade200,
icon: CupertinoIcons.cart,
onPressed: () {},
),
ProfileScreenCardView(
title: 'History',
accentColor: Colors.red.shade200,
icon: CupertinoIcons.clock,
onPressed: () {},
),
ProfileScreenCardView(
title: 'Favourites',
accentColor: Colors.purple.shade200,
icon: CupertinoIcons.heart,
onPressed: () {},
),
ProfileScreenCardView(
title: 'Help & Support',
accentColor: Colors.green.shade200,
icon: CupertinoIcons.phone,
onPressed: () {},
),
ProfileScreenCardView(
title: 'Rate Us',
accentColor: Colors.amber.shade200,
icon: CupertinoIcons.star,
onPressed: () {},
),
],
),
).p(16);
}
}
class ProfileScreenCardView extends StatelessWidget {
const ProfileScreenCardView(
{Key? key,
required this.title,
required this.accentColor,
required this.icon,
required this.onPressed})
: super(key: key);
final String title;
final Color accentColor;
final IconData icon;
final Function onPressed;
@override
Widget build(BuildContext context) {
return Card(
color: Colors.white,
margin: const EdgeInsets.only(bottom: 16),
elevation: 4,
shadowColor: Colors.grey.shade100,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
child: Row(
children: [
Container(
height: 35,
width: 35,
decoration:
BoxDecoration(shape: BoxShape.circle, color: accentColor),
child: Center(
child: Icon(
icon,
size: 20,
color: Colors.white,
),
),
),
8.widthBox,
title.text.lg.semiBold.make(),
const Spacer(),
const Icon(Icons.keyboard_arrow_right),
],
).p(12),
);
}
}
| 0 |
mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib | mirrored_repositories/Flutter-Open-Source-Apps/Flutter Open Source Apps/Intermediate/flutter-ecommerce-app-ui/lib/screens/login.dart | import 'dart:ui';
import 'package:ecommerce_app_isaatech/components/blur_container.dart';
import 'package:ecommerce_app_isaatech/components/buttons.dart';
import 'package:ecommerce_app_isaatech/components/textfields.dart';
import 'package:ecommerce_app_isaatech/constants/images.dart';
import 'package:ecommerce_app_isaatech/screens/home/main_home.dart';
import 'package:ecommerce_app_isaatech/screens/signup.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:velocity_x/velocity_x.dart';
class LoginScreen extends StatefulWidget {
static const String id = '/login';
const LoginScreen({Key? key}) : super(key: key);
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen>
with SingleTickerProviderStateMixin {
late AnimationController _blurAnimationController;
@override
void initState() {
_blurAnimationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 4),
lowerBound: 0,
upperBound: 6,
);
super.initState();
_blurAnimationController.forward();
_blurAnimationController.addListener(() {
setState(() {});
});
}
@override
void dispose() {
super.dispose();
_blurAnimationController.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(children: [
Container(
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
Images.loginBg,
),
fit: BoxFit.cover,
)),
),
BlurContainer(value: _blurAnimationController.value),
SafeArea(
child: Form(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
double.infinity.widthBox,
const Spacer(),
const Spacer(),
_buildTitleText(context),
const Spacer(),
const PrimaryTextField(
hintText: 'Name',
prefixIcon: Icons.person,
),
24.heightBox,
const PrimaryTextField(
hintText: 'Password',
isObscure: true,
prefixIcon: CupertinoIcons.padlock,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () {},
style: const ButtonStyle(),
child: const Text(
'Forgot your password?',
style: TextStyle(color: Colors.black),
),
),
24.widthBox,
],
),
const Spacer(),
AuthButton(
text: 'Sign In',
onPressed: () {
Navigator.of(context).pushNamed(UserDashboard.id);
}),
const Spacer(),
RichText(
text: TextSpan(children: [
TextSpan(
text: 'Don\'t have an account? ',
style: TextStyle(
fontSize: 17,
color: Theme.of(context).colorScheme.onBackground)),
TextSpan(
text: 'Create',
style: TextStyle(
fontSize: 17,
color: Theme.of(context).colorScheme.onBackground,
fontWeight: FontWeight.bold,
decoration: TextDecoration.underline),
recognizer: TapGestureRecognizer()
..onTap = () {
Navigator.of(context).pushNamed(SignUpScreen.id);
}),
]),
),
],
).p(24),
),
),
]),
);
}
Column _buildTitleText(BuildContext context) {
return Column(
children: [
Text(
'Hello',
softWrap: true,
style: TextStyle(
fontSize: 85,
fontWeight: FontWeight.w600,
color: Theme.of(context).colorScheme.onBackground),
),
Text(
'Sign in to your account',
softWrap: true,
style: Theme.of(context).textTheme.headline6,
),
],
);
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.