repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
mirrored_repositories/Portfolio-Flutter-App/lib
|
mirrored_repositories/Portfolio-Flutter-App/lib/responsive/responsive_layout_screen.dart
|
import 'package:flutter/material.dart';
import '../utils/dimensions.dart';
class ResponsiveLayout extends StatelessWidget {
final Widget webScreenLayout;
final Widget mobileScreenLayout;
const ResponsiveLayout(this.mobileScreenLayout, this.webScreenLayout,
{super.key});
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (context, constraints) {
if (constraints.maxWidth > webScreenSize) {
return webScreenLayout;
} else {
return mobileScreenLayout;
}
});
}
}
| 0
|
mirrored_repositories/Portfolio-Flutter-App/lib
|
mirrored_repositories/Portfolio-Flutter-App/lib/responsive/web_screen_layout.dart
|
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter/material.dart';
class WebScreen extends StatelessWidget {
const WebScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SingleChildScrollView(
child: FutureBuilder(
future: DefaultAssetBundle.of(context).loadString('asset/data.json'),
builder: (context, snapshot) {
var data = jsonDecode(snapshot.data.toString());
return Column(
children: [
Row(
children: [
Column(
children: [
SizedBox(
width: 640,
height: 380,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Text(
data['title'],
style: const TextStyle(
fontSize: 60,
fontWeight: FontWeight.bold,
),
),
Container(
width: 100,
height: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 131, 38, 253),
),
child: const Text(
'Hire Me ✋',
),
),
],
),
),
),
Row(
children: [
SizedBox(
width: 210,
height: 210,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 0, 195, 153),
),
margin: const EdgeInsets.all(5.0),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['experience'] + "+",
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const Text(
"Years Experience",
style: TextStyle(
fontWeight: FontWeight.bold,
),
)
]),
),
),
SizedBox(
width: 210,
height: 210,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 255, 193, 60),
),
margin: const EdgeInsets.all(5.0),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['projects'] + "+",
style: const TextStyle(
fontSize: 30,
color: Colors.black,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const Text(
"Handled Projects",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
]),
),
),
SizedBox(
width: 210,
height: 210,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 255, 109, 122),
),
margin: const EdgeInsets.all(5.0),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['clients'] + "+",
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const Text(
"Clients",
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
],
),
),
),
],
)
],
),
Column(
children: [
Row(
children: [
SizedBox(
width: 700,
height: 80,
child: Container(
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 29, 27, 30),
),
child: Row(
children: [
Text(
"Bim",
style: TextStyle(
color: Colors.grey[400],
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Text(
"Graph",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Spacer(),
IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
color: Colors.white,
)
],
)),
),
],
),
Row(
children: [
Column(
children: [
SizedBox(
child: Container(
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20)),
child: Image.asset(
'asset/images/30.jpg',
width: 200,
height: 400,
),
),
)
],
),
Column(
children: [
SizedBox(
width: 480,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 29, 27, 30),
),
child: Row(
children: [
const Text("Name:"),
const Spacer(),
Text(
data['name'],
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
],
),
),
),
SizedBox(
width: 480,
height: 330,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: [
const Text("Based in:"),
const Spacer(),
Text(
data['location'],
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
),
),
],
),
Container(
margin: const EdgeInsets.all(10.0),
child: Image.asset(
"asset/images/map.png",
width: 300,
height: 225,
),
),
],
),
),
),
SizedBox(
width: 480,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color:
const Color.fromARGB(255, 29, 27, 30),
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.linkedin,
color: Colors.white,
),
),
),
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.twitter,
color: Colors.white,
),
),
),
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.facebook,
color: Colors.white,
),
),
),
Container(
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.instagram,
color: Colors.white,
),
),
),
],
),
),
)
],
),
],
)
],
),
],
),
Row(
children: [
SizedBox(
width: 850,
height: 300,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: const [
Text(
"UI Portfolio",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Spacer(),
TextButton(
onPressed: null,
child: Text(
"See All",
style: TextStyle(color: Colors.white),
),
),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
width: 250,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.asset(
"asset/images/1.jpg",
width: 200,
height: 200,
),
),
),
SizedBox(
width: 250,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.asset(
"asset/images/2.jpg",
width: 200,
height: 200,
),
),
),
SizedBox(
width: 250,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.asset(
"asset/images/3.jpg",
width: 200,
height: 200,
),
),
),
],
),
],
),
),
),
SizedBox(
width: 500,
height: 300,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: const [
Text(
"About",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Spacer(),
TextButton(
onPressed: null,
child: Text(
"Resume",
style: TextStyle(color: Colors.white),
),
),
],
),
Container(
padding: const EdgeInsets.all(8.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
child: Text(
data['about'],
style: const TextStyle(
fontSize: 16,
),
),
),
],
),
),
),
],
),
],
);
},
),
),
);
}
}
| 0
|
mirrored_repositories/Portfolio-Flutter-App/lib
|
mirrored_repositories/Portfolio-Flutter-App/lib/responsive/mobile_screen_layout.dart
|
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class MobileScreen extends StatelessWidget {
const MobileScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
body: SingleChildScrollView(
child: FutureBuilder(
future: DefaultAssetBundle.of(context).loadString('asset/data.json'),
builder: (context, snapshot) {
var data = jsonDecode(snapshot.data.toString());
return Column(
children: [
Column(
children: [
Row(
children: [
SizedBox(
width: 600,
height: 100,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Row(
children: [
Text(
"Bim",
style: TextStyle(
color: Colors.grey[400],
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Text(
"Graph",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
const Spacer(),
IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
color: Colors.white,
)
],
),
),
),
],
),
SizedBox(
width: 600,
height: 350,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Text(
data['title'],
style: const TextStyle(
fontSize: 50,
fontWeight: FontWeight.bold,
),
),
Container(
width: 100,
height: 40,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 131, 38, 253),
),
child: const Text(
'Hire Me ✋',
),
),
],
),
),
),
Row(
children: [
SizedBox(
width: 200,
height: 200,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 0, 200, 153),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['experience'] + "+",
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const Text(
"Years Experience",
style: TextStyle(
fontWeight: FontWeight.bold,
),
)
]),
),
),
SizedBox(
width: 200,
height: 200,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 255, 193, 60),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['projects'] + "+",
style: const TextStyle(
fontSize: 30,
color: Colors.black,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const Text(
"Handled Projects",
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
]),
),
),
SizedBox(
width: 200,
height: 200,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 255, 109, 122),
),
alignment: Alignment.center,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
data['clients'] + "+",
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const Text(
"Clients",
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
],
),
),
),
],
),
],
),
Column(
children: [
Row(
children: [
Column(
children: [
SizedBox(
width: 600,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: [
const Text("Name:"),
const Spacer(),
Text(
data['name'],
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
],
),
SizedBox(
child: Container(
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.all(10.0),
decoration: BoxDecoration(
borderRadius:
BorderRadius.circular(20)),
child: Image.asset(
'asset/images/30.jpg',
width: 100,
height: 200,
),
),
),
],
),
),
),
SizedBox(
width: 600,
height: 340,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: [
const Text("Based in:"),
const Spacer(),
Text(
data['location'],
style: const TextStyle(
fontWeight: FontWeight.bold,
fontSize: 18,
),
),
],
),
Container(
margin: const EdgeInsets.all(10.0),
child: Image.asset(
"asset/images/map.png",
width: 300,
height: 225,
),
),
],
),
),
),
SizedBox(
width: 600,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.linkedin,
color: Colors.white,
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.twitter,
color: Colors.white,
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.facebook,
color: Colors.white,
),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(
255, 29, 37, 90),
),
child: IconButton(
onPressed: () {},
icon: const FaIcon(
FontAwesomeIcons.instagram,
color: Colors.white,
),
),
),
],
),
),
)
],
),
],
)
],
),
SizedBox(
width: 600,
height: 250,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: const [
Text(
"About",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Spacer(),
TextButton(
onPressed: null,
child: Text(
"Resume",
style: TextStyle(color: Colors.white),
),
),
],
),
const SizedBox(
height: 10,
),
Text(
data['about'],
style: const TextStyle(
fontSize: 15,
),
),
],
),
),
),
SizedBox(
width: 850,
height: 700,
child: Container(
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(20.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: const Color.fromARGB(255, 29, 27, 30),
),
child: Column(
children: [
Row(
children: const [
Text(
"UI Portfolio",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
),
),
Spacer(),
TextButton(
onPressed: null,
child: Text(
"See All",
style: TextStyle(color: Colors.white),
),
),
],
),
const SizedBox(
height: 10,
),
Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
SizedBox(
width: 250,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.asset(
"asset/images/1.jpg",
width: 200,
height: 200,
),
),
),
SizedBox(
width: 250,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.asset(
"asset/images/2.jpg",
width: 200,
height: 200,
),
),
),
SizedBox(
width: 250,
child: ClipRRect(
borderRadius: BorderRadius.circular(60),
child: Image.asset(
"asset/images/3.jpg",
width: 200,
height: 200,
),
),
),
],
),
],
),
),
),
],
);
},
),
),
);
}
}
| 0
|
mirrored_repositories/Portfolio-Flutter-App/lib
|
mirrored_repositories/Portfolio-Flutter-App/lib/utils/dimensions.dart
|
const webScreenSize = 610;
const ipadScreenSize = 768;
| 0
|
mirrored_repositories/Portfolio-Flutter-App
|
mirrored_repositories/Portfolio-Flutter-App/test/widget_test.dart
|
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:portfolio_task/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/startup-name-generator
|
mirrored_repositories/startup-name-generator/lib/main.dart
|
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have clicked the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
| 0
|
mirrored_repositories/startup-name-generator
|
mirrored_repositories/startup-name-generator/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_app/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/startup-name-generator/startup_namer
|
mirrored_repositories/startup-name-generator/startup_namer/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Startup Name Generator',
theme: new ThemeData(
primaryColor: Colors.lightBlue,
),
home: new RandomWords(),
);
}
}
class RandomWordsState extends State<RandomWords>{
final _suggestions = <WordPair>[];
final _biggerFont = const TextStyle(fontSize: 18);
final _saved = new Set<WordPair>();
void _pushSaved(){
Navigator.of(context).push(
new MaterialPageRoute<void>(
builder: (BuildContext context) {
final Iterable<ListTile> tiles = _saved.map((WordPair pair){
return new ListTile(
title: new Text(
pair.asPascalCase,
style: _biggerFont,
),
);
},
);
final List<Widget> divided = ListTile.divideTiles(
context: context,
tiles: tiles,
).toList();
return new Scaffold(
appBar: new AppBar(
title: const Text('Saved Suggestions'),
),
body: new ListView(children: divided),
);
},
),
);
}
Widget _buildSuggestions(){
return ListView.builder(
padding: const EdgeInsets.all(16.0),
itemBuilder: (context, i) {
if (i.isOdd) return Divider();
final index = i~/2;
if (index >= _suggestions.length){
_suggestions.addAll(generateWordPairs().take(10));
}
return _buildRow(_suggestions[index]);
}
);
}
Widget _buildRow(WordPair pair) {
final bool alreadySaved = _saved.contains(pair);
return ListTile(
title: Text(
pair.asPascalCase,
style: _biggerFont,
),
trailing: new Icon(
alreadySaved ? Icons.favorite : Icons.favorite_border,
color: alreadySaved ? Colors.red : null,
) ,
onTap: () {
setState(() {
if (alreadySaved){
_saved.remove(pair);
} else {
_saved.add(pair);
}
});
},
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text(
'Startup Name Generator',
style: TextStyle(color: Colors.white),
),
actions: <Widget>[
new IconButton(
icon: const Icon(Icons.list),
onPressed: _pushSaved,
color: Colors.white,
alignment: Alignment.center,
),
],
),
body: _buildSuggestions(),
);
}
}
class RandomWords extends StatefulWidget {
@override
RandomWordsState createState() => new RandomWordsState();
}
| 0
|
mirrored_repositories/startup-name-generator/startup_namer
|
mirrored_repositories/startup-name-generator/startup_namer/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:startup_namer/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/JobfinderUIwithflutter
|
mirrored_repositories/JobfinderUIwithflutter/lib/card_widget.dart
|
import 'package:flutter/material.dart';
import 'package:job_finder/const.dart';
class CardWidget extends StatelessWidget {
const CardWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GridView.extent(
maxCrossAxisExtent: 200,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
children: [
jobCard(
"Human Resource",
const Icon(
Icons.people_alt_outlined,
color: cardColor,
),
barColor),
jobCard(
"Building & Architecture",
const Icon(
Icons.architecture_rounded,
color: cardColor,
),
barColor),
jobCard(
"Customer Service",
const Icon(
Icons.headset_mic,
color: barColor,
),
cardColor),
jobCard(
"Hospitality & Leisure",
const Icon(
Icons.hotel_rounded,
color: barColor,
),
cardColor),
jobCard(
"Marketing & Business",
const Icon(
Icons.campaign_rounded,
color: cardColor,
),
barColor),
jobCard(
"Medical & Pharma",
const Icon(
Icons.local_hospital_rounded,
color: cardColor,
),
barColor),
jobCard(
"Developer",
const Icon(
Icons.developer_mode_rounded,
color: barColor,
),
cardColor),
jobCard(
"Software Engg.",
const Icon(
Icons.computer_rounded,
color: barColor,
),
cardColor),
],
);
}
}
//**** Card Widgets
Widget jobCard(String txt, Icon icon, Color int) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: InkWell(
//TODO: Function
onTap: () {},
child: Container(
width: 150,
height: 150,
decoration: BoxDecoration(
boxShadow: [
BoxShadow(
color: Colors.blueGrey.shade200,
blurRadius: 5,
spreadRadius: 1,
offset: const Offset(4, 4))
],
borderRadius: const BorderRadius.all(
Radius.circular(defaultBorderRadius),
),
color: int,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(defaultPadding),
child: icon,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
txt,
style: const TextStyle(
fontSize: 15.0,
fontWeight: FontWeight.w400,
),
),
),
],
),
),
),
);
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter
|
mirrored_repositories/JobfinderUIwithflutter/lib/theme.dart
|
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:job_finder/const.dart';
// ?*** Creating A Final Value For Dark And Light Theme.
final lightThemeData = ThemeData(
brightness: Brightness.light,
primaryColor: primaryColor,
textTheme: GoogleFonts.poppinsTextTheme(ThemeData.light().textTheme),
elevatedButtonTheme: elevatedButtonThemeData,
colorScheme: ThemeData.light()
.colorScheme
.copyWith(secondary: secondaryColorLightTheme),
);
final darkThemeData = ThemeData(
brightness: Brightness.dark,
primaryColor: primaryColor,
scaffoldBackgroundColor: bgColorDarkTheme,
textTheme: GoogleFonts.poppinsTextTheme(ThemeData.dark().textTheme),
colorScheme:
ThemeData.dark().colorScheme.copyWith(secondary: secondaryColorDarkTheme),
);
final elevatedButtonThemeData = ElevatedButtonThemeData(
style: TextButton.styleFrom(
backgroundColor: primaryColor,
padding: const EdgeInsets.all(defaultPadding),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(defaultBorderRadius),
),
),
),
);
| 0
|
mirrored_repositories/JobfinderUIwithflutter
|
mirrored_repositories/JobfinderUIwithflutter/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:job_finder/screens/on_bordingscreen.dart';
import 'package:job_finder/theme.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Job Finder',
theme: lightThemeData,
darkTheme: darkThemeData,
home: const OnBordingScreen(),
);
}
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter
|
mirrored_repositories/JobfinderUIwithflutter/lib/const.dart
|
import 'package:flutter/material.dart';
const primaryColor = Color(0xFFFF494C);
const blueColor = Color(0xFF1FA5C3);
const cardColor = Color(0xFF4a8cf7);
const cardFontColor = Color(0xFF3d7cfe);
const barColor = Color(0xFFfbfbfb);
const cardDesignColor = Color(0xFF7bb0fe);
const infoCardColor = Color(0xFFe2edff);
const infoColor = Color(0xFFbfbfbf);
const fontColor = Color(0xFF64a5fb);
//*** Light Theme
const secondaryColorLightTheme = Color(0xFFEEF1F7);
const textColorLightTheme = Color(0xFF132144);
const bodyTextColorLightTheme = Color(0xFF788198);
//*** Dark Theme
const secondaryColorDarkTheme = Color(0xFF242339);
const bgColorDarkTheme = Color(0xFF19182C);
const textColorDarkTheme = Colors.white;
const bodyTextColorDarkTheme = Color(0xFF9CA5BA);
//*** Margin/Paddings
const defaultPadding = 10.0;
const defaultBorderRadius = 14.0;
| 0
|
mirrored_repositories/JobfinderUIwithflutter/lib
|
mirrored_repositories/JobfinderUIwithflutter/lib/screens/home_page.dart
|
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:job_finder/screens/profile_page.dart';
import '../const.dart';
import 'bookmark_page.dart';
import 'job_page.dart';
class HomePage extends StatefulWidget {
const HomePage({Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
//**** Creating Controller For Updating The Navigation Bar ************//
int _currentIndex = 0;
static const List<Widget> _screens = [
HomePage(),
JobPage(),
BookmarkPage(),
ProfilePage()
];
void _updateIndex(int index) {
setState(() {
_currentIndex = index;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
onTap: _updateIndex,
currentIndex: _currentIndex,
type: BottomNavigationBarType.fixed,
iconSize: 30,
selectedFontSize: 13,
unselectedFontSize: 13,
unselectedItemColor: Colors.grey,
selectedItemColor: cardColor,
items: const [
BottomNavigationBarItem(
label: "Home",
icon: Icon(Icons.home_rounded),
),
BottomNavigationBarItem(
label: "Jobs",
icon: Icon(Icons.view_list_rounded),
),
BottomNavigationBarItem(
label: "Bookmark",
icon: Icon(Icons.bookmarks),
),
BottomNavigationBarItem(
label: "Profile",
icon: Icon(Icons.person),
),
],
),
appBar: AppBar(
automaticallyImplyLeading: false,
foregroundColor: cardColor,
elevation: 0,
backgroundColor: barColor,
actions: [
IconButton(
onPressed: () {},
icon: const Icon(Icons.notifications_none),
),
],
),
body: SafeArea(
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(left: 8.0, right: 8.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
//************* Card Container ****************//
child: Container(
height: 180.0,
width: double.maxFinite,
decoration: BoxDecoration(
color: cardColor,
borderRadius: BorderRadius.circular(20),
),
//******************* Rounded Blur Circle(Stack) ****************//
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Stack(
children: <Widget>[
Positioned(
left: 289,
top: -10,
height: 90,
width: 90,
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 80, sigmaY: 80),
child: Container(
decoration: BoxDecoration(
color:
Colors.transparent.withOpacity(.01),
borderRadius: BorderRadius.circular(50),
),
),
),
),
),
Stack(
children: <Widget>[
Positioned(
right: 289,
bottom: -8,
width: 90,
height: 90,
child: ClipRRect(
borderRadius: BorderRadius.circular(50),
child: BackdropFilter(
filter: ImageFilter.blur(
sigmaX: 80, sigmaY: 80),
child: Container(
decoration: BoxDecoration(
color: Colors.transparent
.withOpacity(.01),
borderRadius:
BorderRadius.circular(50),
),
),
),
),
),
],
),
Padding(
padding: const EdgeInsets.only(
left: 10.0, top: 20.0),
child: RichText(
text: const TextSpan(
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15.0),
text: "Hello Veronica!\n\n",
children: <TextSpan>[
TextSpan(
style: TextStyle(
fontWeight: FontWeight.normal,
fontSize: 14),
text: "Let's Find Your Dream Job!")
],
),
),
),
//************* Search Bar ************//
Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
PreferredSize(
preferredSize: const Size.fromHeight(2.0),
child: Padding(
padding: const EdgeInsets.only(
left: 55.0, bottom: 10.0),
child: Container(
width: 250,
decoration: BoxDecoration(
color: Colors.white,
borderRadius:
BorderRadius.circular(40)),
child: TextFormField(
decoration: const InputDecoration(
hintStyle:
TextStyle(fontSize: 12.0),
prefixIcon: Icon(
Icons.search_rounded,
color: cardColor,
),
border: InputBorder.none),
),
),
),
),
],
),
],
),
),
],
),
),
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: const <Widget>[
Text(
"Recommended",
style: TextStyle(
fontSize: 15.0, fontWeight: FontWeight.w700),
),
Icon(
Icons.arrow_forward,
color: cardColor,
),
],
),
),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: <Widget>[
jobCardTile(
"Frontend Developer",
"Amazon",
"assets/FJob.png",
),
jobCardTile(
"Web Developer",
"Flipkart",
"assets/FJob.png",
),
jobCardTile(
"Flutter Developer",
"Logix Tech",
"assets/FJob.png",
),
jobCardTile(
"Android Developer",
"Google",
"assets/FJob.png",
),
jobCardTile(
"Python Developer",
"Traxmart",
"assets/FJob.png",
),
],
),
),
Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
alignment: Alignment.centerLeft,
height: 50,
width: double.maxFinite,
decoration: BoxDecoration(
// color: infoCardColor,
borderRadius: BorderRadius.circular(0),
),
child: const Text(
" Recently Added ",
style: TextStyle(
fontSize: 15.0,
color: Colors.black,
fontWeight: FontWeight.w700,
),
),
),
),
jobCardTile(
"PHP Developer",
"Apple",
"assets/FJob.png",
),
],
),
),
),
);
}
}
// *** Job Card ********/
Widget jobCardTile(String titletxt, String subtxt, String img) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Card(
shadowColor: infoColor,
elevation: 5.0,
color: barColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
),
child: Column(
// mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
height: 100,
width: 280,
alignment: Alignment.centerLeft,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
child: ListTile(
leading: Image(
image: AssetImage(img),
),
subtitle: Text(
subtxt,
style: const TextStyle(color: infoColor),
),
title: Text(
titletxt,
style: const TextStyle(
color: Colors.black,
fontSize: 15,
fontWeight: FontWeight.w300),
),
),
),
ammountCard("Full Time-N100k-Design"),
],
),
),
),
],
);
}
//*** Info Card Widget
Widget ammountCard(String ammountTxt) {
return Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
alignment: Alignment.center,
height: 50,
width: 250,
decoration: BoxDecoration(
color: infoCardColor,
borderRadius: BorderRadius.circular(20),
),
child: Text(
ammountTxt,
style: const TextStyle(
color: cardFontColor,
fontWeight: FontWeight.w700,
),
),
),
);
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter/lib
|
mirrored_repositories/JobfinderUIwithflutter/lib/screens/job_page.dart
|
import 'package:flutter/cupertino.dart';
class JobPage extends StatefulWidget {
const JobPage({Key? key}) : super(key: key);
@override
State<JobPage> createState() => _JobPageState();
}
class _JobPageState extends State<JobPage> {
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter/lib
|
mirrored_repositories/JobfinderUIwithflutter/lib/screens/home_screen.dart
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:job_finder/card_widget.dart';
import 'package:job_finder/const.dart';
import 'package:job_finder/screens/home_page.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({Key? key}) : super(key: key);
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Container(
// color: Colors.deepOrangeAccent,
height: double.infinity,
width: double.infinity,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
"What Type Of Jobs Are You Looking For?",
strutStyle: const StrutStyle(
fontWeight: FontWeight.bold, fontSize: 15),
style: Theme.of(context).textTheme.headline5,
),
const Text(
"Choose 2-5 job categories and we will optimize the job vacancy for you.",
style: TextStyle(color: infoColor),
),
const Expanded(
// flex: 1,
child: CardWidget(),
),
Container(
width: double.maxFinite,
// height: 90,
decoration: const BoxDecoration(
// color: Colors.deepOrange,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30))),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: MaterialButton(
minWidth: 300,
height: 50,
color: cardColor,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(20),
),
),
onPressed: () {
Get.to(const HomePage());
},
child: const Text(
"Let's Go",
style: TextStyle(color: barColor),
),
),
),
)
],
),
),
),
),
),
);
}
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter/lib
|
mirrored_repositories/JobfinderUIwithflutter/lib/screens/profile_page.dart
|
import 'package:flutter/cupertino.dart';
class ProfilePage extends StatefulWidget {
const ProfilePage({Key? key}) : super(key: key);
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter/lib
|
mirrored_repositories/JobfinderUIwithflutter/lib/screens/bookmark_page.dart
|
import 'package:flutter/cupertino.dart';
class BookmarkPage extends StatefulWidget {
const BookmarkPage({Key? key}) : super(key: key);
@override
State<BookmarkPage> createState() => _BookmarkPageState();
}
class _BookmarkPageState extends State<BookmarkPage> {
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter/lib
|
mirrored_repositories/JobfinderUIwithflutter/lib/screens/on_bordingscreen.dart
|
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../const.dart';
import 'home_screen.dart';
class OnBordingScreen extends StatefulWidget {
const OnBordingScreen({Key? key}) : super(key: key);
@override
State<OnBordingScreen> createState() => _OnBordingScreenState();
}
class _OnBordingScreenState extends State<OnBordingScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded(
child: Image.asset(
Theme.of(context).brightness == Brightness.light
? "assets/FJob.png"
: "assets/FJob.png",
fit: BoxFit.contain,
width: 500,
height: 600,
),
),
Expanded(
child: SafeArea(
top: false,
child: Column(
children: <Widget>[
// const Spacer(),
Text(
"Looking For A Dream Job ? \n 1000+ Jobs Listed Daily",
style: Theme.of(context)
.textTheme
.headline5!
.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: defaultPadding / 2),
const Text(
"Now You Can Easily Find Your Dream\nJob On Job Finder.",
textAlign: TextAlign.center,
),
SizedBox(
width: 150.0,
height: 60,
child: Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
style: TextButton.styleFrom(
backgroundColor: cardColor,
padding: const EdgeInsets.all(defaultPadding),
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(30),
),
),
),
onPressed: () {
Get.to(const HomeScreen());
},
child: const Text("Get Set Go"),
),
),
)
],
),
),
),
],
),
);
}
}
| 0
|
mirrored_repositories/JobfinderUIwithflutter
|
mirrored_repositories/JobfinderUIwithflutter/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:job_finder/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_showcase
|
mirrored_repositories/flutter_showcase/lib/flutter_showcase.dart
|
library flutter_showcase;
export 'src/showcase.dart';
export 'src/templates/templates.dart';
export 'src/templates/simple_template.dart';
export 'src/core/theme.dart';
export 'src/core/template.dart';
export 'src/frame/frame.dart';
export 'src/frame/frame_theme.dart';
| 0
|
mirrored_repositories/flutter_showcase/lib
|
mirrored_repositories/flutter_showcase/lib/src/showcase.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_showcase/src/frame/frame_theme.dart';
import 'package:flutter_showcase/src/templates/templates.dart';
import 'package:flutter_showcase/src/core/theme.dart';
import '../flutter_showcase.dart';
const isShowcaseActive =
bool.fromEnvironment('FLUTTER_SHOWCASE', defaultValue: true);
const isScreenshot =
bool.fromEnvironment('SCREENSHOT_MODE', defaultValue: false);
typedef AppBuilder = Widget Function(BuildContext context, Widget app);
class Showcase extends StatelessWidget {
final Widget app;
final String title;
final String description;
final TemplateThemeData theme;
final List<LinkData> links;
final LinkData logoLink;
final Template template;
const Showcase({
Key key,
this.app,
this.title,
this.theme,
this.description,
this.links,
this.template,
this.logoLink,
}) : super(key: key);
@override
Widget build(BuildContext context) {
if (!isShowcaseActive) {
return app;
}
final _template = template ?? Templates.simple;
final _theme = theme ?? TemplateThemeData.light();
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: _MediaQueryFromWindow(
child: DefaultFrameTheme(
data: _theme.frameTheme,
child: Builder(builder: (context) {
return _template.builder(
context: context,
app: app,
data: TemplateData(
title: title,
links: links,
logoLink: logoLink,
theme: _theme,
description: description),
);
}),
),
),
),
);
}
}
class CustomShowcase extends StatelessWidget {
final Widget app;
final AppBuilder builder;
const CustomShowcase({Key key, this.app, this.builder}) : super(key: key);
@override
Widget build(BuildContext context) {
final _builder = builder;
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: _MediaQueryFromWindow(
child: _builder(context, app),
),
),
);
}
}
/// Builds [MediaQuery] from `window` by listening to [WidgetsBinding].
///
/// It is performed in a standalone widget to rebuild **only** [MediaQuery] and
/// its dependents when `window` changes, instead of rebuilding the entire widget tree.
class _MediaQueryFromWindow extends StatefulWidget {
const _MediaQueryFromWindow({Key key, this.child}) : super(key: key);
final Widget child;
@override
_MediaQueryFromWindowsState createState() => _MediaQueryFromWindowsState();
}
class _MediaQueryFromWindowsState extends State<_MediaQueryFromWindow>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
// ACCESSIBILITY
@override
void didChangeAccessibilityFeatures() {
setState(() {
// The properties of window have changed. We use them in our build
// function, so we need setState(), but we don't cache anything locally.
});
}
// METRICS
@override
void didChangeMetrics() {
setState(() {
// The properties of window have changed. We use them in our build
// function, so we need setState(), but we don't cache anything locally.
});
}
@override
void didChangeTextScaleFactor() {
setState(() {
// The textScaleFactor property of window has changed. We reference
// window in our build function, so we need to call setState(), but
// we don't need to cache anything locally.
});
}
// RENDERING
@override
void didChangePlatformBrightness() {
setState(() {
// The platformBrightness property of window has changed. We reference
// window in our build function, so we need to call setState(), but
// we don't need to cache anything locally.
});
}
@override
Widget build(BuildContext context) {
return MediaQuery(
data: MediaQueryData.fromWindow(WidgetsBinding.instance.window),
child: widget.child,
);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
}
| 0
|
mirrored_repositories/flutter_showcase/lib/src
|
mirrored_repositories/flutter_showcase/lib/src/templates/templates.dart
|
import 'package:flutter_showcase/flutter_showcase.dart';
import 'package:flutter_showcase/src/templates/simple_template.dart';
class Templates {
static Template get simple => SimpleTemplate();
static Template get simpleReverse => SimpleTemplate(reverse: true);
}
| 0
|
mirrored_repositories/flutter_showcase/lib/src
|
mirrored_repositories/flutter_showcase/lib/src/templates/simple_template.dart
|
import 'dart:math';
import 'package:fluid_layout/fluid_layout.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
class SimpleTemplate extends Template {
final bool reverse;
SimpleTemplate({this.reverse});
@override
Widget builder({BuildContext context, TemplateData data, Widget app}) {
final shouldDisplayTemplate = MediaQuery.of(context).size.width > 600;
Widget content =
isScreenshot ? _ScreenshotContent(data: data) : _Content(data: data);
if (!shouldDisplayTemplate) {
return AppWithDrawer(
child: app,
drawer: content,
theme: data.theme,
);
} else {
final sizedChild = Center(child: SizedBox(height: 896, child: content));
final children = reverse == true
? [
Flexible(
flex: 2,
key: Key('Preview'),
child: Align(alignment: Alignment.centerRight, child: app)),
SizedBox(width: 80),
Flexible(flex: 1, child: sizedChild),
]
: [
Expanded(flex: 2, child: sizedChild),
SizedBox(width: 80),
Flexible(flex: 1, key: Key('Preview'), child: app),
];
return Scaffold(
backgroundColor: data.theme.backgroundColor,
body: FluidLayout(
child: Fluid(
child: Builder(
builder: (context) => Padding(
padding: EdgeInsets.symmetric(vertical: 40),
child: Material(
color: Colors.transparent,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children),
),
),
),
),
),
);
}
}
}
class _Content extends StatelessWidget {
final TemplateData data;
const _Content({Key key, this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
final TemplateThemeData theme = data.theme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
DefaultTextStyle(
style: theme.titleTextStyle,
child: Text(
data.title,
maxLines: 3,
overflow: TextOverflow.clip,
),
),
SizedBox(height: 40),
Expanded(
flex: 6,
child: SingleChildScrollView(
child: DefaultTextStyle(
style: theme.descriptionTextStyle,
child: Text(
data.description,
overflow: TextOverflow.clip,
),
),
),
),
if (data.links != null)
Wrap(
crossAxisAlignment: WrapCrossAlignment.start,
spacing: 12,
runSpacing: 12,
children: <Widget>[
...(data.links.map(
(e) => _Link(
data: e,
theme: theme,
),
))
],
),
SizedBox(height: 40),
Row(
children: <Widget>[
InkWell(
onTap: () => launch('https://flutter.dev'),
child: Image(
image: (theme.flutterLogoColor ?? FlutterLogoColor.original)
.image(),
height: 40),
),
if (data.logoLink != null)
Flexible(
child: Container(
alignment: Alignment.bottomLeft,
height: 40,
margin: EdgeInsets.only(left: 32),
child: _LogoLink(data: data.logoLink),
),
),
],
),
SizedBox(height: 4),
],
);
}
}
class _ScreenshotContent extends StatelessWidget {
final TemplateData data;
const _ScreenshotContent({Key key, this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
final TemplateThemeData theme = data.theme;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
DefaultTextStyle(
style: theme.titleTextStyle,
child: Text(
data.title,
maxLines: 3,
textScaleFactor: 1.5,
overflow: TextOverflow.clip,
),
),
SizedBox(height: 40),
Expanded(
child: DefaultTextStyle(
style: theme.descriptionTextStyle,
child: Text(
data.description,
textScaleFactor: 1.5,
softWrap: true,
),
),
),
SizedBox(height: 40),
Row(
children: <Widget>[
InkWell(
onTap: () => launch('https://flutter.dev'),
child: Image(
image: (theme.flutterLogoColor ?? FlutterLogoColor.original)
.image(),
height: 80),
),
],
),
SizedBox(height: 20),
],
);
}
}
class _Link extends StatelessWidget {
final LinkData data;
final TemplateThemeData theme;
const _Link({Key key, this.data, this.theme}) : super(key: key);
@override
Widget build(BuildContext context) {
return FittedBox(
child: ButtonTheme.fromButtonThemeData(
data: theme.buttonTheme,
child: RaisedButton(
elevation: 0,
focusElevation: 0,
hoverElevation: 0,
onPressed: () => {launch(data.url)},
child: IconTheme(
data: theme.buttonIconTheme.merge(IconThemeData(size: 20)),
child: Row(
children: [
if (data.icon != null)
Container(
height: 20,
width: 20,
margin: EdgeInsets.only(right: 12),
child: data.icon),
Text(
data.title,
style: theme.buttonTextStyle,
)
],
),
),
),
),
);
}
}
class _LogoLink extends StatelessWidget {
final LinkData data;
const _LogoLink({Key key, this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return InkWell(
onTap: () => {launch(data.url)},
child: data.icon,
);
}
}
class AppWithDrawer extends StatefulWidget {
final Widget child;
final Widget drawer;
final TemplateThemeData theme;
const AppWithDrawer({Key key, this.child, this.drawer, this.theme})
: super(key: key);
@override
State<StatefulWidget> createState() => _AppWithDrawerState();
}
class _AppWithDrawerState extends State<AppWithDrawer>
with TickerProviderStateMixin {
bool showInfoButton = true;
AnimationController animationController;
@override
void initState() {
animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500),
);
super.initState();
}
_toggle() {
if (animationController.value == 0) {
animationController.forward();
} else {
animationController.animateBack(0);
}
}
@override
Widget build(BuildContext context) {
final theme = widget.theme;
final size = MediaQuery.of(context).size;
final app = GestureDetector(
onTap: () => setState(() => showInfoButton = !showInfoButton),
child: Scaffold(
body: Stack(
fit: StackFit.expand,
children: [
widget.child,
AnimatedPositioned(
duration: Duration(milliseconds: 300),
right: showInfoButton ? 0 : -60,
bottom: 60,
width: 60,
height: 60,
child: InkWell(
onTap: () => _toggle(),
child: Container(
decoration: BoxDecoration(
border: Border(
left: BorderSide(color: theme.titleTextStyle.color),
top: BorderSide(color: theme.titleTextStyle.color),
bottom:
BorderSide(color: theme.titleTextStyle.color)),
color: theme.backgroundColor,
boxShadow: []),
padding: EdgeInsets.all(20),
child: Icon(
FontAwesomeIcons.info,
color: theme.titleTextStyle.color,
),
),
),
),
],
),
));
return Container(
color: theme.backgroundColor,
child: Stack(
fit: StackFit.expand,
children: [
GestureDetector(
onTap: () => _toggle(),
child: Container(
color: theme.backgroundColor,
child: widget.drawer,
padding:
EdgeInsets.only(left: 80, top: 40, right: 20, bottom: 40),
),
),
AnimatedBuilder(
animation: animationController,
builder: (context, child) {
final t = animationController.value;
final scale = 1 - 0.2 * t;
Matrix4 matrix = Matrix4.identity()
..setEntry(3, 2, 0.001)
..rotateY(-pi / 10 * t)
..scale(scale, scale, scale)
..translate(-size.width * t, 0, 0);
return Transform(
transform: matrix,
origin: size.center(Offset.zero),
child: Container(
decoration: BoxDecoration(boxShadow: [
BoxShadow(color: Colors.black45, blurRadius: 12)
]),
child: ClipRRect(
borderRadius:
BorderRadius.circular(24.7 * animationController.value),
clipBehavior: Clip.antiAlias,
child: child,
),
),
);
},
child: app,
)
],
),
);
/* return InnerDrawer(
key: _innerDrawerKey,
scale: IDOffset.horizontal(0.8),
borderRadius: 27,
onTapClose: true,
offset: IDOffset.only(right: 0.9),
backgroundColor: theme.backgroundColor,
rightChild:
scaffold
:,
);*/
}
}
| 0
|
mirrored_repositories/flutter_showcase/lib/src
|
mirrored_repositories/flutter_showcase/lib/src/core/theme.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
import 'package:flutter_showcase/src/frame/frame_theme.dart';
/// An immutable theme for showcase projects
///
class TemplateThemeData {
/// Describes the contrast of the showcase page.
///
final Brightness brightness;
/// Background color of the showcase page
///
final Color backgroundColor;
/// Defines the theme of the device frame
/// that wraps the app
///
final FrameThemeData frameTheme;
/// Defines Flutter logo appearance
/// Options: .original, .white, .dark
///
final FlutterLogoColor flutterLogoColor;
/// Defines text style for the title
///
final TextStyle titleTextStyle;
/// Defines text style for the description text
///
final TextStyle descriptionTextStyle;
/// Defines button theme for the clickable share links
///
final ButtonThemeData buttonTheme;
final TextStyle buttonTextStyle;
final IconThemeData buttonIconTheme;
factory TemplateThemeData({
Brightness brightness,
FlutterLogoColor flutterLogoColor,
TextStyle titleTextStyle,
TextStyle descriptionTextStyle,
Color backgroundColor,
ButtonThemeData buttonTheme,
FrameThemeData frameTheme,
TextStyle buttonTextStyle,
IconThemeData buttonIconTheme,
}) {
brightness ??= Brightness.light;
final bool isDark = brightness == Brightness.dark;
backgroundColor ??= isDark ? Colors.grey[850] : Colors.grey[50];
final textColor = isDark ? Colors.white : Colors.black;
descriptionTextStyle =
TextStyle(color: textColor, height: 1.8, fontSize: 18).merge(
descriptionTextStyle ?? TextStyle(),
);
titleTextStyle = TextStyle(
fontSize: 60.0,
color: textColor,
fontWeight: FontWeight.w400,
textBaseline: TextBaseline.alphabetic,
letterSpacing: -0.5)
.merge(titleTextStyle ?? TextStyle());
buttonTheme ??= ButtonThemeData(
padding: EdgeInsets.all(12),
buttonColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(color: Colors.grey),
),
);
buttonIconTheme ??= IconThemeData();
buttonTextStyle ??= TextStyle();
flutterLogoColor ??= FlutterLogoColor.original;
frameTheme ??= FrameThemeData();
return TemplateThemeData.raw(
brightness: brightness,
flutterLogoColor: flutterLogoColor,
titleTextStyle: titleTextStyle,
backgroundColor: backgroundColor,
descriptionTextStyle: descriptionTextStyle,
buttonTheme: buttonTheme,
buttonTextStyle: buttonTextStyle,
buttonIconTheme: buttonIconTheme,
frameTheme: frameTheme);
}
TemplateThemeData.raw({
this.flutterLogoColor,
this.titleTextStyle,
this.descriptionTextStyle,
this.backgroundColor,
this.buttonTheme,
this.brightness,
this.frameTheme,
this.buttonTextStyle,
this.buttonIconTheme,
}) : assert(flutterLogoColor != null),
assert(titleTextStyle != null),
assert(descriptionTextStyle != null),
assert(backgroundColor != null),
assert(buttonTheme != null),
assert(brightness != null),
assert(buttonTextStyle != null),
assert(buttonIconTheme != null),
assert(frameTheme != null);
static TemplateThemeData light() {
return TemplateThemeData(
brightness: Brightness.light,
titleTextStyle: TextStyle(
fontSize: 60.0,
color: Colors.black,
fontWeight: FontWeight.w400,
textBaseline: TextBaseline.alphabetic,
letterSpacing: -0.5),
flutterLogoColor: FlutterLogoColor.original,
descriptionTextStyle: TextStyle(color: Colors.black),
backgroundColor: Colors.white,
buttonTheme: ButtonThemeData(
buttonColor: Colors.grey[100],
padding: EdgeInsets.all(12),
hoverColor: Colors.grey[200],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(color: Colors.grey),
),
),
);
}
static TemplateThemeData dark() {
return TemplateThemeData(
brightness: Brightness.dark,
titleTextStyle: TextStyle(
fontSize: 60.0,
color: Colors.white,
fontWeight: FontWeight.w400,
textBaseline: TextBaseline.alphabetic,
letterSpacing: -0.5),
descriptionTextStyle: TextStyle(color: Colors.white),
flutterLogoColor: FlutterLogoColor.white,
buttonTheme: ButtonThemeData(
padding: EdgeInsets.all(12),
buttonColor: Colors.grey[900],
hoverColor: Colors.grey[700],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(color: Colors.grey),
),
),
);
}
static TemplateThemeData black() {
return TemplateThemeData(
brightness: Brightness.dark,
titleTextStyle: TextStyle(
fontSize: 60.0,
color: Colors.white,
fontWeight: FontWeight.w400,
textBaseline: TextBaseline.alphabetic,
letterSpacing: -0.5),
descriptionTextStyle: TextStyle(color: Colors.white),
flutterLogoColor: FlutterLogoColor.white,
backgroundColor: Colors.black,
frameTheme: FrameThemeData(
frameColor: Colors.white, statusBarBrightness: Brightness.dark),
buttonTheme: ButtonThemeData(
padding: EdgeInsets.all(12),
buttonColor: Colors.grey[900],
hoverColor: Colors.grey[700],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(color: Colors.grey),
),
),
);
}
}
enum FlutterLogoColor {
original,
white,
black,
}
extension FlutterLogoColorImage on FlutterLogoColor {
ImageProvider image() {
switch (this) {
case FlutterLogoColor.original:
return AssetImage(
'assets/flutter_original.png',
package: 'flutter_showcase',
);
case FlutterLogoColor.white:
return AssetImage(
'assets/flutter_white.png',
package: 'flutter_showcase',
);
case FlutterLogoColor.black:
return AssetImage(
'assets/flutter_black.png',
package: 'flutter_showcase',
);
}
return null;
}
}
| 0
|
mirrored_repositories/flutter_showcase/lib/src
|
mirrored_repositories/flutter_showcase/lib/src/core/template.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
import 'package:flutter_showcase/src/core/theme.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
class TemplateData {
final String title;
final String description;
final List<LinkData> links;
final TemplateThemeData theme;
final LinkData logoLink;
TemplateData({
this.theme,
this.title,
this.logoLink,
this.description,
this.links,
});
}
class LinkData {
final Widget icon;
final String url;
final String title;
LinkData({this.icon, this.url, this.title});
factory LinkData.github(String url) {
return LinkData(
url: url,
title: 'Github',
icon: Icon(FontAwesomeIcons.github),
);
}
factory LinkData.codePen(String url) {
return LinkData(
url: url,
title: 'CodePen',
icon: Icon(FontAwesomeIcons.codepen),
);
}
factory LinkData.pub(String url) {
return LinkData(
url: url,
title: 'Pub.dev',
icon: Image.asset('assets/dart.png', package: 'flutter_showcase'),
);
}
}
abstract class Template {
Widget builder({
BuildContext context,
TemplateData data,
Widget app,
});
Widget screenshotBuilder({
BuildContext context,
TemplateData data,
Widget app,
}) =>
builder(
context: context,
data: data,
app: app,
);
}
| 0
|
mirrored_repositories/flutter_showcase/lib/src
|
mirrored_repositories/flutter_showcase/lib/src/frame/frame.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
import 'package:flutter_showcase/src/frame/frame_theme.dart';
class FrameBuilder extends StatelessWidget {
final Widget app;
final TransitionBuilder builder;
const FrameBuilder({
this.app,
this.builder,
});
@override
Widget build(BuildContext context) {
return Frame(
app: builder(context, app),
);
}
}
class Frame extends StatelessWidget {
final Widget app;
const Frame({Key key, this.app}) : super(key: key);
static TransitionBuilder get builder => (context, app) => Frame(app: app);
@override
Widget build(BuildContext context) {
if (!isShowcaseActive) {
return app;
}
final theme = DefaultFrameTheme.of(context).data;
final shouldDisplayTemplate = MediaQuery.of(context).size.width > 600;
if (!shouldDisplayTemplate) {
return app;
} else {
final MediaQueryData mediaQuery = MediaQueryData(
size: Size(414, 896),
padding: EdgeInsets.only(
top: 44,
bottom: 34,
),
devicePixelRatio: 2,
);
return FittedBox(
child: Material(
color: Colors.transparent,
child: Builder(builder: (context) {
final device = MediaQuery(
data: mediaQuery,
child: SizedBox.fromSize(
size: mediaQuery.size,
child: Stack(
fit: StackFit.expand,
children: <Widget>[
app,
Positioned(
top: 0,
left: 0,
right: 0,
height: 44,
child: _StatusBar(theme: theme),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
margin: EdgeInsets.only(bottom: 8),
height: 4,
width: 140,
decoration: BoxDecoration(
color: theme.statusBarColor,
borderRadius: BorderRadius.circular(4)),
),
)
],
)),
);
return Container(
child: ClipRRect(
clipBehavior: Clip.antiAlias,
borderRadius: BorderRadius.circular(38.5),
child: device),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(50),
border: Border.all(color: theme.frameColor, width: 12)),
);
}),
),
);
}
}
}
class _StatusBar extends StatelessWidget {
final FrameThemeData theme;
const _StatusBar({Key key, this.theme}) : super(key: key);
@override
Widget build(BuildContext context) {
final date = DateTime.now();
return Theme(
data: ThemeData(brightness: theme.statusBarBrightness),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Padding(
padding: EdgeInsets.only(left: 30, top: 4),
child: Text(
'${date.hour}:${date.minute}',
style: TextStyle(
fontWeight: FontWeight.bold, color: theme.statusBarColor),
)),
Padding(
padding: EdgeInsets.only(right: 18),
child: Row(
children: <Widget>[
Icon(
Icons.signal_cellular_4_bar,
size: 14,
),
SizedBox(width: 4),
Icon(Icons.wifi, size: 16),
SizedBox(width: 4),
Icon(CupertinoIcons.battery_charging, size: 20)
],
),
)
],
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/lib/src
|
mirrored_repositories/flutter_showcase/lib/src/frame/frame_theme.dart
|
import 'package:equatable/equatable.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Defines the theme of the device frame
/// that wraps the app
///
/// [frameColor] allows to personalize the color of the device frame
/// [statusBarBrightness] sets the status bar to white/black
///
///
class FrameThemeData implements Equatable {
final Color frameColor;
final Brightness statusBarBrightness;
// const FrameThemeData({this.frameColor, this.statusBarBrightness});
factory FrameThemeData({Color frameColor, Brightness statusBarBrightness}) {
frameColor ??= Colors.black;
statusBarBrightness ??= Brightness.light;
return FrameThemeData.raw(
frameColor: frameColor,
statusBarBrightness: statusBarBrightness,
);
}
const FrameThemeData.raw({
this.frameColor,
this.statusBarBrightness,
}) : assert(frameColor != null),
assert(statusBarBrightness != null);
@override
List<Object> get props => [frameColor, statusBarBrightness];
@override
bool get stringify => false;
Color get statusBarColor =>
statusBarBrightness == Brightness.dark ? Colors.white : Colors.black;
}
class DefaultFrameTheme extends InheritedTheme {
final FrameThemeData data;
DefaultFrameTheme({
Key key,
this.data,
@required Widget child,
}) : super(key: key, child: child);
static DefaultFrameTheme of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DefaultFrameTheme>() ??
DefaultFrameTheme.fallback();
}
DefaultFrameTheme.fallback() : data = FrameThemeData();
@override
bool updateShouldNotify(DefaultFrameTheme oldWidget) {
return data != oldWidget.data;
}
@override
Widget wrap(BuildContext context, Widget child) {
final DefaultFrameTheme defaultSpacing =
context.findAncestorWidgetOfExactType<DefaultFrameTheme>();
return identical(this, defaultSpacing)
? child
: DefaultFrameTheme(
data: data,
child: child,
);
}
/* @override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
}*/
}
| 0
|
mirrored_repositories/flutter_showcase
|
mirrored_repositories/flutter_showcase/test/flutter_showcase_test.dart
|
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
void main() {
}
| 0
|
mirrored_repositories/flutter_showcase
|
mirrored_repositories/flutter_showcase/bin/flutter_showcase.dart
|
import 'dart:io';
import 'package:args/args.dart';
import 'common/directory.dart';
import 'common/html_generator.dart';
import 'common/social_metadata.dart';
import 'screenshot.dart';
bool _useSkia = true;
Future<void> main(List<String> args) async {
final parser = ArgParser();
parser.addOption('title');
parser.addOption('github_url');
parser.addOption('description');
parser.addOption('FLUTTER_WEB_USE_SKIA');
final results = parser.parse(args);
_useSkia = results['FLUTTER_WEB_USE_SKIA'] != "false" ?? true;
/*final Status status = globals.logger.startProgress('Compiling profile for the Web...', timeout: null);*/
final socialMetadata = generateMetadata();
await flutterBuildShowcase();
try {
await takeScreenshot();
} catch (err) {
print(err);
}
generateHtmlFile(socialMetadata);
}
Future flutterBuildShowcase() async {
Directory('build/web_old')..removeIfExistsSync();
Directory('build/web')..renameIfExistsSync('build/web_old');
final process = await Process.start(
'flutter',
[
'build',
'web',
'--dart-define=FLUTTER_WEB_USE_SKIA=${_useSkia ? 'true' : 'false'}',
'--dart-define=FLUTTER_SHOWCASE=true',
],
);
stdout.addStream(process.stdout);
stderr.addStream(process.stderr);
await process.exitCode;
Directory('build/web_showcase')..removeIfExistsSync();
Directory('build/web')..renameIfExistsSync('build/web_showcase');
Directory('build/web_old')..renameIfExistsSync('build/web');
}
//
| 0
|
mirrored_repositories/flutter_showcase
|
mirrored_repositories/flutter_showcase/bin/screenshot.dart
|
import 'dart:io';
import 'common/common.dart';
import 'common/directory.dart';
import 'common/web_driver.dart';
const _appFilePath = 'showcase/src/app.dart';
const _appTestFilePath = 'showcase/src/app_test.dart';
Future takeScreenshot({String browser = 'chrome'}) async {
Directory('showcase/src')..createIfNotExistSync();
final temp = [
File(_appFilePath)..writeAsStringSync(_appFile),
File('showcase/src/app_test.dart')..writeAsStringSync(_appTestFile)
];
WebDriver driver;
if (browser == 'chrome')
driver = ChromeDriver();
else if (browser == 'safari')
driver = SafariDriver();
else
throwToolExit('$browser is not supported');
print('before start');
await driver.start();
print('after driver started');
final screenshotProccess = await Process.start(
'flutter',
[
'drive',
'--target=$_appFilePath',
'--driver=$_appTestFilePath',
'--browser-name=$browser',
'-dweb-server',
'--release',
'--dart-define=SCREENSHOT_MODE=true',
'--dart-define=FLUTTER_SHOWCASE=true'
],
);
await stdout.addStream(screenshotProccess.stdout);
await stderr.addStream(screenshotProccess.stderr);
await screenshotProccess.exitCode;
driver.close();
temp.forEach((file) {
file.deleteSync(recursive: true);
});
}
final String _appFile = '''
import 'package:flutter_driver/driver_extension.dart';
import '../../lib/main.dart' as app;
void main() {
// This line enables the extension
enableFlutterDriverExtension();
// Call the `main()` function of your app or call `runApp` with any widget you
// are interested in testing.
app.main();
}
''';
final String _appTestFile = '''
import 'dart:io';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:test/test.dart';
void main() {
group('Flutter Showcase', () {
// First, define the Finders and use them to locate widgets from the
// test suite. Note: the Strings provided to the `byValueKey` method must
// be the same as the Strings we used for the Keys in step 1.
final counterTextFinder = find.byTooltip('Button');
final buttonFinder = find.byValueKey('increment');
FlutterDriver driver;
// Connect to the Flutter driver before running any tests.
setUpAll(() async {
driver = await FlutterDriver.connect();
});
// Close the connection to the driver after the tests have completed.
tearDownAll(() async {
if (driver != null) {
driver.close();
}
});
test('screenshot', () async {
final image = await driver.screenshot();
var fileCopy = await File('build/web_showcase/social_media.png').writeAsBytes(image);
});
});
}
''';
| 0
|
mirrored_repositories/flutter_showcase
|
mirrored_repositories/flutter_showcase/bin/autogenerate.dart
|
import 'dart:io';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/standard_ast_factory.dart';
import 'package:analyzer/dart/analysis/utilities.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:_fe_analyzer_shared/src/scanner/token.dart';
import 'package:dart_style/dart_style.dart';
import 'common/common.dart';
import 'package:args/args.dart';
import 'dart:convert';
void main(List<String> args) {
final parser = ArgParser();
parser.addOption('dir', defaultsTo: '');
parser.addOption('title');
parser.addOption('github_url');
parser.addOption('description');
parser.addOption('links');
final results = parser.parse(args);
final directoryPath = results['dir'];
print('Auto adding Flutter Showcase to project in path $directoryPath');
try {
addShowcasePackageIfMissing(path: directoryPath);
} catch (e) {
stderr.writeln(
'An error occurred while adding showcase package in ${directoryPath}pubspec.yaml');
throw (e);
}
Map<String, String> linksFromEncodedJson(String links) {
if (links == null) return {};
try {
var codedLinks = links;
if (links.startsWith('"') && links.endsWith('"')) {
codedLinks = links.substring(1, links.length - 1);
}
final json = jsonDecode(codedLinks);
return Map<String, String>.from(json);
} catch (e) {
print(e);
return {};
}
}
try {
ProjectGenerator(
title: results['title'],
description: results['description'],
githubUrl: results['github_url'],
links: linksFromEncodedJson(results['links']),
).generate(path: directoryPath);
} catch (e) {
stderr.writeln(
'An error occurred while generating showcase widget inside ${directoryPath}lib/main.dart\n');
rethrow;
}
}
/// Add missing dependencies to pubspec.yaml
///
void addShowcasePackageIfMissing({String path = ''}) {
final pubspecName = '${path}pubspec.yaml';
final pubspec = File(pubspecName);
final lines = pubspec.readAsLinesSync();
int dependencyLine;
final trackLibraries = {
' flutter_test:': false,
' flutter_showcase:': false,
' flutter_driver:': false,
' test:': false,
};
for (final line in lines.asMap().entries) {
if (line.value.startsWith(' flutter:')) {
dependencyLine = line.key + 2;
} else {
trackLibraries.forEach((key, value) {
if (!value && line.value.contains(key)) {
trackLibraries[key] = true;
}
});
}
}
if (dependencyLine != null) {
trackLibraries.forEach((package, isAlreadyAdded) {
if (!isAlreadyAdded) {
lines.insert(dependencyLine, package);
dependencyLine += 1;
if ({' flutter_driver:', ' flutter_test:'}.contains(package)) {
lines.insert(dependencyLine, ' sdk: flutter');
dependencyLine += 1;
}
}
});
final newFile = lines.join('\n');
pubspec.writeAsStringSync(newFile);
print('Succesfully added packages to project');
return;
} else {
throw ('No dependecy section in $pubspecName');
}
}
class ProjectGenerator {
final String title;
final String description;
final String githubUrl;
final Map<String, String> links;
ProjectGenerator({
this.title = '',
this.description = '',
this.githubUrl = '',
this.links = const {},
});
/// Add missing dependencies to pubspec.yaml
///
void generate({
String path = '',
}) {
final featureSet = FeatureSet.fromEnableFlags([
'extension-methods',
'non-nullable',
]);
final filePath = '${path}lib/main.dart';
final fileContent = File(filePath).readAsStringSync();
// TODO: Add support for WidgetApp and CupertinoApp
if (fileContent.contains('MaterialApp') && fileContent.contains('main')) {
final parseResult = parseString(
content: fileContent,
featureSet: featureSet,
path: filePath,
throwIfDiagnostics: false,
);
final unit = parseResult.unit;
importPackageIfMissing(unit);
var v = AddShowcaseVisitor(this);
unit.visitChildren(v);
var formatter = new DartFormatter();
try {
final newContent = formatter.format(unit.toSource());
File(filePath).writeAsStringSync(newContent);
} on FormatterException catch (ex) {
throwToolExit('Error while formatting new file\n${ex}');
}
print('Adding showcase to project succesfully');
} else {
throwToolExit('There is no MaterialApp in lib/main.dart');
}
}
String addShowcaseProject(String s) {
return '''
Showcase(
title: $title,
description: $description,
links: [
${githubUrl != null ? 'LinkData.github(\'$githubUrl\'),' : ''}
${links['pub'] != null ? 'LinkData.pub(\'${links['pub']}\'),' : ''}
],
app: $s)
''';
}
/// Add missing dependencies to pubspec.yaml
///
void importPackageIfMissing(CompilationUnit unit) {
final packageImport =
'import \'package:flutter_showcase/flutter_showcase.dart\';';
if (!unit.toSource().contains(packageImport)) {
final Directive node = unit.directives.last;
final Directive clone = AstCloner().cloneNode(node);
int offset = clone.offset;
StringToken importToken = StringToken(TokenType.STRING, 'import', offset);
StringToken semiColonToken =
StringToken(TokenType.STRING, ';', offset + packageImport.length - 1);
final packageString =
'\'package:flutter_showcase/flutter_showcase.dart\'';
StringToken st = StringToken(
TokenType.STRING, packageString, offset + importToken.length);
final ssl = astFactory.simpleStringLiteral(st, packageString);
final ImportDirective newDirectory = astFactory.importDirective(null,
null, importToken, ssl, null, null, null, null, null, semiColonToken);
unit.directives.add(newDirectory);
}
}
}
class AddShowcaseVisitor extends RecursiveAstVisitor {
final ProjectGenerator generator;
AddShowcaseVisitor(this.generator);
@override
visitMethodInvocation(MethodInvocation node) {
//Check if Material App exits
if (node.toSource().contains('MaterialApp')) {
if (!node.toSource().startsWith('MaterialApp')) {
var v = AddShowcaseVisitor(generator);
node.visitChildren(v);
} else {
// Check if [builder] argument is called
if (node.toSource().contains('builder:')) {
final builderNode = node.argumentList.arguments
.where((element) => element.toSource().contains('builder:'))
.first;
// Check if [builder] argument contains already a frame builder
if (!builderNode.toSource().contains('Frame.builder') ||
!builderNode.toSource().contains('FrameBuilder')) {
print(builderNode.toSource());
String newString =
'builder: (context, child) => FrameBuilder(app: child, ${builderNode.toString()})';
int offset = builderNode.offset;
StringToken st = StringToken(TokenType.STRING, newString, offset);
final ssl = astFactory.simpleStringLiteral(st, newString);
final NodeReplacer replacer = NodeReplacer(builderNode, ssl);
builderNode.parent.accept(replacer);
}
} else {
// Add frame builder
final builderNode = node.argumentList.arguments.first;
print(builderNode);
String newString =
'${builderNode.toString()}, builder: Frame.builder';
int offset = builderNode.offset;
StringToken st = StringToken(TokenType.STRING, newString, offset);
final ssl = astFactory.simpleStringLiteral(st, newString);
final NodeReplacer replacer = NodeReplacer(builderNode, ssl);
builderNode.parent.accept(replacer);
}
}
}
if (node.toSource().startsWith('runApp') &&
!node.toSource().contains('Showcase')) {
print(node.toSource());
final widget = node.argumentList.arguments.first;
SimpleStringLiteral ssl = _createSimpleStringLiteral(widget);
final NodeReplacer replacer = NodeReplacer(widget, ssl);
widget.parent.accept(replacer);
}
}
SimpleStringLiteral _createSimpleStringLiteral(AstNode node) {
String newString = generator.addShowcaseProject(node.toString());
int offset = node.offset;
StringToken st = StringToken(TokenType.STRING, newString, offset);
return astFactory.simpleStringLiteral(st, newString);
}
}
/*
SimpleStringLiteral _create_SimpleStringLiteral(AstNode node){
String new_string = modify(node.toString());
int line_num = node.offset;
//holds the position and type
StringToken st = new StringToken(
TokenType.STRING,new_string,line_num);
return new SimpleStringLiteral(st, new_string);
}
String modify(String s){
List parts = s.split('=');
var value = parts[1];
List l = parts[0].split('.');
String dynamism = l.sublist(0,l.length-1).join('.');
String propertyName = l.last.trim();
return '${dynamism}.set("${propertyName}",${value})';
}*/
| 0
|
mirrored_repositories/flutter_showcase/bin
|
mirrored_repositories/flutter_showcase/bin/common/html_generator.dart
|
import 'dart:io';
import 'social_metadata.dart';
void generateHtmlFile(SocialMetadata socialMetadata) {
final template = _template(socialMetadata);
File('build/web_showcase/index.html')..writeAsStringSync(template);
}
String _template(SocialMetadata socialMetadata) => '''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<!-- Primary Meta Tags -->
<title>${socialMetadata.title ?? ''}</title>
<meta name="title" content="${socialMetadata.title ?? ''}">
<meta name="description" content="${socialMetadata.description ?? ''}">
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:url" content="${socialMetadata.url ?? ''}">
<meta property="og:title" content="${socialMetadata.title ?? ''}">
<meta property="og:description" content="${socialMetadata.description ?? ''}">
<meta property="og:image" content="./social_media.png">
<!-- Twitter -->
<meta property="twitter:card" content="summary_large_image">
<meta property="twitter:url" content="${socialMetadata.url ?? ''}">
<meta property="twitter:title" content="${socialMetadata.title ?? ''}">
<meta property="twitter:description" content="${socialMetadata.description ?? ''}">
<meta property="og:image" content="./social_media.png">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="example">
<link rel="apple-touch-icon" href="/icons/Icon-192.png">
<!-- Favicon -->
<link rel="shortcut icon" type="image/png" href="/favicon.png"/>
<link rel="manifest" href="/manifest.json">
</head>
<body>
<!-- This script installs service_worker.js to provide PWA functionality to
application. For more information, see:
https://developers.google.com/web/fundamentals/primers/service-workers -->
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/flutter_service_worker.js');
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
''';
| 0
|
mirrored_repositories/flutter_showcase/bin
|
mirrored_repositories/flutter_showcase/bin/common/common.dart
|
void throwToolExit(String message, {int exitCode}) {
throw ToolExit(message, exitCode: exitCode);
}
class ToolExit implements Exception {
ToolExit(this.message, {this.exitCode});
final String message;
final int exitCode;
@override
String toString() => 'Exception: $message';
}
| 0
|
mirrored_repositories/flutter_showcase/bin
|
mirrored_repositories/flutter_showcase/bin/common/social_metadata.dart
|
import 'dart:io';
import 'package:yaml/yaml.dart';
class SocialMetadata {
final String title;
final String description;
final String url;
SocialMetadata({this.title, this.description, this.url});
@override
String toString() => 'SocialMetadata:\n $title,\n $description, \n$url';
}
SocialMetadata generateMetadata() {
try {
String content = File('pubspec.yaml').readAsStringSync();
final doc = loadYaml(content);
String title;
String description;
String url;
if (doc is YamlMap) {
final showcaseNode = doc['showcase'];
if (showcaseNode is YamlMap) {
title = showcaseNode['title'];
description = showcaseNode['description'];
url = showcaseNode['url'];
}
} else {
print('no map $doc');
}
title ??= doc['name'];
description ??= doc['description'];
return SocialMetadata(title: title, description: description, url: url);
} catch (e) {
stderr.writeln('Error while parsion social metadata');
throw (e);
}
}
| 0
|
mirrored_repositories/flutter_showcase/bin
|
mirrored_repositories/flutter_showcase/bin/common/web_driver.dart
|
import 'dart:io';
abstract class WebDriver {
Process process;
List<String> get arguments => [];
String get command;
Future start() async {
assert(process == null, 'driver is already running');
process = await Process.start(
command,
arguments,
);
}
void close() {
assert(process != null, 'driver is already closed');
process.kill(ProcessSignal.sigusr1);
process = null;
}
}
class ChromeDriver extends WebDriver {
@override
String get command => 'chromedriver';
@override
List<String> get arguments => [
'--port=4444',
];
}
class SafariDriver extends WebDriver {
@override
String get command => 'chromedriver';
@override
List<String> get arguments => [
'--port=4444',
];
}
| 0
|
mirrored_repositories/flutter_showcase/bin
|
mirrored_repositories/flutter_showcase/bin/common/directory.dart
|
import 'dart:io';
extension DirectoryUtils on Directory {
Future<Directory> renameIfExists(String name) async {
if (await this.exists()) {
return await this.rename(name);
}
return this;
}
Directory renameIfExistsSync(String name) {
if (existsSync()) {
return this.renameSync(name);
}
return this;
}
Future<Directory> createIfNotExist() async {
if (!(await this.exists())) {
return await this.create(recursive: true);
}
return this;
}
void createIfNotExistSync() {
if (!existsSync()) {
return this.createSync(recursive: true);
}
}
Future<void> removeIfExists() async {
if (await exists()) {
await delete(recursive: true);
}
}
void removeIfExistsSync() {
if (existsSync()) {
deleteSync(recursive: true);
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example
|
mirrored_repositories/flutter_showcase/example/lib/main.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'apps/apps.dart';
import 'indicator/smooth_page_indicator.dart';
import 'indicator/effects/expanding_dots_effect.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
void main() => runApp(Examples());
class Examples extends StatefulWidget {
@override
State<StatefulWidget> createState() => _ExamplesState();
}
class _ExamplesState extends State<Examples> {
PageController pageController;
@override
void initState() {
pageController = PageController(initialPage: 0);
super.initState();
}
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(children: [
PageView.builder(
controller: pageController,
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
if (index > 0 && index <= GskinnerApps.values.length) {
final app = GskinnerApps.values[index - 1];
return app.showcase;
} else {
return Showcase(
title: 'Flutter Showcase',
app: MyApp(pageController: pageController),
description: '''
Share your Flutter project with the world
''',
template: SimpleTemplate(reverse: false),
theme: TemplateThemeData(
backgroundColor: Colors.grey[100],
titleTextStyle:
TextStyle(fontWeight: FontWeight.w700),
descriptionTextStyle: TextStyle(
fontSize: 24,
height: 1.2,
fontWeight: FontWeight.w200)),
links: [
LinkData.github(
'https://github.com/jamesblasco/flutter_showcase'),
LinkData.pub(
'https://github.com/jamesblasco/flutter_showcase')
],
logoLink: LinkData(
icon: Image.asset('assets/jaime_logo.png',
fit: BoxFit.fitHeight),
url: 'https://github.com/jamesblasco'));
}
},
itemCount: 1 + GskinnerApps.values.length),
Align(
alignment: Alignment.centerRight,
child: Padding(
padding: EdgeInsets.all(20),
child: SmoothPageIndicator(
controller: pageController,
count: 1 + GskinnerApps.values.length,
effect: ExpandingDotsEffect(
radius: 14,
dotHeight: 10,
dotWidth: 10,
dotColor: Colors.black12,
activeDotColor: Colors.black87))))
]));
}
}
class MyApp extends StatelessWidget {
final PageController pageController;
const MyApp({Key key, this.pageController}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Showcase',
builder: (context, child) =>
FrameBuilder(app: child, builder: Frame.builder),
debugShowCheckedModeBanner: false,
theme: ThemeData(accentColor: Colors.black, primaryColor: Colors.white),
home: MyHomePage(title: 'Your app', pageController: pageController));
}
}
class MyHomePage extends StatefulWidget {
final PageController pageController;
MyHomePage({Key key, this.title, this.pageController}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('Add your App here',
style: Theme.of(context)
.textTheme
.headline4
.copyWith(color: Colors.black87)),
SizedBox(height: 8),
Text('Make your showcase project interactive',
style: TextStyle(fontSize: 20)),
SizedBox(height: 200),
Text('Scroll down\nto explore some examples',
style: TextStyle(fontSize: 20), textAlign: TextAlign.center),
SizedBox(height: 20),
FloatingActionButton(
onPressed: () => widget.pageController?.animateToPage(1,
duration: Duration(seconds: 1), curve: Curves.easeInOutQuart),
tooltip: 'Scroll',
child: Icon(Icons.arrow_downward))
])));
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib
|
mirrored_repositories/flutter_showcase/example/lib/apps/gskinner_apps.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
import 'package:gooey_edge/demo.dart' deferred as gooey_edge;
import 'package:ticket_fold/demo.dart' deferred as ticket_fold;
import 'package:parallax_travel_cards_list/demo.dart'
deferred as parallax_travel_cards_list;
import 'package:product_detail_zoom/demo.dart' deferred as product_detail_zoom;
import 'package:indie_3d/demo.dart' deferred as indie_3d;
import 'package:constellations_list/demo.dart' deferred as constellations_list;
import 'package:bubble_tab_bar/demo.dart' deferred as bubble_tab_bar;
import 'package:dog_slider/demo.dart' deferred as dog_slider;
import 'package:shared/env.dart';
class GskinnerApp extends StatefulWidget {
final _GskinnerApp app;
final TemplateThemeData theme;
const GskinnerApp({Key key, this.app, this.theme}) : super(key: key);
@override
State<StatefulWidget> createState() => _AppState();
}
class _AppState extends State<GskinnerApp> {
@override
void initState() {
Env.isGalleryActive = true;
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: widget.app.loadLibrary(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
return MaterialApp(
builder: Frame.builder,
debugShowCheckedModeBanner: false,
home: widget.app.page(context),
);
} else {
return Frame.builder(
context, Container(color: widget.theme.backgroundColor));
}
});
}
}
class _GskinnerApp {
final String title;
final String description;
final String githubUrl;
final String codePenUrl;
final Future<dynamic> Function() loadLibrary;
final WidgetBuilder page;
final TemplateThemeData theme;
_GskinnerApp(
{this.title,
this.description,
this.githubUrl,
this.loadLibrary,
this.page,
this.theme,
this.codePenUrl});
Widget get showcase => Showcase(
key: Key('showcase: $title'),
title: title,
template: SimpleTemplate(),
app: GskinnerApp(
app: this,
theme: theme,
),
theme: theme,
description: description,
links: [
LinkData.github(githubUrl),
if (codePenUrl != null) LinkData.codePen(codePenUrl),
],
logoLink: LinkData(
url: 'https://flutter.gskinner.com/',
icon: Opacity(
opacity: 0.8,
child: Padding(
padding: EdgeInsets.only(top: 20),
child: Image.asset(
theme.brightness == Brightness.dark
? 'assets/logo-gskinner-white.png'
: 'assets/logo-gskinner.png',
fit: BoxFit.fitHeight,
)),
),
),
);
}
class GskinnerApps {
static _GskinnerApp gooeyEdge = _GskinnerApp(
title: 'Mindfullness Gooey Transition',
description: '''
Built by gskinner
Three onboarding screens that introducing you to a mindfulness app. Swiping between three screens gives you a fluid transition from one screen to the next.
Draw curved vector paths and use them to mask content. Utilizes a small physics simulation to calculate tension between a set of points.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/gooey_edge',
loadLibrary: gooey_edge.loadLibrary,
codePenUrl: 'https://codepen.io/team/codepen/pen/XWmXMBb',
page: (_) => gooey_edge.GooeyEdgeDemo(title: 'Gooey Edge Demo'),
theme: TemplateThemeData(
brightness: Brightness.dark,
buttonTheme: ButtonThemeData(
buttonColor: Color(0xFF4259B2),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
textTheme: ButtonTextTheme.accent,
padding: EdgeInsets.all(16),
),
flutterLogoColor: FlutterLogoColor.white,
descriptionTextStyle: TextStyle(
color: Colors.white70,
fontWeight: FontWeight.w300,
fontFamily: 'OpenSans',
package: 'gooey_edge'),
titleTextStyle: TextStyle(
color: Colors.white,
fontFamily: 'DMSerifDisplay',
package: 'gooey_edge'),
backgroundColor: Color(0xFFE95B43),
frameTheme: FrameThemeData(statusBarBrightness: Brightness.dark),
buttonTextStyle: TextStyle(
fontSize: 16,
letterSpacing: .8,
fontFamily: 'OpenSans',
fontWeight: FontWeight.w600,
color: Colors.white,
package: 'gooey_edge'),
buttonIconTheme: IconThemeData(color: Colors.white)),
);
static _GskinnerApp ticketFold = _GskinnerApp(
title: 'Boarding Pass Cards',
description: '''
Built by gskinner
All your boarding passes in one place, tapping them flips the card open to see more details about your flight.
Uses the Transform widget to create a folding card effect. In this case a boarding pass with multiple folds, each fold containing a child widget.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/ticket_fold',
loadLibrary: ticket_fold.loadLibrary,
page: (_) => ticket_fold.TicketFoldDemo(),
theme: TemplateThemeData(
brightness: Brightness.light,
buttonTheme: ButtonThemeData(
buttonColor: Color(0xFF083e64),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
textTheme: ButtonTextTheme.accent,
padding: EdgeInsets.all(16),
),
flutterLogoColor: FlutterLogoColor.original,
descriptionTextStyle: TextStyle(
color: Color(0xFF083e64),
fontWeight: FontWeight.w300,
fontFamily: 'OpenSans',
package: 'gooey_edge'),
titleTextStyle: TextStyle(
color: Color(0xFF212121),
fontFamily: 'OpenSans',
fontSize: 50,
fontWeight: FontWeight.w700,
package: 'ticket_fold'),
backgroundColor: Color(0xFFf0f0f0),
buttonTextStyle: TextStyle(
fontSize: 16,
letterSpacing: .8,
fontFamily: 'OpenSans',
fontWeight: FontWeight.w600,
color: Colors.white,
package: 'ticket_fold'),
buttonIconTheme: IconThemeData(color: Colors.white)),
);
static _GskinnerApp parallaxTravelCardsList = _GskinnerApp(
title: 'Travel Cards',
description: '''
Built by gskinner
Browse different destination cards from around the world and see hotel recommendations.
Use a Stack widget to create a parallax effect inside of a list, while also using a Transform to give it a 3D card effect.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/parallax_travel_cards_list',
loadLibrary: parallax_travel_cards_list.loadLibrary,
page: (_) => parallax_travel_cards_list.TravelCardDemo(),
theme: TemplateThemeData(
brightness: Brightness.light,
buttonTheme: ButtonThemeData(
buttonColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
padding: EdgeInsets.all(16),
),
flutterLogoColor: FlutterLogoColor.black,
descriptionTextStyle: TextStyle(
color: Color(0xFF666666),
height: 1.5,
fontWeight: FontWeight.w300,
fontFamily: 'OpenSans',
package: 'parallax_travel_cards_list'),
titleTextStyle: TextStyle(
color: Color(0xFF1a1a1a),
height: 1,
fontFamily: 'DMSerifDisplay',
package: 'parallax_travel_cards_list'),
backgroundColor: Color(0xffdaf3f7),
buttonTextStyle: TextStyle(
fontSize: 16,
letterSpacing: .8,
fontFamily: 'OpenSans',
fontWeight: FontWeight.w600,
color: Color(0xFF1a1a1a),
package: 'ticket_fold'),
buttonIconTheme: IconThemeData(color: Color(0xFF1a1a1a))),
);
static _GskinnerApp productDetailZoom = _GskinnerApp(
title: 'Product Zoom Transition',
description: '''
Built by gskinner
Looking for the perfect speaker? Get a better look at the Classic Speaker 2700 by zooming in and discovering its great features.
Example of an animated png sequence within a Hero animation; also uses a Canvas to render and animate a product detail overlay.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/product_detail_zoom',
loadLibrary: product_detail_zoom.loadLibrary,
page: (_) => product_detail_zoom.ProductDetailZoomDemo(),
theme: TemplateThemeData(
brightness: Brightness.dark,
buttonTheme: ButtonThemeData(
buttonColor: Colors.white,
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
textTheme: ButtonTextTheme.accent,
padding: EdgeInsets.all(16),
),
flutterLogoColor: FlutterLogoColor.white,
descriptionTextStyle: TextStyle(
fontFamily: 'WorkSans',
color: Colors.white70,
fontWeight: FontWeight.w400,
letterSpacing: 2,
package: 'product_detail_zoom'),
titleTextStyle: TextStyle(
fontFamily: 'WorkSans',
fontWeight: FontWeight.bold,
package: 'product_detail_zoom',
color: Colors.white,
height: 1.1,
letterSpacing: 5),
frameTheme: FrameThemeData(
frameColor: Colors.white,
statusBarBrightness: Brightness.dark,
),
backgroundColor: Colors.black,
buttonTextStyle: TextStyle(
fontFamily: 'WorkSans',
color: Colors.black,
fontWeight: FontWeight.bold,
letterSpacing: 2,
package: 'product_detail_zoom'),
buttonIconTheme: IconThemeData(color: Colors.black)),
);
// Doesn't work well with Flutter Web yet
static _GskinnerApp indie3d = _GskinnerApp(
title: 'Feature Artist Carousel.',
description: '''
Built by gskinner
Explore three new indie artists, all with a distinct visual style applied to them.
Uses a custom 3D model renderer and blending mask to create a fun and unique background effect.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/indie_3d',
theme: TemplateThemeData.black(),
loadLibrary: indie_3d.loadLibrary,
page: (_) => indie_3d.Indie3dHome(),
);
// Doesn't work well with Flutter Web yet
static _GskinnerApp constellationsList = _GskinnerApp(
title: 'Guide To the Stars Particles',
description: '''
Built by gskinner
Learn about different constellations in the night sky. Tap on the names to travel through space and see what a constellation looks like.
Shows how to use an animated Canvas as the primary background for your app. In this case, a starfield effect that controls its animation speed based on user scrolling and page transitions.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/constellations_list',
theme: TemplateThemeData.black(),
loadLibrary: constellations_list.loadLibrary,
page: (_) => constellations_list.ConstellationsListDemo(),
);
static _GskinnerApp bubbleTabBar = _GskinnerApp(
title: 'Icon Flip Button Bar',
description: '''
Built by gskinner
Flipping icons, revealing colors and text helps this button bar stand out.
Example of a bespoke NavigationBar with animated buttons that change size, shape, and color when selected.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/bubble_tab_bar',
loadLibrary: bubble_tab_bar.loadLibrary,
page: (_) => bubble_tab_bar.BubbleTabBarDemo(),
);
static _GskinnerApp dogSlider = _GskinnerApp(
title: 'Dog Toy Slider',
description: '''
Built by gskinner
Order your pup some more dog toys! Watch the dog chase the ball as you increase or decrease the amount of fetch balls you want to order.
Use a Flare animation to create a custom Slider control. Creates a custom FlareControl class for playback while the slider itself is painted on a Canvas.
''',
githubUrl:
'https://github.com/gskinnerTeam/flutter_vignettes/tree/master/vignettes/dog_slider',
loadLibrary: dog_slider.loadLibrary,
page: (_) => dog_slider.DogSliderDemo(),
theme: TemplateThemeData(
brightness: Brightness.light,
titleTextStyle: TextStyle(
fontSize: 60.0,
fontFamily: "Quicksand",
package: 'dog_slider',
color: Color(0xff174d4c),
fontWeight: FontWeight.w600,
textBaseline: TextBaseline.alphabetic,
height: 1.2),
flutterLogoColor: FlutterLogoColor.original,
descriptionTextStyle: TextStyle(
color: Colors.black,
fontFamily: "Quicksand",
package: 'dog_slider',
),
buttonTextStyle: TextStyle(color: Colors.white),
buttonIconTheme: IconThemeData(color: Colors.white),
buttonTheme: ButtonThemeData(
buttonColor: Color(0xff2cb5b5),
padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16),
textTheme: ButtonTextTheme.primary,
hoverColor: Color(0xff2cb5b5),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
),
));
static List<_GskinnerApp> values = [
gooeyEdge,
parallaxTravelCardsList,
ticketFold,
productDetailZoom,
dogSlider,
// bubbleTabBar,
//constellationsList,
//indie3d
];
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib
|
mirrored_repositories/flutter_showcase/example/lib/apps/nike_app.dart
|
import 'dart:math';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_showcase/flutter_showcase.dart';
class Product {
final String title;
final String subtitle;
final String price;
final String category;
final String imageUrl;
Product({
this.title,
this.subtitle,
this.price,
this.category,
this.imageUrl,
});
}
class AssetConstants {
static const nikeAirmax =
'https://user-images.githubusercontent.com/20706361/78980641-e5ba1880-7b50-11ea-8356-6842e56dbd48.png';
static const flyKnit =
'https://user-images.githubusercontent.com/20706361/78982399-a55c9980-7b54-11ea-87da-f507cb88a2fa.png';
static const pegasusZoom =
'https://user-images.githubusercontent.com/20706361/78983457-d211b080-7b56-11ea-9c0e-39fa9e51aa9f.png';
static const pegasus36 =
'https://user-images.githubusercontent.com/20706361/78982836-95918500-7b55-11ea-8aba-5615c5fdf784.png';
static const phantom =
'https://user-images.githubusercontent.com/20706361/78983860-9d522900-7b57-11ea-938c-983505fe703c.png';
static const nikeAppLogo = 'https://user-images.githubusercontent.com/20706361/78985475-7d246900-7b5b-11ea-8c4e-8d2040812b3c.png';
}
class NikeApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
builder: Frame.builder,
theme: ThemeData(
primarySwatch: Colors.blue,
),
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>
with SingleTickerProviderStateMixin {
List<Product> _products = [];
PageController _pageController;
double _currentPage = 0;
String _productCategory = 'TRAINING';
AnimationController _animationController;
Animation<Offset> _searchOffsetAnimation;
Animation<Offset> _cartOffsetAnimation;
Animation<double> _nikeLogoOffsetAnimation;
Animation<Offset> _productBackgroundOffsetAnimation;
Animation<Offset> _productOffsetAnimation;
bool _isAnimated = false;
@override
void initState() {
super.initState();
_pageController = PageController(initialPage: 0)
..addListener(() {
setState(() {
_currentPage = _pageController.page;
});
});
// Initialize products
final product1 = Product(
title: 'Nike PhantomVNM\nClub FG',
subtitle: 'PHANTOM PROJECT',
price: '\$69.99',
category: 'Football',
imageUrl: AssetConstants.phantom,
);
final product2 = Product(
title: 'Nike Epic\nReact Flyknit 2',
subtitle: 'EPIC REACT',
price: '\$79.99',
category: 'Running',
imageUrl: AssetConstants.flyKnit,
);
final product3 = Product(
title: 'Nike Air Zoom\nPegasus 36',
subtitle: 'ZOOM PROJECT',
price: '\$89.99',
category: 'Running',
imageUrl: AssetConstants.pegasus36,
);
final product4 = Product(
title: 'Nike Zoom\nPegasus Turbo 2',
subtitle: 'ZOOM PROJECT',
price: '\$99.99',
category: 'Running',
imageUrl: AssetConstants.pegasusZoom,
);
_products.addAll([product1, product2, product3, product4]);
// Prepare animations
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 750),
);
_nikeLogoOffsetAnimation = Tween<double>(
begin: -1000,
end: 0,
).animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.linearToEaseOut,
),
);
// Prepare entrance animation
_animationController.forward();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Color(0xFFF3F3F3),
appBar: AppBar(
leading: Icon(
Icons.search,
color: Colors.black,
),
backgroundColor: Color(0xFFF3F3F3),
elevation: 0,
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 12),
child: Icon(
Icons.shopping_cart,
color: Colors.black,
),
),
],
),
body: Center(
child: AnimatedBuilder(
animation: _animationController,
builder: (BuildContext context, Widget child) {
return Stack(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: size.height * 0.60,
width: size.width,
child: PageView.builder(
physics: BouncingScrollPhysics(),
itemCount: _products.length,
controller: _pageController,
itemBuilder: (BuildContext context, int index) {
_productCategory = _products[index].category;
if (index == _currentPage.floor()) {
return PageItemView(
product: _products[index],
index: index,
page: _currentPage,
alignment: FractionalOffset.centerRight,
);
} else if (index == _currentPage.floor() + 1) {
return PageItemView(
product: _products[index],
index: index,
page: _currentPage,
alignment: FractionalOffset.centerLeft,
);
} else {
return PageItemView(
product: _products[index],
index: index,
page: _currentPage,
);
}
},
),
),
],
),
Transform.translate(
offset: Offset(
size.width / 2 - 25,
_nikeLogoOffsetAnimation.value,
),
child: Container(
height: 100,
width: 50,
child: Image.network(AssetConstants.nikeAppLogo),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(
bottom: 48,
left: 32,
right: 32,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Icon(
Icons.arrow_back,
size: 16,
),
InkWell(
onTap: () {
setState(() {
_isAnimated = !_isAnimated;
});
if (_isAnimated) {
_animationController.forward();
} else {
_animationController.reverse();
}
},
child: Text(
_productCategory.toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w300,
letterSpacing: 2,
),
),
),
Icon(
Icons.arrow_forward,
size: 16,
),
],
),
),
),
],
);
},
),
),
);
}
}
class PageItemView extends StatefulWidget {
final double _defaultItemHeight = 500;
final double _defaultPerspective = 0.002;
final double _defaultAngle = pi / 2;
final double _defaultProductAngle = -1;
final Alignment _defaultAlignment = FractionalOffset.center;
final double itemHeight;
final Product product;
final int index;
final double page;
final double perspective;
final double angle;
final double productAngle;
final Alignment alignment;
PageItemView({
Key key,
@required this.product,
@required this.index,
@required this.page,
this.itemHeight,
this.perspective,
this.angle,
this.productAngle,
this.alignment,
}) : assert(index != null, 'index must not be null!'),
assert(index != null, 'page must not be null!'),
super(key: key);
@override
State<StatefulWidget> createState() {
return _PageItemViewState();
}
}
class _PageItemViewState extends State<PageItemView> {
double get _itemHeight => widget.itemHeight ?? widget._defaultItemHeight;
Alignment get _alignment => widget.alignment ?? widget._defaultAlignment;
Product get _product => widget.product;
int get _index => widget.index ?? 0;
double get _page => widget.page ?? 0;
double get _perspective => widget.perspective ?? widget._defaultPerspective;
double get _angle => widget.angle ?? widget._defaultAngle;
double get _productAngle => widget.angle ?? widget._defaultProductAngle;
@override
Widget build(BuildContext context) {
return Container(
child: Stack(
alignment: Alignment.center,
children: <Widget>[
_alignment != null
? Transform(
transform: Matrix4.identity()
..setEntry(3, 2, _perspective)
..scale(1 - lerpDouble(0, -0.25, _index - _page))
..rotateY(_angle * (_page - _index)),
alignment: _alignment,
child: _buildBackground(_itemHeight),
)
: _buildBackground(_itemHeight),
Transform.translate(
offset: Offset(0, -20),
child: Transform.rotate(
angle: _productAngle * (_page - _index),
child: Container(
height: 160,
child: Center(
child: Transform.rotate(
angle: 276,
child: Image.network(_product.imageUrl),
),
),
),
),
),
],
),
);
}
Widget _buildBackground(double height) {
return Container(
height: height,
width: 250,
margin: const EdgeInsets.all(32),
// TODO: Apparently, box shadow is slow in this transition. Action item: Investigate and file an issue
// boxShadow: [
// BoxShadow(
// offset: Offset(0, 0),
// color: Color(0xFFE3E3E3),
// blurRadius: 30,
// ),
// ],
child: ClipRRect(
clipBehavior: Clip.antiAlias,
borderRadius: BorderRadius.circular(16),
child: Stack(
children: [
Container(
height: height,
color: Colors.white,
),
Align(
alignment: Alignment.topCenter,
child: Padding(
padding: const EdgeInsets.only(top: 32.0),
child: Text(
_product.title.toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w300,
letterSpacing: 1,
),
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 32.0),
child: Text(
_product.subtitle.toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w300,
letterSpacing: 2,
),
),
),
Container(
height: 48,
color: Colors.black,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Expanded(
child: Text(
_product.price.toUpperCase(),
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w300,
letterSpacing: 2,
),
),
),
Container(
height: 48,
width: 48,
color: Color(0xFF232323),
child: Icon(
Icons.add,
color: Colors.white30,
),
)
],
),
),
],
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib
|
mirrored_repositories/flutter_showcase/example/lib/apps/apps.dart
|
export 'nike_app.dart';
export 'gskinner_apps.dart';
| 0
|
mirrored_repositories/flutter_showcase/example/lib
|
mirrored_repositories/flutter_showcase/example/lib/indicator/smooth_page_indicator.dart
|
import 'package:flutter/material.dart';
import 'effects/indicator_effect.dart';
import 'effects/expanding_dots_effect.dart';
import 'painters/indicator_painter.dart';
class SmoothPageIndicator extends AnimatedWidget {
// a PageView controller to listen for page offset updates
final PageController controller;
/// Holds effect configuration to be used in the [IndicatorPainter]
final IndicatorEffect effect;
/// The number of children in [PageView]
final int count;
/// If [textDirection] is [TextDirection.rtl], page offset will be reversed
final TextDirection textDirection;
SmoothPageIndicator({
@required this.controller,
@required this.count,
this.textDirection,
this.effect = const ExpandingDotsEffect(),
Key key,
}) : assert(controller != null),
assert(effect != null),
assert(count != null),
super(listenable: controller, key: key);
@override
Widget build(BuildContext context) {
// if textDirection is not provided use the nearest directionality up the widgets tree;
final isRTL =
(textDirection ?? Directionality.of(context)) == TextDirection.rtl;
return CustomPaint(
// different effects have different sizes
// so we calculate size based on the provided effect
size: effect.calculateSize(count),
// rebuild the painter with the new offset every time it updates
painter: effect.buildPainter(
count,
_currentPage,
isRTL,
),
);
}
double get _currentPage {
try {
return controller.page ?? controller.initialPage.toDouble();
} catch (Exception) {
return controller.initialPage.toDouble();
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib/indicator
|
mirrored_repositories/flutter_showcase/example/lib/indicator/effects/indicator_effect.dart
|
import 'package:flutter/material.dart';
import '../painters/indicator_painter.dart';
abstract class IndicatorEffect {
// Singe dot width
final double dotWidth;
// Singe dot height
final double dotHeight;
// The horizontal space between dots
final double spacing;
// Single dot radius
final double radius;
// Inactive dots color or all dots in some effects
final Color dotColor;
// The active dot color
final Color activeDotColor;
// Inactive dots paint style (fill|stroke) defaults to fill.
final PaintingStyle paintStyle;
/// This is ignored if [paintStyle] is PaintStyle.fill
final double strokeWidth;
const IndicatorEffect({
@required this.strokeWidth,
@required this.dotWidth,
@required this.dotHeight,
@required this.spacing,
@required this.radius,
@required this.dotColor,
@required this.paintStyle,
@required this.activeDotColor,
}) : assert(radius != null),
assert(dotColor != null || paintStyle != null || strokeWidth != null),
assert(activeDotColor != null),
assert(dotWidth != null),
assert(dotHeight != null),
assert(spacing != null),
assert(dotWidth >= 0 &&
dotHeight >= 0 &&
spacing >= 0 &&
strokeWidth >= 0);
// Builds a new painter every time the page offset changes
IndicatorPainter buildPainter(int count, double offset, bool isRTL);
// Calculates the size of canvas based on
// dots count, size and spacing
//
// Other effects can override this function
// to calculate their own size
Size calculateSize(int count) {
return Size(dotWidth * count + (spacing * (count - 1)), dotHeight);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib/indicator
|
mirrored_repositories/flutter_showcase/example/lib/indicator/effects/expanding_dots_effect.dart
|
import 'package:flutter/material.dart';
import '../painters/expanding_dots_painter.dart';
import '../painters/indicator_painter.dart';
import 'indicator_effect.dart';
class ExpandingDotsEffect extends IndicatorEffect {
/// [expansionFactor] is multiplied by [dotWidth] to resolve
/// the width of the expanded dot.
final double expansionFactor;
const ExpandingDotsEffect({
this.expansionFactor = 3,
double offset,
double dotWidth = 16.0,
double dotHeight = 16.0,
double spacing = 8.0,
double radius = 16.0,
Color activeDotColor = Colors.indigo,
Color dotColor = Colors.grey,
double strokeWidth = 1.0,
PaintingStyle paintStyle = PaintingStyle.fill,
}) : assert(expansionFactor != null),
assert(expansionFactor > 1),
super(
dotWidth: dotWidth,
dotHeight: dotHeight,
spacing: spacing,
radius: radius,
strokeWidth: strokeWidth,
paintStyle: paintStyle,
dotColor: dotColor,
activeDotColor: activeDotColor);
@override
Size calculateSize(int count) {
// Add the expanded dot width to our size calculation
return Size(dotWidth,
((dotHeight + spacing) * (count - 1)) + (expansionFactor * dotHeight));
}
@override
IndicatorPainter buildPainter(int count, double offset, bool isRTL) {
return ExpandingDotsPainter(
count: count, offset: offset, effect: this, isRTL: isRTL);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib/indicator
|
mirrored_repositories/flutter_showcase/example/lib/indicator/painters/indicator_painter.dart
|
import 'package:flutter/material.dart';
import '../effects/indicator_effect.dart'
;
abstract class IndicatorPainter extends CustomPainter {
/// The raw offset from the [PageController].page
///
/// This is called raw because it's used to resolve
/// the final [offset] based on [isRTL] property
final double _rawOffset;
/// This holds the directional offset
final double offset;
// The count of pages
final int count;
// The provided effect is passed to this super class
// to make some calculations and paint still dots
final IndicatorEffect _effect;
// Inactive dot paint or base paint in one-color effects.
final Paint dotPaint;
// The Radius of all dots
final Radius dotRadius;
IndicatorPainter(
this._rawOffset,
this.count,
this._effect,
bool _isRTL,
) : assert(_isRTL != null),
dotRadius = Radius.circular(_effect.radius),
dotPaint = Paint()
..color = _effect.dotColor
..style = _effect.paintStyle
..strokeWidth = _effect.strokeWidth,
offset = _isRTL ? (count - 1) - _rawOffset : _rawOffset;
// The distance between dot lefts
double get distance => _effect.dotWidth + _effect.spacing;
@override
void paint(Canvas canvas, Size size) {
// Paint still dots if the sub class calls super
for (int i = 0; i < count; i++) {
final xPos = (i * distance);
final yPos = size.height / 2;
final bounds = Rect.fromLTRB(xPos, yPos - _effect.dotHeight / 2,
xPos + _effect.dotWidth, yPos + _effect.dotHeight / 2);
RRect rect = RRect.fromRectAndRadius(bounds, dotRadius);
canvas.drawRRect(rect, dotPaint);
}
}
@override
bool shouldRepaint(IndicatorPainter oldDelegate) {
// only repaint if the raw offset changes
return oldDelegate._rawOffset != _rawOffset;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/lib/indicator
|
mirrored_repositories/flutter_showcase/example/lib/indicator/painters/expanding_dots_painter.dart
|
import 'package:flutter/material.dart';
import '../effects/expanding_dots_effect.dart';
import 'indicator_painter.dart';
class ExpandingDotsPainter extends IndicatorPainter {
final ExpandingDotsEffect effect;
ExpandingDotsPainter({
@required double offset,
@required this.effect,
@required int count,
@required bool isRTL,
}) : super(offset, count, effect, isRTL);
@override
void paint(Canvas canvas, Size size) {
final int current = offset.floor();
double drawingOffset = -effect.spacing;
final dotOffset = offset - current;
for (int i = 0; i < count; i++) {
Color color = effect.dotColor;
final activeDotHeight = effect.dotHeight * effect.expansionFactor;
final expansion =
(dotOffset / 2 * ((activeDotHeight - effect.dotHeight) / .5));
final yPos = drawingOffset + effect.spacing;
double height = effect.dotHeight;
if (i == current) {
color = Color.lerp(effect.activeDotColor, effect.dotColor, dotOffset);
height = activeDotHeight - expansion;
} else if (i - 1 == current) {
height = effect.dotHeight + expansion;
color =
Color.lerp(effect.activeDotColor, effect.dotColor, 1.0 - dotOffset);
}
final xPos = size.width / 2;
final rRect = RRect.fromLTRBR(
xPos - effect.dotWidth / 2,
yPos,
xPos + effect.dotWidth / 2,
yPos + height,
dotRadius,
);
drawingOffset = rRect.bottom;
canvas.drawRRect(rRect, dotPaint..color = color);
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/fx_renderer.dart
|
import 'dart:ui';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'utils/sprite_sheet.dart';
import 'particlefx/particle_fx.dart';
import 'particlefx/particle_fx_painter.dart';
import 'touchpoint_notification.dart';
import 'fx_entry.dart';
class FxRenderer extends StatefulWidget {
final SpriteSheet spriteSheet;
final FXEntry fx;
final Size size;
FxRenderer({this.fx, this.size, key, this.spriteSheet}) : super(key:key);
@override
_FxRendererState createState() => _FxRendererState();
}
class _FxRendererState extends State<FxRenderer> with SingleTickerProviderStateMixin {
final GlobalKey _key = GlobalKey();
Ticker _ticker;
ParticleFX _fxWidget;
@override
void initState() {
super.initState();
_ticker = createTicker(_tick)..start();
_fxWidget = widget.fx.create(spriteSheet: widget.spriteSheet, size: widget.size);
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
void didUpdateWidget(FxRenderer oldWidget) {
if (oldWidget.size != widget.size || oldWidget.fx != widget.fx) {
_fxWidget = widget.fx.create(spriteSheet: widget.spriteSheet, size: widget.size);
}
super.didUpdateWidget(oldWidget);
}
void setTouchPoint([Offset pt]) {
TouchPointChangeNotification()..dispatch(context);
if (_fxWidget != null) { _fxWidget.touchPoint = pt; }
}
void _tick(Duration duration) {
if (_fxWidget != null) { _fxWidget.tick(duration); }
}
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTapDown: (TapDownDetails details) => setTouchPoint(details.localPosition),
onTapUp: (_) => setTouchPoint(),
onPanStart: (DragStartDetails details) => setTouchPoint(details.localPosition),
onPanEnd: (_) => setTouchPoint(),
onPanUpdate: (DragUpdateDetails details) => setTouchPoint(details.localPosition),
child: CustomPaint(
painter: ParticleFXPainter(fx: _fxWidget),
child: Container(), // force it to fill the available area, and capture touch inputs.
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/fx_switcher.dart
|
import 'package:flutter/material.dart';
import 'main.dart';
typedef FXChangeCallback = void Function(int);
class FXSwitcher extends StatelessWidget {
static final List<String> buttonNames = ['Waterfall', 'Fireworks', 'Comet', 'Pinwheel'];
static final List<String> selectedPaths = ['waterfall-selected', 'fireworks-selected', 'comet-selected', 'pinwheel-selected'];
static final List<String> paths = ['waterfall-idle', 'fireworks-idle', 'comet-idle', 'pinwheel-idle'];
final int activeEffect;
final FXChangeCallback callback;
FXSwitcher({this.activeEffect, this.callback});
@override
Widget build(context) {
return Align(
alignment: Alignment.bottomCenter,
child: Container(
width: 320,
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [0, 1, 2, 3]
.map((int index) => _FXSwitcherButton(
name: buttonNames[index],
image:
AssetImage('assets/buttons/${activeEffect == index ? selectedPaths[index] : paths[index]}.png', package: App.pkg),
handleTap: () => _handleButtonPress(index),
))
.toList(),
),
),
);
}
void _handleButtonPress(int index) {
callback?.call(index);
}
}
class _FXSwitcherButton extends StatelessWidget {
final String name;
final ImageProvider image;
final VoidCallback handleTap;
_FXSwitcherButton({this.name, this.image, this.handleTap});
@override
Widget build(context) {
return Column(children: [
GestureDetector(
onTap: handleTap,
child: Image(
image: image,
width: 56,
height: 52,
),
),
Padding(
padding: EdgeInsets.all(2.0),
),
Text(
name,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 12, package: App.pkg),
),
]);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/fx_entry.dart
|
import 'package:flutter/material.dart';
import 'particlefx/particle_fx.dart';
import 'utils/sprite_sheet.dart';
class FXEntry {
ParticleFX Function({SpriteSheet spriteSheet, Size size}) create;
String name;
ImageProvider icon;
FXEntry(this.name, {@required this.create, this.icon});
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:shared/env.dart';
import 'demo.dart';
void main() => runApp(App());
class App extends StatelessWidget {
static String _pkg = "sparkle_party";
static String get pkg => Env.getPackage(_pkg);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(fontFamily: "TitilliumWeb" ),
home: SparklePartyDemo(),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/touchpoint_notification.dart
|
import 'package:flutter/material.dart';
class TouchPointChangeNotification extends Notification {}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/demo.dart
|
import 'package:flutter/material.dart';
import 'package:shared/ui/blend_mask.dart';
import 'fx_renderer.dart';
import 'fx_entry.dart';
import 'main.dart';
import 'particlefx/fireworks.dart';
import 'particlefx/pinwheel.dart';
import 'particlefx/comet.dart';
import 'particlefx/waterfall.dart';
import 'fx_switcher.dart';
import 'touchpoint_notification.dart';
import 'utils/sprite_sheet.dart';
class SparklePartyDemo extends StatefulWidget {
static final List<FXEntry> fxs = [
FXEntry("Waterfall", create: ({spriteSheet, size}) => Waterfall(spriteSheet: spriteSheet, size: size)),
FXEntry("Fireworks", create: ({spriteSheet, size}) => Fireworks(spriteSheet: spriteSheet, size: size)),
FXEntry("Comet", create: ({spriteSheet, size}) => Comet(spriteSheet: spriteSheet, size: size)),
FXEntry("Pinwheel", create: ({spriteSheet, size}) => Pinwheel(spriteSheet: spriteSheet, size: size)),
];
static final List<String> instructions = [
'TOUCH AND DRAG ON THE SCREEN',
'TAP OR DRAG ON THE SCREEN',
'DRAG ON THE SCREEN',
'DRAG ON THE SCREEN',
];
@override
_SparklePartyDemoState createState() => _SparklePartyDemoState();
}
class _SparklePartyDemoState extends State<SparklePartyDemo> with TickerProviderStateMixin {
int _fxIndex = 0;
int _buttonIndex = 0;
AnimationController _transitionController;
AnimationController _textController;
@override
void initState() {
_transitionController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 350),
);
_textController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 800),
);
Listenable.merge([_transitionController, _textController]).addListener(() {
setState(() {});
});
super.initState();
}
@override
void dispose() {
_transitionController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
//Main Background image
Positioned.fill(
child: Image.asset("assets/sparkleparty_bg.png", fit: BoxFit.cover, package: App.pkg),
),
//Centered logo png
Center(
child: Image.asset("assets/sparkleparty_logo.png", package: App.pkg),
),
Opacity(
opacity: 1.0 - _transitionController.value,
child: NotificationListener<TouchPointChangeNotification>(
onNotification: _handleInteraction,
child: LayoutBuilder(
builder: (context, constraints) {
return FxRenderer(
fx: SparklePartyDemo.fxs[_fxIndex],
size: constraints.biggest,
spriteSheet: SpriteSheet(
imageProvider: AssetImage("assets/sparkleparty_spritesheet_2.png", package: App.pkg),
length: 16, // number of frames in the sprite sheet.
frameWidth: 64,
frameHeight: 64,
),
);
},
),
),
),
IgnorePointer(
child: Center(
child: Image.asset("assets/sparkleparty_logo_outline.png", package: App.pkg),
),
),
if (!_textController.isCompleted) ...{
Align(
alignment: Alignment.bottomCenter,
child: Container(
padding: EdgeInsets.only(bottom: 136),
child: BlendMask(
blendMode: BlendMode.srcOver,
opacity: 1.0 - _textController.value,
child: Text(
SparklePartyDemo.instructions[_fxIndex],
textAlign: TextAlign.center,
style: TextStyle(color: Colors.white, fontWeight: FontWeight.w600, fontSize: 12, package: App.pkg),
),
),
),
),
},
FXSwitcher(activeEffect: _buttonIndex, callback: _handleFxChange),
],
),
);
}
void _handleFxChange(int index) {
if (index == _fxIndex) return;
setState(() => _buttonIndex = index);
_transitionController.forward(from: 0.0).whenComplete(() {
setState(() => _fxIndex = index);
_transitionController.reverse(from: 1.0);
_textController.reverse();
});
}
bool _handleInteraction(TouchPointChangeNotification notification) {
if (_textController.velocity <= 0) {
_textController.forward();
}
return false;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/particlefx/particle_fx.dart
|
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import '../utils/sprite_sheet.dart';
import '../utils/vertex_helpers.dart';
// Abstract particle effects class, extended by specific effects implementations.
abstract class ParticleFX with ChangeNotifier {
SpriteSheet spriteSheet;
double width;
double height;
int count;
Offset touchPoint;
Offset center;
List<Particle> particles;
Int32List colors;
Float32List uv;
Float32List xy;
ui.Vertices vertices;
ParticleFX({@required this.spriteSheet, @required Size size, this.count=10000}) {
width = size.width;
height = size.height;
xy = Float32List(12 * count);
uv = Float32List(12 * count);
colors = Int32List(6 * count);
particles = List<Particle>(count);
center = Offset(width/2, height/2);
}
// Fills in the Particle list, and resets each Particle.
// Override to add more capability if needed.
void fillInitialData() {
for (int i=0; i<count; i++) {
particles[i] = Particle();
resetParticle(i);
}
}
// resets the basic Particle, and hides it.
Particle resetParticle(int i) {
Particle o = particles[i];
o.x = o.y = o.vx = o.vy = o.life = 0;
o.frame = spriteSheet.length ~/ 2;
o.animate = false;
injectColor(i, colors, 0);
injectVertex(i, xy, 0, 0, 0, 0);
spriteSheet.injectTexCoords(i, uv, o.frame);
return o;
}
// Called each tick by the parent & updates all the particles.
// Override to add effect specific logic, and call super to initiate the draw.
void tick(Duration duration) {
if (spriteSheet.image == null) { return; }
vertices = ui.Vertices.raw(
VertexMode.triangles,
xy,
textureCoordinates: uv,
colors: colors
);
notifyListeners();
}
}
// Basic Particle class, which can be extended to add additional data.
class Particle {
double x;
double y;
double vx; // velocity x
double vy;
double life;
int frame;
bool animate;
Particle({this.x = 0.0, this.y = 0.0, this.vx = 0.0, this.vy = 0.0, this.life = 0, this.frame = 0, this.animate = false});
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/particlefx/fireworks.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import '../utils/rnd.dart';
import '../utils/sprite_sheet.dart';
import '../utils/vertex_helpers.dart';
import 'particle_fx.dart';
// Animated particle effects. Note that this just manages the data, ParticleFieldPainter renders the effect.
class Fireworks extends ParticleFX {
double _hue = 120.0;
int _cooldown = 0; // ticks before another firework is allowed
int _nextAuto = 10; // ticks before another firework is automatically triggered
Offset _touchPoint;
Fireworks({@required SpriteSheet spriteSheet, @required Size size}) :
super(spriteSheet: spriteSheet, size: size);
@override
void fillInitialData() {
for (int i=0; i<count; i++) {
particles[i] = _Particle();
resetParticle(i);
}
}
@override
set touchPoint(Offset pt) {
// avoid premature clears from fast taps.
if (pt != null && _cooldown <= 0) {
_touchPoint = pt;
_cooldown = 4;
}
}
void _activateParticle(int i, Offset pt, double wow) {
_Particle o = particles[i];
o.x = pt.dx;
o.y = pt.dy;
double maxv = wow * 18;
double a = Rnd.getRad();
double v = Rnd.getDouble(0.5, maxv);
o.vx = sin(a) * v;
o.vy = cos(a) * v - 5;
// fake 3d effect:
o.z = 0.0;
o.vz = cos(v/maxv * pi/2) * wow;
o.animate = false;
o.life = Rnd.getDouble(60, 100);
double h = (_hue + Rnd.getDouble(0, 40.0)) % 360.0;
int color = HSLColor.fromAHSL(1.0, h, 1.0, 0.45).toColor().value;
injectColor(i, colors, color);
}
// Called each tick by the parent & updates all the particles
@override
void tick(Duration duration) {
if (spriteSheet.image == null) { return; }
if (particles[0] == null) { fillInitialData(); }
int frameCount = spriteSheet.length;
int addCount = 0;
double wow = 0.0;
if (_touchPoint != null) {
wow = Rnd.getDouble(0.4, 1.0);
addCount = (wow * 600).floor();
_hue = Rnd.getDeg();
}
for (int i=0; i<count; i++) {
_Particle o = particles[i];
if (o.life == 0 && --addCount > 0) { _activateParticle(i, _touchPoint, wow); }
else if (o.life == 0) { continue; }
o.vy += 0.2;
o.vy *= 0.95;
o.y += o.vy;
o.vx *= 0.95;
o.x += o.vx;
o.vz *= 0.98;
o.z += o.vz;
if (--o.life <= 0) {
resetParticle(i);
continue;
}
double r = (o.life/100 * 0.7 + 0.3) * (8 + (o.z));
injectVertex(i, xy, o.x - r, o.y - r, o.x + r, o.y + r);
if (o.life < 30 && !o.animate) {
o.animate = true;
injectColor(i, colors, 0xFFFFFFFF);
}
if (o.animate) { spriteSheet.injectTexCoords(i, uv, Rnd.getInt(0, frameCount)); }
}
_touchPoint = null;
if (--_cooldown < -_nextAuto) {
touchPoint = Offset(Rnd.getDouble(0.2, 0.8) * width, Rnd.getDouble(0.2, 0.6) * height);
_nextAuto = Rnd.getInt(10, 90);
}
super.tick(duration);
}
}
class _Particle extends Particle {
double z = 0.0; // fake 3d
double vz = 0.0;
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/particlefx/waterfall.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import '../utils/rnd.dart';
import '../utils/sprite_sheet.dart';
import '../utils/vertex_helpers.dart';
import 'particle_fx.dart';
// Animated particle effects. Note that this just manages the data, ParticleFieldPainter renders the effect.
class Waterfall extends ParticleFX {
double _hue = 0.0;
Waterfall({@required SpriteSheet spriteSheet, @required Size size}) :
super(spriteSheet: spriteSheet, size: size, count: size.shortestSide > 600 ? 40000 : 20000);
@override
void fillInitialData() {
for (int i=0; i<count; i++) {
particles[i] = _Particle();
resetParticle(i);
}
}
@override
Particle resetParticle(int i) {
Particle o = super.resetParticle(i);
o.y = Rnd.ratio * height;
return o;
}
void _activateParticle(int i) {
_Particle o = particles[i];
o.x = Rnd.ratio * width;
o.y = 0.0;
o.vx = Rnd.getDouble(-2, 2);
o.vy = Rnd.ratio * 5;
o.animate = Rnd.getBool(0.02);
o.scale = Rnd.getDouble(0.8, 1.2);
double h = (_hue + Rnd.ratio * 40.0 + o.x/width*90.0) % 360;
int color = HSLColor.fromAHSL(1.0, h, 1.0, o.animate ? 1.0 : 0.4).toColor().value;
injectColor(i, colors, color);
}
// Called each tick by the parent & updates all the particles
@override
void tick(Duration duration) {
if (spriteSheet.image == null) { return; }
if (particles[0] == null) { fillInitialData(); }
_hue -= 1;
int frameCount = spriteSheet.length;
const double maxD = 100.0;
for (int i=0; i<count; i++) {
_Particle o = particles[i];
double dx, dy, d;
if (touchPoint != null &&
(dy = touchPoint.dy - o.y) < maxD &&
(dx = touchPoint.dx - o.x) < maxD &&
(d = sqrt(dx*dx + dy*dy)) < maxD) {
double a = atan2(dy, dx);
double v = (maxD - d)/maxD * -1.0;
o.vx += v * cos(a);
o.vy += v * sin(a);
}
o.vy += 0.1;
o.x += o.vx;
o.vx *= 0.99;
o.y += o.vy;
if (o.y > height) { _activateParticle(i); }
double r = 12.0 * o.scale;
injectVertex(i, xy, o.x - r, o.y - r, o.x + r, o.y + r);
if (o.animate) { spriteSheet.injectTexCoords(i, uv, (++o.frame % frameCount)); }
}
super.tick(duration);
}
}
class _Particle extends Particle {
double scale = 1.0;
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/particlefx/particle_fx_painter.dart
|
import 'package:flutter/material.dart';
import 'particle_fx.dart';
// Renders a ParticleFX.
class ParticleFXPainter extends CustomPainter {
ParticleFX fx;
// ParticleFX is a ChangeNotifier, so we can use it as the repaint notifier.
ParticleFXPainter({@required this.fx,}) : super(repaint: fx);
@override
void paint(Canvas canvas, Size size) {
if (fx.vertices == null) { return; }
Paint paint = Paint()..shader = ImageShader(
fx.spriteSheet.image,
TileMode.clamp, TileMode.clamp,
Matrix4.identity().storage
);
canvas.drawVertices(fx.vertices, BlendMode.dstIn, paint);
}
@override
bool shouldRepaint(_) => true;
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/particlefx/comet.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import '../utils/rnd.dart';
import '../utils/sprite_sheet.dart';
import '../utils/vertex_helpers.dart';
import 'particle_fx.dart';
// Animated particle effects. Note that this just manages the data, ParticleFieldPainter renders the effect.
class Comet extends ParticleFX {
double _hue = 0.0;
Offset _prevPoint;
double _power = 0.0;
Offset _point;
Comet({@required SpriteSheet spriteSheet, @required Size size}) :
super(spriteSheet: spriteSheet, size: size) {
center = Offset(width * 0.5, 30);
_point = Offset(width * 0.5, height + 50);
}
void _activateParticle(int i, Offset pt, double m) {
Particle o = particles[i];
o.x = pt.dx;
o.y = pt.dy;
double a = Rnd.getRad();
double v = Rnd.getDouble(3.0, 10.0) * m;
o.vx = sin(a) * v;
o.vy = cos(a) * v;
o.animate = true;
o.frame = Rnd.getInt(0, spriteSheet.length);
o.life = Rnd.getDouble(50, 100) * (0.5 + 0.5*m);
double h = (_hue*0.5 + Rnd.ratio * 40.0 + a/pi * 30) % 360;
int color = HSLColor.fromAHSL(1.0, h, 1.0, Rnd.getBool(0.1) ? 1.0 : 0.4).toColor().value;
injectColor(i, colors, color);
if (o.animate) { o.frame = Rnd.getInt(0, spriteSheet.length); }
}
@override
void tick(Duration duration) {
if (spriteSheet.image == null) { return; }
if (particles[0] == null) { fillInitialData(); }
_point += ((touchPoint ?? center) - _point) * (touchPoint == null ? 0.05 : 0.2);
_hue += 10;
int frameCount = spriteSheet.length;
double m = _updatePower();
int addCount = (180 * m).toInt();
for (int i=0; i<count; i++) {
Particle o = particles[i];
if (o.life == 0 && --addCount > 0) { _activateParticle(i, _point, m); }
else if (o.life == 0) { continue; }
o.vy += 0.25;
o.vy *= 0.99;
o.x += o.vx;
o.vx *= 0.99;
o.y += o.vy;
o.life -= 1.2;
if (o.life <= 0) {
resetParticle(i);
continue;
}
double r = o.life/100 * 24;
injectVertex(i, xy, o.x - r, o.y - r, o.x + r, o.y + r);
spriteSheet.injectTexCoords(i, uv, (++o.frame % frameCount));
}
_prevPoint = touchPoint;
super.tick(duration);
}
double _updatePower() {
double m = 0.25;
if (touchPoint != null && _prevPoint != null) {
double dx = touchPoint.dx - _prevPoint.dx;
double dy = touchPoint.dy - _prevPoint.dy;
m = min(1, sqrt(dx*dx + dy*dy)/20 + m);
}
_power += (m - _power) * 0.05;
return _power;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/particlefx/pinwheel.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import '../utils/rnd.dart';
import '../utils/sprite_sheet.dart';
import '../utils/vertex_helpers.dart';
import 'particle_fx.dart';
// Animated particle effects. Note that this just manages the data, ParticleFieldPainter renders the effect.
class Pinwheel extends ParticleFX {
double _hue = 0.0;
Offset _point;
int arms = 11;
Pinwheel({@required SpriteSheet spriteSheet, @required Size size}) :
super(spriteSheet: spriteSheet, size: size) {
_point = center;
}
void _activateParticle(int i, Offset pt) {
Particle o = particles[i];
o.x = pt.dx;
o.y = pt.dy;
double a = Rnd.getInt(0, arms) / arms * pi * 2 - _hue * 0.007 + Rnd.getDouble(0, pi/arms/2);
double v = Rnd.getDouble(10, 12.0);
o.vx = sin(a) * v;
o.vy = cos(a) * v;
o.animate = true;
o.life = Rnd.getDouble(60, 100);
o.frame = 0;
double h = (_hue*0.2 + Rnd.ratio * 40.0 + a/pi * 180) % 360;
int color = HSLColor.fromAHSL(1.0, h, 1.0, Rnd.getBit(0.05) * 0.6 + 0.4).toColor().value;
injectColor(i, colors, color);
if (o.animate) { o.frame = Rnd.getInt(0, spriteSheet.length); }
}
// Called each tick by the parent & updates all the particles
@override
void tick(Duration duration) {
if (spriteSheet.image == null) { return; }
if (particles[0] == null) { fillInitialData(); }
_point += ((touchPoint ?? center) - _point) * (touchPoint == null ? 0.05 : 0.2);
_hue += 10;
int frameCount = spriteSheet.length;
int addCount = touchPoint != null ? 200 : 20;
for (int i=0; i<count; i++) {
Particle o = particles[i];
if (o.life == 0 && --addCount > 0) { _activateParticle(i, _point); }
else if (o.life == 0) { continue; }
o.x += o.vx;
o.y += o.vy;
o.life *= 0.95;
o.life -= 1;
if (o.life <= 0) {
resetParticle(i);
continue;
}
double r = o.life/100 * 48;
injectVertex(i, xy, o.x - r, o.y - r, o.x + r, o.y + r);
if (o.animate) { spriteSheet.injectTexCoords(i, uv, (++o.frame % frameCount)); }
}
super.tick(duration);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/utils/vertex_helpers.dart
|
import 'dart:typed_data';
void injectVertex(int i, Float32List list, double l, double t, double r, double b) {
i *= 12;
// Injects position values for the 6 corners (two triangles) of a sprite.
// right triangle:
list[i + 0] = l; // x1 - tl
list[i + 1] = t; // y1
list[i + 2] = r; // x2 - tr
list[i + 3] = t; // y2
list[i + 4] = l; // x3 - bl
list[i + 5] = b; // y3
// right triangle:
list[i + 6] = r; // x1 - tr
list[i + 7] = t; // y1
list[i + 8] = r; // x2 - br
list[i + 9] = b; // y2
list[i + 10] = l; // x3 - bl
list[i + 11] = b; // y3
}
void injectColor(int i, Int32List list, int color) {
i *= 6;
// Injects color values for the 6 corners (two triangles) of a sprite.
list[i + 0] = list[i + 1] = list[i + 2] = list[i + 3] = list[i + 4] = list[i + 5] = color;
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/utils/rnd.dart
|
import 'dart:math';
class Rnd {
static int _seed = DateTime.now().millisecondsSinceEpoch;
static Random random = Random(_seed);
static set seed(int val) => random = Random(_seed = val);
static int get seed => _seed;
static get ratio => random.nextDouble();
static int getInt(int min, int max) {
return min + random.nextInt(max-min);
}
static double getDouble(double min, double max) {
return min + random.nextDouble() * (max - min);
}
static bool getBool([double chance=0.5]) {
return random.nextDouble() < chance;
}
static int getBit([double chance=0.5]) {
return random.nextDouble() < chance ? 1 : 0;
}
static int getSign([double chance=0.5]) {
return random.nextDouble() < chance ? 1 : -1;
}
static double getDeg() {
return getDouble(0, 360);
}
static double getRad() {
return getDouble(0, pi * 2);
}
static List shuffle(List list) {
for (int i=0, l = list.length; i<l; i++) {
int j = random.nextInt(l);
if (j==i) { continue; }
dynamic item = list[j];
list[j] = list[i];
list[i] = item;
}
return list;
}
static dynamic getItem(List list) {
return list[(list.length * random.nextDouble()).floor()];
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib
|
mirrored_repositories/flutter_showcase/example/apps/sparkle_party/lib/utils/sprite_sheet.dart
|
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'vertex_helpers.dart';
import 'package:flutter/material.dart';
// Simple sprite sheet helper.
class SpriteSheet {
ui.Image image; // null until the ImageProvide finishes loading.
int frameWidth;
int frameHeight;
int length;
Float32List positions; // cached positions.
SpriteSheet({@required ImageProvider imageProvider, @required this.length, @required this.frameWidth, this.frameHeight = 0}) {
// Resolve the provider into a stream, then listen for it to complete.
// This will happen synchronously if it's already loaded into memory.
ImageStream stream = imageProvider.resolve(ImageConfiguration());
ImageStreamListener listener = ImageStreamListener((info, _) { image = info.image; _calculatePositions(); });
stream.addListener(listener);
}
Rect getFrame(int frame) {
// Given a frame index, return the rect that describes that frame in the image.
if (image == null || frame == null || frame < 0 || frame >= length) { return null; }
int i = frame * 4;
return Rect.fromLTRB(positions[i], positions[i+1], positions[i+2], positions[i+3]);
}
void injectTexCoords(int i, Float32List list, int frame) {
int j = frame * 4;
Float32List pos = positions;
injectVertex(i, list, pos[j+0], pos[j+1], pos[j+2], pos[j+3]);
}
void _calculatePositions() {
positions = Float32List(length * 4);
int cols = (image.width / frameWidth).floor();
int w = frameWidth;
int h = frameHeight == 0 ? image.height : frameHeight; // default to the image's height
for (int i=0; i< length; i++) {
double x = (i % cols) * w + 0.0;
double y = (i / cols).floor() * h + 0.0;
positions[i * 4 + 0] = x; // x1
positions[i * 4 + 1] = y; // y1
positions[i * 4 + 2] = x + w; // x2
positions[i * 4 + 3] = y + h; // y2
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/fluid_icon.dart
|
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:shared/ui/path_util.dart';
// Users of this class shouldn't have to explicitly import fluid_icon_data
import './fluid_icon_data.dart';
export './fluid_icon_data.dart';
class FluidFillIcon extends StatelessWidget {
static const double iconDataScale = 0.9;
final FluidFillIconData _iconData;
/// A normalzied value between 0 and 1
final double _fillAmount;
final double _scaleY;
FluidFillIcon(FluidFillIconData iconData, double fillAmount, double scaleY)
: _iconData = iconData, _fillAmount = fillAmount, _scaleY = scaleY;
@override
Widget build(context) {
return CustomPaint(
painter: _FluidFillIconPainter(_iconData.paths, _fillAmount, _scaleY),
);
}
}
class _FluidFillIconPainter extends CustomPainter {
List<ui.Path> _paths;
double _fillAmount;
double _scaleY;
_FluidFillIconPainter(List<ui.Path> paths, double fillAmount, double scaleY)
: _paths = paths, _fillAmount = fillAmount, _scaleY = scaleY;
@override
void paint(canvas, size) {
final paintBackground = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2.4
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..color = Colors.grey;
final paintForeground = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2.4
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..color = Colors.black;
// Scale around (0, height / 2)
canvas.translate(0.0, size.height / 2);
canvas.scale(1.0, _scaleY);
// Center around (width / 2, height / 2) and apply the icon data scale
canvas.translate(size.width / 2, 0.0);
canvas.scale(FluidFillIcon.iconDataScale, FluidFillIcon.iconDataScale);
// Draw the background greyed out path
for (final path in _paths) {
canvas.drawPath(path, paintBackground);
}
// Draw the black foreground path to simulate a filling effect
if (_fillAmount > 0.0) {
for (final path in _paths) {
canvas.drawPath(extractPartialPath(path, 0.0, _fillAmount), paintForeground);
}
}
}
@override
bool shouldRepaint(_FluidFillIconPainter oldWidget) {
return _fillAmount != oldWidget._fillAmount;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/curves.dart
|
import 'dart:math' as math;
import 'package:flutter/animation.dart';
class CenteredElasticOutCurve extends Curve {
final double period;
CenteredElasticOutCurve([this.period = 0.4]);
@override
double transform(double x) {
// Bascially just a slightly modified version of the built in ElasticOutCurve
return math.pow(2.0, -10.0 * x) * math.sin(x * 2.0 * math.pi / period) + 0.5;
}
}
class CenteredElasticInCurve extends Curve {
final double period;
CenteredElasticInCurve([this.period = 0.4]);
@override
double transform(double x) {
// Bascially just a slightly modified version of the built in ElasticInCurve
return -math.pow(2.0, 10.0 * (x - 1.0)) * math.sin((x - 1.0) * 2.0 * math.pi / period) + 0.5;
}
}
class LinearPointCurve extends Curve {
final double pIn;
final double pOut;
LinearPointCurve(this.pIn, this.pOut);
@override
double transform(double x) {
// Just a simple bit of linear interpolation math
final lowerScale = pOut / pIn;
final upperScale = (1.0 - pOut) / (1.0 - pIn);
final upperOffset = 1.0 - upperScale;
return x < pIn ? x * lowerScale : x * upperScale + upperOffset;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/main.dart
|
import 'package:flutter/material.dart';
import './demo.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FluidNavBarDemo(),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/fluid_button.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/animation.dart';
import './fluid_icon.dart';
import './curves.dart';
typedef void FluidNavBarButtonPressedCallback();
class FluidNavBarButton extends StatefulWidget {
static const nominalExtent = const Size(64, 64);
final FluidFillIconData _iconData;
final bool _selected;
final FluidNavBarButtonPressedCallback _onPressed;
FluidNavBarButton(FluidFillIconData iconData, bool selected, FluidNavBarButtonPressedCallback onPressed)
: _iconData = iconData, _selected = selected, _onPressed = onPressed;
@override
State createState() {
return _FluidNavBarButtonState(_iconData, _selected, _onPressed);
}
}
class _FluidNavBarButtonState extends State<FluidNavBarButton> with SingleTickerProviderStateMixin {
static const double _activeOffset = 16;
static const double _defaultOffset = 0;
static const double _radius = 25;
FluidFillIconData _iconData;
bool _selected;
FluidNavBarButtonPressedCallback _onPressed;
AnimationController _animationController;
Animation<double> _animation;
_FluidNavBarButtonState(FluidFillIconData iconData, bool selected, FluidNavBarButtonPressedCallback onPressed)
: _iconData = iconData,
_selected = selected,
_onPressed = onPressed;
@override
void initState() {
_animationController = AnimationController(
duration: const Duration(milliseconds: 1666),
reverseDuration: const Duration(milliseconds: 833),
vsync: this);
_animation = Tween<double>(begin: 0.0, end: 1.0).animate(_animationController)
..addListener(() {
setState(() {
});
});
_startAnimation();
super.initState();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(context) {
const ne = FluidNavBarButton.nominalExtent;
final offsetCurve = _selected ? ElasticOutCurve(0.38) : Curves.easeInQuint;
final scaleCurve = _selected ? CenteredElasticOutCurve(0.6) : CenteredElasticInCurve(0.6);
final progress = LinearPointCurve(0.28, 0.0).transform(_animation.value);
final offset = Tween<double>(
begin: _defaultOffset,
end: _activeOffset
).transform(offsetCurve.transform(progress));
final scaleCurveScale = 0.50;
final scaleY = 0.5 + scaleCurve.transform(progress) * scaleCurveScale + (0.5 - scaleCurveScale / 2);
// Create a parameterizable flat button with a fluid fill icon
return GestureDetector(
// We wan't to know when this button was tapped, don't bother letting out children know as well
onTap: _onPressed,
behavior: HitTestBehavior.opaque,
child: Container(
// Alignment container to the circle
constraints: BoxConstraints.tight(ne),
alignment: Alignment.center,
child: Container(
// This container just draws a circle with a certain radius and offset
margin: EdgeInsets.all(ne.width / 2 - _radius),
constraints: BoxConstraints.tight(Size.square(_radius * 2)),
decoration: ShapeDecoration(
color: Colors.white,
shape: CircleBorder(),
),
transform: Matrix4.translationValues(0, -offset, 0),
// Create a fluid fill icon that get's filled in with a slight delay to the buttons animation
child: FluidFillIcon(
_iconData,
LinearPointCurve(0.25, 1.0).transform(_animation.value),
scaleY,
),
),
),
);
}
@override
void didUpdateWidget(oldWidget) {
setState(() {
_selected = widget._selected;
});
_startAnimation();
super.didUpdateWidget(oldWidget);
}
void _startAnimation() {
if (_selected) {
_animationController.forward();
} else {
_animationController.reverse();
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/fluid_nav_bar.dart
|
import 'package:flutter/material.dart';
import './fluid_icon.dart';
import './fluid_button.dart';
import './curves.dart';
typedef void FluidNavBarChangeCallback(int selectedIndex);
class FluidNavBar extends StatefulWidget {
static const double nominalHeight = 56.0;
final FluidNavBarChangeCallback onChange;
FluidNavBar({ this.onChange });
@override
State createState() => _FluidNavBarState();
}
class _FluidNavBarState extends State<FluidNavBar> with TickerProviderStateMixin {
int _selectedIndex = 0;
AnimationController _xController;
AnimationController _yController;
@override
void initState() {
_xController = AnimationController(
vsync: this,
animationBehavior: AnimationBehavior.preserve
);
_yController = AnimationController(
vsync: this,
animationBehavior: AnimationBehavior.preserve
);
Listenable.merge([ _xController, _yController ]).addListener(() {
setState(() {
});
});
super.initState();
}
@override
void didChangeDependencies() {
_xController.value = _indexToPosition(_selectedIndex) / MediaQuery.of(context).size.width;
_yController.value = 1.0;
super.didChangeDependencies();
}
@override
void dispose() {
_xController.dispose();
_yController.dispose();
super.dispose();
}
@override
Widget build(context) {
// The fluid nav bar consists of two components, the liquid background pane and the buttons
// Build a stack with the buttons overlayed on top of the background pane
final appSize = MediaQuery.of(context).size;
final height = FluidNavBar.nominalHeight;
return Container(
width: appSize.width,
height: FluidNavBar.nominalHeight,
child: Stack(
children: [
Positioned(
left: 0,
top: 0,
width: appSize.width,
height: height,
child: _buildBackground(),
),
Positioned(
left: (appSize.width - _getButtonContainerWidth()) / 2,
top: 0,
width: _getButtonContainerWidth(),
height: height,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _buildButtons(),
),
),
],
),
);
}
Widget _buildBackground() {
// This widget acts purely as a container that controlls how the `_BackgroundCurvePainter` draws
final inCurve = ElasticOutCurve(0.38);
return CustomPaint(
painter: _BackgroundCurvePainter(
_xController.value * MediaQuery.of(context).size.width,
Tween<double>(
begin: Curves.easeInExpo.transform(_yController.value),
end: inCurve.transform(_yController.value),
).transform(_yController.velocity.sign * 0.5 + 0.5),
Colors.white,
),
);
}
List<FluidNavBarButton> _buildButtons() {
List<FluidFillIconData> icons = [
FluidFillIcons.home,
FluidFillIcons.user,
FluidFillIcons.window,
];
var buttons = List<FluidNavBarButton>(3);
for (var i = 0; i < 3; ++i) {
buttons[i] = FluidNavBarButton(icons[i], _selectedIndex == i, () => _handlePressed(i));
}
return buttons;
}
double _getButtonContainerWidth() {
double width = MediaQuery.of(context).size.width;
if (width > 400.0) {
width = 400.0;
}
return width;
}
double _indexToPosition(int index) {
// Calculate button positions based off of their
// index (works with `MainAxisAlignment.spaceAround`)
const buttonCount = 3.0;
final appWidth = MediaQuery.of(context).size.width;
final buttonsWidth = _getButtonContainerWidth();
final startX = (appWidth - buttonsWidth) / 2;
return startX
+ index.toDouble() * buttonsWidth / buttonCount
+ buttonsWidth / (buttonCount * 2.0);
}
void _handlePressed(int index) {
if (_selectedIndex == index || _xController.isAnimating)
return;
setState(() {
_selectedIndex = index;
});
_yController.value = 1.0;
_xController.animateTo(
_indexToPosition(index) / MediaQuery.of(context).size.width,
duration: Duration(milliseconds: 620));
Future.delayed(
Duration(milliseconds: 500),
() {
_yController.animateTo(1.0, duration: Duration(milliseconds: 1200));
},
);
_yController.animateTo(0.0, duration: Duration(milliseconds: 300));
if (widget.onChange != null) {
widget.onChange(index);
}
}
}
class _BackgroundCurvePainter extends CustomPainter {
// Top: 0.6 point, 0.35 horizontal
// Bottom:
static const _radiusTop = 54.0;
static const _radiusBottom = 44.0;
static const _horizontalControlTop = 0.6;
static const _horizontalControlBottom = 0.5;
static const _pointControlTop = 0.35;
static const _pointControlBottom = 0.85;
static const _topY = -10.0;
static const _bottomY = 54.0;
static const _topDistance = 0.0;
static const _bottomDistance = 6.0;
final double _x;
final double _normalizedY;
final Color _color;
_BackgroundCurvePainter(double x, double normalizedY, Color color)
: _x = x, _normalizedY = normalizedY, _color = color;
@override
void paint(canvas, size) {
// Paint two cubic bezier curves using various linear interpolations based off of the `_normalizedY` value
final norm = LinearPointCurve(0.5, 2.0).transform(_normalizedY) / 2;
final radius = Tween<double>(
begin: _radiusTop,
end: _radiusBottom
).transform(norm);
// Point colinear to the top edge of the background pane
final anchorControlOffset = Tween<double>(
begin: radius * _horizontalControlTop,
end: radius * _horizontalControlBottom
).transform(LinearPointCurve(0.5, 0.75).transform(norm));
// Point that slides up and down depending on distance for the target x position
final dipControlOffset = Tween<double>(
begin: radius * _pointControlTop,
end: radius * _pointControlBottom
).transform(LinearPointCurve(0.5, 0.8).transform(norm));
final y = Tween<double>(
begin: _topY,
end: _bottomY
).transform(LinearPointCurve(0.2, 0.7).transform(norm));
final dist = Tween<double>(
begin: _topDistance,
end: _bottomDistance
).transform(LinearPointCurve(0.5, 0.0).transform(norm));
final x0 = _x - dist / 2;
final x1 = _x + dist / 2;
final path = Path()
..moveTo(0, 0)
..lineTo(x0 - radius, 0)
..cubicTo(x0 - radius + anchorControlOffset, 0, x0 - dipControlOffset, y, x0, y)
..lineTo(x1, y)
..cubicTo(x1 + dipControlOffset, y, x1 + radius - anchorControlOffset, 0, x1 + radius, 0)
..lineTo(size.width, 0)
..lineTo(size.width, size.height)
..lineTo(0, size.height);
final paint = Paint()
..color = _color;
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(_BackgroundCurvePainter oldPainter) {
return _x != oldPainter._x
|| _normalizedY != oldPainter._normalizedY
|| _color != oldPainter._color;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/demo.dart
|
import 'package:flutter/material.dart';
import './content/home.dart';
import './content/account.dart';
import './content/grid.dart';
import './fluid_nav_bar.dart';
class FluidNavBarDemo extends StatefulWidget {
@override
State createState() {
return _FluidNavBarDemoState();
}
}
class _FluidNavBarDemoState extends State {
Widget _child;
@override
void initState() {
_child = HomeContent();
super.initState();
}
@override
Widget build(context) {
// Build a simple container that switches content based of off the selected navigation item
return MaterialApp(
home: Scaffold(
backgroundColor: Color(0xFF75B7E1),
extendBody: true,
body: _child,
bottomNavigationBar: FluidNavBar(onChange: _handleNavigationChange),
),
);
}
void _handleNavigationChange(int index) {
setState(() {
switch (index) {
case 0:
_child = HomeContent();
break;
case 1:
_child = AccountContent();
break;
case 2:
_child = GridContent();
break;
}
_child = AnimatedSwitcher(
switchInCurve: Curves.easeOut,
switchOutCurve: Curves.easeIn,
duration: Duration(milliseconds: 500),
child: _child,);
});
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/fluid_icon_data.dart
|
import 'dart:ui' as ui;
import 'dart:math' as math;
import 'package:flutter/material.dart';
class FluidFillIconData {
final List<ui.Path> paths;
FluidFillIconData(this.paths);
}
class FluidFillIcons {
static final platform = FluidFillIconData([
ui.Path()..moveTo(0, -6)..lineTo(10, -6),
ui.Path()..moveTo(5, 0)..lineTo(-5, 0),
ui.Path()..moveTo(-10, 6)..lineTo(0, 6),
]);
static final window = FluidFillIconData([
ui.Path()..addRRect(RRect.fromLTRBXY(-12, -12, -2, -2, 2, 2)),
ui.Path()..addRRect(RRect.fromLTRBXY(2, -12, 12, -2, 2, 2)),
ui.Path()..addRRect(RRect.fromLTRBXY(-12, 2, -2, 12, 2, 2)),
ui.Path()..addRRect(RRect.fromLTRBXY(2, 2, 12, 12, 2, 2)),
]);
static final arrow = FluidFillIconData([
ui.Path()..moveTo(-10, 6)..lineTo(10, 6)..moveTo(10, 6)..lineTo(3, 0)..moveTo(10, 6)..lineTo(3, 12),
ui.Path()..moveTo(10, -6)..lineTo(-10, -6)..moveTo(-10, -6)..lineTo(-3, 0)..moveTo(-10, -6)..lineTo(-3, -12),
]);
static final user = FluidFillIconData([
ui.Path()..arcTo(Rect.fromLTRB(-5, -16, 5, -6), 0, 1.9 * math.pi, true),
ui.Path()..arcTo(Rect.fromLTRB(-10, 0, 10, 20), 0, -1.0 * math.pi, true),
]);
static final home = FluidFillIconData([
ui.Path()..addRRect(RRect.fromLTRBXY(-10, -2, 10, 10, 2, 2)),
ui.Path()..moveTo(-14, -2)..lineTo(14, -2)..lineTo(0, -16)..close(),
]);
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/content/account.dart
|
import 'package:flutter/material.dart';
import 'package:shared/ui/placeholder/placeholder_card_short.dart';
class AccountContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.only(left: 20, right: 20, top: 20),
child: ListView.builder(
itemCount: 9,
itemBuilder: (content, index) {
return Container(
padding: EdgeInsets.symmetric(vertical: 12),
child: PlaceholderCardShort(color: Color(0xFF99D3F7), backgroundColor: Color(0xFFC7EAFF)),
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/content/home.dart
|
import 'package:flutter/material.dart';
import 'package:shared/ui/placeholder/placeholder_card_tall.dart';
class HomeContent extends StatelessWidget {
@override
Widget build(context) {
return Container(
padding: EdgeInsets.only(left: 20, right: 20, top: 20),
child: ListView.builder(
itemCount: 9,
itemBuilder: (content, index) {
return Container(
padding: EdgeInsets.symmetric(vertical: 12),
child: PlaceholderCardTall(height: 200, color: Color(0xFF99D3F7), backgroundColor: Color(0xFFC7EAFF)),
);
},
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib
|
mirrored_repositories/flutter_showcase/example/apps/fluid_nav_bar/lib/content/grid.dart
|
import 'package:flutter/material.dart';
import 'package:shared/ui/placeholder/placeholder_image_with_text.dart';
class GridContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
bool isLandscape = MediaQuery.of(context).size.aspectRatio > 1;
var columnCount = isLandscape ? 3 : 2;
return Container(
padding: EdgeInsets.only(left: 8, right: 8, top: 20),
child: GridView.count(
crossAxisCount: columnCount,
children: List.generate(20, (index) {
return PlaceholderImageWithText(color: Color(0xFF99D3F7), backgroundColor: Color(0xFFC7EAFF));
}),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/particle_field.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'particle.dart';
// Animated particle effects. Note that this just manages the data, ParticleFieldPainter renders the effect.
class ParticleField with ChangeNotifier {
List<Particle> particles = [];
int lastT = 0;
ParticleField();
// Creates the "delete" effect: red particles exploding from a horizontal line
void lineExplosion(x, y, w, [count = 150]) {
for (int i = 0; i < count; i++) {
particles.add(Particle(
x: x + i / count * w, // evenly spaced along the line
y: y,
vx: Random().nextDouble() * 5.0 - 5.0,
vy: Random().nextDouble() * 3.0 - 2.5,
life: Random().nextDouble() * 0.5 + 0.5,
color: Color(0xffcb4a65).withOpacity(i.isEven ? 0.8 : 0.3)
));
}
}
// Creates the "favorite" effect: blue particles exploding out from a central point (like a firework)
void pointExplosion(x, y, [count = 55]) {
for (int i = 0; i < count; i++) {
double rot = i / count * pi * 2; // angle to apply velocity
double vel = Random().nextDouble() * 2 + .5;
particles.add(Particle(
x: x + 18 * cos(rot),
y: y + 18 * sin(rot),
vx: cos(rot) * vel,
vy: sin(rot) * vel,
life: Random().nextDouble() * 0.5 + 0.5,
color: Color(0xff54d8e6).withOpacity(i.isEven ? 0.8 : 0.3)
));
}
}
// Called each tick by the parent & updates all the particles
void tick(Duration duration) {
// Calculate how much time has ellapsed since the last tick, and calculate a multiplier from that.
double t = min(1.5, (duration.inMilliseconds - lastT) / 1000 * 60);
lastT = duration.inMilliseconds;
int l = particles.length;
for (int i = l - 1; i >= 0; i--) {
// Update each particle's properties.
Particle o = particles[i];
o.vy += 0.05 * t; // "gravity"
o.x += o.vx * t;
o.y += o.vy * t;
o.hue = (o.hue + o.vhue) % 360;
o.life -= 0.01 * t;
if (o.life <= 0.0) {
particles.removeAt(i);
}
}
// If we started this tick with particles, then notify the ParticleFieldPainter that it needs to re-paint.
if (l > 0) {
notifyListeners();
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/removed_swipe_item.dart
|
import 'package:flutter/material.dart';
import 'swipe_item.dart';
// This replaces the list item widget when it is deleted, and implements the deletion animation.
class RemovedSwipeItem extends StatelessWidget {
final Animation<double> animation;
RemovedSwipeItem({this.animation});
@override
Widget build(BuildContext context) {
return SizeTransition(
axis: Axis.vertical,
sizeFactor: animation, // animate height to 0
child: Container(
height: SwipeItem.nominalHeight,
decoration: BoxDecoration(
gradient: SwipeItem.getGradient(Color(0xffcb4a65), 1.0, 1.0),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/particle_field_painter.dart
|
import 'package:flutter/material.dart';
import 'particle_field.dart';
import 'components/sprite_sheet.dart';
// Renders a ParticleField.
class ParticleFieldPainter extends CustomPainter {
ParticleField field;
SpriteSheet spriteSheet;
// ParticleField is a ChangeNotifier, so we can use it as the repaint notifier.
ParticleFieldPainter({@required this.field, this.spriteSheet}) : super(repaint: field);
@override
void paint(Canvas canvas, Size size) {
if (spriteSheet.image == null) {
return;
} // image hasn't loaded
Paint fill = new Paint();
List<RSTransform> transforms = [];
List<Rect> rects = [];
List<Color> colors = [];
int frameCount = spriteSheet.length;
field.particles.forEach((o) {
// Each particle has a transformation entry, which tells drawAtlas where to draw it.
transforms.add(RSTransform.fromComponents(
translateX: o.x, translateY: o.y, rotation: 0, scale: o.life, anchorX: 0, anchorY: 0));
// And a rect entry, which describes the portion (frame) of the sprite sheet image to use as the source.
rects.add(spriteSheet.getFrame((frameCount * o.life * 2 % frameCount).floor()));
// And a color entry, which is composited with the frame via the blend mode.
colors.add(o.color);
});
// Draw all of the particles based on the data entries.
canvas.drawAtlas(
spriteSheet.image,
transforms,
rects,
colors,
BlendMode.dstIn, // Use the sprite frame as an alpha mask for the color
Rect.fromLTWH(0.0, 0.0, size.width, size.height),
fill,
);
}
@override
bool shouldRepaint(_) => true;
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/swipe_item.dart
|
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:shared/physics/constrained_scroll_physics.dart';
import 'demo_data.dart';
import 'message_card.dart';
enum SwipeAction { remove, favorite }
// List item that handles right & left swiping.
class SwipeItem extends StatefulWidget {
static const double swipeDistance = 96.0;
static const double nominalHeight = 110.0;
// Exposed as a static helper method so it can also be used by RemovedSwipeItem:
static LinearGradient getGradient(Color color, double ratio, double sign) {
return LinearGradient(
colors: [
color.withOpacity(ratio * 1.0),
color.withOpacity(ratio * 0.30),
color.withOpacity(ratio * 0.10),
],
stops: [
0.012,
0.012,
1.0,
],
begin: Alignment(sign, 0.0),
end: Alignment(-sign * ratio, 0.0),
);
}
final Email data;
final bool isEven;
final Function(GlobalKey, {SwipeAction action}) onSwipe; // called when a row is swiped left.
SwipeItem({@required this.data, this.onSwipe, @required this.isEven});
@override
State<SwipeItem> createState() {
return SwipeItemState();
}
}
class SwipeItemState extends State<SwipeItem> {
ScrollController _scrollController;
double _swipeDistance = 0.0;
Key _key = GlobalKey();
bool _isPerformingAction = false;
SwipeItemState();
@override
void initState() {
_resetScrollController();
super.initState();
}
@override
Widget build(BuildContext context) {
// Determine the swipe state. How far, what direction, etc.
final double swipeRatio = math.min(1.0, _swipeDistance.abs() / SwipeItem.swipeDistance);
final bool lToR = _swipeDistance < 0.0;
final double swipeSign = _swipeDistance.sign;
final double swipeDistance = _swipeDistance.abs();
final Color indicatorColor = lToR ? Color(0xff4ac0cb) : Color(0xffcb4a65);
// Draw the item based on the swipe state:
return Container(
key: _key,
alignment: Alignment.center,
height: SwipeItem.nominalHeight,
// Gradient background:
decoration: BoxDecoration(
gradient: SwipeItem.getGradient(indicatorColor, swipeRatio, swipeSign),
),
child: Stack(children: [
// The swipe indicator icon:
Positioned.fill(
child: Align(
alignment: Alignment(swipeSign, 0.0),
child: Transform(
alignment: FractionalOffset(0.5, 0.5),
transform: Matrix4.identity()
..translate(swipeDistance * swipeSign * -0.5, 0.0)
..scale(0.5 + 0.5 * swipeRatio),
child: Stack(alignment: Alignment.center, children: [
Container(
width: 28,
height: 28,
decoration: BoxDecoration(
boxShadow: [
if (widget.data.isFavorite && lToR)
BoxShadow(color: Colors.white70.withOpacity(swipeRatio), blurRadius: 18)
],
borderRadius: BorderRadius.circular(50),
color: widget.data.isFavorite || !lToR ? Colors.white : Colors.transparent),
),
Icon(
lToR ? Icons.stars : Icons.cancel,
color: indicatorColor,
size: 36.0,
)
]),
),
),
),
// The item content inside a horizontal scroll view that will provide the swipe physics for us:
SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: ConstrainedScrollPhysics(
maxOverscroll: SwipeItem.swipeDistance * 1.2,
),
controller: _scrollController,
child: Opacity(
opacity: 1.0 - swipeRatio * 0.9,
child: Transform.scale(
scale: 1.0 - swipeRatio * 0.1,
child: EmailCard(
email: widget.data,
backgroundColor: widget.isEven ? Color(0xff272845) : Color(0xff323052),
)),
)),
]),
);
}
void _resetScrollController() {
// _scrollController is attached to the horizontal scroll view, and notifies _handleSwipe of changes.
_scrollController?.dispose();
_scrollController = new ScrollController();
_scrollController.addListener(_handleSwipe);
}
void _handleSwipe() {
double d = _scrollController.position.pixels;
if (d > SwipeItem.swipeDistance && !_isPerformingAction) {
// Completed a left swipe. Call onRemove, and reset the scroll controller to release the swipe.
widget.onSwipe?.call(_key, action: SwipeAction.remove);
_resetScrollController();
} else if (d < -SwipeItem.swipeDistance && !_isPerformingAction) {
_isPerformingAction = true;
// Right swipe.
widget.onSwipe?.call(_key, action: SwipeAction.favorite);
_scrollController
.animateTo(0, duration: Duration(milliseconds: 800), curve: Interval(.25, 1, curve: Curves.easeOutQuad))
.whenComplete(() => _isPerformingAction = false);
}
// Redraw the item with the new swipe distance:
setState(() {
_swipeDistance = d;
});
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/demo_data.dart
|
import 'dart:math';
class Email {
final String from;
final String subject;
final String body;
bool isRead;
bool isFavorite;
int randNum = Random().nextInt(999);
Email({this.from, this.subject, this.body, this.isRead = false, this.isFavorite = false});
toggleFavorite() {
this.isFavorite = !this.isFavorite;
}
}
class DemoData {
final List<Email> _inbox = [
Email(
from: 'Jeffrey Evans',
subject: 'Re: Workshop Preperation',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Jordan Chow',
isRead: true,
subject: 'Reservation Confirmed for Brooklyn',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Katherine Woodward',
subject: 'Rough outline',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Maddie Toohey',
isRead: true,
subject: 'Daily Recap for Tuesday, October 30',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Tamia Clouthier',
isRead: true,
subject: 'Workshop Information',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Daniel Song',
subject: 'Possible Urgent Absence',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Andrew Argue',
subject: 'Vacation Request',
isRead: true,
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Jeffrey Evans',
subject: 'Re: Workshop Preperation',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Jordan Chow',
isRead: true,
subject: 'Reservation Confirmed for Brooklyn',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Katherine Woodward',
subject: 'Rough outline',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Maddie Toohey',
isRead: true,
subject: 'Daily Recap for Tuesday, October 30',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Tamia Clouthier',
isRead: true,
subject: 'Workshop Information',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Daniel Song',
subject: 'Possible Urgent Absence',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Andrew Argue',
subject: 'Vacation Request',
isRead: true,
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Jeffrey Evans',
subject: 'Re: Workshop Preperation',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Jordan Chow',
isRead: true,
subject: 'Reservation Confirmed for Brooklyn',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Katherine Woodward',
subject: 'Rough outline',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Maddie Toohey',
isRead: true,
subject: 'Daily Recap for Tuesday, October 30',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Tamia Clouthier',
isRead: true,
subject: 'Workshop Information',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Daniel Song',
subject: 'Possible Urgent Absence',
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
Email(
from: 'Andrew Argue',
subject: 'Vacation Request',
isRead: true,
body:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at viverra sem. Suspendisse gravida magna in lorem vehicula…',
),
];
int getIndexOf(Email email) {
return _inbox.indexWhere((Email inbox) => inbox.subject == email.subject);
}
List<Email> getData() {
return _inbox;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/message_card.dart
|
import 'package:flutter/material.dart';
import 'demo_data.dart';
import 'main.dart';
import 'swipe_item.dart';
// Content for the list items.
class EmailCard extends StatelessWidget {
final Email email;
final Color backgroundColor;
EmailCard({this.email, this.backgroundColor});
@override
Widget build(BuildContext context) {
double w = MediaQuery.of(context).size.width;
return Container(
width: w + 0.1,
height: SwipeItem.nominalHeight,
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 12.0),
decoration: BoxDecoration(
color: backgroundColor,
boxShadow: [
BoxShadow(
blurRadius: 8.0,
color: Colors.black.withOpacity(0.5),
)
],
),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
if (email.isRead)
Padding(
padding: const EdgeInsets.only(right: 8.0),
child: Icon(Icons.lens, size: 12.0, color: Color(0xffaa07de)),
),
Expanded(
child:
Text(email.from, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14, letterSpacing: .3, package: App.pkg)),
),
Text('11:45 PM', style: TextStyle(fontSize: 11, letterSpacing: .3, package: App.pkg)),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(email.subject, style: TextStyle(fontSize: 11, letterSpacing: .3, package: App.pkg)),
if (email.isFavorite) Icon(Icons.star, size: 18.0, color: Color(0xff55c8d4)),
],
),
SizedBox(height: 2.0),
Text(
email.body,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, letterSpacing: .3, color: Color(0xff9293bf), package: App.pkg),
),
SizedBox(
width: 16.0,
),
],
));
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:particle_swipe/components/particle_app_bar.dart';
import 'package:shared/env.dart';
import 'components/colored_safe_area.dart';
import 'demo.dart';
void main() => runApp(App());
class App extends StatelessWidget {
static String _pkg = "particle_swipe";
static String get pkg => Env.getPackage(_pkg);
@override
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarBrightness: Brightness.dark,
));
return MaterialApp(
title: 'Particle Swipe',
debugShowCheckedModeBanner: false,
theme: ThemeData(
appBarTheme: AppBarTheme(brightness: Brightness.dark),
canvasColor: Color(0xFF161719),
accentColor: Color(0xffc932d9),
textTheme: Theme.of(context).textTheme.apply(bodyColor: Colors.white, fontFamily: 'OpenSans'),
iconTheme: Theme.of(context).iconTheme.copyWith(color: Colors.white),
),
home: Scaffold(
body: SafeArea(
child: Column(children: [
ParticleAppBar(),
Flexible(child: ParticleSwipeDemo()),
]),
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/demo.dart
|
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'demo_data.dart';
import 'list_model.dart';
import 'main.dart';
import 'particle_field.dart';
import 'particle_field_painter.dart';
import 'removed_swipe_item.dart';
import 'components/sprite_sheet.dart';
import 'swipe_item.dart';
class ParticleSwipeDemo extends StatefulWidget {
final List data;
ParticleSwipeDemo() : data = DemoData().getData();
@override
State<StatefulWidget> createState() {
return ParticleSwipeDemoState();
}
}
class ParticleSwipeDemoState extends State<ParticleSwipeDemo> with SingleTickerProviderStateMixin {
//static const double headerHeight = 80;
GlobalKey<AnimatedListState> _listKey = GlobalKey<AnimatedListState>();
ListModel _model;
SpriteSheet _spriteSheet;
ParticleField _particleField;
Ticker _ticker;
@override
void initState() {
// Create the "sparkle" sprite sheet for the particles:
_spriteSheet = SpriteSheet(
imageProvider: AssetImage("images/circle_spritesheet.png", package: App.pkg),
length: 15, // number of frames in the sprite sheet.
frameWidth: 10,
frameHeight: 10,
);
// This synchronizes the data with the animated list:
_model = ListModel(
initialItems: widget.data,
listKey: _listKey, // ListModel uses this to look up the list its acting on.
removedItemBuilder: (dynamic removedItem, BuildContext context, Animation<double> animation) =>
RemovedSwipeItem(animation: animation),
);
_particleField = ParticleField();
_ticker = createTicker(_particleField.tick)..start();
super.initState();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
// Draw the header and List UI with a ParticleFieldPainter layered over top:
return Stack(children: <Widget>[
_buildList(),
Positioned.fill(
child: IgnorePointer(
child: CustomPaint(painter: ParticleFieldPainter(field: _particleField, spriteSheet: _spriteSheet)),
)),
]);
}
Widget _buildList() {
return AnimatedList(
key: _listKey, // used by the ListModel to find this AnimatedList
initialItemCount: _model.length,
physics: ClampingScrollPhysics(),
itemBuilder: (BuildContext context, int index, _) {
var item = _model[index];
return SwipeItem(data: item, isEven: index.isEven, onSwipe: (key, {action}) => _performSwipeAction(item, key, action));
},
);
}
void _performSwipeAction(Email data, GlobalKey key, SwipeAction action) {
// Get item's render box, and use it to calculate the position for the particle effect:
final RenderBox box = key.currentContext.findRenderObject();
Offset position = box.localToGlobal(Offset.zero, ancestor: context.findRenderObject());
double x = position.dx;
double y = position.dy;
double w = box.size.width;
if (action == SwipeAction.remove) {
// Delay the start of the effect a little bit, so the item is mostly closed before it begins.
Future.delayed(Duration(milliseconds: 100)).then((_) => _particleField.lineExplosion(x, y, w));
// Remove the item (using the ItemModel to sync everything), and redraw the UI (to update count):
setState(() {
_model.removeAt(_model.indexOf(data), duration: Duration(milliseconds: 200));
widget.data.remove(data);
});
}
if (action == SwipeAction.favorite) {
data.toggleFavorite();
if (data.isFavorite) {
_particleField.pointExplosion(x + 60, y + 46, 100);
}
}
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/list_model.dart
|
// Keeps a Dart List in sync with an AnimatedList.
// copied from https://flutter.dev/docs/catalog/samples/animated-list
// and modified to add duration
import 'package:flutter/material.dart';
class ListModel<E> {
ListModel({
@required this.listKey,
@required this.removedItemBuilder,
Iterable<E> initialItems,
}) : assert(listKey != null),
assert(removedItemBuilder != null),
_items = List<E>.from(initialItems ?? <E>[]);
final GlobalKey<AnimatedListState> listKey;
final dynamic removedItemBuilder;
final List<E> _items;
AnimatedListState get _animatedList => listKey.currentState;
void insert(int index, E item, {Duration duration}) {
_items.insert(index, item);
_animatedList.insertItem(index, duration: duration);
}
E removeAt(int index, {Duration duration}) {
final E removedItem = _items.removeAt(index);
if (removedItem != null) {
_animatedList.removeItem(index,
(BuildContext context, Animation<double> animation) {
return removedItemBuilder(removedItem, context, animation);
}, duration: duration);
}
return removedItem;
}
int get length => _items.length;
E operator [](int index) => _items[index];
int indexOf(E item) => _items.indexOf(item);
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/particle.dart
|
import 'package:flutter/material.dart';
// Stores the data associated with a particle.
class Particle {
double x;
double y;
double hue;
Color color;
double vx; // velocity x
double vy;
double vhue;
double life;
Particle(
{this.x = 0.0,
this.y = 0.0,
this.vx = 0.0,
this.vy = 0.0,
this.life = 1.0,
this.hue = 0.0,
this.vhue = 0.0,
this.color = Colors.transparent});
// Returns an offset representing this particles, optionally with a transformation applied.
Offset toOffset([Matrix4 transform]) {
Offset o = Offset(x, y);
if (transform == null) {
return o;
}
return MatrixUtils.transformPoint(transform, o);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/components/colored_safe_area.dart
|
import 'package:flutter/material.dart';
class ColoredSafeArea extends StatelessWidget {
//Color properties, gradient takes priority
final Color color;
final Gradient gradient;
//Passed through to SafeArea
final bool left;
final bool top;
final bool right;
final bool bottom;
final EdgeInsets minimum;
final Widget child;
const ColoredSafeArea({Key key, this.left = true, this.top = true, this.right = true, this.bottom = true, this.minimum, this.child, this.color, this.gradient})
: super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
children: [
(gradient != null)
? Container(
decoration: BoxDecoration(gradient: gradient),
)
: Container(
color: color ?? Color(0x0),
),
SafeArea(child: child, left: left, right: right, top: top, bottom: bottom, minimum: minimum ?? EdgeInsets.all(0))
],
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/components/particle_app_bar.dart
|
import 'package:flutter/material.dart';
import '../main.dart';
class ParticleAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(gradient: LinearGradient(colors: [Color(0xffaa07de), Color(0xffde4ed6)])),
child: SafeArea(
child: Stack(children: <Widget>[
SafeArea(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 26),
child: Row(children: <Widget>[
Icon(Icons.menu, size: 28),
SizedBox(width: 18),
Text('Inbox', style: TextStyle(fontFamily: 'OpenSans', fontSize: 21, letterSpacing: .3, package: App.pkg))
]),
)),
]),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib
|
mirrored_repositories/flutter_showcase/example/apps/particle_swipe/lib/components/sprite_sheet.dart
|
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
// Simple sprite sheet helper.
class SpriteSheet {
ui.Image image; // null until the ImageProvide finishes loading.
int frameWidth;
int frameHeight;
int length;
SpriteSheet({@required ImageProvider imageProvider, @required this.length, @required this.frameWidth, this.frameHeight = 0}) {
// Resolve the provider into a stream, then listen for it to complete.
// This will happen synchronously if it's already loaded into memory.
ImageStream stream = imageProvider.resolve(ImageConfiguration());
ImageStreamListener listener = ImageStreamListener((info, _) { image = info.image; });
stream.addListener(listener);
}
Rect getFrame(int index) {
// Given a frame index, return the rect that describes that frame in the image.
if (image == null || index < 0 || index >= length) { return null; }
int cols = (image.width / frameWidth).floor();
int x = index % cols;
int y = (index / cols).floor();
int h = frameHeight == 0 ? image.height : frameHeight; // default to the image's height
return Rect.fromLTWH(x * frameWidth + 0.0, y * h + 0.0, frameWidth + 0.0, h + 0.0);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/details.dart
|
import 'package:flutter/material.dart';
import 'package:product_detail_zoom/pulsing_button.dart';
import 'package:shared/ui/sprite.dart';
import 'components/delayed_fade_in.dart';
import 'main.dart';
import 'product_details_transition.dart';
class ProductDetailView extends StatelessWidget {
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
double screenRatio = screenSize.height / screenSize.width;
double frameRatio = screenRatio < 2 ? screenRatio / 2 : .95;
double frameWidth = screenSize.width * frameRatio;
double frameHeight = (500 * frameWidth) / 360;
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.topCenter,
child: Hero(
tag: 'hero-speaker',
child: Container(
width: frameWidth,
height: frameHeight,
child: Sprite(
image: AssetImage("images/speaker_sprite.png", package: App.pkg), frameWidth: 360, frameHeight: 500, frame: 59)),
),
),
Align(
alignment: Alignment.topCenter,
child: Container(width: frameWidth, height: frameHeight, child: ProductDetailsTransition())),
Align(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.only(bottom: 18.0, left: 76, right: 76),
child: MaterialButton(
height: 55,
minWidth: double.infinity,
onPressed: () {},
color: Colors.white,
textColor: Colors.black,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
child: Text(
'Buy Now \$349.95'.toUpperCase(),
style: TextStyle(fontFamily: 'WorkSans', fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 2, package: App.pkg),
),
),
),
),
Align(
alignment: Alignment(.6, 0),
child: DelayedFadeIn(
delay: Duration(seconds: 1),
child: PulsingButton(
onPressed: () => Navigator.of(context).pop(),
icon: Icons.remove,
),
),
)
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/product_details_transition.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'components/circle_painter.dart';
import 'main.dart';
class ProductDetailsTransition extends StatelessWidget {
final double animationValue;
final CurvedAnimation _curvedAnimation;
final TextStyle bodyStyle =
TextStyle(fontFamily: 'WorkSans', fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 2, package: App.pkg);
ProductDetailsTransition({Key key, this.animationValue = 1})
: _curvedAnimation = CurvedAnimation(curve: Interval(0, .8, curve: Curves.easeOut), parent: AlwaysStoppedAnimation(animationValue)),
super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
fit: StackFit.expand,
overflow: Overflow.visible,
children: [
Positioned(
top: 25,
left: 45,
child: _SpeakerAttribute(
attribute: 'Spectacular tonal range',
animation: _getAttributeAnimWithInterval(0, .85),
lineHeight: 270,
),
),
Positioned(
top: 75,
left: 95,
child: _SpeakerAttribute(
attribute: 'Superior-grade aluminum',
animation: _getAttributeAnimWithInterval(.35, .95),
lineHeight: 250,
),
),
Positioned(
top: 120,
left: 175,
child: _SpeakerAttribute(
attribute: 'Deep 30Hz bass',
animation: _getAttributeAnimWithInterval(.45, 1),
lineHeight: 185,
),
),
ScaleTransition(
scale: Tween<double>(begin: .6, end: 1).animate(_curvedAnimation),
child: SlideTransition(
position: Tween<Offset>(begin: Offset(.6, .7), end: Offset(.1, .95)).animate(_curvedAnimation),
child: FadeTransition(
opacity: Tween<double>(begin: 0, end: 1).animate(_getCurvedAnimWithInterval(.2, 1)),
child: Transform(
transform: Matrix4.identity()
..setEntry(3, 2, 0.01)
..rotateY(Tween<double>(begin: -.09, end: 0).transform(CurvedAnimation(
curve: Interval(0, .8),
parent: AlwaysStoppedAnimation(animationValue),
).value)),
child: Container(
width: 300,
height: 500,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text('Perfect Sound'.toUpperCase(),
style: bodyStyle.copyWith(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 52, height: .9)),
Text(
'This is our best speaker yet.',
textAlign: TextAlign.start,
style: bodyStyle.copyWith(color: Colors.white, height: 1.5, fontWeight: FontWeight.w600, fontSize: 20),
),
],
),
),
)),
),
),
],
);
}
CurvedAnimation _getCurvedAnimWithInterval(double begin, double end) {
return CurvedAnimation(curve: Interval(begin, end), parent: _curvedAnimation);
}
CurvedAnimation _getAttributeAnimWithInterval(double begin, double end) {
var attributeAnim = CurvedAnimation(curve: Interval(.65, 1), parent: AlwaysStoppedAnimation(animationValue));
return CurvedAnimation(curve: Interval(begin, end), parent: attributeAnim);
}
}
class _SpeakerAttribute extends StatelessWidget {
final double lineHeight;
final Animation animation;
final String attribute;
const _SpeakerAttribute({Key key, this.lineHeight = 150, this.attribute, this.animation}) : super(key: key);
@override
Widget build(BuildContext context) {
double lineHeight = Tween<double>(begin: 0, end: this.lineHeight).transform(Curves.easeInOutQuad.transform(animation.value));
return Stack(
overflow: Overflow.visible,
children: <Widget>[
SlideTransition(
position: Tween<Offset>(begin: Offset(0, -.5), end: Offset.zero).animate(_getAnimationWithInterval(.2, 1)),
child: FadeTransition(
opacity: _getAnimationWithInterval(.15, .95),
child: Text(
attribute,
style: TextStyle(fontFamily: 'WorkSans', letterSpacing: 3, color: Colors.white, fontSize: 13.5, package: App.pkg),
),
),
),
Positioned(
top: lineHeight / 2 + 17,
left: -lineHeight / 2 + 5,
child: Transform.rotate(
angle: pi / 2,
child: Container(
width: lineHeight,
height: 1,
color: Colors.white,
),
),
),
Positioned(
top: lineHeight + 17,
left: 5,
child: FadeTransition(
opacity: Tween<double>(begin: 0, end: 1).animate(_getAnimationWithInterval(0, .3)),
child: CustomPaint(
painter: CirclePainter(
radius: 3,
color: Colors.white,
)),
),
),
],
);
}
CurvedAnimation _getAnimationWithInterval(double begin, double end) {
return CurvedAnimation(curve: Interval(begin, end), parent: animation);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/product_details_hero_flight.dart
|
import 'package:flutter/material.dart';
import 'package:shared/ui/animated_sprite.dart';
import 'main.dart';
import 'product_details_transition.dart';
class ProductDetailsHeroFlight extends StatelessWidget {
final Animation<double> animation;
final BuildContext toHeroContext;
final double framwWidth;
final double framwHeight;
const ProductDetailsHeroFlight({Key key, @required this.animation, @required this.toHeroContext, this.framwWidth, this.framwHeight})
: super(key: key);
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.topCenter,
children: <Widget>[
Container(
width: framwWidth,
height: framwHeight,
child: AnimatedSprite(
image: AssetImage("images/speaker_sprite.png", package: App.pkg),
frameWidth: 360,
frameHeight: 500,
animation: Tween(begin: 0.0, end: 59.0).animate(CurvedAnimation(curve: Interval(0, .8), parent: animation)),
),
),
Container(
width: framwWidth,
height: framwHeight,
child: AnimatedBuilder(
animation: animation,
builder: (BuildContext context, Widget child) {
return DefaultTextStyle(
style: DefaultTextStyle.of(toHeroContext).style,
child: ProductDetailsTransition(animationValue: animation.value),
);
},
),
)
],
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/pulsing_button.dart
|
import 'package:flutter/material.dart';
import 'components/circle_painter.dart';
class PulsingButton extends StatefulWidget {
final Function onPressed;
final IconData icon;
const PulsingButton({Key key, @required this.onPressed, @required this.icon}) : super(key: key);
@override
State<StatefulWidget> createState() => _PulsingButtonState();
}
class _PulsingButtonState extends State<PulsingButton> with SingleTickerProviderStateMixin {
AnimationController _btnAnimController;
CurvedAnimation _btnAnim;
@override
void initState() {
super.initState();
_btnAnimController = AnimationController(vsync: this, duration: Duration(milliseconds: 1200))..repeat();
_btnAnim = CurvedAnimation(curve: Curves.linear, parent: _btnAnimController);
}
@override
void dispose() {
_btnAnimController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: <Widget>[
FadeTransition(
opacity: Tween<double>(begin: .7, end: 0).animate(_btnAnim),
child: ScaleTransition(
scale: Tween<double>(begin: .5, end: 1).animate(_btnAnim),
child: CustomPaint(
painter: CirclePainter(
radius: 28,
color: Color(0xff27aeef),
),
//Add a sizedbox child to the CustomPaint, to give the button more hit area
child: SizedBox(
width: 70,
height: 70,
),
),
),
),
AnimatedBuilder(
animation: _btnAnimController,
builder: (BuildContext context, Widget child) {
double opacity = Tween<double>(begin: .7, end: .9).transform(_btnAnim.value);
return MaterialButton(
height: 28,
splashColor: Color(0xff0f668f),
hoverColor: Color(0xff0f668f),
color: Color(0xff27aeef).withOpacity(opacity),
textColor: Colors.white,
child: Icon(widget.icon),
shape: CircleBorder(),
onPressed: widget.onPressed,
);
},
)
],
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:shared/env.dart';
import 'demo.dart';
void main() => runApp(App());
class App extends StatelessWidget {
static String _pkg = "product_detail_zoom";
static String get pkg => Env.getPackage(_pkg);
@override
Widget build(BuildContext context) {
const title = '3D Product Detail Zoom';
return MaterialApp(
title: title,
themeMode: ThemeMode.dark,
home: ProductDetailZoomDemo(),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/demo.dart
|
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:product_detail_zoom/product_details_hero_flight.dart';
import 'package:shared/ui/sprite.dart';
import 'components/circle_painter.dart';
import 'components/fade_color_page_route.dart';
import 'details.dart';
import 'main.dart';
import 'pulsing_button.dart';
class ProductDetailZoomDemo extends StatefulWidget {
@override
State<StatefulWidget> createState() => _ProductDetailZoomDemoState();
}
class _ProductDetailZoomDemoState extends State<ProductDetailZoomDemo> with SingleTickerProviderStateMixin {
AnimationController _transitionAnimController;
bool _isFirstInit;
Size _screenSize;
double _frameHeight;
double _frameWidth;
double _buttonAlpha = 0;
TextStyle bodyStyle = TextStyle(fontFamily: 'WorkSans', fontWeight: FontWeight.bold, fontSize: 16, letterSpacing: 2, package: App.pkg);
@override
void initState() {
super.initState();
_isFirstInit = true;
_buttonAlpha = 0;
_transitionAnimController = AnimationController(vsync: this, duration: Duration(milliseconds: 1600));
_transitionIn();
}
void _transitionIn() async {
await Future.delayed(Duration(milliseconds: 1000));
setState(() => _buttonAlpha = 1);
}
@override
void dispose() {
_transitionAnimController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
_screenSize = MediaQuery.of(context).size;
_initFrameValues();
return Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child: Stack(
children: <Widget>[
_buildAppBar(),
//Create a Hero tagged to match the instance details view
Hero(
tag: 'hero-speaker',
//Use a custom flightShuttleBuilder to control the hero transition
flightShuttleBuilder: (flightContext, animation, flightDirection, fromHeroContext, toHeroContext) {
return ProductDetailsHeroFlight(
animation: animation,
toHeroContext: toHeroContext,
framwWidth: _frameWidth,
framwHeight: _frameHeight,
);
},
//The child of the hero, is the main speaker animation
child: Align(
alignment: Alignment.topCenter,
child: Container(
width: _frameWidth,
height: _frameHeight,
child: Sprite(
image: AssetImage("images/speaker_sprite.png", package: App.pkg), frameWidth: 360, frameHeight: 500, frame: 1)),
),
),
Align(
alignment: Alignment(0, 0),
child: Transform.translate(
offset: Offset(100, -70),
child: AnimatedOpacity(
duration: Duration(milliseconds: 350),
opacity: _buttonAlpha,
child: PulsingButton(
onPressed: _handleOnPressed,
icon: Icons.add,
),
),
),
),
Align(
alignment: Alignment.bottomCenter,
child: Container(
width: double.infinity,
height: _screenSize.height * .43,
margin: EdgeInsets.symmetric(horizontal: 40),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
_buildSpeakerDescription(),
Container(
padding: const EdgeInsets.only(right: 36.0, left: 36.0),
child: Column(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(top: 18, bottom: 12.0),
child: _buildBuyNowButton(),
),
_buildLearnMoreButton()
],
),
)
],
),
),
),
],
)),
);
}
void _initFrameValues() {
double screenRatio = _screenSize.height / _screenSize.width;
double frameRatio = screenRatio < 2 ? screenRatio / 2 : .95;
_frameWidth = _screenSize.width * frameRatio;
_frameHeight = (500 * _frameWidth) / 360;
}
Widget _buildSpeakerDescription() {
return SlideTransition(
position: Tween(begin: Offset.zero, end: Offset(-.1, 0))
.animate(CurvedAnimation(curve: Interval(.5, 1, curve: Curves.easeOut), parent: _transitionAnimController)),
child: Column(
children: <Widget>[
Text('Classic Speaker 2700'.toUpperCase(),
textAlign: TextAlign.justify,
style: bodyStyle.copyWith(fontWeight: FontWeight.w900, color: Colors.white, height: 1.1, fontSize: 30, letterSpacing: 5)),
SizedBox(height: 8),
Text(
'This speaker provides a home soundscape unlike any other with its high quality sound and sleek design. You won\'t believe it until you hear it.',
textAlign: TextAlign.start,
style: bodyStyle.copyWith(color: Colors.white, fontSize: 12, letterSpacing: 2.8, height: 1.3))
],
),
);
}
Widget _buildBuyNowButton() {
return MaterialButton(
height: 55,
onPressed: () {},
color: Colors.white,
textColor: Colors.black,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50)),
child: Text(
'Buy Now \$349.95'.toUpperCase(),
style: bodyStyle,
),
);
}
Widget _buildLearnMoreButton() {
return MaterialButton(
height: 55,
onPressed: () {},
color: Colors.transparent,
textColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(50), side: BorderSide(color: Colors.white, width: 1.5)),
child: Text(
'Learn More'.toUpperCase(),
style: bodyStyle,
),
);
}
Widget _buildAppBar() {
return AppBar(
leading: Icon(CupertinoIcons.left_chevron, color: Colors.white, size: 36),
actions: <Widget>[
Padding(
padding: const EdgeInsets.only(right: 24.0),
child: Image.asset('images/shopping_bag.png', width: 20, height: 20, fit: BoxFit.contain, package: App.pkg),
)
],
backgroundColor: Colors.transparent,
elevation: 0,
);
}
bool _isTransitioning = false;
void _handleOnPressed() async {
this._isFirstInit = false;
//Don't accept button presses if we're currently fading the btn in or out
if (_buttonAlpha < 1) return;
//Fade button out
setState(() => _buttonAlpha = 0);
//Kick off main animation sequence
_transitionAnimController.forward().whenComplete(() => _transitionAnimController.reset());
//Wait a bit to let the btn fade out
await Future.delayed(Duration(milliseconds: 300));
//Show new page route, which will place the Hero on top of everything
Navigator.push(
context,
FadeColorPageRoute(
color: Colors.black,
enterPage: ProductDetailView(),
));
//Fade button back in, now that hero is covering it
setState(() => _buttonAlpha = 1);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/components/circle_painter.dart
|
import 'package:flutter/widgets.dart';
class CirclePainter extends CustomPainter {
final Paint _paint;
final Color color;
final double radius;
CirclePainter({this.color, this.radius})
: _paint = Paint()
..color = color
..strokeWidth = 10.0
..style = PaintingStyle.fill;
@override
void paint(Canvas canvas, Size size) {
canvas.drawCircle(Offset(size.width / 2, size.height / 2), radius, _paint);
}
@override
bool shouldRepaint(CirclePainter oldDelegate) {
return oldDelegate.color != color || oldDelegate.radius != radius;
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/components/delayed_fade_in.dart
|
import 'package:flutter/material.dart';
class DelayedFadeIn extends StatefulWidget {
final Widget child;
final Duration duration;
final Duration delay;
const DelayedFadeIn({Key key, this.child, @required this.delay, this.duration = const Duration(milliseconds: 700)})
: super(key: key);
@override
State<StatefulWidget> createState() => _DelayedFadeInState();
}
class _DelayedFadeInState extends State<DelayedFadeIn> with SingleTickerProviderStateMixin {
AnimationController _animationController;
@override
void initState() {
super.initState();
_animationController = AnimationController(vsync: this);
_animationController.duration = widget.duration + widget.delay;
_animationController.forward(from: 0);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return FadeTransition(
opacity: CurvedAnimation(curve: Interval(.9, 1), parent: _animationController), child: widget.child);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib
|
mirrored_repositories/flutter_showcase/example/apps/product_detail_zoom/lib/components/fade_color_page_route.dart
|
import 'package:flutter/material.dart';
class FadeColorPageRoute extends PageRouteBuilder {
final Widget enterPage;
final Color color;
FadeColorPageRoute({this.enterPage, @required this.color})
: super(
transitionDuration: Duration(seconds: 3),
pageBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) =>
enterPage,
transitionsBuilder: (
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
Animation fadeOut = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(curve: Interval(0, .2), parent: animation));
Animation fadeIn = Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(curve: Interval(.8, 1), parent: animation));
return Stack(children: <Widget>[
FadeTransition(
opacity: fadeOut,
child: Container(
width: double.infinity,
height: double.infinity,
color: color,
),
),
FadeTransition(
opacity: fadeIn,
child: child,
)
]);
},
);
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/hotel_list_renderer.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'demo_data.dart';
import 'styles.dart';
class HotelListRenderer extends StatelessWidget {
final List<HotelData> hotels;
HotelListRenderer(this.hotels);
@override
Widget build(BuildContext context) {
Size size = MediaQuery.of(context).size;
return Padding(
padding: EdgeInsets.only(right: Styles.hzScreenPadding * 1.5, left: Styles.hzScreenPadding * 1.5, bottom: 20),
child: Container(
width: double.infinity,
height: size.height * .25,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Hotels'.toUpperCase(),
style: Styles.hotelsTitleSection,
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: hotels.map((hotel) => _buildHotelData(hotel)).toList(),
),
)
],
),
),
);
}
Widget _buildHotelData(HotelData hotel) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 3),
child: Text(hotel.name, style: Styles.hotelTitle),
),
Row(
children: <Widget>[
_buildFiveStars(hotel),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Text(hotel.rate.toString(), style: Styles.hotelScore),
),
Text('(${hotel.reviews})', style: Styles.hotelData),
],
)
],
),
Text(
'\$${hotel.price.toInt()}',
style: Styles.hotelPrice,
)
],
);
}
Widget _buildFiveStars(HotelData hotel) {
List<Widget> stars = [];
for (int i = 0; i < hotel.rate.toInt(); i++) {
stars.add(Icon(Icons.star, color: Color(0xFFfeda7d), size: 13));
}
return Row(
children: stars,
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/styles.dart
|
import 'package:flutter/material.dart';
import 'main.dart';
class Styles {
static const double hzScreenPadding = 18.0;
static const double cardBorderRadius = 10.0;
static final TextStyle baseTitle = TextStyle(fontFamily: 'DMSerifDisplay', package: App.pkg);
static final TextStyle baseBody = TextStyle(fontFamily: 'OpenSans', package: App.pkg);
static final TextStyle appHeader = baseTitle.copyWith(color: Color(0xFF0e0e0e), fontSize: 36, height: 1.2);
static final TextStyle cardTitle = baseTitle.copyWith(height: 1, color: Color(0xFF1a1a1a), fontSize: 25);
static final TextStyle cardSubtitle = baseBody.copyWith(color: Color(0xFF666666), height: 1.8, fontSize: 12);
static final TextStyle cardAction =
baseBody.copyWith(color: Color(0xFFa6998b), fontSize: 12, height: 1, fontWeight: FontWeight.w600, letterSpacing: 0.1);
static final TextStyle hotelsTitleSection = baseBody.copyWith(color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold, height: 2);
static final TextStyle hotelTitle = baseBody.copyWith(color: Colors.black, fontSize: 14, fontWeight: FontWeight.w600);
static final TextStyle hotelPrice = baseBody.copyWith(color: Color(0xff4d4d4d), fontSize: 13);
static final TextStyle hotelScore = baseBody.copyWith(color: Color(0xff0e0e0e), fontSize: 11);
static final TextStyle hotelData = baseBody.copyWith(color: Colors.grey[700], fontSize: 11);
static final TextStyle detailsTitleSection = baseBody.copyWith(color: Colors.black, fontSize: 14, fontWeight: FontWeight.bold);
static final TextStyle detailsCardTitle = baseBody.copyWith(color: Colors.black, fontSize: 10, letterSpacing: 0.5);
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/demo_data.dart
|
import 'package:flutter/material.dart';
class CityData {
final String name;
final String title;
final String description;
final String information;
final Color color;
final List<HotelData> hotels;
CityData({
this.title,
this.name,
this.description,
this.information,
this.color,
this.hotels,
});
}
class HotelData {
final String name;
double rate;
final int reviews;
final double price;
HotelData(this.name, {this.reviews, this.price}) : rate = 5.0;
}
class DemoData {
CityData _city = CityData(
name: 'Paris',
title: 'Paris, France',
description: 'Get ready to explore the city of love filled with romantic scenery and experiences.',
information:
'Paris, located along the Seine River, in the north-central part of France. For centuries, Paris has been one of the world’s most important and attractive cities.',
color: Color(0xfffdeed5),
hotels: [
HotelData('Shangri-La Hotel Paris', reviews: 201, price: 593.0),
HotelData('Hôtel Trinité Haussmann', reviews: 133, price: 391),
HotelData('Maison Breguet', reviews: 128, price: 399),
]);
CityData getCity() => _city;
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/city_details_page.dart
|
import 'package:flutter/material.dart';
import 'city_scenery.dart';
import 'demo_data.dart';
import 'main.dart';
import 'styles.dart';
class CityDetailsPage extends StatelessWidget {
final CityData city;
CityDetailsPage(this.city);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
_buildHeroWidget(context),
_buildCityDetails(),
],
),
_buildBackButton(context),
],
),
);
}
Widget _buildHeroWidget(context) {
return Hero(
tag: '${city.name}-hero',
flightShuttleBuilder: _buildFlightWidget,
child: Container(
height: MediaQuery.of(context).size.height * .55,
width: double.infinity,
child: CityScenery(
animationValue: 1,
city: city,
),
),
);
}
Widget _buildFlightWidget(BuildContext flightContext, Animation<double> heroAnimation,
HeroFlightDirection flightDirection, BuildContext fromHeroContext, BuildContext toHeroContext) {
return AnimatedBuilder(
animation: heroAnimation,
builder: (context, child) {
return DefaultTextStyle(
style: DefaultTextStyle.of(toHeroContext).style,
child: CityScenery(
city: city,
animationValue: heroAnimation.value,
),
);
},
);
}
Widget _buildCityDetails() {
return Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(
children: <Widget>[
Text(city.title, style: Styles.appHeader),
Padding(
padding: const EdgeInsets.only(
top: 8,
left: Styles.hzScreenPadding * 1.5,
right: Styles.hzScreenPadding * 1.5,
),
child: Text(city.information, style: Styles.cardSubtitle, textAlign: TextAlign.center),
),
],
),
// Cards section
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.only(bottom: 16.0),
child: Text('Experiences for every interest'.toUpperCase(), style: Styles.detailsTitleSection),
),
_ExperiencesSection()
],
)
],
),
);
}
Widget _buildBackButton(BuildContext context) {
return SafeArea(
child: IconButton(
padding: EdgeInsets.only(left: Styles.hzScreenPadding),
icon: Icon(Icons.arrow_back_ios, size: 18),
onPressed: () {
Navigator.pop(context);
}),
);
}
}
class _ExperiencesSection extends StatelessWidget {
final List<String> experiences = ['Arts', 'Food And Drink', 'Classes'];
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
return Container(
height: screenSize.height * .15,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[for (var experience in experiences) _buildExperienceCard(screenSize, experience)],
));
}
Widget _buildExperienceCard(Size screenSize, experience) {
return Card(
elevation: 1,
child: Container(
color: Colors.white,
height: screenSize.height * .22,
width: screenSize.width * .3,
child: Column(
children: <Widget>[
Expanded(
child: Image.asset(
'images/Small-Cards/${experience.replaceAll(' ', '')}.png',
fit: BoxFit.cover,
width: double.infinity,
package: App.pkg,
),
),
Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
experience,
style: Styles.detailsCardTitle,
),
),
),
],
),
),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/city_scenery.dart
|
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'components/rotation_3d.dart';
import 'demo_data.dart';
import 'main.dart';
import 'styles.dart';
class CityScenery extends StatelessWidget {
final double animationValue;
final CityData city;
const CityScenery({Key key, this.animationValue = 0, @required this.city}) : super(key: key);
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
var animation = AlwaysStoppedAnimation(animationValue);
return Stack(
alignment: Alignment.center,
children: <Widget>[
_buildBackgroundTransition(animation),
_buildCardInfo(animation, screenSize),
_buildRoadTransition(animation, screenSize),
_buildCloudsAnimation(animation),
_buildCityAndTreesTransition(animation, screenSize),
_buildLeavesAnimation(animation),
],
);
}
Widget _buildCardInfo(Animation animation, Size screenSize) {
return FadeTransition(
opacity: Tween<double>(begin: 1.0, end: 0).animate(CurvedAnimation(curve: Interval(0, .22), parent: animation)),
child: Container(
padding: EdgeInsets.only(right: 35.0, left: 35.0, bottom: 8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
// Sized box gives the space of the city image in the stack
SizedBox(height: screenSize.height * .22),
Padding(
padding: const EdgeInsets.only(top: 22.0),
child: Text(city.title, style: Styles.cardTitle),
),
Text(city.description, textAlign: TextAlign.center, style: Styles.cardSubtitle),
Padding(
padding: const EdgeInsets.symmetric(vertical: 12.0),
child: Text('Learn More'.toUpperCase(), style: Styles.cardAction),
)
],
),
),
);
}
Widget _buildBackgroundTransition(Animation animation) {
var gradientStart =
ColorTween(begin: city.color, end: Color(0xFFfde9c8)).animate(CurvedAnimation(curve: Curves.easeOut, parent: animation));
var gradientEnd = ColorTween(begin: city.color, end: Color(0xFFfdf8f1)).evaluate(animation);
var borderRadiusAnimation = Tween<double>(begin: Styles.cardBorderRadius, end: 0).transform(animationValue);
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(borderRadiusAnimation),
boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 8)],
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [gradientStart.value, gradientEnd],
)),
);
}
Widget _buildRoadTransition(Animation animation, Size screenSize) {
double scale = .55 * .2;
return FadeTransition(
opacity: Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(curve: Interval(.7, 1, curve: Curves.easeIn), parent: animation)),
child: SlideTransition(
position: Tween<Offset>(begin: Offset(0, -1.4), end: Offset.zero).animate(animation),
child: SizeTransition(
sizeFactor: animation,
axis: Axis.vertical,
axisAlignment: -1,
child: Center(
child: Align(
alignment: Alignment.bottomCenter,
child: Image.asset(
'images/Road.png',
width: double.infinity,
height: screenSize.height * scale - 5,
fit: BoxFit.fitHeight,
package: App.pkg,
),
),
),
),
),
);
}
Widget _buildCloudsAnimation(Animation animation) {
return FadeTransition(
opacity: animation,
child: _Clouds(),
);
}
Widget _buildCityAndTreesTransition(Animation animation, Size screenSize) {
// City Image Animation
var sizeStart = Size(screenSize.width * .55, screenSize.height * .24);
var sizeEnd = Size(screenSize.width, screenSize.height * .35);
var sizeTransition =
Tween(begin: sizeStart, end: sizeEnd).animate(CurvedAnimation(curve: Interval(.25, 1, curve: Curves.easeIn), parent: animation));
var cityPositionTransition = Tween(begin: Offset(0, -screenSize.height * .112), end: Offset.zero)
.animate(CurvedAnimation(curve: Interval(0.5, 1, curve: Curves.easeIn), parent: animation));
//Trees Animations
var treesOpacityTransition =
Tween<double>(begin: 0, end: 1).animate(CurvedAnimation(curve: Interval(.75, 1, curve: Curves.easeIn), parent: animation));
return Transform.translate(
offset: cityPositionTransition.value,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
_CityImage(
size: sizeTransition.value,
city: city,
),
FadeTransition(
opacity: treesOpacityTransition,
child: _Trees(),
),
],
),
);
}
Widget _buildLeavesAnimation(Animation animation) {
return FadeTransition(
opacity: animation,
child: _Leaves(),
);
}
}
class _Clouds extends StatefulWidget {
final double animationValue;
_Clouds({this.animationValue = 0.5});
@override
_CloudsState createState() => _CloudsState();
}
class _CloudsState extends State<_Clouds> with SingleTickerProviderStateMixin {
static Map<String, _CloudsState> _cachedState = {};
Ticker _ticker;
double _animationValue;
@override
void initState() {
super.initState();
//Restore old state from the static cache, workaround because Hero causes our widget to lose state
var prevState = _cachedState[widget.key.toString()];
if (prevState != null) {
_animationValue = prevState._animationValue;
} else {
_animationValue = widget.animationValue;
}
//Replace cached state with ourselves
_cachedState[widget.key.toString()] = this;
_ticker = Ticker(_onTick)..start();
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
_onTick(Duration d) {
double speed = .0003;
setState(() {
if (_animationValue <= 1)
_animationValue += speed;
else
_animationValue = 0;
});
}
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
var dxPosition = Tween<double>(begin: -screenSize.width * .1, end: screenSize.width * 1.8).transform(_animationValue);
return Stack(
children: <Widget>[
Positioned(
top: screenSize.height * .065,
left: dxPosition - (screenSize.width * 0.65),
child: Image.asset(
'images/CloudLarge.png',
width: screenSize.width * .2,
package: App.pkg,
),
),
Positioned(
top: screenSize.height * .12,
left: dxPosition * .5,
child: Image.asset(
'images/CloudSmall.png',
width: screenSize.width * .15,
package: App.pkg,
),
)
],
);
}
}
class _Leaves extends StatefulWidget {
@override
_LeavesState createState() => _LeavesState();
}
class _LeavesState extends State<_Leaves> with SingleTickerProviderStateMixin {
static Map<String, _LeavesState> _cachedState = {};
Ticker _ticker;
double _animationValue;
@override
initState() {
super.initState();
//Restore old state from the static cache, workaround because Hero causes our widget to lose state
var prevState = _cachedState[widget.key.toString()];
if (prevState != null) {
_animationValue = prevState._animationValue;
} else {
_animationValue = 0;
}
//Replace cached state with ourselves
_cachedState[widget.key.toString()] = this;
_ticker = Ticker(_onTick)..start();
}
_onTick(Duration d) {
double speed = .001;
setState(() {
if (_animationValue + speed < 1)
_animationValue += speed;
else
_animationValue = 0;
});
}
@override
void dispose() {
_ticker.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
_Leaf(
animationValue: _animationValue,
rotationScale: 1.5,
curve: Curves.easeInOutSine,
getCurvePath: (double screenPosition) => sin(screenPosition) * 15 + 200),
_Leaf(
animationValue: _animationValue,
rotationScale: 1.7,
curve: Curves.linearToEaseOut,
getCurvePath: (double screenPosition) => -cos(screenPosition) * 30 + 130),
_Leaf(
animationValue: _animationValue,
rotationScale: 1.2,
curve: Curves.ease,
getCurvePath: (double screenPosition) => atan(screenPosition) * 10 + 150),
],
);
}
}
class _Leaf extends StatelessWidget {
final double animationValue;
final double rotationScale;
final Function getCurvePath;
final Curve curve;
_Leaf({@required this.animationValue, @required this.getCurvePath, this.curve = Curves.linear, this.rotationScale = 1});
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
var dxPosition =
Tween<double>(begin: -10, end: screenSize.width + 10).transform(Interval(0, .9, curve: this.curve).transform(animationValue));
var dyPosition = Tween<double>(begin: 0, end: pi * 2).transform(animationValue);
var rotation = Tween<double>(begin: 0, end: 360).transform(Curves.easeOutSine.transform(animationValue));
return Positioned(
child: Rotation3d(
rotationY: rotation * rotationScale,
child: Image.asset(
'images/BlowingLeaf.png',
width: screenSize.width * .015 + Random().nextDouble() * .01,
package: App.pkg,
)),
bottom: getCurvePath(dyPosition),
left: dxPosition,
);
}
}
class _Trees extends StatelessWidget {
@override
Widget build(BuildContext context) {
Size screenSize = MediaQuery.of(context).size;
return Stack(
children: <Widget>[
Positioned(
bottom: screenSize.height * .07,
right: screenSize.width * .2,
child: _getTreeAsset(screenSize, false),
),
Positioned(
bottom: screenSize.height * .07,
left: screenSize.width * .2,
child: _getTreeAsset(screenSize, false),
),
Positioned(
bottom: screenSize.height * .01,
right: screenSize.width * .1,
child: _getTreeAsset(screenSize, true),
),
Positioned(
bottom: screenSize.height * .01,
left: screenSize.width * .1,
child: _getTreeAsset(screenSize, true),
),
],
);
}
Widget _getTreeAsset(Size screenSize, bool isFront) {
double sizeProportion = isFront ? .08 : .05;
return Image.asset(
'images/Tree.png',
width: screenSize.width * sizeProportion,
package: App.pkg,
);
}
}
class _CityImage extends StatelessWidget {
final Size size;
final CityData city;
const _CityImage({Key key, this.size, this.city}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
width: size.width,
height: size.height,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
Image.asset('images/${city.name}/${city.name}-Back.png', package: App.pkg,),
Image.asset('images/${city.name}/${city.name}-Middle.png', package: App.pkg,),
Image.asset('images/${city.name}/${city.name}-Front.png', package: App.pkg,),
],
)),
Image.asset('images/Ground.png', width: size.width, package: App.pkg,)
],
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/main.dart
|
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared/env.dart';
import 'demo.dart';
void main() => runApp(App());
class App extends StatelessWidget {
static String _pkg = "parallax_travel_cards_hero";
static String get pkg => Env.getPackage(_pkg);
@override
Widget build(BuildContext context) {
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitDown,
DeviceOrientation.portraitUp,
]);
return MaterialApp(
title: 'Hero Travel Card',
theme: ThemeData(brightness: Brightness.light),
home: HeroCardDemo(),
);
}
}
| 0
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero
|
mirrored_repositories/flutter_showcase/example/apps/parallax_travel_cards_hero/lib/demo.dart
|
import 'package:flutter/material.dart';
import 'city_scenery.dart';
import 'city_details_page.dart';
import 'demo_data.dart';
import 'hotel_list_renderer.dart';
import 'styles.dart';
import 'components/white_page_route.dart';
class HeroCardDemo extends StatelessWidget {
final CityData city = DemoData().getCity();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: _buildAppBar(),
backgroundColor: Colors.white,
//Create a column of items, with the cityCard expanding to fill the empty space
body: Container(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
_buildHeader(),
Expanded(child: _buildCityCard(context)),
HotelListRenderer(city.hotels),
],
),
),
);
}
Widget _buildAppBar() {
return AppBar(
elevation: 0.0,
leading: Icon(Icons.menu, color: Colors.black),
backgroundColor: Colors.white,
brightness: Brightness.light,
actions: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: Styles.hzScreenPadding),
child: Icon(Icons.search, color: Colors.black),
)
],
);
}
Widget _buildHeader() {
return Padding(
padding: EdgeInsets.only(right: Styles.hzScreenPadding * 3, left: Styles.hzScreenPadding * 3),
child: Text('Get ready for your trip', textAlign: TextAlign.center, style: Styles.appHeader),
);
}
Widget _buildCityCard(context) {
return Center(
child: GestureDetector(
onTap: () => _handlePressedBtn(context),
child: Container(
constraints: BoxConstraints(minHeight: 290, minWidth: 250, maxHeight: MediaQuery.of(context).size.height * .43, maxWidth: 300),
child: Hero(tag: '${city.name}-hero', child: CityScenery(city: city)),
),
),
);
}
void _handlePressedBtn(context) {
var detailPage = CityDetailsPage(city);
Navigator.push(context, WhitePageRoute(enterPage: detailPage));
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.