repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/FlutterLoginUI
|
mirrored_repositories/FlutterLoginUI/lib/SignInScreen.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_login_ui/SignUpScreen.dart';
import 'package:flutter_login_ui/utils/EnterExitRoute.dart';
class SignInScreen extends StatefulWidget {
@override
_SignInScreenState createState() => _SignInScreenState();
}
class _SignInScreenState extends State<SignInScreen> {
bool passwordVisible;
final Color accentColor = Colors.orange;
final Color darkColor = Colors.black;
@override
void initState() {
super.initState();
passwordVisible = true;
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: LayoutBuilder(
builder: (BuildContext context, BoxConstraints viewportConstraints) {
return SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: body(),
),
);
},
),
);
}
Widget body() {
return Container(
// Add box decoration
color: darkColor,
child: Center(
child: Padding(
padding: EdgeInsets.all(20),
child: Card(
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
height: 100,
width: double.maxFinite,
color: accentColor,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.all(20),
child: Text(
"Login",
style: TextStyle(
color: darkColor,
fontSize: 24,
fontWeight: FontWeight.w400),
),
),
Padding(
padding: EdgeInsets.all(20),
child: FloatingActionButton(
backgroundColor: Colors.black,
onPressed: () {
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SignUpScreen()),
);*/
Navigator.push(
context,
EnterExitRoute(
exitPage: SignInScreen(),
enterPage: SignUpScreen()));
},
child: Icon(
Icons.arrow_forward,
color: Colors.orangeAccent,
),
),
)
],
),
),
Container(
padding: EdgeInsets.all(20),
child: Column(
children: <Widget>[
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.all(10),
child: Icon(
Icons.perm_identity,
color: darkColor,
),
),
Expanded(
child: TextFormField(
decoration: InputDecoration(
labelText: 'Username',
labelStyle: TextStyle(
color: darkColor,
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: darkColor,
),
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: darkColor,
),
),
),
),
),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
Padding(
padding: EdgeInsets.all(10),
child: Icon(
Icons.lock,
color: darkColor,
),
),
Expanded(
child: TextFormField(
obscureText: passwordVisible,
decoration: InputDecoration(
labelText: 'Password',
labelStyle: TextStyle(
color: darkColor,
),
suffixIcon: IconButton(
icon: Icon(
passwordVisible
? Icons.visibility_off
: Icons.visibility,
color: Colors.black,
),
onPressed: () {
setState(() {
passwordVisible = !passwordVisible;
});
},
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: darkColor,
),
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(
color: darkColor,
),
),
),
),
),
],
),
Container(
margin: EdgeInsets.only(top: 50, bottom: 10),
child: SizedBox(
height: 50,
width: double.maxFinite,
child: RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30),
),
onPressed: () {},
textColor: darkColor,
color: accentColor,
padding: EdgeInsets.all(10),
child: Text(
"SIGN IN",
),
),
),
),
Container(
margin: EdgeInsets.only(bottom: 10),
child: Text("Forgot your password?"),
)
],
),
),
],
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/FlutterLoginUI/lib
|
mirrored_repositories/FlutterLoginUI/lib/utils/SlideLeftRoute.dart
|
import 'package:flutter/cupertino.dart';
class SlideLeftRoute extends PageRouteBuilder {
final Widget page;
SlideLeftRoute({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
SlideTransition(
position: Tween<Offset>(
begin: const Offset(1, 0),
end: Offset.zero,
).animate(animation),
child: child,
),
);
}
| 0
|
mirrored_repositories/FlutterLoginUI/lib
|
mirrored_repositories/FlutterLoginUI/lib/utils/ScaleRoute.dart
|
import 'package:flutter/cupertino.dart';
class ScaleRoute extends PageRouteBuilder {
final Widget page;
ScaleRoute({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
ScaleTransition(
scale: Tween<double>(
begin: 0.0,
end: 1.0,
).animate(
CurvedAnimation(
parent: animation,
curve: Curves.fastOutSlowIn,
),
),
child: child,
),
);
}
| 0
|
mirrored_repositories/FlutterLoginUI/lib
|
mirrored_repositories/FlutterLoginUI/lib/utils/SlideRightRoute.dart
|
import 'package:flutter/cupertino.dart';
class SlideRightRoute extends PageRouteBuilder {
final Widget page;
SlideRightRoute({this.page})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
page,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
SlideTransition(
position: Tween<Offset>(
begin: const Offset(-1, 0),
end: Offset.zero,
).animate(animation),
child: child,
),
);
}
| 0
|
mirrored_repositories/FlutterLoginUI/lib
|
mirrored_repositories/FlutterLoginUI/lib/utils/EnterExitRoute.dart
|
import 'package:flutter/cupertino.dart';
class EnterExitRoute extends PageRouteBuilder {
final Widget enterPage;
final Widget exitPage;
EnterExitRoute({this.exitPage, this.enterPage})
: super(
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
enterPage,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) =>
Stack(
children: <Widget>[
SlideTransition(
position: new Tween<Offset>(
begin: const Offset(0.0, 0.0),
end: const Offset(-1.0, 0.0),
).animate(animation),
child: exitPage,
),
SlideTransition(
position: new Tween<Offset>(
begin: const Offset(1.0, 0.0),
end: Offset.zero,
).animate(animation),
child: enterPage,
)
],
),
);
}
| 0
|
mirrored_repositories/FlutterLoginUI
|
mirrored_repositories/FlutterLoginUI/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:flutter_login_ui/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/FlutterShare
|
mirrored_repositories/FlutterShare/lib/main.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/home.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
Firestore.instance.settings(timestampsInSnapshotsEnabled: true).then(
(_) => print("TimeStamps Enabled Successfully"),
onError: (_) => print("ERROR TimeStamps not enabled"));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Malik\'s Instagram',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.deepPurple,
accentColor: Colors.teal,
),
home: Home(),
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/widgets/progress.dart
|
import 'package:flutter/material.dart';
Container circularProgress() {
return Container(
alignment: Alignment.center,
padding: EdgeInsets.only(top: 10.0),
child: CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.purple),
));
}
Container linearProgress() {
return Container(
padding: EdgeInsets.only(bottom: 10.0),
child: LinearProgressIndicator(
valueColor: AlwaysStoppedAnimation(Colors.purple),
),
);
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/widgets/post_tile.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluttershare/pages/post_screen.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/widgets/custom_image.dart';
import 'package:fluttershare/widgets/post.dart';
class PostTile extends StatelessWidget {
Post post;
PostTile(this.post);
showPost(context)
{
Navigator.push(context, MaterialPageRoute(builder: (_)=>PostScreen(postId: post.postId,userId: post.ownerId,)));
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => showPost(context),
child: cachedNetworkImage(post.mediaUrl),
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/widgets/custom_image.dart
|
import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
Widget cachedNetworkImage(String mediaUrl) {
return CachedNetworkImage(
imageUrl: mediaUrl,
fit: BoxFit.cover,
placeholder: (ctx, url) => Padding(
padding: EdgeInsets.all(16),
child: CircularProgressIndicator(),
),
errorWidget: (ctx, _, __) => Icon(Icons.error),
);
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/widgets/post.dart
|
import 'dart:async';
import 'package:animator/animator.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/comments.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/pages/profile.dart';
import 'package:fluttershare/widgets/custom_image.dart';
import 'package:fluttershare/widgets/progress.dart';
class Post extends StatefulWidget {
final String postId;
final String ownerId;
final String username;
final String location;
final String description;
final String mediaUrl;
final dynamic likes;
Post({
this.postId,
this.ownerId,
this.username,
this.location,
this.description,
this.mediaUrl,
this.likes,
});
factory Post.fromDocument(DocumentSnapshot doc) {
return Post(
postId: doc['postId'],
ownerId: doc['ownerId'],
username: doc['username'],
location: doc['location'],
description: doc['description'],
mediaUrl: doc['mediaUrl'],
likes: doc['likes'],
);
}
int getLikeCount(likes) {
// if no likes, return 0
if (likes == null) {
return 0;
}
int count = 0;
// if the key is explicitly set to true, add a like
likes.values.forEach((val) {
if (val == true) {
count += 1;
}
});
return count;
}
@override
_PostState createState() => _PostState(
postId: this.postId,
ownerId: this.ownerId,
username: this.username,
location: this.location,
description: this.description,
mediaUrl: this.mediaUrl,
likes: this.likes,
likeCount: getLikeCount(this.likes),
);
}
class _PostState extends State<Post> {
final String userId = currentUser?.id;
final String postId;
final String ownerId;
final String username;
final String location;
final String description;
final String mediaUrl;
int likeCount;
Map likes;
bool isLiked;
bool showHeart = false;
_PostState({
this.postId,
this.ownerId,
this.username,
this.location,
this.description,
this.mediaUrl,
this.likes,
this.likeCount,
});
buildLikeLogic() {
isLiked = likes[userId] == true;
if (isLiked) {
postsRef
.document(ownerId)
.collection("userPosts")
.document(postId)
.updateData({"likes.$userId": false});
//remove like from feed
removeLikeFromFeed();
setState(() {
likeCount -= 1;
isLiked = false;
likes[userId] = false;
});
} else if (!isLiked) {
postsRef
.document(ownerId)
.collection("userPosts")
.document(postId)
.updateData({"likes.$userId": true});
//update like in feed
addLikeToFeed();
setState(() {
likeCount += 1;
isLiked = true;
likes[userId] = true;
showHeart = true;
});
Timer(Duration(milliseconds: 500), () {
setState(() {
showHeart = false;
});
});
}
}
addLikeToFeed() {
bool isOwner = currentUser.id == ownerId;
if (!isOwner) {
activityFeedRef
.document(ownerId)
.collection("feedItems")
.document(postId)
.setData({
"type": "like",
"username": currentUser.username,
"userId": currentUser.id,
"userProfileImg": currentUser.photoUrl,
"postId": postId,
"mediaUrl": mediaUrl,
"timestamp": DateTime.now(),
});
}
}
removeLikeFromFeed() {
bool isOwner = currentUser.id == ownerId;
if (!isOwner) {
activityFeedRef
.document(ownerId)
.collection("feedItems")
.document(postId)
.get()
.then((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
}
}
buildPostHeader() {
return FutureBuilder(
future: usersRef.document(ownerId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
User user = User.fromDocument(snapshot.data);
bool isPostOwner = currentUser.id == user.id;
return ListTile(
leading: CircleAvatar(
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
backgroundColor: Colors.grey,
),
title: GestureDetector(
onTap: () => showProfile(
context,
profileId: user.id,
),
child: Text(
user.username??"",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
subtitle: Text(location),
trailing: isPostOwner
? IconButton(
onPressed: () => handleDeletePost(context),
icon: Icon(Icons.delete),
)
: Text(""),
);
},
);
}
buildPostImage() {
return GestureDetector(
onDoubleTap: () => buildLikeLogic(),
child: Stack(
alignment: Alignment.center,
children: <Widget>[
cachedNetworkImage(mediaUrl),
showHeart
? Animator(
duration: Duration(milliseconds: 400),
tween: Tween(begin: 0.8, end: 1.4),
curve: Curves.easeInOutBack,
cycles: 0,
builder: (anim) => Transform.scale(
scale: anim.value,
child: Icon(
Icons.favorite,
color: Colors.grey.withOpacity(0.6),
size: 150,
)),
)
: Text("")
],
),
);
}
buildPostFooter() {
return FutureBuilder(
future: usersRef.document(ownerId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
User user = User.fromDocument(snapshot.data);
return Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(padding: EdgeInsets.only(top: 40.0, left: 20.0)),
GestureDetector(
onTap: () => buildLikeLogic(),
child: Icon(
isLiked ? Icons.favorite : Icons.favorite_border,
size: 28.0,
color: Colors.pink,
),
),
Padding(padding: EdgeInsets.only(right: 20.0)),
GestureDetector(
onTap: () => showComments(context,
ownerId: ownerId, postId: postId, mediaUrl: mediaUrl),
child: Icon(
Icons.chat,
size: 28.0,
color: Colors.blue[900],
),
),
],
),
Row(
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
"$likeCount likes",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
],
),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
margin: EdgeInsets.only(left: 20.0),
child: Text(
"${user.username} ",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
Expanded(child: Text(description))
],
),
],
);
}
);
}
@override
Widget build(BuildContext context) {
isLiked = likes[userId] == true;
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
buildPostHeader(),
buildPostImage(),
buildPostFooter()
],
);
}
showComments(BuildContext context,
{String ownerId, String postId, String mediaUrl}) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Comments(
postId: postId,
ownerId: ownerId,
mediaUrl: mediaUrl,
)));
}
showProfile(context, {String profileId}) {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => Profile(
profileId: profileId,
)));
}
deletePost() async {
//now Delete uploaded firebase object of post
postsRef
.document(ownerId)
.collection("userPosts")
.document(postId)
.get()
.then((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
//now Delete uploaded image
stoarageRef.child("post_$postId").delete();
//delete from activity feed also
await activityFeedRef
.document(ownerId)
.collection("feedItems")
.where("postId", isEqualTo: postId)
.getDocuments()
.then((docs){
docs.documents.forEach((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
});
//finally delete all comments also GOD!!
await commmentsRef
.document(ownerId)
.collection("comments")
.getDocuments()
.then((docs){
docs.documents.forEach((doc) {
if (doc.exists) {
doc.reference.delete();
}
});
});
}
handleDeletePost(BuildContext parentContext) {
return showDialog(
context: parentContext,
builder: (ctx) {
return SimpleDialog(
title: Text("Remove this post"),
children: <Widget>[
SimpleDialogOption(
child: Text("Remove", style: TextStyle(color: Colors.red)),
onPressed: () {
Navigator.pop(context);
deletePost();
},
),
SimpleDialogOption(
child: Text("Cancel"),
onPressed: () => Navigator.pop(context),
),
],
);
});
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/widgets/header.dart
|
import 'package:flutter/material.dart';
AppBar header(context, {bool isAppTitle = false, String titleText,bool removeBackButton=false}) {
return AppBar(
automaticallyImplyLeading: removeBackButton,
title: Text(
isAppTitle ? "FlutterShare" : titleText,
style: TextStyle(
color: Colors.white,
fontFamily: isAppTitle ? "Signatra" : "",
fontSize: isAppTitle ? 50.0 : 22.0,
),
overflow: TextOverflow.ellipsis,
),
centerTitle: true,
backgroundColor: Theme.of(context).accentColor,
);
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/post_screen.dart
|
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/post.dart';
class PostScreen extends StatelessWidget {
final String userId;
final String postId;
PostScreen({this.userId, this.postId});
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: postsRef
.document(userId)
.collection("userPosts")
.document(postId)
.get(),
builder: (ctx, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
Post post = Post.fromDocument(snapshot.data);
return Center(
child: Scaffold(
appBar: header(context, titleText: post.description),
body: Container(
padding: EdgeInsets.only(bottom:40),
child: ListView(
children: <Widget>[
Container(
child: post,
)
],
),
),
),
);
},
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/create_account.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluttershare/widgets/header.dart';
class CreateAccount extends StatefulWidget {
@override
_CreateAccountState createState() => _CreateAccountState();
}
class _CreateAccountState extends State<CreateAccount> {
final snackbarKey = GlobalKey<ScaffoldState>();
final formkey = GlobalKey<FormState>();
String username;
submit()
{ var _form = formkey.currentState;
if(_form.validate())
{
_form.save();
SnackBar snackBar = SnackBar(content: Text("Welcome $username!"),);
snackbarKey.currentState.showSnackBar(snackBar);
Timer(Duration(seconds:2),(){
Navigator.pop(context,username);
});
}
}
Future<bool> dothis() async
{
if(username == null)
{
SnackBar snackBar = SnackBar(content: Text("Please Enter your Username..."),);
snackbarKey.currentState.showSnackBar(snackBar);
return false;
}
return true;
}
@override
Widget build(BuildContext parentContext) {
return WillPopScope(
onWillPop: dothis,
child: Scaffold(
key: snackbarKey,
appBar: header(context, titleText: "Set up your profile ",removeBackButton: true,),
body: ListView(
children: <Widget>[
Container(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 25),
child: Center(
child: Text(
"Enter a Username",
style: TextStyle(fontSize: 25),
),
),
),
Padding(
padding: EdgeInsets.all(16),
child: Container(
child: Form(
autovalidate: true,
key: formkey,
child: TextFormField(
validator: (val) {
if(val.trim().length<3||val.isEmpty)
{
return "Username too short";
}else if(val.trim().length>12)
{
return "Username too long";
}else{
return null;
}
},
onSaved: (val) => username = val,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelStyle: TextStyle(fontSize: 15),
labelText: "username",
hintText: "Must be atleast 3 characters"),
),
),
),
),
GestureDetector(
onTap: submit,
child: Container(
height: 50,
width: 350,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(7)),
child: Center(
child: Text(
"Submit",
style: TextStyle(
fontSize: 15,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
),
),
],
),
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/profile.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/edit_profile.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/post.dart';
import 'package:fluttershare/widgets/post_tile.dart';
import 'package:fluttershare/widgets/progress.dart';
class Profile extends StatefulWidget {
final String profileId;
Profile({this.profileId});
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
final String currentUserId = currentUser?.id;
bool isFollowing = false;
String postOrientation = "grid";
bool isLoading = false;
int postCount = 0;
int followerCount = 0;
int followingCount = 0;
List<Post> posts = [];
@override
void initState() {
super.initState();
getProfilePosts();
getFollowers();
getFollowing();
checkIfFollowing();
}
getFollowers() async
{
QuerySnapshot doc = await followersRef.document(widget.profileId).collection("userFollowers").getDocuments();
setState(() {
followerCount = doc.documents.length;
});
}
getFollowing() async
{
QuerySnapshot doc = await followingRef.document(widget.profileId).collection("userFollowers").getDocuments();
setState(() {
followingCount = doc.documents.length;
});
}
checkIfFollowing() async
{
DocumentSnapshot doc = await followersRef.document(widget.profileId).collection("userFollowers").document(currentUserId).get();
setState(() {
isFollowing = doc.exists;
});
}
getProfilePosts() async {
setState(() {
isLoading = true;
});
QuerySnapshot snapshot = await postsRef
.document(widget.profileId)
.collection('userPosts')
.orderBy('timestamp', descending: true)
.getDocuments();
setState(() {
isLoading = false;
postCount = snapshot.documents.length;
posts = snapshot.documents.map((doc) => Post.fromDocument(doc)).toList();
});
}
Column buildCountColumn(String label, String count) {
return Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
count,
style: TextStyle(fontSize: 22.0, fontWeight: FontWeight.bold),
),
Container(
margin: EdgeInsets.only(top: 4.0),
child: Text(
label,
style: TextStyle(
color: Colors.grey,
fontSize: 15.0,
fontWeight: FontWeight.w400,
),
),
),
],
);
}
editProfile() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => EditProfile(userId: currentUserId)));
}
Container buildButton({String text, Function function}) {
return Container(
padding: EdgeInsets.only(top: 2.0),
child: FlatButton(
onPressed: function,
child: Container(
width: 230.0,
height: 27.0,
child: Text(
text,
style: TextStyle(
color: isFollowing ? Colors.black : Colors.white,
fontWeight: FontWeight.bold,
),
),
alignment: Alignment.center,
decoration: BoxDecoration(
color: isFollowing ? Colors.white : Colors.blue,
border: Border.all(
color: isFollowing ? Colors.grey : Colors.blue,
),
borderRadius: BorderRadius.circular(5.0),
),
),
),
);
}
buildProfileButton() {
// viewing your own profile - should show edit profile button
bool isProfileOwner = currentUserId == widget.profileId;
if (isProfileOwner) {
return buildButton(text: "Edit Profile", function: editProfile);
}else if(isFollowing)
{
return buildButton(text: "Unfollow", function: handleUnfollowuser);
}else if(!isFollowing)
{
return buildButton(text: "Follow", function: handlefollowuser);
}
}
handleUnfollowuser()
{
setState(() {
isFollowing = false;
});
// remove follower
followersRef.document(widget.profileId).collection("userFollowers").document(currentUserId).get().then((doc){if(doc.exists){doc.reference.delete();}});
// remove profile from the list of profiles we are following
followingRef.document(currentUserId).collection("userFollowing").document(widget.profileId).get().then((doc){if(doc.exists){doc.reference.delete();}});
// delete from activityFeed Notifications
activityFeedRef.document(widget.profileId).collection("feedItems").document(currentUserId).get().then((doc){if(doc.exists){doc.reference.delete();}});
setState(() {
followerCount--;
});
}
handlefollowuser()
{
setState(() {
isFollowing = true;
});
// add follower to the profile we followed
followersRef.document(widget.profileId).collection("userFollowers").document(currentUserId).setData({});
// add profile in the list of profiles we are following
followingRef.document(currentUserId).collection("userFollowing").document(widget.profileId).setData({});
// show in activityFeed Notifications
activityFeedRef.document(widget.profileId).collection("feedItems").document(currentUserId).setData({
"type":"follow",
"ownerId":widget.profileId,
"username":currentUser.username,
"userId" : currentUserId,
"userProfileImg" : currentUser.photoUrl,
"timestamp" : DateTime.now(),
});
setState(() {
followerCount++;
});
}
buildProfileHeader() {
return FutureBuilder(
future: usersRef.document(widget.profileId).get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return circularProgress();
}
User user = User.fromDocument(snapshot.data);
return Padding(
padding: EdgeInsets.all(16.0),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom:12.0),
child: CircleAvatar(
radius: 40.0,
backgroundColor: Colors.grey,
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
),
),
Expanded(
flex: 1,
child: Padding(
padding: const EdgeInsets.only(top:8.0),
child: Column(
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
buildCountColumn("posts", postCount.toString()),
buildCountColumn("followers", followerCount.toString()),
buildCountColumn("following", followingCount.toString()),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
buildProfileButton(),
],
),
],
),
),
),
],
),
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(top: 12.0),
child: Text(
user.username??"",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16.0,
),
),
),
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(top: 4.0),
child: Text(
user.displayName,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(top: 2.0),
child: Text(
user.bio,
),
),
],
),
);
},
);
}
buildProfilePosts() {
if (isLoading) {
return circularProgress();
}else if(posts.isEmpty)
{
return Container(
color: Colors.white,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SvgPicture.asset("assets/images/no_content.svg", height: 260),
Container(
padding: EdgeInsets.only(top: 20),
child: Text(
"No Posts",
style: TextStyle(fontSize: 40, color: Colors.redAccent,fontWeight: FontWeight.bold),
),
)
],
),
);
}
else if(postOrientation == 'grid'){
List<GridTile> gridtiles = [];
posts.forEach((post) {
gridtiles.add(GridTile(
child: PostTile(post),
));
});
return GridView.count(
crossAxisCount: 3,
crossAxisSpacing: 1.5,
mainAxisSpacing: 1.5,
childAspectRatio: 1.0,
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
children: gridtiles,
);
}else if(postOrientation == 'linear')
{
return Column(
children: posts,
);
}
}
buildPostOrientationTile() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
IconButton(
icon: Icon(Icons.grid_on),
onPressed: ()
{
setState(() {
postOrientation = 'grid';
});
},
color: postOrientation == 'grid' ? Theme.of(context).primaryColor : Colors.grey,
),
IconButton(
icon: Icon(Icons.list),
onPressed: ()
{
setState(() {
postOrientation = 'linear';
});
},
color: postOrientation == 'grid' ? Colors.grey : Theme.of(context).primaryColor,
),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: header(context, titleText: "Profile"),
body: ListView(
children: <Widget>[
buildProfileHeader(),
Divider(),
buildPostOrientationTile(),
Divider(
height: 0.0,
),
buildProfilePosts(),
],
),
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/edit_profile.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import "package:flutter/material.dart";
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/home.dart';
class EditProfile extends StatefulWidget {
final String userId;
EditProfile({this.userId});
@override
_EditProfileState createState() => _EditProfileState();
}
class _EditProfileState extends State<EditProfile> {
final key = GlobalKey<ScaffoldState>();
bool isLoading = false;
User user;
TextEditingController nameController = TextEditingController();
TextEditingController bioController = TextEditingController();
bool nameIsValid = true;
bool bioIsValid = true;
getUser() async {
DocumentSnapshot doc = await usersRef.document(widget.userId).get();
user = User.fromDocument(doc);
nameController.text = user.displayName;
bioController.text = user.bio;
setState(() {
isLoading = false;
});
}
@override
void initState() {
// TODO: implement initState
setState(() {
isLoading = true;
});
getUser();
}
buildDisplayNameField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 12),
child: Text(
"Display Name",
style: TextStyle(color: Colors.grey),
)),
TextField(
controller: nameController,
decoration: InputDecoration(
hintText: "Update Display Name",
errorText: nameIsValid ? null : "Please enter a valid Name"),
)
],
);
}
buildBioField() {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 12),
child: Text(
"Bio",
style: TextStyle(color: Colors.grey),
)),
TextField(
controller: bioController,
decoration: InputDecoration(
hintText: "Update Bio",
errorText: bioIsValid ? null : "Please enter a valid bio ",
),
)
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
key: key,
appBar: AppBar(
backgroundColor: Colors.white,
title: Text(
"Edit Profile",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(
Icons.done,
size: 30,
color: Colors.green,
),
onPressed: () => Navigator.of(context).pop(),
)
],
),
body: isLoading
? Center(child: CircularProgressIndicator())
: ListView(
children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 16, bottom: 8),
child: CircleAvatar(
backgroundColor: Colors.grey,
backgroundImage:
CachedNetworkImageProvider(user.photoUrl),
),
),
Padding(
padding: EdgeInsets.all(16),
child: Column(
children: <Widget>[
buildDisplayNameField(),
buildBioField(),
],
),
),
RaisedButton(
onPressed: () => validateInput(),
child: Text(
"Update Profile",
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.blue,
fontSize: 20),
),
),
Container(
padding: EdgeInsets.all(16),
child: FlatButton.icon(
onPressed: logout,
icon: Icon(
Icons.cancel,
color: Colors.red,
),
label: Text(
"Logout",
style: TextStyle(color: Colors.red, fontSize: 20),
)),
)
],
)
],
),
);
}
validateInput() {
setState(() {
nameController.text.trim().length < 3 ||
nameController.text.isEmpty
? nameIsValid = false
: nameIsValid = true;
bioController.text.trim().length > 100
? bioIsValid = false
: bioIsValid = true;
});
if (nameIsValid && bioIsValid) {
usersRef.document(widget.userId).updateData({
"displayName": nameController.text.trim(),
"bio": bioController.text.trim(),
});
SnackBar snackBar = SnackBar(
content: Text("Profile Successfully Updated!"),
);
key.currentState.showSnackBar(snackBar);
}
}
logout() {
googleSignIn.signOut();
Navigator.push(context, MaterialPageRoute(builder: (_)=> Home()));
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/comments.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:timeago/timeago.dart' as timeago;
class Comments extends StatefulWidget {
final String postId;
final String ownerId;
final String mediaUrl;
Comments({this.postId, this.ownerId, this.mediaUrl});
@override
CommentsState createState() => CommentsState(
mediaUrl: this.mediaUrl,
ownerId: this.ownerId,
postId: this.postId,
);
}
class CommentsState extends State<Comments> {
TextEditingController commentController = TextEditingController();
String mediaUrl;
String postId;
String ownerId;
CommentsState({this.mediaUrl, this.ownerId, this.postId});
buildComments() {
return StreamBuilder(
stream: commmentsRef
.document(postId)
.collection("comments")
.orderBy("timestamp", descending: false)
.snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
List<Comment> comments = [];
snapshot.data.documents.forEach((doc) {
comments.add(Comment.from(doc));
});
return ListView(
children: comments,
);
},
);
}
addComment() {
commmentsRef.document(postId).collection("comments").add({
"username": currentUser.username,
"comment": commentController.text,
"timestamp": DateTime.now(),
"avatarUrl": currentUser.photoUrl,
"userId": ownerId
});
bool isOwner = currentUser.id == ownerId;
if(!isOwner)
{
activityFeedRef.document(ownerId).collection("feedItems").add({
"type" : "comment",
"username" : currentUser.username,
"userId" : currentUser.id,
"userProfileImg" : currentUser.photoUrl,
"postId" : postId,
"mediaUrl" : mediaUrl,
"timestamp" : DateTime.now(),
});
}
commentController.clear();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: header(context, titleText: "Comments"),
body: Column(
children: <Widget>[
Expanded(
child: buildComments(),
),
Divider(),
ListTile(
title: TextField(
controller: commentController,
decoration: InputDecoration(
labelText: "Enter your comment...",
),
),
trailing: OutlineButton(
onPressed: () => addComment(),
child: Text("POST"),
borderSide: BorderSide.none,
),
),
],
),
);
}
}
class Comment extends StatelessWidget {
String username;
String comment;
Timestamp timestamp;
String avatarUrl;
String userId;
Comment({
this.username,
this.comment,
this.timestamp,
this.avatarUrl,
this.userId,
});
factory Comment.from(doc) {
return Comment(
avatarUrl: doc["avatarUrl"],
comment: doc["comment"],
timestamp: doc["timestamp"],
username: doc["username"],
userId: doc["userId"],
);
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
ListTile(
title: Text(comment),
subtitle: Text(
timeago.format(timestamp.toDate()),
style: TextStyle(color: Colors.grey),
),
leading: CircleAvatar(
backgroundColor: Colors.grey,
backgroundImage: CachedNetworkImageProvider(avatarUrl),
),
),
],
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/timeline.dart
|
import 'package:flutter/material.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/pages/search.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:fluttershare/widgets/post.dart';
import 'package:fluttershare/widgets/progress.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
final usersRef = Firestore.instance.collection("users");
class Timeline extends StatefulWidget {
final String currentUser;
Timeline({this.currentUser});
@override
_TimelineState createState() => _TimelineState();
}
class _TimelineState extends State<Timeline> {
List<Post> posts = [];
List<String> following = [];
@override
void initState() {
super.initState();
getTimeline();
getFollowing();
}
getFollowing() async {
QuerySnapshot followingSnapshot = await followingRef
.document(widget.currentUser)
.collection("userFollowing")
.getDocuments();
List<String> ids =
followingSnapshot.documents.map((doc) => doc.documentID).toList();
setState(() {
this.following = ids;
});
}
getTimeline() async {
print(widget.currentUser);
QuerySnapshot docs = await timelineRef
.document(widget.currentUser)
.collection("timelinePosts")
.orderBy("timestamp", descending: true)
.getDocuments();
List<Post> firebasePosts = [];
print(docs.documents);
firebasePosts = docs.documents
.map((doc) => Post.fromDocument(doc))
.toList();
setState(() {
this.posts = firebasePosts;
});
}
buildTimeline() {
print(posts);
if (posts == null) {
return Center(child: CircularProgressIndicator());
} else if (posts.isEmpty) {
return buildUsersToFollow();
} else {
return ListView(
children: posts,
);
}
}
buildUsersToFollow() {
return StreamBuilder(
stream:
usersRef.orderBy("timestamp", descending: true).limit(30).snapshots(),
builder: (ctx, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
List<UserResult> users = [];
snapshot.data.documents.forEach((doc) {
if (doc.exists) {
User user = User.fromDocument(doc);
bool isOwner = currentUser.id == user.id;
bool isFollowing = following.contains(user.id);
if (isOwner || isFollowing) {
return;
} else {
UserResult userResult = UserResult(user);
users.add(userResult);
}
}
});
return Container(
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.all(12),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.person_add,
color: Theme.of(context).primaryColor,
size: 30.0,
),
SizedBox(
width: 8,
),
Text(
"Users To Follow",
style: TextStyle(
fontSize: 30, color: Theme.of(context).primaryColor),
)
],
),
),
Column(
children: users,
),
],
),
);
},
);
}
@override
Widget build(context) {
return Scaffold(
appBar: header(context, isAppTitle: true),
body: RefreshIndicator(
onRefresh: () => getTimeline(),
child: Container(
padding: EdgeInsets.only(top: 10,bottom: 30),
child: buildTimeline(),
)),
);
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/search.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/pages/profile.dart';
class Search extends StatefulWidget {
@override
_SearchState createState() => _SearchState();
}
class _SearchState extends State<Search> with AutomaticKeepAliveClientMixin<Search> {
Future<QuerySnapshot> searchResultsFuture;
TextEditingController textEditingController = TextEditingController();
handleSearch(String query) {
Future<QuerySnapshot> users = usersRef
.orderBy("displayName")
.startAt([query])
.getDocuments();
setState(() {
searchResultsFuture = users;
});
}
AppBar buildSearchField() {
return AppBar(
backgroundColor: Colors.white,
titleSpacing: 2.0,
//leading: SizedBox(height: 0.0,width: 0.0,),
title: TextFormField(
controller: textEditingController,
decoration: InputDecoration(
filled: true,
hintText: "Search for a person... ",
prefixIcon: Icon(
Icons.account_box,
size: 28,
),
suffixIcon: IconButton(
icon: Icon(Icons.clear),
onPressed: () {
textEditingController.clear();
},
),
),
onFieldSubmitted: handleSearch,
),
);
}
Container buildNoContent() {
return Container(
child: Center(
child: ListView(
shrinkWrap: true,
children: <Widget>[
SvgPicture.asset(
"assets/images/search.svg",
height: MediaQuery.of(context).size.height * 0.4,
),
Text(
"Find Users",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 60,
fontWeight: FontWeight.w600,
color: Colors.white,
fontStyle: FontStyle.italic),
)
],
),
),
);
}
buildSearchResults() {
return FutureBuilder(
future: searchResultsFuture,
builder: (ctx, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
List<UserResult> searchResults = [];
snapshot.data.documents.forEach((doc) {
User user = User.fromDocument(doc);
searchResults.add(UserResult(user));
});
return ListView(
children: searchResults,
);
},
);
}
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return Scaffold(
backgroundColor: Theme.of(context).primaryColor.withOpacity(0.8),
appBar: buildSearchField(),
body:
searchResultsFuture == null ? buildNoContent() : buildSearchResults(),
);
}
}
class UserResult extends StatelessWidget {
final User user;
UserResult(this.user);
@override
Widget build(BuildContext context) {
return Container(
color: Theme.of(context).primaryColor.withOpacity(0.7),
child: Column(
children: <Widget>[
GestureDetector(
onTap: () => showProfile(context,profileId: user.id),
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey,
backgroundImage: CachedNetworkImageProvider(user.photoUrl),
),
title: Text(user.displayName,
style: TextStyle(
color: Colors.white, fontWeight: FontWeight.bold)),
subtitle: Text(
user.username ?? "",
style: TextStyle(color: Colors.white),
),
),
),
Divider(
height: 2.0,
color: Colors.white54,
)
],
),
);
}
showProfile(context, {String profileId})
{
Navigator.push(context, MaterialPageRoute(builder: (_) => Profile(profileId: profileId,)));
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/upload.dart
|
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:geolocator/geolocator.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:image/image.dart' as Im;
import 'package:uuid/uuid.dart';
class Upload extends StatefulWidget {
User currentUser;
Upload({this.currentUser});
@override
_UploadState createState() => _UploadState();
}
class _UploadState extends State<Upload> with AutomaticKeepAliveClientMixin<Upload> {
File file;
bool isLoading = false;
String postId = Uuid().v4();
TextEditingController captionController = TextEditingController();
TextEditingController locationController = TextEditingController();
handlePhotoFromCamera() async {
Navigator.pop(context);
File image = await ImagePicker.pickImage(
source: ImageSource.camera, maxHeight: 675, maxWidth: 900);
setState(() {
file = image;
});
}
handlePhotoFromGallery() async {
Navigator.pop(context);
File image = await ImagePicker.pickImage(
source: ImageSource.gallery, maxHeight: 675, maxWidth: 900);
setState(() {
file = image;
});
}
selectImage(BuildContext contextq) {
showDialog(
context: contextq,
builder: (ctx) {
return Padding(
padding: const EdgeInsets.all(30.0),
child: SimpleDialog(
title: Text("Create a Post"),
children: <Widget>[
SizedBox(
height: 20,
),
SimpleDialogOption(
child: Text(
"Photo with Camera ",
style: TextStyle(fontSize: 20),
),
onPressed: handlePhotoFromCamera,
),
SizedBox(
height: 20,
),
SimpleDialogOption(
child: Text(
"Image From Gallery ",
style: TextStyle(fontSize: 20),
),
onPressed: handlePhotoFromGallery,
),
SizedBox(
height: 20,
),
SimpleDialogOption(
child: Text(
"Cancel ",
style: TextStyle(fontSize: 20),
),
onPressed: () => Navigator.pop(context),
),
],
),
);
});
}
buildSplashScreen() {
return Container(
color: Theme.of(context).accentColor.withOpacity(0.6),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SvgPicture.asset("assets/images/upload.svg", height: 260),
Padding(
padding: EdgeInsets.only(top: 20),
child: RaisedButton(
onPressed: () => selectImage(context),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
child: Text(
"Upload",
style: TextStyle(fontSize: 22, color: Colors.white),
),
color: Colors.deepOrange,
),
)
],
),
);
}
clearImage() {
setState(() {
file = null;
});
}
compressImage() async {
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
Im.Image imageFile = Im.decodeImage(file.readAsBytesSync());
final compressedImage = File("$path/img_$postId.jpg")
..writeAsBytesSync(Im.encodeJpg(imageFile, quality: 85));
setState(() {
file = compressedImage;
});
}
Future<String> uploadImage() async {
StorageUploadTask uploadTask =
stoarageRef.child("post_$postId.jpg").putFile(file);
StorageTaskSnapshot storageSnap = await uploadTask.onComplete;
String downloadUrl = await storageSnap.ref.getDownloadURL();
return downloadUrl;
}
createPostInFireStore(String mediaUrl, String location, String description) {
postId = Uuid().v4();
postsRef
.document(widget.currentUser.id)
.collection("userPosts")
.document(postId)
.setData({
"postId": postId,
"ownerId": widget.currentUser.id,
"username": widget.currentUser.username,
"mediaUrl": mediaUrl,
"description": description,
"location": location,
"timestamp": timestamp,
"likes": {},
});
captionController.clear();
locationController.clear();
setState(() {
file=null;
isLoading =false;
});
}
handleSubmit() async {
print("Handle Submit");
setState(() {
isLoading = true;
});
await compressImage();
String mediaUrl = await uploadImage();
createPostInFireStore(
mediaUrl, locationController.text , captionController.text);
}
buildUploadForm() {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white70,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Colors.black,
),
onPressed: clearImage,
),
title: Text(
"Caption Post",
style: TextStyle(color: Colors.black),
),
actions: <Widget>[
FlatButton(
child: Text(
"POST",
style: TextStyle(
color: Colors.blueAccent,
fontWeight: FontWeight.bold,
fontSize: 20),
),
onPressed: isLoading ? null : () => handleSubmit(),
)
],
),
body: ListView(
children: <Widget>[
isLoading ? LinearProgressIndicator() : Text(""),
Container(
height: 220,
width: MediaQuery.of(context).size.width * 0.9,
child: Center(
// child: AspectRatio(
// aspectRatio: 11 / 9,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(file), fit: BoxFit.contain)),
),
// ),
),
),
SizedBox(
height: 10,
),
ListTile(
leading: CircleAvatar(
backgroundImage:
CachedNetworkImageProvider(widget.currentUser.photoUrl),
),
title: Container(
width: 250,
child: TextField(
controller: captionController,
decoration: InputDecoration(
hintText: "Enter Your Caption..", border: InputBorder.none),
),
),
),
Divider(),
ListTile(
leading: Icon(Icons.pin_drop, size: 35),
title: TextField(
controller: locationController,
decoration: InputDecoration(
hintText: "Where was this photo taken?",
border: InputBorder.none),
),
),
Container(
height: 100,
width: 200,
alignment: Alignment.center,
child: RaisedButton.icon(
color: Colors.blueAccent,
textColor: Colors.white,
onPressed: () => handleCurrentLocation(),
icon: Icon(Icons.my_location),
label: Text("Use My Current Location"),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
),
),
],
),
);
}
handleCurrentLocation() async
{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high,);
List<Placemark> placemarks = await Geolocator().placemarkFromCoordinates(position.latitude, position.longitude);
Placemark placemark = placemarks[0];
String formattedAddress = '${placemark.locality} , ${placemark.country}';
locationController.text = formattedAddress;
}
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
return file == null ? buildSplashScreen() : buildUploadForm();
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/home.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttershare/models/user.dart';
import 'package:fluttershare/pages/activity_feed.dart';
import 'package:fluttershare/pages/create_account.dart';
import 'package:fluttershare/pages/profile.dart';
import 'package:fluttershare/pages/search.dart';
import 'package:fluttershare/pages/timeline.dart';
import 'package:fluttershare/pages/upload.dart';
import 'package:google_sign_in/google_sign_in.dart';
final GoogleSignIn googleSignIn = GoogleSignIn();
final stoarageRef = FirebaseStorage.instance.ref();
final usersRef = Firestore.instance.collection('users');
final postsRef = Firestore.instance.collection('posts');
final commmentsRef = Firestore.instance.collection('comments');
final activityFeedRef = Firestore.instance.collection('feed');
final followersRef = Firestore.instance.collection('followers');
final followingRef = Firestore.instance.collection('following');
final timelineRef = Firestore.instance.collection('timeline');
final DateTime timestamp = DateTime.now();
User currentUser;
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
final scaffoldKey = GlobalKey<ScaffoldState>();
FirebaseMessaging firebaseMessaging = FirebaseMessaging();
bool isAuth = false;
PageController pageController;
int pageIndex = 0;
static int flag = 0;
@override
void initState() {
super.initState();
pageController = PageController();
// Detects when user signed in
googleSignIn.onCurrentUserChanged.listen((account) {
handleSignIn(account);
}, onError: (err) {
print('Error signing in: $err');
});
// Reauthenticate user when app is opened
googleSignIn.signInSilently(suppressErrors: false).then((account) {
handleSignIn(account);
}).catchError((err) {
print('Error signing in: $err');
});
}
handleSignIn(GoogleSignInAccount account) async {
if (account != null) {
await createUserInFirestore();
setState(() {
isAuth = true;
});
configurePushNotification();
} else {
setState(() {
isAuth = false;
});
}
}
configurePushNotification() {
final GoogleSignInAccount user = googleSignIn.currentUser;
firebaseMessaging.getToken().then((token) {
print(token);
usersRef
.document(user.id)
.updateData({"androidNotificationToken": token});
});
firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print("on message: $message");
final String recepientId = message["data"]["recipient"];
final String body = message["notification"]["body"];
//final String title = message["notification"]["title"];
if (recepientId == user.id) {
print("Notification Shown!");
SnackBar snackBar = SnackBar(
content: Text(
body,
overflow: TextOverflow.ellipsis,
));
scaffoldKey.currentState.showSnackBar(snackBar);
}
print("Notification not shown");
});
}
Future<void> createUserInFirestore() async {
// 1) check if user exists in users collection in database (according to their id)
final GoogleSignInAccount user = googleSignIn.currentUser;
DocumentSnapshot doc = await usersRef.document(user.id).get();
if (!doc.exists) {
// 2) if the user doesn't exist, then we want to take them to the create account page
String username;
// if (flag == 0) {
// flag = 1;
username = await Navigator.push(
context, MaterialPageRoute(builder: (context) => CreateAccount()));
//}
// 3) get username from create account, use it to make new user document in users collection
usersRef.document(user.id).setData({
"id": user.id,
"username": username,
"photoUrl": user.photoUrl,
"email": user.email,
"displayName": user.displayName,
"bio": "",
"timestamp": timestamp
});
//make the user his own followers so that his posts are included in the timeline
followersRef
.document(user.id)
.collection("userFollowers")
.document(user.id)
.setData({});
doc = await usersRef.document(user.id).get();
}
currentUser = User.fromDocument(doc);
}
@override
void dispose() {
pageController.dispose();
super.dispose();
}
login() {
googleSignIn.signIn();
}
logout() {
googleSignIn.signOut();
}
onPageChanged(int pageIndex) {
setState(() {
this.pageIndex = pageIndex;
});
}
onTap(int pageIndex) {
pageController.animateToPage(
pageIndex,
duration: Duration(milliseconds: 300),
curve: Curves.easeInOut,
);
}
Scaffold buildAuthScreen() {
return Scaffold(
body: PageView(
children: <Widget>[
Timeline(currentUser: currentUser.id),
ActivityFeed(),
Upload(currentUser: currentUser),
Search(),
Profile(profileId: currentUser?.id),
],
controller: pageController,
onPageChanged: onPageChanged,
physics: NeverScrollableScrollPhysics(),
),
bottomNavigationBar: CupertinoTabBar(
backgroundColor: Colors.white,
currentIndex: pageIndex,
onTap: onTap,
activeColor: Theme.of(context).primaryColor,
items: [
BottomNavigationBarItem(icon: Icon(Icons.whatshot)),
BottomNavigationBarItem(icon: Icon(Icons.notifications_active)),
BottomNavigationBarItem(
icon: Icon(
Icons.photo_camera,
size: 35.0,
),
),
BottomNavigationBarItem(icon: Icon(Icons.search)),
BottomNavigationBarItem(icon: Icon(Icons.account_circle)),
]),
);
// return RaisedButton(
// child: Text('Logout'),
// onPressed: logout,
// );
}
Scaffold buildUnAuthScreen() {
return Scaffold(
key: scaffoldKey,
body: Stack(
children: <Widget>[
Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topRight,
end: Alignment.bottomLeft,
colors: [
Theme.of(context).accentColor,
Theme.of(context).primaryColor,
],
),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'FlutterShare',
style: TextStyle(
fontFamily: "Signatra",
fontSize: 90.0,
color: Colors.white,
),
),
GestureDetector(
onTap: login,
child: Container(
width: 260.0,
height: 60.0,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(
'assets/images/google_signin_button.png',
),
fit: BoxFit.cover,
),
),
),
),
],
),
),
Positioned(
bottom: MediaQuery.of(context).size.height * 0.2,left: MediaQuery.of(context).size.width * 0.25,
child: Text("Powered By Malik Solutions"+'\u1d40'+'\u1d39', style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold)),
)
],
),
);
}
@override
Widget build(BuildContext context) {
return isAuth ? buildAuthScreen() : buildUnAuthScreen();
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/pages/activity_feed.dart
|
import 'package:cached_network_image/cached_network_image.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttershare/pages/home.dart';
import 'package:fluttershare/pages/post_screen.dart';
import 'package:fluttershare/pages/profile.dart';
import 'package:fluttershare/widgets/header.dart';
import 'package:timeago/timeago.dart' as timeago;
class ActivityFeed extends StatefulWidget {
@override
_ActivityFeedState createState() => _ActivityFeedState();
}
class _ActivityFeedState extends State<ActivityFeed> {
getActivityFeed() async {
QuerySnapshot snapshot = await activityFeedRef
.document(currentUser.id)
.collection("feedItems")
.orderBy("timestamp", descending: true)
.limit(50)
.getDocuments();
snapshot.documents.forEach((doc) {
print("every documents");
});
return snapshot.documents;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: header(context, titleText: "Activity Feed"),
body: Container(
child: FutureBuilder(
future: getActivityFeed(),
builder: (ctx, snapshot) {
if (!snapshot.hasData) {
return Center(child: CircularProgressIndicator());
}
List<ActivityFeedItem> activityFeedItems = [];
snapshot.data.forEach((doc) {
activityFeedItems.add(ActivityFeedItem.from(doc));
});
return ListView.builder(
itemCount: activityFeedItems.length,
itemBuilder: (ctx, index) => activityFeedItems[index]);
},
),
),
);
}
}
Widget mediaPreview;
String feedText;
class ActivityFeedItem extends StatelessWidget {
String username;
String comment;
Timestamp timestamp;
String avatarUrl; //
String mediaUrl; //
String userId; //
String type;
String postId;
ActivityFeedItem(this.username, this.comment, this.timestamp, this.avatarUrl,
this.userId, this.mediaUrl, this.type,this.postId);
factory ActivityFeedItem.from(doc) {
return ActivityFeedItem(
doc["username"],
doc["comment"],
doc["timestamp"],
doc["userProfileImg"],
doc["userId"],
doc["mediaUrl"],
doc["type"],
doc["postId"],
);
}
showPost(context)
{
Navigator.push(context, MaterialPageRoute(builder: (_)=>PostScreen(postId: postId,userId: userId,)));
}
configureMediaPreview(BuildContext context) {
if (type == "like" || type == "comment") {
mediaPreview = GestureDetector(
onTap: () => showPost(context),
child: Container(
height: 50,
width: 50,
child: AspectRatio(
aspectRatio: 16 / 9,
child: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: CachedNetworkImageProvider(mediaUrl),
fit: BoxFit.cover)),
),
),
),
);
} else {
mediaPreview = Text("");
}
if (type == 'like') {
feedText = " liked your post";
} else if (type == 'follow') {
feedText = ' is following you';
} else if (type == 'comment') {
feedText = ' replied: $comment';
} else {
feedText = " Error: type $type";
}
}
@override
Widget build(BuildContext context) {
configureMediaPreview(context);
return Padding(
padding: const EdgeInsets.only(bottom: 2.0),
child: Container(
color: Colors.white54,
child: ListTile(
leading: CircleAvatar(
backgroundColor: Colors.grey,
backgroundImage: CachedNetworkImageProvider(avatarUrl),
),
title: GestureDetector(
onTap: () => showProfile(context,profileId: userId),
child: RichText(
overflow: TextOverflow.ellipsis,
text: TextSpan(
style: TextStyle(fontSize: 14, color: Colors.black),
children: [
TextSpan(text: username,style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(text: "$feedText"),
]
),
),
),
subtitle: Text(timeago.format(timestamp.toDate())),
trailing: mediaPreview,
),
),
);
}
showProfile(context, {String profileId})
{
Navigator.push(context, MaterialPageRoute(builder: (_) => Profile(profileId: profileId,)));
}
}
| 0
|
mirrored_repositories/FlutterShare/lib
|
mirrored_repositories/FlutterShare/lib/models/user.dart
|
import 'package:cloud_firestore/cloud_firestore.dart';
class User
{
final String id;
final String email;
final String displayName;
final String photoUrl;
final String bio;
final String username;
User({this.id,this.email,this.displayName,this.photoUrl,this.bio,this.username});
factory User.fromDocument(DocumentSnapshot doc)
{
return User(
id: doc["id"],
email: doc["email"],
displayName: doc["displayName"],
photoUrl: doc["photoUrl"],
bio: doc["bio"],
username: doc["username"],
);
}
}
| 0
|
mirrored_repositories/flutter_intro_slider_screen
|
mirrored_repositories/flutter_intro_slider_screen/lib/intro_view.dart
|
import 'package:flutter/material.dart';
class IntroView extends StatefulWidget {
final List<Widget> pages;
final VoidCallback onIntroCompleted;
const IntroView({
Key key,
@required this.pages,
@required this.onIntroCompleted,
}) : assert(pages != null),
assert(onIntroCompleted != null),
super(key: key);
@override
_IntroViewState createState() => _IntroViewState();
}
class _IntroViewState extends State<IntroView> {
PageController _pageController;
int _currentPage = 0;
@override
void initState() {
_pageController = PageController(
initialPage: _currentPage,
);
super.initState();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
Future<bool> _onBackPressed() async {
if (_currentPage == 0) {
return true;
} else if (_currentPage == 1) {
setState(() {
_currentPage = 0;
_changePageItem();
});
} else if (_currentPage == 2) {
setState(() {
_currentPage = 1;
_changePageItem();
});
}
}
_changePageItem() {
_pageController.animateToPage(
_currentPage,
duration: const Duration(milliseconds: 600),
curve: Curves.ease,
);
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: _onBackPressed,
child: Stack(
children: <Widget>[
NotificationListener<ScrollEndNotification>(
onNotification: (x) {
setState(() {
_currentPage = _pageController.page.round();
});
return false;
},
child: PageView(
children: widget.pages,
controller: _pageController,
),
),
Align(
alignment: Alignment.bottomCenter,
child: _buildBottomButtons(),
),
],
),
);
}
bool get _isFinalPage => _currentPage == widget.pages.length - 1;
Widget _buildBottomButtons() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Opacity(
opacity: _isFinalPage ? 0.0 : 1.0,
child: _buildButton("SKIP", _gotoLastPage),
),
_buildNavIndicator(),
_isFinalPage
? _buildButton("DONE", widget.onIntroCompleted)
: _buildButton("NEXT", _gotoNextPage),
],
),
);
}
Widget _buildButton(String title, VoidCallback callback) {
return FlatButton(
child: Text(
title,
style: TextStyle(color: Colors.white),
),
onPressed: callback,
);
}
void _gotoLastPage() {
_pageController.animateToPage(
widget.pages.length - 1,
duration: const Duration(milliseconds: 600),
curve: Curves.ease,
);
}
void _gotoNextPage() {
_pageController.nextPage(
duration: const Duration(milliseconds: 600),
curve: Curves.easeInOut,
);
}
Widget _buildNavIndicator() {
final indicatorList = <Widget>[];
for (int i = 0; i < widget.pages.length; i++)
indicatorList.add(_buildIndicator(i == _currentPage));
return Row(children: indicatorList);
}
Widget _buildIndicator(bool isActive) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: DecoratedBox(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: isActive ? Colors.white : Colors.white30,
),
child: SizedBox(width: 8, height: 8),
),
);
}
}
| 0
|
mirrored_repositories/flutter_intro_slider_screen
|
mirrored_repositories/flutter_intro_slider_screen/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_intro_screen/intro_view.dart';
Future<void> main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return IntroView(
pages: <Widget>[
FlutterLogo(
colors: Colors.blue,
),
FlutterLogo(
colors: Colors.red,
),
FlutterLogo(
colors: Colors.purple,
),
],
onIntroCompleted: () {
print("Slider Into is Completed");
},
);
}
}
| 0
|
mirrored_repositories/flutter_intro_slider_screen
|
mirrored_repositories/flutter_intro_slider_screen/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:flutter_intro_screen/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/FlutterMobx
|
mirrored_repositories/FlutterMobx/lib/home_screen.dart
|
import 'package:email_validator/email_validator.dart';
import 'package:flutter/material.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
bool _buttonEnable = false;
void _nextStep(){
print("Botão ativado");
}
void _changeEmail(value){
print(value);
//recriando a tela
setState(() {
_buttonEnable = EmailValidator.validate(value);
});
}
@override
Widget build(BuildContext context) {
print("Desenhando a tela ..");
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Title(color: Colors.white, child:Text("Utilizando set State")),
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(25.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
onChanged: _changeEmail,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(labelText: "E-mail"),
enableSuggestions: false,
autocorrect: false,
),
Padding(padding: const EdgeInsets.all(8.0),
child: MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0)
),
minWidth: double.infinity,
height: 57.0,
child: Text(
'Continuar',
style: TextStyle(fontSize: 20.0),
),
onPressed: _buttonEnable ? _nextStep :null,
textColor: Colors.white,
color: Colors.blue,
disabledColor: Colors.grey,
))
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/FlutterMobx
|
mirrored_repositories/FlutterMobx/lib/home_screen_mobx.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_new_mobx/stores/email_store.dart';
class HomeScreenMobx extends StatelessWidget {
@override
Widget build(BuildContext context) {
final emailStore = EmailStore();
void _nextStep() {
print("Botão ativado");
}
print("Desenhando a tela ..");
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
title: Title(color: Colors.white, child: Text("Utilizando Mobx")),
),
body: Container(
child: Padding(
padding: const EdgeInsets.all(25.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
onChanged: emailStore.changeEmail,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(labelText: "E-mail"),
enableSuggestions: false,
autocorrect: false,
),
Observer(builder: (_) => materialButton(emailStore, _nextStep))
],
),
),
),
);
}
Padding materialButton(EmailStore emailStore, void _nextStep()) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(10.0)),
minWidth: double.infinity,
height: 57.0,
child: Text(
'Continuar',
style: TextStyle(fontSize: 20.0),
),
onPressed: emailStore.buttonEnable ? _nextStep : null,
textColor: Colors.white,
color: Colors.blue,
disabledColor: Colors.grey,
));
}
}
| 0
|
mirrored_repositories/FlutterMobx
|
mirrored_repositories/FlutterMobx/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_new_mobx/home_screen_mobx.dart';
import 'package:flutter_new_mobx/home_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
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: HomeScreenMobx(),
);
}
}
| 0
|
mirrored_repositories/FlutterMobx/lib
|
mirrored_repositories/FlutterMobx/lib/stores/email_store.dart
|
import 'package:email_validator/email_validator.dart';
import 'package:mobx/mobx.dart';
part 'email_store.g.dart';
class EmailStore = _EmailStore with _$EmailStore;
abstract class _EmailStore with Store{
@observable
bool buttonEnable = false;
@action
void changeEmail(value){
print(value);
buttonEnable = EmailValidator.validate(value);
}
}
| 0
|
mirrored_repositories/FlutterMobx/lib
|
mirrored_repositories/FlutterMobx/lib/stores/email_store.g.dart
|
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'email_store.dart';
// **************************************************************************
// StoreGenerator
// **************************************************************************
// ignore_for_file: non_constant_identifier_names, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic
mixin _$EmailStore on _EmailStore, Store {
final _$buttonEnableAtom = Atom(name: '_EmailStore.buttonEnable');
@override
bool get buttonEnable {
_$buttonEnableAtom.context.enforceReadPolicy(_$buttonEnableAtom);
_$buttonEnableAtom.reportObserved();
return super.buttonEnable;
}
@override
set buttonEnable(bool value) {
_$buttonEnableAtom.context.conditionallyRunInAction(() {
super.buttonEnable = value;
_$buttonEnableAtom.reportChanged();
}, _$buttonEnableAtom, name: '${_$buttonEnableAtom.name}_set');
}
final _$_EmailStoreActionController = ActionController(name: '_EmailStore');
@override
void changeEmail(dynamic value) {
final _$actionInfo = _$_EmailStoreActionController.startAction();
try {
return super.changeEmail(value);
} finally {
_$_EmailStoreActionController.endAction(_$actionInfo);
}
}
}
| 0
|
mirrored_repositories/FlutterMobx
|
mirrored_repositories/FlutterMobx/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:flutter_new_mobx/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/HandPicked_Shop
|
mirrored_repositories/HandPicked_Shop/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:handpicked_shop/view_screen/navbar/bootomNavBar.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "HandPicked",
debugShowCheckedModeBanner: false,
home: BottomNavBar(),
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/model/handPicked_model.dart
|
import 'package:flutter/material.dart';
class PickedData {
final String title;
final String siteName;
final Image image;
final int price;
PickedData({this.price, this.title, this.siteName, this.image});
}
List<PickedData> getPickedData = [
PickedData(
title: "40% OFF on Canon 1DX M2",
siteName: "beauty.com",
price: 2499,
image: Image.asset(
'assets/camera.jpg',
fit: BoxFit.cover,
),
),
PickedData(
title: "40% OFF on Skullcandy Bluetooth Headset ",
siteName: "headset_market.com",
price: 1200,
image: Image.asset(
'assets/headphone.jpg',
fit: BoxFit.cover,
),
),
// PickedData(
// title: "40% OFF on Canon 1DX M2",
// siteName: "beauty.com",
// price: 2499,
// image: Image.asset(
// '',
// fit: BoxFit.cover,
// ),
// ),
];
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/model/hotestDeal.dart
|
import 'package:flutter/material.dart';
class HottestDealModel {
final String title;
final Image image;
final int price;
final String discountPer;
HottestDealModel({this.discountPer, this.price, this.title, this.image});
}
List<HottestDealModel> getHottestDealModel = [
HottestDealModel(
title: "DJI Spark Fly Drone",
price: 596,
image: Image.asset(
'assets/drone.jpg',
fit: BoxFit.cover,
),
discountPer: "45% OFF"),
HottestDealModel(
title: "Converse Sneakers",
price: 99,
discountPer: "20% OFF",
image: Image.asset(
'assets/shoes.jpg',
fit: BoxFit.cover,
),
),
HottestDealModel(
title: "Samsung Galaxy S9",
price: 799,
image: Image.asset(
'assets/samsung.jpg',
fit: BoxFit.cover,
),
discountPer: "20% OFF"),
HottestDealModel(
title: "JBL Echo",
price: 69,
discountPer: "50% OFF",
image: Image.asset(
'assets/jbl.jpg',
fit: BoxFit.cover,
),
),
HottestDealModel(
title: "Business Laptop",
price: 596,
image: Image.asset(
'assets/laptop.jpg',
fit: BoxFit.cover,
),
discountPer: "15% OFF"),
HottestDealModel(
title: "Oculus Quest",
price: 490,
discountPer: "20% OFF",
image: Image.asset(
'assets/vr.jpg',
fit: BoxFit.cover,
),
),
];
| 0
|
mirrored_repositories/HandPicked_Shop/lib/view_screen
|
mirrored_repositories/HandPicked_Shop/lib/view_screen/navbar/bootomNavBar.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/helper/colors.dart';
import 'package:handpicked_shop/view_screen/screens/decks_hottestDeal.dart';
import 'package:handpicked_shop/view_screen/screens/homescreen.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:velocity_x/velocity_x.dart';
class BottomNavBar extends StatefulWidget {
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _value = 0;
List<Widget> _chil = [
HomeScreen(),
DecksHottestScreen(),
Center(
child: text('Loading Favs...'),
),
Center(
child: text('Loading Profile...'),
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
onTap: (val) {
_value = val;
setState(() {});
},
selectedItemColor: Vx.black,
unselectedItemColor: greyColor,
selectedIconTheme: IconThemeData(color: blueColor),
unselectedLabelStyle: TextStyle(color: greyColor),
type: BottomNavigationBarType.shifting,
currentIndex: _value,
items: [
BottomNavigationBarItem(
label: "Home",
icon: Icon(Icons.home),
),
BottomNavigationBarItem(
label: "decks",
icon: Icon(Icons.local_offer_rounded),
),
BottomNavigationBarItem(
label: "Favs",
icon: Icon(Icons.favorite),
),
BottomNavigationBarItem(
label: "Prof",
icon: Icon(Icons.person),
),
],
),
body: _chil[_value],
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib/view_screen
|
mirrored_repositories/HandPicked_Shop/lib/view_screen/screens/decks_hottestDeal.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:handpicked_shop/model/hotestDeal.dart';
import 'package:handpicked_shop/view_screen/screens/detail_decks_hottestDeal.dart';
import 'package:handpicked_shop/widget/appbar.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:velocity_x/velocity_x.dart';
class DecksHottestScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(
context,
title:
text("Hottest Deals", color: Vx.black, fontWeight: FontWeight.bold),
actions: [
Padding(
padding: EdgeInsets.only(
right: context.screenWidth * 0.04,
),
child: Icon(
Icons.notes,
color: Vx.black,
),
),
],
),
body: SingleChildScrollView(
physics: BouncingScrollPhysics(),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: context.screenWidth * 0.03,
vertical: context.screenHeight * 0.01),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
15.heightBox,
StaggeredGridView.countBuilder(
crossAxisCount: 2,
crossAxisSpacing: 15,
mainAxisSpacing: 15,
staggeredTileBuilder: (index) {
return StaggeredTile.count(1, index.isEven ? 1.2 : 1.8);
},
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemCount: getHottestDealModel.length,
itemBuilder: (_, index) {
var data = getHottestDealModel[index];
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => DetailDecksHottestDeal(
hottestDealModel: data,
),
),
);
},
child: buildStaggeredImageAndIntro(context, data),
);
}),
],
),
),
),
);
}
Widget buildStaggeredImageAndIntro(
BuildContext context, HottestDealModel data) {
return Container(
height: context.screenHeight * 0.6,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
height: context.screenHeight * 0.29,
width: context.screenWidth,
child: Hero(tag: "${data.title}", child: data.image)),
),
7.heightBox,
text(data.title),
7.heightBox,
Row(
mainAxisSize: MainAxisSize.min,
children: [
text(
"\$" + data.price.toString(),
fontWeight: FontWeight.bold,
size: context.textTheme.subtitle2.fontSize,
color: Vx.blue500,
),
7.widthBox,
text(
data.discountPer,
fontWeight: FontWeight.bold,
size: context.textTheme.subtitle2.fontSize,
color: Vx.gray300,
),
],
),
],
),
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib/view_screen
|
mirrored_repositories/HandPicked_Shop/lib/view_screen/screens/detail_homescreen.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/model/handPicked_model.dart';
import 'package:handpicked_shop/widget/elevatedbutton.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:velocity_x/velocity_x.dart';
class DetailHandPickedScreen extends StatelessWidget {
final PickedData pickedData;
const DetailHandPickedScreen({Key key, this.pickedData}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
buildStackImageIcon(context),
buildImageDetailAndButton(context),
],
),
),
),
);
}
Widget buildImageDetailAndButton(BuildContext context) {
return Container(
width: context.screenWidth,
transform: Matrix4.translationValues(0, -26, 0),
height: context.screenHeight * 0.4,
decoration: BoxDecoration(
color: Vx.white,
borderRadius: BorderRadius.circular(30),
),
child: Padding(
padding: EdgeInsets.symmetric(
vertical: context.screenHeight * 0.03,
horizontal: context.screenWidth * 0.03),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
text(pickedData.title,
size: context.textTheme.headline5.fontSize,
fontWeight: FontWeight.bold),
9.heightBox,
Row(
children: [
text("\$" + pickedData.price.toString(),
color: Vx.gray400,
size: context.textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
12.widthBox,
Icon(
Icons.star,
color: Vx.amber500,
),
2.widthBox,
text("4.9",
fontWeight: FontWeight.bold,
size: context.textTheme.headline6.fontSize,
color: Vx.gray300),
],
),
15.heightBox,
text(pickedData.siteName,
fontWeight: FontWeight.bold,
size: context.textTheme.headline6.fontSize,
color: Vx.gray500),
80.heightBox,
buildElevatedButton(context),
],
),
),
);
}
Widget buildStackImageIcon(BuildContext context) {
return Stack(
children: [
Container(
height: context.screenHeight * 0.6,
width: context.screenWidth,
child: Hero(tag: "${pickedData.title}", child: pickedData.image)),
Positioned(
child: IconButton(
icon: Icon(
Icons.arrow_back,
),
onPressed: () {
Navigator.pop(context);
}),
)
],
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib/view_screen
|
mirrored_repositories/HandPicked_Shop/lib/view_screen/screens/homescreen.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/helper/colors.dart';
import 'package:handpicked_shop/model/handPicked_model.dart';
import 'package:handpicked_shop/view_screen/screens/detail_homescreen.dart';
import 'package:handpicked_shop/view_screen/screens/bannerPost.dart';
import 'package:handpicked_shop/widget/appbar.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:handpicked_shop/widget/textfield.dart';
import 'package:velocity_x/velocity_x.dart';
class HomeScreen extends StatefulWidget {
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: buildAppBar(
context,
title: Row(
mainAxisSize: MainAxisSize.min,
children: [
text(
"Hand",
color: Vx.black,
),
text(
"Picked",
color: blueColor,
fontWeight: FontWeight.bold,
)
],
),
actions: [
Padding(
padding: EdgeInsets.only(
right: context.screenWidth * 0.04,
),
child: Icon(
Icons.notes,
color: Vx.black,
),
),
],
),
body: Padding(
padding: EdgeInsets.symmetric(
horizontal: context.screenWidth * 0.03,
vertical: context.screenHeight * 0.01),
child: ListView(
physics: BouncingScrollPhysics(),
children: [
BannerPost(),
18.heightBox,
buildTextField(),
18.heightBox,
buildListOFDetail(context),
],
),
),
);
}
Widget buildListOFDetail(BuildContext context) {
return Container(
height: context.screenHeight * 0.9,
child: ListView.builder(
physics: NeverScrollableScrollPhysics(),
itemCount: getPickedData.length,
itemBuilder: (_, index) {
return InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => DetailHandPickedScreen(
pickedData: getPickedData[index],
),
),
);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
height: context.screenHeight * 0.3,
width: context.screenWidth,
child: Hero(
tag: "${getPickedData[index].title}",
child: getPickedData[index].image)),
7.heightBox,
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: text(
getPickedData[index].title,
fontWeight: FontWeight.bold,
size: 18,
),
),
// 90.widthBox,
text(
"\$ " + getPickedData[index].price.toString(),
fontWeight: FontWeight.bold,
size: 18,
),
],
),
3.heightBox,
text(getPickedData[index].siteName, color: greyColor),
18.heightBox,
],
),
);
}),
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib/view_screen
|
mirrored_repositories/HandPicked_Shop/lib/view_screen/screens/detail_decks_hottestDeal.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/widget/elevatedbutton.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:velocity_x/velocity_x.dart';
import 'package:handpicked_shop/model/hotestDeal.dart';
class DetailDecksHottestDeal extends StatelessWidget {
final HottestDealModel hottestDealModel;
const DetailDecksHottestDeal({Key key, this.hottestDealModel})
: super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Stack(
children: [
buildImage(context),
Positioned(
child: IconButton(
icon: Icon(
Icons.arrow_back,
),
onPressed: () {
Navigator.pop(context);
}),
)
],
),
buildImageDetailInformationButton(context),
],
),
),
),
);
}
Widget buildImage(BuildContext context) {
return Container(
height: context.screenHeight * 0.6,
width: context.screenWidth,
child: Hero(
tag: "${hottestDealModel.title}", child: hottestDealModel.image));
}
Widget buildImageDetailInformationButton(BuildContext context) {
return Container(
width: context.screenWidth,
transform: Matrix4.translationValues(0, -26, 0),
height: context.screenHeight * 0.4,
decoration: BoxDecoration(
color: Vx.white,
borderRadius: BorderRadius.circular(30),
),
child: Padding(
padding: EdgeInsets.symmetric(
vertical: context.screenHeight * 0.03,
horizontal: context.screenWidth * 0.03),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
text(hottestDealModel.title,
size: context.textTheme.headline5.fontSize,
fontWeight: FontWeight.bold),
9.heightBox,
Row(
children: [
text("\$" + hottestDealModel.price.toString(),
color: Vx.gray400,
size: context.textTheme.headline6.fontSize,
fontWeight: FontWeight.bold),
19.widthBox,
text(hottestDealModel.discountPer,
fontWeight: FontWeight.bold,
size: context.textTheme.headline6.fontSize,
color: Vx.gray300),
12.widthBox,
Icon(
Icons.star,
color: Vx.amber500,
),
2.widthBox,
text("4.9",
fontWeight: FontWeight.bold,
size: context.textTheme.headline6.fontSize,
color: Vx.gray300),
],
),
35.heightBox,
Row(
children: [
buildOutlinedGenerated(context, name: "-"),
9.widthBox,
buildOutlinedGenerated(context, name: "1"),
9.widthBox,
buildOutlinedGenerated(context, name: "+"),
],
),
80.heightBox,
buildElevatedButton(context),
],
),
),
);
}
Widget buildOutlinedGenerated(BuildContext context, {String name}) {
return OutlinedButton(
style: OutlinedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
elevation: 8.0,
minimumSize:
Size(context.screenWidth * 0.13, context.screenHeight * 0.06),
backgroundColor: Vx.gray300),
onPressed: () {},
child: text(name, color: Vx.black),
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib/view_screen
|
mirrored_repositories/HandPicked_Shop/lib/view_screen/screens/bannerPost.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:velocity_x/velocity_x.dart';
class BannerPost extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
height: context.screenHeight * 0.26,
width: context.screenWidth,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(20)),
child: ListView(
scrollDirection: Axis.horizontal,
children: [
buildStackTYpe(
context,
background: Vx.red100,
assetImage: Image.asset(
"assets/bannerMobile.png",
fit: BoxFit.cover,
),
discountText: "Flat 15% OFF",
),
12.widthBox,
buildStackTYpe(
context,
background: Vx.blue200,
assetImage: Image.asset(
"assets/bannerheadphone.png",
fit: BoxFit.cover,
),
attentionText: "Best\nDeal".toUpperCase(),
productName: "on HeadPhone",
discountText: "Flat 20% OFF",
),
12.widthBox,
buildStackTYpe(
context,
background: Vx.cyan200,
assetImage: Image.asset(
"assets/bannerMobile.png",
fit: BoxFit.cover,
),
productName: "on Samsung",
discountText: "Flat 15% OFF",
),
],
),
);
}
Widget buildStackTYpe(BuildContext context,
{Color background,
Widget assetImage,
String attentionText,
String discountText,
String productName}) {
return Stack(
children: [
Container(
decoration: BoxDecoration(
color: background, borderRadius: BorderRadius.circular(20)),
height: context.screenHeight * 0.3,
width: context.screenWidth * 0.8,
),
Positioned(
top: context.screenHeight * 0.05,
right: context.screenWidth * 0.0,
child: Container(
width: context.screenWidth * 0.45,
child: assetImage,
),
),
Positioned(
top: context.screenHeight * 0.06,
left: context.screenWidth * 0.05,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
alignment: Alignment.center,
color: Vx.white,
width: context.screenWidth * 0.2,
child: text(
attentionText ?? "Best\nBuy".toUpperCase(),
size: context.textTheme.headline5.fontSize,
fontWeight: FontWeight.bold,
),
),
15.heightBox,
text(
discountText,
size: context.textTheme.headline5.fontSize,
fontWeight: FontWeight.bold,
),
text(
productName ?? "on Samsung",
color: Vx.gray400,
size: 17,
),
],
),
),
],
);
}
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/widget/text.dart
|
import 'package:flutter/material.dart';
Widget text(String text, {Color color, FontWeight fontWeight, double size}) {
return Text(
text,
style: TextStyle(
color: color,
fontSize: size,
fontWeight: fontWeight,
),
);
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/widget/appbar.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/helper/colors.dart';
Widget buildAppBar(BuildContext context, {Widget title, List<Widget> actions}) {
return AppBar(
backgroundColor: transparentColor,
elevation: 0,
title: title,
actions: actions);
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/widget/textfield.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/helper/colors.dart';
import 'package:velocity_x/velocity_x.dart';
Widget buildTextField() {
return TextField(
decoration: InputDecoration(
suffixIcon: IconButton(
icon: Icon(
Icons.search,
size: 30,
),
onPressed: () {
print('shsh');
},
),
hintText: "What are you looking for?",
hintStyle: TextStyle(color: greyColor),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(color: greyColor),
borderRadius: BorderRadius.circular(20),
),
enabledBorder: OutlineInputBorder(
borderSide: BorderSide(color: greyColor),
borderRadius: BorderRadius.circular(20),
),
fillColor: Vx.gray200,
filled: true,
),
);
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/widget/elevatedbutton.dart
|
import 'package:flutter/material.dart';
import 'package:handpicked_shop/helper/colors.dart';
import 'package:handpicked_shop/widget/text.dart';
import 'package:velocity_x/velocity_x.dart';
Widget buildElevatedButton(BuildContext context) {
return ElevatedButton(
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
primary: pinkAccentColor,
minimumSize:
Size(context.screenWidth * 0.99, context.screenHeight * 0.06),
),
onPressed: () {},
child: text('Add to Cart', size: context.textTheme.headline6.fontSize),
);
}
| 0
|
mirrored_repositories/HandPicked_Shop/lib
|
mirrored_repositories/HandPicked_Shop/lib/helper/colors.dart
|
import 'package:flutter/material.dart';
Color blueColor = Colors.blue;
Color transparentColor = Colors.transparent;
Color whiteColor = Colors.white;
Color greyColor = Colors.grey;
Color indigoColor = Colors.indigo;
Color pinkAccentColor = Colors.pinkAccent;
| 0
|
mirrored_repositories/HandPicked_Shop
|
mirrored_repositories/HandPicked_Shop/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:handpicked_shop/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/portfolio_with_flutter
|
mirrored_repositories/portfolio_with_flutter/lib/main.dart
|
import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'dart:math';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
// final customColor = Colors.teal;
// List<final> customColor = List<String>(3);
int number = 0;
int note = 1;
final List<Color> customColor = [
Colors.teal,
Colors.red,
Colors.yellow,
Colors.blue,
Colors.orange,
Colors.green,
Colors.purple,
Colors.pink,
Colors.brown,
Colors.black,
Colors.indigo
];
@override
Widget build(BuildContext context) {
void play(int a) {
final player = AudioPlayer();
player.play(AssetSource('note$a.wav'));
}
int checkSound(int a) {
if (a == 8) {
a = 1;
}
return a;
}
return MaterialApp(
home: Scaffold(
backgroundColor: customColor[number],
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InteractiveViewer(
boundaryMargin: EdgeInsets.all(42.0),
scaleEnabled: true,
child: MaterialButton(
onPressed: () {
print(number);
setState(() {
number = Random().nextInt(11);
note = checkSound(note);
play(note);
note++;
});
},
child: CircleAvatar(
//backgroundColor: Colors.red,
backgroundImage: AssetImage('images/profile.jpg'),
radius: 60.0,
),
),
),
InteractiveViewer(
boundaryMargin: EdgeInsets.all(200.0),
// minScale: 0.1,
// maxScale: 1.6,
child: MaterialButton(
padding: EdgeInsets.all(0.0),
onPressed: () {
print(number);
setState(() {
number = Random().nextInt(11);
note = checkSound(note);
play(note);
note++;
});
},
child: Text('Sagnik_Bhattacharya',
style: TextStyle(
fontFamily: 'Pacifico',
fontSize: 30.0,
letterSpacing: 1.5,
color: Colors.white,
fontWeight: FontWeight.bold,
)),
),
),
InteractiveViewer(
boundaryMargin: EdgeInsets.all(200.0),
child: Text('FLUTTER DEVELOPER',
style: TextStyle(
fontFamily: 'SourceSansPro',
fontSize: 20.0,
letterSpacing: 2.5,
color: Colors.teal[100],
fontWeight: FontWeight.bold,
)),
),
SizedBox(
height: 20.0,
width: 150.0,
child: Divider(
color: Colors.teal[100],
),
),
InteractiveViewer(
boundaryMargin: EdgeInsets.all(200.0),
child: MaterialButton(
onPressed: () {
print(number);
setState(() {
number = Random().nextInt(11);
note = checkSound(note);
play(note);
note++;
});
},
child: Card(
margin:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 0.0),
color: Colors.white,
child: ListTile(
leading: Icon(
Icons.phone,
color: Colors.teal.shade900,
),
title: Text(
'+91 9804 044 741',
style: TextStyle(
fontFamily: 'SourceSansPro',
fontWeight: FontWeight.bold,
fontSize: 22,
color: Colors.teal.shade800,
),
),
)),
),
),
InteractiveViewer(
boundaryMargin: EdgeInsets.all(200.0),
child: MaterialButton(
onPressed: () {
print(number);
setState(() {
number = Random().nextInt(11);
note = checkSound(note);
play(note);
note++;
});
},
child: Card(
margin:
EdgeInsets.symmetric(vertical: 10.0, horizontal: 0.0),
color: Colors.white,
child: ListTile(
leading: Icon(
Icons.email,
color: Colors.teal.shade900,
),
title: Text(
'sagnik@codingliquids.com',
style: TextStyle(
fontFamily: 'SourceSansPro',
fontWeight: FontWeight.bold,
fontSize: 18,
color: Colors.teal.shade800,
),
),
)),
),
)
],
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Profile-UI
|
mirrored_repositories/Flutter-Profile-UI/lib/main.dart
|
//import 'dart:html';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Profile(),
theme: ThemeData(fontFamily: 'Poppins'),
));
}
class Profile extends StatefulWidget {
@override
_ProfileState createState() => _ProfileState();
}
class _ProfileState extends State<Profile> {
int counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: (){
setState(() {
counter = counter + 1;
});
},
child: Container(
width: 60,
height: 60,
child: Icon(
Icons.add
),
decoration: BoxDecoration(
shape: BoxShape.circle,
gradient: LinearGradient(
colors: [Colors.deepPurple[800],Colors.deepPurpleAccent],)),
),
),
body: Stack(
children: [
Column(
children: [
Expanded(
flex:5,
child:Container(
width: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.deepPurple[800],Colors.deepPurpleAccent],
),
),
child: Column(
children: [
SizedBox(height: 110.0,),
CircleAvatar(
radius: 65.0,
backgroundImage: AssetImage('assets/erza.jpg'),
backgroundColor: Colors.white,
),
SizedBox(height: 10.0,),
Text('Erza Scarlet',
style: TextStyle(
color:Colors.white,
fontSize: 20.0,
)),
SizedBox(height: 10.0,),
Text('S Class Mage',
style: TextStyle(
color:Colors.white,
fontSize: 15.0,
),)
]
),
),
),
Expanded(
flex:5,
child: Container(
color: Colors.grey[200],
child: Center(
child:Card(
margin: EdgeInsets.fromLTRB(0.0, 45.0, 0.0, 0.0),
child: Container(
width: 310.0,
height:290.0,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Information",
style: TextStyle(
fontSize: 17.0,
fontWeight: FontWeight.w800,
),),
Divider(color: Colors.grey[300],),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Icon(
Icons.home,
color: Colors.blueAccent[400],
size: 35,
),
SizedBox(width: 20.0,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Guild",
style: TextStyle(
fontSize: 15.0,
),),
Text("FairyTail, Magnolia",
style: TextStyle(
fontSize: 12.0,
color: Colors.grey[400],
),)
],
)
],
),
SizedBox(height: 20.0,),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Icon(
Icons.auto_awesome,
color: Colors.yellowAccent[400],
size: 35,
),
SizedBox(width: 20.0,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Magic",
style: TextStyle(
fontSize: 15.0,
),),
Text("Spatial & Sword Magic, Telekinesis",
style: TextStyle(
fontSize: 12.0,
color: Colors.grey[400],
),)
],
)
],
),
SizedBox(height: 20.0,),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Icon(
Icons.favorite,
color: Colors.pinkAccent[400],
size: 35,
),
SizedBox(width: 20.0,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Loves",
style: TextStyle(
fontSize: 15.0,
),),
Text("Eating cakes",
style: TextStyle(
fontSize: 12.0,
color: Colors.grey[400],
),)
],
)
],
),
SizedBox(height: 20.0,),
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Icon(
Icons.people,
color: Colors.lightGreen[400],
size: 35,
),
SizedBox(width: 20.0,),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text("Team",
style: TextStyle(
fontSize: 15.0,
),),
Text("Team Natsu",
style: TextStyle(
fontSize: 12.0,
color: Colors.grey[400],
),)
],
)
],
),
],
),
)
)
)
),
),
),
],
),
Positioned(
top:MediaQuery.of(context).size.height*0.45,
left: 20.0,
right: 20.0,
child: Card(
child: Padding(
padding:EdgeInsets.all(16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Container(
child:Column(
children: [
Text('Battles',
style: TextStyle(
color: Colors.grey[400],
fontSize: 14.0
),),
SizedBox(height: 5.0,),
Text("$counter",
style: TextStyle(
fontSize: 15.0,
),)
],
)
),
Container(
child: Column(
children: [
Text('Birthday',
style: TextStyle(
color: Colors.grey[400],
fontSize: 14.0
),),
SizedBox(height: 5.0,),
Text('April 7th',
style: TextStyle(
fontSize: 15.0,
),)
]),
),
Container(
child:Column(
children: [
Text('Age',
style: TextStyle(
color: Colors.grey[400],
fontSize: 14.0
),),
SizedBox(height: 5.0,),
Text('19 yrs',
style: TextStyle(
fontSize: 15.0,
),)
],
)
),
],
),
)
)
)
],
),
);
}
}
| 0
|
mirrored_repositories/smart_home
|
mirrored_repositories/smart_home/lib/main.dart
|
import 'package:flutter/material.dart';
import 'home/home_page.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 const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
| 0
|
mirrored_repositories/smart_home/lib
|
mirrored_repositories/smart_home/lib/util/smart_device_box.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class SmartDeviceBox extends StatelessWidget {
final String smartDeviceName;
final String iconPath;
final bool powerOn;
final void Function(bool)? onChanged;
const SmartDeviceBox({
super.key,
required this.smartDeviceName,
required this.iconPath,
required this.powerOn,
required this.onChanged,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(15.0),
child: Container(
decoration: BoxDecoration(
color: powerOn ? Colors.grey[900] : Colors.grey[300],
borderRadius: BorderRadius.circular(24),
),
padding: const EdgeInsets.symmetric(vertical: 25),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
//icon
Image.asset(
iconPath,
height: 45,
color: powerOn ? Colors.white : Colors.black,
),
//smart device name + switch
Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(left: 25),
child: Text(
smartDeviceName,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
color: powerOn ? Colors.white : Colors.black),
),
),
),
RotatedBox(
quarterTurns: 1,
child: CupertinoSwitch(
value: powerOn,
onChanged: onChanged,
),
)
],
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/smart_home/lib
|
mirrored_repositories/smart_home/lib/home/home_page.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:smart_home/util/smart_device_box.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//padding constants
final double horizontalPadding = 25;
final double verticalPadding = 10;
//list of smart devices
List mySmartDevices = [
//[smartDeviceName, iconPath, powerStatus]
['Smart Light', 'assets/icons/light-bulb.png', true],
['Smart AC', 'assets/icons/air-conditioner.png', false],
['Smart TV', 'assets/icons/smart-tv.png', false],
['Smart Fan', 'assets/icons/fan.png', false],
];
//power button switched
void powerSwitchChanged(bool value, int index) {
setState(
() {
mySmartDevices[index][2] = value;
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[200],
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
//custom app bar
Padding(
padding: EdgeInsets.symmetric(
horizontal: horizontalPadding, vertical: verticalPadding),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
//menu icon
Image.asset(
'assets/icons/menu.png',
height: 35,
),
//account icon
const Icon(Icons.person, size: 35),
],
),
),
const SizedBox(
height: 20,
),
//Welcome home Creflo
Padding(
padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Welcome Home',
style: TextStyle(
fontSize: 20,
color: Colors.grey[700],
),
),
Text(
'CREFLO BARAK',
style: GoogleFonts.bebasNeue(
fontSize: 60,
),
),
],
),
),
const SizedBox(height: 25),
Padding(
padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
child: Divider(
color: Colors.grey[350],
thickness: 1,
),
),
const SizedBox(height: 25),
//smart devices + grid
Padding(
padding: EdgeInsets.symmetric(horizontal: horizontalPadding),
child: const Text(
'Smart Devices',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: GridView.builder(
itemCount: mySmartDevices.length,
physics: const NeverScrollableScrollPhysics(),
padding: const EdgeInsets.all(25),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 1 / 1.3,
),
itemBuilder: (context, index) {
return SmartDeviceBox(
smartDeviceName: mySmartDevices[index][0],
iconPath: mySmartDevices[index][1],
powerOn: mySmartDevices[index][2],
onChanged: (value) => powerSwitchChanged(value, index),
);
},
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/smart_home
|
mirrored_repositories/smart_home/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:smart_home/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/MM-Calculator-Flutter
|
mirrored_repositories/MM-Calculator-Flutter/lib/mmcalculator.dart
|
import 'package:flutter/material.dart';
class MMcalculator extends StatefulWidget {
const MMcalculator({Key? key}) : super(key: key);
@override
State<MMcalculator> createState() => _MMcalculatorState();
}
class _MMcalculatorState extends State<MMcalculator> {
String num1 = "";
String num2 = "";
String operator = "";
String result = "";
String equals = "";
bool isonnum1 = true;
void operation(String title) {
if (title == "del") {
num1 = "";
num2 = "";
operator = "";
result = "";
isonnum1 = true;
equals = "";
}
else if (title == "=") {
equals = "=";
if (num1.isEmpty) {
num1 = "0";
}
if (num2.isEmpty) {
num2 = "0";
}
if (operator.isEmpty) {
operator = "+";
}
int number1 = int.parse(num1);
int number2 = int.parse(num2);
int answer = 0;
if (operator == "+") {
answer = number1 + number2;
} else if (operator == "-") {
answer = number1 - number2;
} else if (operator == "/") {
if (number2 == 0) {
number2 = 1;
}
answer = (number1 / number2) as int;
} else if (operator == "*") {
answer = number1 * number2;
}
result = answer.toString();
} else if (title == "+" || title == "-" || title == "*" || title == "/") {
operator = title;
isonnum1 = false;
} else {
if (isonnum1) {
if(num1.length < 9) {
num1 += title;
}
}
else {
if (num2.length < 9) {
num2 += title;
}
}
}
setState(() {});
}
Widget button(String title) {
return GestureDetector(
onTap: () {
print(title);
operation(title);
},
child: Container(
width: MediaQuery.of(context).size.width / 4 - 10,
height: MediaQuery.of(context).size.height / 8 - 10,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.3),
spreadRadius: 2,
blurRadius: 2,
offset: const Offset(0, 3),
),
],
color: const Color(0xff123456),
borderRadius: const BorderRadius.all(
Radius.circular(10.0),
),
),
margin: const EdgeInsets.symmetric(horizontal: 5, vertical: 5),
child: Center(
child: Text(
title,
style: const TextStyle(fontSize: 25, color: Colors.white),
),
),
),
);
}
Widget buttonrow(List<String> titles) {
return Row(
children: [
button(titles[0]),
button(titles[1]),
button(titles[2]),
button(titles[3]),
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: Center(
child: Text('MMCalculator', style: TextStyle(shadows: [
Shadow(
color: Colors.black.withOpacity(0.3),
offset: const Offset(1, 2),
blurRadius: 15
),
]),),
),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(
bottom: Radius.circular(20),
),
),
),
body: Column(
children: [
Container(
color: Colors.white,
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height / 2 - 80,
child: Center(
child: Wrap(children: [
Text(
num1,
style: const TextStyle(fontSize: 55.0),
),
Text(
operator,
style: const TextStyle(fontSize: 55.0),
),
Text(
num2,
style: const TextStyle(fontSize: 55.0),
),
Text(
equals,
style: const TextStyle(fontSize: 55.0),
),
Text(
result,
style: const TextStyle(fontSize: 55.0),
)
]),
)),
Container(
decoration: const BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20.0),
topRight: Radius.circular(21.0),
),
),
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height / 2,
child: Column(children: [
buttonrow(["7", "8", "9", "/"]),
buttonrow(["4", "5", "6", "*"]),
buttonrow(["1", "2", "3", "-"]),
buttonrow(["del", "0", "=", "+"]),
]))
],
),
);
}
}
| 0
|
mirrored_repositories/MM-Calculator-Flutter
|
mirrored_repositories/MM-Calculator-Flutter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:mm_test/mmcalculator.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: MMcalculator()
);
}
}
| 0
|
mirrored_repositories/MM-Calculator-Flutter
|
mirrored_repositories/MM-Calculator-Flutter/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mm_test/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Flutter Tab Bar
|
mirrored_repositories/Flutter-Practice-Projects/Flutter Tab Bar/lib/main.dart
|
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TabBar Demo',
theme: ThemeData(
primarySwatch: Colors.grey,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'TabBar Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: AppBar(
bottom: TabBar(
indicatorColor: Colors.amberAccent,
// indicatorSize: TabBarIndicatorSize.label,
// indicatorWeight: 10,
indicator: BoxDecoration(
borderRadius: BorderRadius.circular(50), // Creates border
color: Colors.greenAccent),
tabs: [
Tab(icon: Icon(Icons.flight)),
Tab(icon: Icon(Icons.directions_transit)),
Tab(icon: Icon(Icons.directions_car)),
],
),
title: Center(child: Text('Tabs Demo')),
),
body: TabBarView(
children: [
Icon(Icons.flight, size: 350),
Icon(Icons.directions_transit, size: 350),
Icon(Icons.directions_car, size: 350),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Flutter Tab Bar
|
mirrored_repositories/Flutter-Practice-Projects/Flutter Tab Bar/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:flutter_tabbar/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-Practice-Projects/BLoC Pattern
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern/lib/counterEvent.dart
|
abstract class CounterEvent {}
class IncrementEvent extends CounterEvent {}
class DecrementEvent extends CounterEvent {}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern/lib/counter_bloc.dart
|
import 'dart:async';
import 'package:project001/counterEvent.dart';
class CounterBloc {
int _counter = 0;
final _counterStateController = StreamController<int>();
StreamSink<int> get _inCounter => _counterStateController.sink;
Stream<int> get counter => _counterStateController.stream;
final _counterEventController = StreamController<CounterEvent>();
Sink<CounterEvent> get counterEventSink => _counterEventController.sink;
CounterBloc() {
_counterEventController.stream.listen(_mapEventToState);
}
void _mapEventToState(CounterEvent event) {
if (event is IncrementEvent)
_counter++;
else
_counter--;
_inCounter.add(_counter);
}
void dispose() {
_counterStateController.close();
_counterEventController.close();
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/counterEvent.dart';
import 'package:project001/counter_bloc.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final _bloc = CounterBloc();
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Center(
child: StreamBuilder(
stream: _bloc.counter,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'you have pressed button ${snapshot.data} times',
style: Theme.of(context).textTheme.bodyText1,
),
],
);
},
),
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () => _bloc.counterEventSink.add(IncrementEvent()),
tooltip: 'Increment',
child: Icon(Icons.add),
),
SizedBox(
width: 10,
),
FloatingActionButton(
onPressed: () => _bloc.counterEventSink.add(DecrementEvent()),
tooltip: 'Decrement',
child: Icon(Icons.remove),
),
],
),
);
}
@override
void dispose() {
super.dispose();
_bloc.dispose();
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern
|
mirrored_repositories/Flutter-Practice-Projects/BLoC Pattern/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:project001/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-Practice-Projects/flutter_credit_card_view_demo
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo/lib/credit_card_page.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_credit_card/credit_card_form.dart';
import 'package:flutter_credit_card/credit_card_model.dart';
import 'package:flutter_credit_card/flutter_credit_card.dart';
class CreditCardPage extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return CreditCardPageState();
}
}
class CreditCardPageState extends State<CreditCardPage> {
String cardNumber = '';
String expiryDate = '';
String cardHolderName = '';
String cvvCode = '';
bool isCvvFocused = false;
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal[50],
appBar: AppBar(
automaticallyImplyLeading: false,
title: Text('Flutter Credit Card View Demo'),
),
resizeToAvoidBottomInset: true,
body: SafeArea(
child: Column(
children: <Widget>[
CreditCardWidget(
cardBgColor: Colors.redAccent[200],
cardNumber: cardNumber,
expiryDate: expiryDate,
cardHolderName: cardHolderName,
cvvCode: cvvCode,
showBackView: isCvvFocused,
obscureCardNumber: true,
obscureCardCvv: true,
),
Expanded(
child: SingleChildScrollView(
child: Column(
children: [
CreditCardForm(
formKey: formKey,
onCreditCardModelChange: onCreditCardModelChange,
obscureCvv: true,
obscureNumber: true,
cardNumberDecoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Number',
hintText: 'XXXX XXXX XXXX XXXX',
),
expiryDateDecoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Expired Date',
hintText: 'XX/XX',
),
cvvCodeDecoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'CVV',
hintText: 'XXX',
),
cardHolderDecoration: const InputDecoration(
border: OutlineInputBorder(),
labelText: 'Card Holder Name',
),
),
SizedBox(height: 20,),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8.0),
),
child: Container(
margin: const EdgeInsets.all(8),
child: const Text(
'Validate',
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
),
),
color: const Color(0xff1b447b),
onPressed: () {
if (formKey.currentState.validate()) {
print('valid!');
_showValidDialog(context,"Valid","Your card successfully valid !!!");
} else {
print('invalid!');
}
},
)
],
),
),
),
],
),
),
);
}
Future <AlertDialog> _showValidDialog(BuildContext context, String title, String content,) {
showDialog<AlertDialog>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
backgroundColor: Color(0xff1b447b),
title: Text(title),
content: Text(content),
actions: [
FlatButton(
child: Text(
"Ok",
style: TextStyle(fontSize: 18,color: Colors.cyan),
),
onPressed: () {
Navigator.of(context).pop();
}),
],
);
},
);
}
void onCreditCardModelChange(CreditCardModel creditCardModel) {
setState(() {
cardNumber = creditCardModel.cardNumber;
expiryDate = creditCardModel.expiryDate;
cardHolderName = creditCardModel.cardHolderName;
cvvCode = creditCardModel.cvvCode;
isCvvFocused = creditCardModel.isCvvFocused;
});
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter_credit_card_view_demo/splash_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData.dark(),
home: Splash(),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo/lib/splash_page.dart
|
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_credit_card_view_demo/credit_card_page.dart';
class Splash extends StatefulWidget {
@override
VideoState createState() => VideoState();
}
class VideoState extends State<Splash> with SingleTickerProviderStateMixin{
var _visible = true;
AnimationController animationController;
Animation<double> animation;
startTime() async {
var _duration = new Duration(seconds: 2);
return new Timer(_duration, navigationPage);
}
void navigationPage() {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => CreditCardPage()));
}
@override
void initState() {
super.initState();
animationController = new AnimationController(
vsync: this, duration: new Duration(seconds: 1));
animation =
new CurvedAnimation(parent: animationController, curve: Curves.easeOut);
animation.addListener(() => this.setState(() {}));
animationController.forward();
setState(() {
_visible = !_visible;
});
startTime();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
fit: StackFit.expand,
children: <Widget>[
new Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(padding: EdgeInsets.only(bottom: 30.0),child:new Image.asset('assets/images/powered_by.png',height: 25.0,fit: BoxFit.scaleDown,))
],),
new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Image.asset(
'assets/images/devs.jpg',
width: animation.value * 250,
height: animation.value * 250,
),
],
),
],
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo
|
mirrored_repositories/Flutter-Practice-Projects/flutter_credit_card_view_demo/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:flutter_credit_card_view_demo/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-Practice-Projects/Settings Button (Popup Menu Button)
|
mirrored_repositories/Flutter-Practice-Projects/Settings Button (Popup Menu Button)/lib/constants.dart
|
class Constants {
static const String Subscribe = 'Subscribe';
static const String Settings = 'settings';
static const String SignOut = 'Sign Out';
static const List<String> choices = <String>[Subscribe, Settings, SignOut];
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Settings Button (Popup Menu Button)
|
mirrored_repositories/Flutter-Practice-Projects/Settings Button (Popup Menu Button)/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/constants.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: [
PopupMenuButton<String>(
onSelected: choiseAction,
itemBuilder: (BuildContext context) {
return Constants.choices.map((String choice) {
return PopupMenuItem<String>(
value: choice,
child: Text(choice),
);
}).toList();
},
)
],
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Text(
'Body',
),
],
),
),
);
}
void choiseAction(String choice) {
if (choice == Constants.Settings) {
print('settings');
} else if (choice == Constants.Subscribe) {
print('Subscribe');
} else if (choice == Constants.SignOut) {
print('SignOut');
}
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Settings Button (Popup Menu Button)
|
mirrored_repositories/Flutter-Practice-Projects/Settings Button (Popup Menu Button)/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:project001/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-Practice-Projects/State Management using Scoped Model
|
mirrored_repositories/Flutter-Practice-Projects/State Management using Scoped Model/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/models/user.dart';
import 'package:scoped_model/scoped_model.dart';
void main() => runApp(new MyApp(
user: User(),
));
class MyApp extends StatelessWidget {
final User user;
const MyApp({Key key, this.user}) : super(key: key);
@override
Widget build(BuildContext context) {
return ScopedModel<User>(
model: user,
child: new MaterialApp(
title: 'Flutter Stepper Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Stepper Tutorial'),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: Center(
child: ScopedModelDescendant<User>(
builder: (context, child, model) {
return Text(
model.name,
style: Theme.of(context).textTheme.title,
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => Navigator.push(
context, MaterialPageRoute(builder: (context) => ChangeNamePage())),
child: Icon(Icons.navigate_next),
),
);
}
}
class ChangeNamePage extends StatefulWidget {
@override
ChangeNamePageState createState() {
return new ChangeNamePageState();
}
}
class ChangeNamePageState extends State<ChangeNamePage> {
final TextEditingController _nameController = TextEditingController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Padding(
padding: EdgeInsets.all(8.0),
child: ScopedModelDescendant<User>(
builder: (context, child, model) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextField(
controller: _nameController,
decoration: InputDecoration(labelText: model.name),
),
RaisedButton(
onPressed: () {
model.changeName(_nameController.text);
setState(() {
_nameController.text = '';
});
Scaffold.of(context).showSnackBar(SnackBar(
content: Text('name chaanged to ${model.name}'),
));
},
child: Text('change name'),
),
],
);
},
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/State Management using Scoped Model/lib
|
mirrored_repositories/Flutter-Practice-Projects/State Management using Scoped Model/lib/models/user.dart
|
import 'package:scoped_model/scoped_model.dart';
class User extends Model {
String _name = 'satyam goyal';
String get name => _name;
void changeName(String name) {
this._name = name;
notifyListeners();
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/State Management using Scoped Model
|
mirrored_repositories/Flutter-Practice-Projects/State Management using Scoped Model/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:project001/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-Practice-Projects/Stepper
|
mirrored_repositories/Flutter-Practice-Projects/Stepper/lib/main.dart
|
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _currentstep = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stepper(
steps: _mySteps(),
currentStep: this._currentstep,
onStepTapped: (step) {
setState(() {
this._currentstep = step;
});
},
onStepContinue: () {
setState(() {
if (this._currentstep < this._mySteps().length - 1) {
this._currentstep = this._currentstep + 1;
} else {
// logic to check if everything is completed
print('completed');
}
});
},
onStepCancel: () {
setState(() {
if (this._currentstep > 0) {
this._currentstep = this._currentstep - 1;
} else {
this._currentstep = 0;
}
});
},
),
);
}
List<Step> _mySteps() {
List<Step> _steps = [
Step(
title: Text('Step 1'),
content: TextField(),
isActive: _currentstep >= 0,
),
Step(
title: Text('Step 2'),
content: TextField(),
isActive: _currentstep >= 1,
),
Step(
title: Text('Step 3'),
content: TextField(),
isActive: _currentstep >= 2,
),
];
return _steps;
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Stepper
|
mirrored_repositories/Flutter-Practice-Projects/Stepper/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:project001/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-Practice-Projects/Tablet & Phone layout - Orientation Tutorial
|
mirrored_repositories/Flutter-Practice-Projects/Tablet & Phone layout - Orientation Tutorial/lib/main.dart
|
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
final double shortestSide = MediaQuery.of(context).size.shortestSide;
final bool useMobileLayout = shortestSide < 600;
final Orientation orientation = MediaQuery.of(context).orientation;
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: useMobileLayout
? buildPhoneGridView(orientation: orientation)
: buildTabletGridView(orientation: orientation),
);
}
GridView buildPhoneGridView({@required Orientation orientation}) {
return GridView.count(
crossAxisCount: orientation == Orientation.portrait ? 2 : 3,
children: List.generate(100, (index) {
return Card(
child: Container(
alignment: Alignment.center,
color: Colors.teal[100 * (index % 9)],
child: new Text('grid item $index'),
),
);
}),
);
}
GridView buildTabletGridView({@required Orientation orientation}) {
return GridView.count(
crossAxisCount: orientation == Orientation.portrait ? 4 : 5,
children: List.generate(100, (index) {
return Card(
child: Container(
alignment: Alignment.center,
color: Colors.teal[100 * (index % 9)],
child: new Text('grid item $index'),
),
);
}),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Tablet & Phone layout - Orientation Tutorial
|
mirrored_repositories/Flutter-Practice-Projects/Tablet & Phone layout - Orientation Tutorial/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:project001/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-Practice-Projects/Dialogs for waiting, confirmation and information
|
mirrored_repositories/Flutter-Practice-Projects/Dialogs for waiting, confirmation and information/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/dialogs.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Dialogs dialogs = new Dialogs();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: () {
dialogs.information(
context, 'This is project 001', 'description');
},
child: Text('Information Dialog'),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: () async {
dialogs.waiting(
context, 'This is project 001', 'description');
await Future.delayed(Duration(seconds: 2));
Navigator.pop(context);
},
child: Text('Waiting Dialog'),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: () {
dialogs.confirm(
context, 'This is project 001', 'description');
},
child: Text('Confirm Dialog'),
)
],
)
],
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Dialogs for waiting, confirmation and information
|
mirrored_repositories/Flutter-Practice-Projects/Dialogs for waiting, confirmation and information/lib/dialogs.dart
|
import 'package:flutter/material.dart';
class Dialogs {
information(BuildContext context, String title, String description) {
return showDialog(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: [Text(description)],
),
),
actions: [
FlatButton(
onPressed: () => Navigator.pop(context),
child: Text("OK"),
)
],
);
});
}
waiting(BuildContext context, String title, String description) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: [Text(description)],
),
),
);
});
}
_confirmResult(bool isYes, BuildContext context) {
if (isYes == true) {
print('yes action');
Navigator.pop(context);
} else {
print('Cancel action');
Navigator.pop(context);
}
}
confirm(BuildContext context, String title, String description) {
return showDialog(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: [Text(description)],
),
),
actions: [
FlatButton(
onPressed: () => _confirmResult(false, context),
child: Text("Cancel"),
),
FlatButton(
onPressed: () => _confirmResult(true, context),
child: Text("Yes"),
)
],
);
});
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Dialogs for waiting, confirmation and information
|
mirrored_repositories/Flutter-Practice-Projects/Dialogs for waiting, confirmation and information/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:project001/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-Practice-Projects/Background Design CustomPaint
|
mirrored_repositories/Flutter-Practice-Projects/Background Design CustomPaint/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/home.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Background Design CustomPaint
|
mirrored_repositories/Flutter-Practice-Projects/Background Design CustomPaint/lib/home.dart
|
import 'package:flutter/material.dart';
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomPaint(
painter: BluePainter(),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
class BluePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final height = size.height;
final width = size.width;
Paint paint = Paint();
Path mainBackground = Path();
mainBackground.addRect(Rect.fromLTRB(0, 0, width, height));
paint.color = Colors.blue.shade700;
canvas.drawPath(mainBackground, paint);
Path ovalPath = Path();
// Start paint from 20% height to the left
ovalPath.moveTo(0, height * 0.2);
// paint a curve from current position to middle of the screen
ovalPath.quadraticBezierTo(
width * 0.45, height * 0.25, width * 0.51, height * 0.5);
// Paint a curve from current position to bottom left of screen at width * 0.1
ovalPath.quadraticBezierTo(width * 0.58, height * 0.8, width * 0.1, height);
// draw remaining line to bottom left side
ovalPath.lineTo(0, height);
// Close line to reset it back
ovalPath.close();
paint.color = Colors.blue.shade600;
canvas.drawPath(ovalPath, paint);
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return oldDelegate != this;
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Background Design CustomPaint
|
mirrored_repositories/Flutter-Practice-Projects/Background Design CustomPaint/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:project001/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-Practice-Projects/3D Clock With Dark and Light Theme
|
mirrored_repositories/Flutter-Practice-Projects/3D Clock With Dark and Light Theme/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:image_view_3d/screen/clock.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Pinged",
debugShowCheckedModeBanner: false,
home: Clock(),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/3D Clock With Dark and Light Theme/lib
|
mirrored_repositories/Flutter-Practice-Projects/3D Clock With Dark and Light Theme/lib/screen/clock.dart
|
import 'package:analog_clock/analog_clock.dart';
import 'package:flutter/material.dart';
import 'package:day_night_switch/day_night_switch.dart';
class Clock extends StatefulWidget {
@override
_ClockState createState() => _ClockState();
}
class _ClockState extends State<Clock> {
bool value = false;
@override
Widget build(BuildContext context) {
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;
return SafeArea(
child: Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: value ? Colors.black : Colors.white,
onPressed: () {
setState(() {
value = !value;
});
},
),
body: AnimatedContainer(
duration: Duration(milliseconds: 600),
// Provide an optional curve to make the animation feel smoother.
color: value ? Colors.grey[200] : Colors.grey[850],
curve: Curves.linearToEaseOut,
child: Center(
child: AnimatedContainer(
duration: Duration(seconds: 1),
//height: height/2,
width: width / 2,
// padding: EdgeInsets.all(5),
decoration: BoxDecoration(
// border: Border.all(width: 2.0, color: Colors.black),
color: value ? Colors.grey[300] : Colors.grey[850],
//sborderRadius: BorderRadius.all(Radius.circular(50)),
shape: BoxShape.circle,
),
child: AnalogClock(
hourHandColor: value ? Colors.black : Colors.white,
minuteHandColor: value ? Colors.black : Colors.white,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: value ? Colors.grey[500] : Colors.grey[900],
offset: Offset(5, 5),
blurRadius: 15,
spreadRadius: 1,
),
BoxShadow(
color: value ? Colors.white : Colors.grey[800],
offset: Offset(-5, -5),
blurRadius: 12,
spreadRadius: 1)
],
//border: Border.all(width: 2.0, color: Colors.black),
color: value ? Colors.white : Colors.grey[850],
shape: BoxShape.circle),
width: 150.0,
isLive: true,
showNumbers: false,
showDigitalClock: false,
datetime: DateTime(2019, 1, 1, 9, 12, 15),
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/3D Clock With Dark and Light Theme
|
mirrored_repositories/Flutter-Practice-Projects/3D Clock With Dark and Light Theme/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:image_view_3d/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-Practice-Projects/Linting
|
mirrored_repositories/Flutter-Practice-Projects/Linting/lib/main.dart
|
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
// void myMethod() {
// debugPrint('hello');
// }
// Future<int> myMethod() {
// // debugPrint('hello');
// return Future.value(1);
// }
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Linting
|
mirrored_repositories/Flutter-Practice-Projects/Linting/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:linting/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-Practice-Projects/Perspective in Flutter
|
mirrored_repositories/Flutter-Practice-Projects/Perspective in Flutter/lib/main.dart
|
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Perspective',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
Offset _offset = Offset.zero;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Transform(
// Transform widget
transform: Matrix4.identity()
..setEntry(3, 2, 0.001) // perspective
..rotateX(0.01 * _offset.dy)
..rotateY(-0.01 * _offset.dx),
alignment: FractionalOffset.center,
child: GestureDetector(
onPanUpdate: (details) => setState(() => _offset += details.delta),
onDoubleTap: () => setState(() => _offset = Offset.zero),
child: _defaultApp(context),
));
}
_defaultApp(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('The Matrix 3D'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.bodyText2,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Perspective in Flutter
|
mirrored_repositories/Flutter-Practice-Projects/Perspective in Flutter/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:perspective_on_flutter/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-Practice-Projects/BottomSheet (Modal)
|
mirrored_repositories/Flutter-Practice-Projects/BottomSheet (Modal)/lib/modal.dart
|
import 'package:flutter/material.dart';
class Modal {
mainBottomSheet(BuildContext context) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
_createTile(context, 'Message', Icons.message, _action1),
_createTile(context, 'Take Photo', Icons.camera_alt, _action2),
_createTile(context, 'Images', Icons.photo_library, _action3),
],
);
});
}
ListTile _createTile(
BuildContext context, String name, IconData icon, Function action) {
return ListTile(
leading: Icon(icon),
title: Text(name),
onTap: () {
Navigator.pop(context);
action();
},
);
}
_action1() {
print('action 1');
}
_action2() {
print('action 2');
}
_action3() {
print('action 3');
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/BottomSheet (Modal)
|
mirrored_repositories/Flutter-Practice-Projects/BottomSheet (Modal)/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/modal.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Modal modal = new Modal();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Text(
'Body',
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: () => modal.mainBottomSheet(context),
child: new Icon(Icons.add),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/BottomSheet (Modal)
|
mirrored_repositories/Flutter-Practice-Projects/BottomSheet (Modal)/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:project001/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-Practice-Projects/Infinite scrolling ListView, HTTP GET
|
mirrored_repositories/Flutter-Practice-Projects/Infinite scrolling ListView, HTTP GET/lib/main.dart
|
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> dogImages = new List();
ScrollController _scrollController = new ScrollController();
@override
void initState() {
super.initState();
fetchFive();
_scrollController.addListener(() {
print(_scrollController.position.pixels);
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
// if we are at the bottom of the page
// we will fetch 5 more images
fetchFive();
}
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: ListView.builder(
controller: _scrollController,
itemCount: dogImages.length,
itemBuilder: (BuildContext context, int index) {
return Container(
constraints: BoxConstraints.tightFor(height: 150.0),
child: Image.network(
dogImages[index],
fit: BoxFit.fitWidth,
),
);
},
),
);
}
fetch() async {
final response = await http.get('https://dog.ceo/api/breeds/image/random');
if (response.statusCode == 200) {
setState(() {
dogImages.add(json.decode(response.body)['message']);
});
} else {
throw Exception('Failed to load images');
}
}
fetchFive() {
for (int i = 0; i < 5; i++) {
fetch();
}
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Infinite scrolling ListView, HTTP GET
|
mirrored_repositories/Flutter-Practice-Projects/Infinite scrolling ListView, HTTP GET/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:project001/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-Practice-Projects/Privacy Policy , Markdown and Dialog
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:project001/src/pages/sign_in_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
brightness: Brightness.dark,
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: SignInPage(),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/shared
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/shared/dialogs/policy_dialog.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
class PolicyDialog extends StatelessWidget {
PolicyDialog({
Key key,
this.radius = 8,
@required this.mdFileName,
}) : assert(mdFileName.contains('.md'), 'The file must contain the .md extension'),
super(key: key);
final double radius;
final String mdFileName;
@override
Widget build(BuildContext context) {
return Dialog(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(radius)),
child: Column(
children: [
Expanded(
child: FutureBuilder(
future: Future.delayed(Duration(milliseconds: 150)).then((value) {
return rootBundle.loadString('assets/$mdFileName');
}),
builder: (context, snapshot) {
if (snapshot.hasData) {
return Markdown(
data: snapshot.data,
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
),
FlatButton(
padding: EdgeInsets.all(0),
color: Theme.of(context).buttonColor,
onPressed: () => Navigator.of(context).pop(),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(radius),
bottomRight: Radius.circular(radius),
),
),
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(radius),
bottomRight: Radius.circular(radius),
),
),
alignment: Alignment.center,
height: 50,
width: double.infinity,
child: Text(
"CLOSE",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Theme.of(context).textTheme.button.color,
),
),
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/shared
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/shared/authentication/terms_of_use.dart
|
import 'package:animations/animations.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:project001/src/shared/dialogs/policy_dialog.dart';
class TermsOfUse extends StatelessWidget {
const TermsOfUse({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
text: "By creating an account, you are agreeing to our\n",
style: Theme.of(context).textTheme.bodyText1,
children: [
TextSpan(
text: "Terms & Conditions ",
style: TextStyle(fontWeight: FontWeight.bold),
recognizer: TapGestureRecognizer()
..onTap = () {
// Open dialog of terms and conditions
showModal(
context: context,
configuration: FadeScaleTransitionConfiguration(),
builder: (context) {
return PolicyDialog(
mdFileName: 'terms_and_conditions.md',
);
});
},
),
TextSpan(text: "and "),
TextSpan(
text: "Privacy Policy! ",
style: TextStyle(fontWeight: FontWeight.bold),
recognizer: TapGestureRecognizer()
..onTap = () {
// Open dialog of terms and conditions
showDialog(
context: context,
builder: (context) {
return PolicyDialog(
mdFileName: 'privacy_policy.md',
);
});
},
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/shared
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/shared/authentication/or_divider.dart
|
import 'package:flutter/material.dart';
class OrDivider extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
horizontalLine(),
Text("OR", style: Theme.of(context).textTheme.subtitle1),
horizontalLine(),
],
);
}
Widget horizontalLine() {
return Container(
margin: const EdgeInsets.all(12),
height: 2,
width: 124,
color: Colors.grey,
);
}
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/lib/src/pages/sign_in_page.dart
|
import 'package:flutter/material.dart';
import 'package:project001/src/shared/authentication/or_divider.dart';
import 'package:project001/src/shared/authentication/terms_of_use.dart';
class SignInPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final textTheme = Theme.of(context).textTheme;
return Scaffold(
body: SingleChildScrollView(
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: MediaQuery.of(context).size.height,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Container(
child: Column(
children: <Widget>[
SizedBox(height: kToolbarHeight * 2),
Text(
"Sign up",
style: textTheme.headline4
.copyWith(fontWeight: FontWeight.bold),
),
],
),
),
Column(
children: <Widget>[
Text(
"Sign up fields here",
style: textTheme.headline6,
),
smallHeightSpacing,
OrDivider(),
smallHeightSpacing,
InkWell(
onTap: () {}, // push to sign up
child: Text(
"Sign in",
style: textTheme.headline6,
),
),
SizedBox(height: 74),
TermsOfUse(),
],
),
],
),
),
),
);
}
SizedBox get smallHeightSpacing => SizedBox(height: 12);
}
| 0
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog
|
mirrored_repositories/Flutter-Practice-Projects/Privacy Policy , Markdown and Dialog/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:project001/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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.