repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/switch_checkbox.dart | import 'package:flutter/material.dart';
void main() {
runApp(SwitchAndCheckboxApp());
}
// SwitchAndCheckboxApp
class SwitchAndCheckboxApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "单选开关和复选框",
home: Scaffold(
appBar: AppBar(
title: Text("单选开关和复选框"),
),
body: new SwitchAndCheckBoxTestRoute(),
));
}
}
// SwitchAndCheckBoxTestRoute
class SwitchAndCheckBoxTestRoute extends StatefulWidget {
@override
_SwitchAndCheckBoxTestRouteState createState() =>
new _SwitchAndCheckBoxTestRouteState();
}
// _SwitchAndCheckBoxTestRouteState
class _SwitchAndCheckBoxTestRouteState extends State<SwitchAndCheckBoxTestRoute> {
int _sex = 1;
int _status = 2;
bool _switchSelected = true; //维护单选开关状态
bool _checkboxSelected = true; //维护复选框状态
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Row(
children: <Widget>[
Text('性别'),
Radio(
value: 1,
onChanged: (value) {
setState(() {
this._sex = value;
});
},
groupValue: this._sex,
),
Text('男'),
Radio(
value: 2,
onChanged: (value) {
setState(() {
this._sex = value;
});
},
groupValue: this._sex,
),
Text('女'),
],
),
// 组合选择项1
RadioListTile(
value: 1,
groupValue: this._status,
onChanged: (value) {
setState(() {
this._status = value;
});
},
title: Text("标题"),
subtitle: Text("这是二级标题"),
secondary: Icon(Icons.help),
selected: this._status == 1,
),
// 组合选择项2
RadioListTile(
value: 2,
groupValue: this._status,
onChanged: (value) {
setState(() {
this._status = value;
});
},
title: Text("标题"),
subtitle: Text("这是二级标题"),
secondary:
Image.network('https://www.itying.com/images/flutter/1.png'),
selected: this._status == 2,
),
Switch(
value: _switchSelected, //当前状态
onChanged: (newValue) {
//重新构建页面
setState(() {
_switchSelected = newValue;
});
},
),
SwitchListTile(
value: _switchSelected, //当前状态
title: Text("性别"),
subtitle: Text("请输入男或者女"),
secondary: Icon(Icons.person_add),
onChanged: (newValue) {
//重新构建页面
setState(() {
_switchSelected = newValue;
});
},
),
Checkbox(
value: _checkboxSelected,
activeColor: Colors.red, //选中时的颜色
onChanged: (newValue) {
setState(() {
_checkboxSelected = newValue;
});
},
),
CheckboxListTile(
value: _checkboxSelected,
activeColor: Colors.red, //选中时的颜色
title: Text("标题"),
subtitle: Text("这是副标题"),
secondary: Icon(Icons.help),
selected: this._checkboxSelected,
checkColor: Colors.blue,
onChanged: (newValue) {
setState(() {
_checkboxSelected = newValue;
});
},
),
],
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/fijkplayer.dart | import 'package:flutter/material.dart';
import '/pages/demo1.dart' show Demo1;
import '/pages/demo2.dart' show Demo2;
void main() {
// debugPaintSizeEnabled = true;
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'fijkplayer_skin demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Home(),
);
}
}
class Home extends StatelessWidget {
const Home({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView(
children: <Widget>[
MyButton(
text: "完整例子(剧集、播放速度)",
cb: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Demo1(),
),
);
},
),
MyButton(
text: "精简例子",
cb: () {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Demo2(),
),
);
},
),
],
),
);
}
}
class MyButton extends StatelessWidget {
Function cb;
String text;
MyButton({
Key key,
this.cb,
this.text,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(
left: 10,
right: 10,
),
child: ElevatedButton(
style: ButtonStyle(
elevation: MaterialStateProperty.all(0),
backgroundColor: MaterialStateProperty.all(Colors.blue),
),
onPressed: () => cb(),
child: Text(
text,
style: TextStyle(
color: Colors.white,
),
),
),
);
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/bottom_navigation_bar_3.dart | import 'package:flutter/material.dart';
import 'tool/config.dart';
import 'bottom_nav_pages/bottom_nav_pages_a.dart';
import 'bottom_nav_pages/bottom_nav_pages_b.dart';
import 'bottom_nav_pages/bottom_nav_pages_c.dart';
import 'bottom_nav_pages/bottom_nav_pages_d.dart';
void main() {
runApp(BottomNavBar());
}
class BottomNavBar extends StatefulWidget {
const BottomNavBar({Key key}) : super(key: key);
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _currentIndex = 0; //记录当前选择的是哪一个
String title = '首页';
@override
Widget build(BuildContext context) {
final List<Widget> _pages = [
HomePage(
title: this.title,
),
BusinessPage(
title: this.title,
),
MyLocationPage(
title: this.title,
),
PersonPage(
title: this.title,
)
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('底部导航'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {},
backgroundColor: Colors.white,
child: Icon(
Icons.camera,
color: Colors.blue,
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
body: _pages[_currentIndex], //展示组件
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: true,
type: BottomNavigationBarType.fixed,
fixedColor: Colors.redAccent,
// unselectedLabelStyle: TextStyle(color: Colors.orange),
unselectedItemColor: Colors.grey,
// selectedItemColor: Colors.orange,
currentIndex: this._currentIndex,
onTap: (int index) {
//点击事件
setState(() {
//修改状态,会自动刷新Widget
this._currentIndex = index;
this.title = bottomNavBarList[this._currentIndex]['title'];
});
},
items: bottomNavBarList
.map((e) => BottomNavigationBarItem(
icon: Icon(e['icon']), label: e['title']))
.toList()),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/future_2.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
print("initState:${DateTime.now()}");
_loadUserInfo();
print("initState:${DateTime.now()}");
super.initState();
}
@override
Widget build(BuildContext context) {
return Container();
}
Future _getUserInfo() async {
await Future.delayed(Duration(milliseconds: 3000));
return "我是用户";
}
Future _loadUserInfo() async {
print("_loadUserInfo:${DateTime.now()}");
_getUserInfo().then((info) {
print(info);
});
print("_loadUserInfo:${DateTime.now()}");
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/form.dart | import 'package:flutter/material.dart';
import 'tool/shared_preferences_utils.dart';
import 'pages/index_page.dart';
void main() => runApp(LoginPage());
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
GlobalKey<FormState> _loginKey = GlobalKey<FormState>();
String _userName = "";
String _password = "";
void _login(BuildContext context) {
var _loginForm = _loginKey.currentState;
if (_loginForm.validate()) {
_loginForm.save();
// SharedPreferencesUtils.clear();
SharedPreferencesUtils.savePreference('username', _userName);
SharedPreferencesUtils.savePreference('password', _password);
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => IndexPage(),
));
}
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Builder(
builder: (context) {
return Scaffold(
body: Center(
child: Column(
children: <Widget>[
Container(
padding: const EdgeInsets.all(10.0),
child: Form(
key: _loginKey,
child: Column(
children: <Widget>[
TextFormField(
decoration: InputDecoration(
labelText: '请输入用户名',
),
onSaved: (value) {
_userName = value;
},
validator: (value) {
return value.trim().length < 6
? '用户名长度不够6位'
: null;
},
),
TextFormField(
decoration: InputDecoration(
labelText: '请输入密码',
),
obscureText: true,
onSaved: (value) {
_password = value;
},
validator: (value) {
return value.trim().length < 6
? '密码长度不够6位'
: null;
},
),
Container(
margin: const EdgeInsets.only(top: 20.0),
width: 400.0,
height: 40.0,
child: ElevatedButton(
onPressed: () {
_login(context);
},
child: Text('登录'),
),
),
],
)),
)
],
),
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/tab_bar.dart | import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: "TabBarWidget",
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin{
TabController _tabController;
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this,length: 6);
this._tabController.addListener(() {
print(this._tabController.toString());
print(this._tabController.index);
print(this._tabController.length);
print(this._tabController.previousIndex);
});
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("顶部Tab切换"),
bottom: TabBar(
tabs: <Widget>[
Tab(text: "热门",icon: Icon(Icons.directions_car)),
Tab(text: "推荐"),
Tab(text: "关注"),
Tab(text: "收藏"),
Tab(text: "新增"),
Tab(text: "点赞"),
],
controller: _tabController, // 记得要带上tabController
),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
Center(
child: Text("这是热门的内容")
),
Center(
child: Text("这是推荐的内容")
),
Center(
child: Text("这是关注的内容")
),
Center(
child: Text("这是收藏的内容")
),
Center(
child: Text("这是新增的内容")
),
Center(
child: Text("这是点赞的内容")
)
],
),
);
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/context_2.dart | import 'package:flutter/material.dart';
void main() => runApp(MyHomePage());
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
// class _MyHomePageState extends State<MyHomePage> {
// @override
// Widget build(BuildContext context) {
// return MaterialApp(
// home: Scaffold(
// appBar: AppBar(title: Text('context')),
// drawer: Drawer(),
// floatingActionButton: FloatingActionButton(onPressed: () {
// Scaffold.of(context).openDrawer();
// }),
// ),
// );
// }
// }
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('context')),
drawer: Drawer(),
floatingActionButton: Builder(
builder: (ctx) {
return FloatingActionButton(onPressed: () {
Scaffold.of(ctx).openDrawer();
});
},
)),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/theme_2.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '/tool/app_theme.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
const appName = 'Custom Themes';
return MaterialApp(
title: appName,
theme: AppTheme.lightTheme,
darkTheme: AppTheme.darkTheme,
home: const MyHomePage(
title: appName,
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
title,
style: Theme.of(context).textTheme.headline1,
),
),
body: Center(
child: Container(
color: Theme.of(context).colorScheme.secondary,
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.bodyText2,
),
),
),
floatingActionButton: Theme(
data: Theme.of(context).copyWith(splashColor: Colors.yellow),
child: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/main_login.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
//根组件
return MaterialApp(
title: "myapp",
//调试
// /showSemanticsDebugger: true,
home: Scaffold(
appBar: AppBar(
title: Text('登录页'),
),
//键盘悬浮于界面之上
resizeToAvoidBottomInset: false,
body: HomePage(),
),
theme: ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
double _left = 0.0;
double _top = 0.0;
double _width = 0.0;
double _height = 0.0;
GlobalKey _key = GlobalKey();
TapGestureRecognizer _tapGestureRecognizer;
@override
void initState() {
super.initState();
_tapGestureRecognizer = TapGestureRecognizer();
_tapGestureRecognizer.onTap = myTap;
}
void myTap() {
print('11');
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
Container(
color: Colors.white
),
Container(
// height: 300,
padding: EdgeInsets.only(top: 60, left: 16, right: 16),
margin: EdgeInsets.only(top: 120, left: 16, right: 16),
decoration: BoxDecoration(
color: Colors.white, borderRadius: BorderRadius.circular(10)),
child: Column(
children: <Widget>[
SizedBox(
height: 40,
),
TextField(
keyboardType: TextInputType.phone,
maxLines: 1,
maxLength: 30,
decoration: InputDecoration(
prefixIcon: Icon(Icons.phone_iphone),
hintText: "请输入手机号",
contentPadding:
EdgeInsets.symmetric(horizontal: 10, vertical: 10)),
),
TextField(
keyboardType: TextInputType.phone,
maxLines: 1,
maxLength: 30,
obscureText: true,
decoration: InputDecoration(
prefixIcon: Icon(Icons.lock_outline),
suffixIcon: Icon(Icons.remove_red_eye),
hintText: "请输密码",
contentPadding:
EdgeInsets.symmetric(horizontal: 10, vertical: 10)),
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[Text('忘记密码?')],
),
SizedBox(
height: 10,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CupertinoButton(
child: Text('登 录'),
onPressed: () {},
color: Colors.blue,
)
],
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('验证码登录'),
Container(
height: 12,
padding: EdgeInsets.symmetric(horizontal: 10),
child: VerticalDivider(
width: 2.0,
color: Colors.blue,
),
),
InkWell(
onTap: () {},
child: Text('新用户主注册'),
)
],
),
),
SizedBox(
height: 20,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Checkbox(
value: true,
onChanged: (v) {},
),
Text.rich(TextSpan(
text: '我已经阅读并同意遵守',
style: TextStyle(color: Colors.grey[400]),
children: [
TextSpan(
recognizer: _tapGestureRecognizer,
text: '《服务许可协议》',
style: TextStyle(
color: Colors.grey,
decoration: TextDecoration.underline))
]))
],
),
],
),
),
Container(
alignment: Alignment.center,
margin: EdgeInsets.only(top: 50),
child: Column(
children: <Widget>[
Container(
width: 100,
height: 100,
child: Image.asset("assets/images/logo.jpg"),
),
SizedBox(
height: 10,
),
Text('登 录',style: TextStyle(
fontSize: 20
),)
],
),
)
],
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/notification_custom.dart | import 'package:flutter/material.dart';
void main() => runApp(NotificationDemo());
class NotificationDemo extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _NotificationDemoState();
}
}
class _NotificationDemoState extends State {
String _notificationData = '';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'NotificationDemo',
home: new Scaffold(
appBar: AppBar(
title: Text('NotificationDemo'),
),
body: NotificationListener<MyNotification>(
onNotification: (notification) {
setState(() {
_notificationData = notification.notificationStr;
});
return true;
},
child: Column(
children: <Widget>[
Text(_notificationData),
Builder(
builder: (context) {
return Container(
width: double.infinity,
child: ElevatedButton(
child: Text('发送通知'),
onPressed: () {
MyNotification('notification_data')
.dispatch(context);
}),
);
},
)
],
),
)),
);
}
}
class MyNotification extends Notification{
String notificationStr;
MyNotification(this.notificationStr);
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/theme.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
const appName = 'Custom Themes';
final ThemeData theme = ThemeData();
return MaterialApp(
title: appName,
theme: ThemeData(
// 1.亮度: light-dark
brightness: Brightness.light,
// 2.primarySwatch: primaryColor/accentColor的结合体
primarySwatch: Colors.red,
// 3.主要颜色: 导航/底部TabBar
primaryColor: Colors.pink,
// 4.次要颜色: FloatingActionButton/按钮颜色
accentColor: Colors.orange,
// 5.卡片主题
cardTheme: CardTheme(
color: Colors.greenAccent,
elevation: 10,
shape: Border.all(width: 3, color: Colors.red),
margin: EdgeInsets.all(10)
),
// 6.按钮主题
buttonTheme: ButtonThemeData(
minWidth: 0,
height: 25
),
// 7.文本主题
textTheme: TextTheme(
headline1: TextStyle(fontSize: 30, color: Colors.blue),
bodyText1: TextStyle(fontSize: 10),
)
),
home: const MyHomePage(
title: appName,
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Container(
color: Theme.of(context).colorScheme.secondary,
child: Text(
'Text with a background color',
style: Theme.of(context).textTheme.bodyText2,
),
),
),
floatingActionButton: Theme(
data: Theme.of(context).copyWith(splashColor: Colors.yellow),
child: FloatingActionButton(
onPressed: () {},
child: const Icon(Icons.add),
),
),
);
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/dynamic_route.dart | import 'package:flutter/material.dart';
import '/pages/students.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
const appName = '动态路由';
return MaterialApp(
title: appName,
home: const MyHomePage(
title: appName,
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Container(
color: Theme.of(context).colorScheme.primary,
child: Text(
'动态路由',
style: Theme.of(context).textTheme.headline6,
),
),
),
floatingActionButton: Theme(
data: Theme.of(context).copyWith(splashColor: Colors.yellow),
child: FloatingActionButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(
builder: (context) => Students(name: "jjj"),
))
.then((value) => print(value));
},
child: const Icon(Icons.add),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/tab_bar_2.dart | import 'package:flutter/material.dart';
import '/tabs/tabs_his.dart';
import '/tabs/tabs_pic.dart';
import '/tabs/tabs_news.dart';
void main() {
runApp(MaterialApp(
title: "TabBarWidget",
home: MyApp(),
));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with SingleTickerProviderStateMixin {
TabController _tabController;
List tabs = ["新闻", "历史", "图片"];
int index = 0;
@override
void initState() {
super.initState();
_tabController = TabController(vsync: this, length: tabs.length);
this._tabController.addListener(() {
index = this._tabController.index;
});
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("顶部Tab切换2"),
bottom: TabBar(
controller: _tabController,
tabs: tabs.map((e) => Tab(text: e)).toList()),
),
body: TabBarView(
controller: _tabController,
children: <Widget>[
TabsNews(index: this.index,title: tabs[this.index],),
TabsHis(index: this.index,title: tabs[this.index],),
TabsPic(index: this.index,title: tabs[this.index],),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/awesome_dialog.dart | import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Fancy Dialog Example',
theme: ThemeData.dark(),
home: HomePage(),
//onGenerateRoute: RouteGenerator.generateRoute,
);
}
}
class HomePage extends StatefulWidget {
const HomePage({
Key key,
}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Awesome Dialog Example'),
),
body: Center(
child: Container(
padding: EdgeInsets.all(16),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
AnimatedButton(
text: 'Info Dialog fixed width and sqare buttons',
pressEvent: () {
AwesomeDialog(
context: context,
dialogType: DialogType.INFO_REVERSED,
borderSide: BorderSide(color: Colors.green, width: 2),
width: 280,
buttonsBorderRadius: BorderRadius.all(Radius.circular(2)),
headerAnimationLoop: false,
animType: AnimType.BOTTOMSLIDE,
title: 'INFO',
desc: 'Dialog description here...',
showCloseIcon: true,
btnCancelOnPress: () {},
btnOkOnPress: () {},
)..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Question Dialog With Custom BTN Style',
pressEvent: () {
AwesomeDialog(
context: context,
dialogType: DialogType.QUESTION,
headerAnimationLoop: false,
animType: AnimType.BOTTOMSLIDE,
title: 'Question',
desc: 'Dialog description here...',
buttonsTextStyle: TextStyle(color: Colors.black),
showCloseIcon: true,
btnCancelOnPress: () {},
btnOkOnPress: () {},
)..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Info Dialog Without buttons',
pressEvent: () {
AwesomeDialog(
context: context,
headerAnimationLoop: true,
animType: AnimType.BOTTOMSLIDE,
title: 'INFO',
desc:
'Lorem ipsum dolor sit amet consectetur adipiscing elit eget ornare tempus, vestibulum sagittis rhoncus felis hendrerit lectus ultricies duis vel, id morbi cum ultrices tellus metus dis ut donec. Ut sagittis viverra venenatis eget euismod faucibus odio ligula phasellus,',
)..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Warning Dialog',
color: Colors.orange,
pressEvent: () {
AwesomeDialog(
context: context,
dialogType: DialogType.WARNING,
headerAnimationLoop: false,
animType: AnimType.TOPSLIDE,
showCloseIcon: true,
closeIcon: Icon(Icons.close_fullscreen_outlined),
title: 'Warning',
desc:
'Dialog description here..................................................',
btnCancelOnPress: () {},
onDissmissCallback: (type) {
debugPrint('Dialog Dissmiss from callback $type');
},
btnOkOnPress: () {})
..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Error Dialog',
color: Colors.red,
pressEvent: () {
AwesomeDialog(
context: context,
dialogType: DialogType.ERROR,
animType: AnimType.RIGHSLIDE,
headerAnimationLoop: true,
title: 'Error',
desc:
'Dialog description here..................................................',
btnOkOnPress: () {},
btnOkIcon: Icons.cancel,
btnOkColor: Colors.red)
..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Succes Dialog',
color: Colors.green,
pressEvent: () {
AwesomeDialog(
context: context,
animType: AnimType.LEFTSLIDE,
headerAnimationLoop: false,
dialogType: DialogType.SUCCES,
showCloseIcon: true,
title: 'Succes',
desc:
'Dialog description here..................................................',
btnOkOnPress: () {
debugPrint('OnClcik');
},
btnOkIcon: Icons.check_circle,
onDissmissCallback: (type) {
debugPrint('Dialog Dissmiss from callback $type');
})
..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'No Header Dialog',
color: Colors.cyan,
pressEvent: () {
AwesomeDialog(
context: context,
headerAnimationLoop: false,
dialogType: DialogType.NO_HEADER,
title: 'No Header',
desc:
'Dialog description here..................................................',
btnOkOnPress: () {
debugPrint('OnClcik');
},
btnOkIcon: Icons.check_circle,
)..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Custom Body Dialog',
color: Colors.blueGrey,
pressEvent: () {
AwesomeDialog(
context: context,
animType: AnimType.SCALE,
dialogType: DialogType.INFO,
body: Center(
child: Text(
'If the body is specified, then title and description will be ignored, this allows to further customize the dialogue.',
style: TextStyle(fontStyle: FontStyle.italic),
),
),
title: 'This is Ignored',
desc: 'This is also Ignored',
)..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Auto Hide Dialog',
color: Colors.purple,
pressEvent: () {
AwesomeDialog(
context: context,
dialogType: DialogType.INFO,
animType: AnimType.SCALE,
title: 'Auto Hide Dialog',
desc: 'AutoHide after 2 seconds',
autoHide: Duration(seconds: 2),
)..show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Testing Dialog',
color: Colors.orange,
pressEvent: () {
AwesomeDialog(
context: context,
keyboardAware: true,
dismissOnBackKeyPress: false,
dialogType: DialogType.WARNING,
animType: AnimType.BOTTOMSLIDE,
btnCancelText: "Cancel Order",
btnOkText: "Yes, I will pay",
title: 'Continue to pay?',
// padding: const EdgeInsets.all(5.0),
desc:
'Please confirm that you will pay 3000 INR within 30 mins. Creating orders without paying will create penalty charges, and your account may be disabled.',
btnCancelOnPress: () {},
btnOkOnPress: () {},
).show();
},
),
SizedBox(
height: 16,
),
AnimatedButton(
text: 'Body with Input',
color: Colors.blueGrey,
pressEvent: () {
AwesomeDialog dialog;
dialog = AwesomeDialog(
context: context,
animType: AnimType.SCALE,
dialogType: DialogType.INFO,
keyboardAware: true,
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
'Form Data',
style: Theme.of(context).textTheme.headline6,
),
SizedBox(
height: 10,
),
Material(
elevation: 0,
color: Colors.blueGrey.withAlpha(40),
child: TextFormField(
autofocus: true,
minLines: 1,
decoration: InputDecoration(
border: InputBorder.none,
labelText: 'Title',
prefixIcon: Icon(Icons.text_fields),
),
),
),
SizedBox(
height: 10,
),
Material(
elevation: 0,
color: Colors.blueGrey.withAlpha(40),
child: TextFormField(
autofocus: true,
keyboardType: TextInputType.multiline,
maxLengthEnforced: true,
minLines: 2,
maxLines: null,
decoration: InputDecoration(
border: InputBorder.none,
labelText: 'Description',
prefixIcon: Icon(Icons.text_fields),
),
),
),
SizedBox(
height: 10,
),
AnimatedButton(
isFixedHeight: false,
text: 'Close',
pressEvent: () {
dialog.dismiss();
})
],
),
),
)..show();
},
),
],
),
),
)));
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/swiper.dart | import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.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(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<Image> imgs = [
//建立了一个图片数组
Image.network(
"https://images.unsplash.com/photo-1477346611705-65d1883cee1e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
fit: BoxFit.cover,
),
Image.network(
"https://images.unsplash.com/photo-1498550744921-75f79806b8a7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80",
fit: BoxFit.cover,
),
Image.network(
"https://images.unsplash.com/photo-1451187580459-43490279c0fa?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
fit: BoxFit.cover,
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("图片轮播"),
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Text("样式1:"),
Container(
height: 175,
child: Swiper(
itemBuilder: (BuildContext context, int index) {
//条目构建函数传入了index,根据index索引到特定图片
return imgs[index];
},
itemCount: imgs.length,
autoplay: true,
pagination: new SwiperPagination(), //这些都是控件默认写好的,直接用
control: new SwiperControl(),
),
),
Text("样式2:"),
Container(
height: 175,
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return imgs[index];
},
itemCount: imgs.length,
autoplay: true,
pagination: new SwiperPagination(),
control: new SwiperControl(),
viewportFraction: 0.8,
scale: 0.9,
),
),
Text("样式3:"),
Container(
height: 175,
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return imgs[index];
},
itemCount: imgs.length,
autoplay: true,
pagination: new SwiperPagination(),
control: new SwiperControl(),
itemWidth: 300.0,
layout: SwiperLayout.STACK,
),
),
Text("样式4:"),
Container(
height: 175,
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return imgs[index];
},
itemCount: imgs.length,
autoplay: true,
pagination: new SwiperPagination(),
control: new SwiperControl(),
itemWidth: 300.0,
itemHeight: 400.0,
layout: SwiperLayout.TINDER,
),
),
Text("样式5:"),
Container(
height: 175,
child: Swiper(
itemBuilder: (BuildContext context, int index) {
return imgs[index];
},
itemCount: imgs.length,
autoplay: true,
pagination: new SwiperPagination(),
control: new SwiperControl(),
layout: SwiperLayout.CUSTOM,
customLayoutOption: new CustomLayoutOption(
startIndex: -1, stateCount: 3)
.addRotate([-45.0 / 180, 0.0, 45.0 / 180]).addTranslate([
new Offset(-370.0, -40.0),
new Offset(0.0, 0.0),
new Offset(370.0, -40.0)
]),
itemWidth: 300.0,
itemHeight: 200.0,
),
),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'splash_page.dart';
import 'splash_page_with_timer.dart';
import 'splash_page_with_animation.dart';
import 'widgets/date_picker.dart';
import 'widgets/webview_flutter.dart';
import 'widgets/webview_flutter_2.dart';
import 'widgets/webview_flutter_load_html.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
InAppLocalhostServer localhostServer = new InAppLocalhostServer();
void main() async {
await localhostServer.start();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = '';
String localUrl = 'assets/index.html';
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(statusBarColor: Colors.transparent));
return new MaterialApp(
title: title,
debugShowCheckedModeBanner: false,
home: WebViewPageLoadHTML(url:localUrl, isLocalUrl: true)
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/drawer.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '/widgets/j_drawer.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
const appName = 'drawer';
return MaterialApp(
title: appName,
home: const MyHomePage(
title: appName,
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({Key key, this.title}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Container(),
),
drawer: JDrawer());
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/future_internet_request.dart | import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
getData().then((result) {
print("接口返回的数据是:${result}");
}).whenComplete(() {
print("异步任务处理完成");
});
print("我是在请求数据后面的代码");
super.initState();
}
@override
Widget build(BuildContext context) {
return Container();
}
Future<Response> getData() async {
String url = "http://v.juhe.cn/toutiao/index";
String key = "4c52313fc9247e5b4176aed5ddd56ad7";
String type = "keji";
print("开始请求数据");
Response response =
await Dio().get(url, queryParameters: {"type": type, "key": key});
print("请求完成");
return response;
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/bottom_navigation_bar_2.dart | import 'package:flutter/material.dart';
import 'tool/config.dart';
import 'bottom_nav_pages/bottom_nav_pages_a.dart';
import 'bottom_nav_pages/bottom_nav_pages_b.dart';
import 'bottom_nav_pages/bottom_nav_pages_c.dart';
import 'bottom_nav_pages/bottom_nav_pages_d.dart';
void main() {
runApp(BottomNavBar());
}
class BottomNavBar extends StatefulWidget {
const BottomNavBar({Key key}) : super(key: key);
@override
_BottomNavBarState createState() => _BottomNavBarState();
}
class _BottomNavBarState extends State<BottomNavBar> {
int _currentIndex = 0; //记录当前选择的是哪一个
String title = '首页';
@override
Widget build(BuildContext context) {
final List<Widget> _pages = [
HomePage(
title: this.title,
),
BusinessPage(
title: this.title,
),
MyLocationPage(
title: this.title,
),
PersonPage(
title: this.title,
)
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('底部导航'),
),
body: _pages[_currentIndex], //展示组件
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: true,
type: BottomNavigationBarType.fixed,
fixedColor: Colors.redAccent,
// unselectedLabelStyle: TextStyle(color: Colors.orange),
unselectedItemColor: Colors.grey,
// selectedItemColor: Colors.orange,
currentIndex: this._currentIndex,
onTap: (int index) {
//点击事件
setState(() {
//修改状态,会自动刷新Widget
this._currentIndex = index;
this.title = bottomNavBarList[this._currentIndex]['title'];
});
},
items: bottomNavBarList
.map((e) => BottomNavigationBarItem(
icon: Icon(e['icon']), label: e['title']))
.toList()),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/shape.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',
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("shape"),
),
body: Column(
children: [
Card(
shape: BeveledRectangleBorder(
side: BorderSide(width: 1, color: Colors.red),
borderRadius: BorderRadius.circular(10)),
child: Image.network(
'https://ssyerv1.oss-cn-hangzhou.aliyuncs.com/picture/389e31d03d36465d8acd9939784df6f0.jpg!sswm',
fit: BoxFit.cover,),
),
Container(
width: 220,
height: 120,
decoration: ShapeDecoration(
image: DecorationImage(
image: NetworkImage('https://ssyerv1.oss-cn-hangzhou.aliyuncs.com/picture/389e31d03d36465d8acd9939784df6f0.jpg!sswm'),
fit: BoxFit.cover,
),
shape: CircleBorder(
side: BorderSide(
width: 2,
color: Colors.blue,
style: BorderStyle.solid,
),
),
),
),
Container(
width: 220,
height: 120,
decoration: ShapeDecoration(
image: DecorationImage(
image: NetworkImage('https://ssyerv1.oss-cn-hangzhou.aliyuncs.com/picture/389e31d03d36465d8acd9939784df6f0.jpg!sswm'),
fit: BoxFit.cover,
),
shape: StadiumBorder(
side: BorderSide(
width: 2,
color: Colors.blue,
style: BorderStyle.solid,
),
),
),
),
Container(
width: 220,
height: 120,
decoration: ShapeDecoration(
image: DecorationImage(
image: NetworkImage('https://ssyerv1.oss-cn-hangzhou.aliyuncs.com/picture/389e31d03d36465d8acd9939784df6f0.jpg!sswm'),
fit: BoxFit.cover,
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20),
side: BorderSide(
width: 2,
color: Colors.blue,
style: BorderStyle.solid,
),
),
),
),
],
));
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/context.dart | import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: TextButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SecondPage()));
},
child: Text('跳转')),
),
),
);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
);
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/splash_page.dart | import 'package:flutter/material.dart';
class SplashPage extends StatefulWidget {
SplashPage({Key key, this.title}) : super(key: key);
final String title;
@override
State<StatefulWidget> createState() {
return _SplashPageState();
}
}
class _SplashPageState extends State<SplashPage> {
@override
void initState() {
// TODO: do something to init
super.initState();
}
@override
Widget build(BuildContext context) {
return Builder(builder: (context) {
return Container(
child: Image(image: AssetImage('assets/images/splash.png'), fit: BoxFit.fill,),
);
});
}
} | 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/test.dart | import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (Platform.isAndroid) {
await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GlobalKey webViewKey = GlobalKey();
InAppWebViewController webViewController;
InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
mediaPlaybackRequiresUserGesture: false,
),
android: AndroidInAppWebViewOptions(
useHybridComposition: true,
),
ios: IOSInAppWebViewOptions(
allowsInlineMediaPlayback: true,
));
PullToRefreshController pullToRefreshController;
String url = "";
double progress = 0;
final urlController = TextEditingController();
@override
void initState() {
super.initState();
pullToRefreshController = PullToRefreshController(
options: PullToRefreshOptions(
color: Colors.blue,
),
onRefresh: () async {
if (Platform.isAndroid) {
webViewController?.reload();
} else if (Platform.isIOS) {
webViewController?.loadUrl(
urlRequest: URLRequest(url: await webViewController?.getUrl()));
}
},
);
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text("Official InAppWebView website")),
body: SafeArea(
child: Column(children: <Widget>[
TextField(
decoration: InputDecoration(
prefixIcon: Icon(Icons.search)
),
controller: urlController,
keyboardType: TextInputType.url,
onSubmitted: (value) {
var url = Uri.parse(value);
if (url.scheme.isEmpty) {
url = Uri.parse("https://www.google.com/search?q=" + value);
}
webViewController?.loadUrl(
urlRequest: URLRequest(url: url));
},
),
Expanded(
child: Stack(
children: [
InAppWebView(
key: webViewKey,
initialUrlRequest:
URLRequest(url: Uri.parse("https://inappwebview.dev/")),
initialOptions: options,
pullToRefreshController: pullToRefreshController,
onWebViewCreated: (controller) {
webViewController = controller;
},
onLoadStart: (controller, url) {
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
androidOnPermissionRequest: (controller, origin, resources) async {
return PermissionRequestResponse(
resources: resources,
action: PermissionRequestResponseAction.GRANT);
},
shouldOverrideUrlLoading: (controller, navigationAction) async {
var uri = navigationAction.request.url;
if (![ "http", "https", "file", "chrome",
"data", "javascript", "about"].contains(uri.scheme)) {
if (await canLaunch(url)) {
// Launch the App
await launch(
url,
);
// and cancel the request
return NavigationActionPolicy.CANCEL;
}
}
return NavigationActionPolicy.ALLOW;
},
onLoadStop: (controller, url) async {
pullToRefreshController.endRefreshing();
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
onLoadError: (controller, url, code, message) {
pullToRefreshController.endRefreshing();
},
onProgressChanged: (controller, progress) {
if (progress == 100) {
pullToRefreshController.endRefreshing();
}
setState(() {
this.progress = progress / 100;
urlController.text = this.url;
});
},
onUpdateVisitedHistory: (controller, url, androidIsReload) {
setState(() {
this.url = url.toString();
urlController.text = this.url;
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
},
),
progress < 1.0
? LinearProgressIndicator(value: progress)
: Container(),
],
),
),
ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
child: Icon(Icons.arrow_back),
onPressed: () {
webViewController?.goBack();
},
),
ElevatedButton(
child: Icon(Icons.arrow_forward),
onPressed: () {
webViewController?.goForward();
},
),
ElevatedButton(
child: Icon(Icons.refresh),
onPressed: () {
webViewController?.reload();
},
),
],
),
]))),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/app_bar.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'tool/tools.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
final SystemUiOverlayStyle _style =
SystemUiOverlayStyle(statusBarColor: Colors.transparent);
@override
Widget build(BuildContext context) {
final title = 'app bar';
SystemChrome.setSystemUIOverlayStyle(_style);
return MaterialApp(
title: title,
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text(title),
actions: [
IconButton(
icon: Icon(Icons.favorite),
onPressed: () {
showWarnToast("提示");
}),
PopupMenuButton<String>(
padding: EdgeInsets.all(0),
itemBuilder: (context) => [
PopupMenuItem<String>(
child: Row(
children: [
Icon(
Icons.mail,
color: Colors.black,
),
Text(
'邮件邮件邮件',
style: TextStyle(
fontSize: 18, backgroundColor: Colors.red),
)
],
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
),
value: 'mail',
),
PopupMenuItem<String>(
child: Row(
children: [
Icon(Icons.search, color: Colors.black),
Text(
'搜索',
style: TextStyle(
fontSize: 18, backgroundColor: Colors.red),
)
],
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
),
value: 'search',
),
],
onSelected: (value) {
switch (value) {
case 'mail':
showWarnToast(value);
break;
case 'search':
showWarnToast(value);
break;
}
},
),
],
),
body: Stack(
children: <Widget>[
new Center(),
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/lib/sliver_app_bar.dart | import 'package:flutter/material.dart';
void main() {
runApp(MyHomePage());
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key key}) : super(key: key);
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ScrollController _scrollController;
VoidCallback onChange;
@override
void initState() {
super.initState();
_scrollController = ScrollController();
onChange = () {
print('onChange');
};
_scrollController.addListener(onChange);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: new CustomScrollView(
//滚动方向
scrollDirection: Axis.vertical,
//是否反转滚动方向
reverse: false,
//监听事件等等控制器
controller: _scrollController,
//true 的话 controller 一定要为null
primary: false,
//滑动效果,如阻尼效果等等
physics: const BouncingScrollPhysics(),
//滑动控件是否在头部上面滑过去
shrinkWrap: false,
//0到1之间,到顶部的距离
anchor: 0.0,
//“预加载”的区域,0.0 为关闭预加载
cacheExtent: 0.0,
slivers: <Widget>[
SliverAppBar(
elevation: 5,
forceElevated: true,
expandedHeight: 250.0,
//stretch: true,
floating: true,
snap: true,
pinned: false,
flexibleSpace: FlexibleSpaceBar(
title: const Text('SliverAppBar'),
background: Image.network(
'https://cn.bing.com/th?id=OIP.xq1C2fmnSw5DEoRMC86vJwD6D6&pid=Api&rs=1',
fit: BoxFit.fill,
),
//标题是否居中
centerTitle: true,
//标题间距
titlePadding: EdgeInsetsDirectional.only(start: 0, bottom: 16),
collapseMode: CollapseMode.none,
),
),
SliverFixedExtentList(
itemExtent: 80.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return Card(
child: Container(
alignment: Alignment.center,
color: Colors.primaries[(index % 18)],
child: Text(''),
),
);
},
),
),
],
semanticChildCount: 6, //可见子元素的总数
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/bottom_nav_pages/bottom_nav_pages_c.dart | import 'package:flutter/material.dart';
class MyLocationPage extends StatelessWidget {
String title;
MyLocationPage({Key key, this.title,}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
alignment: Alignment.center,
color: Colors.greenAccent,
child: Text(
this.title,
style: TextStyle(color: Colors.black, fontSize: 40.0),
),
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/bottom_nav_pages/bottom_nav_pages_b.dart | import 'package:flutter/material.dart';
class BusinessPage extends StatelessWidget {
String title;
BusinessPage({Key key, this.title,}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
alignment: Alignment.center,
color: Colors.blueAccent,
child: Text(
this.title,
style: TextStyle(color: Colors.black, fontSize: 40.0),
),
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/bottom_nav_pages/bottom_nav_pages_a.dart | import 'package:flutter/material.dart';
import '../tool/shared_preferences_utils.dart';
class HomePage extends StatefulWidget {
String title;
HomePage({
Key key,
this.title,
}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String username;
String password;
@override
Widget build(BuildContext context) {
getUername();
getPassword();
return Container(
alignment: Alignment.center,
// color: Colors.redAccent,
child: Column(
children: [
Text(
this.username != null ? "用户名:${this.username}" : "",
style: TextStyle(color: Colors.black, fontSize: 40.0),
),
Text(
this.password != null ? "密 码:${this.password}" : "",
style: TextStyle(color: Colors.black, fontSize: 40.0),
),
],
),
);
}
getUername() {
SharedPreferencesUtils.get("username").then((value) {
setState(() {
this.username = value;
});
});
}
getPassword() {
SharedPreferencesUtils.get("password").then((value) {
setState(() {
this.password = value;
});
});
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/bottom_nav_pages/bottom_nav_pages_d.dart | import 'package:flutter/material.dart';
class PersonPage extends StatelessWidget {
String title;
PersonPage({Key key, this.title,}) : super(key: key);
@override
Widget build(BuildContext context) {
// TODO: implement build
return Container(
alignment: Alignment.center,
color: Colors.black38,
child: Text(
this.title,
style: TextStyle(color: Colors.black, fontSize: 40.0),
),
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/date_picker.dart | import 'package:flutter/material.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class DatePickerPubDemo extends StatefulWidget {
DatePickerPubDemo({Key key}) : super(key: key);
_DatePickerPubDemoState createState() => _DatePickerPubDemoState();
}
class _DatePickerPubDemoState extends State<DatePickerPubDemo> {
DateTime _dateTime = DateTime.now();
void _showDatePicker() {
DatePicker.showDatePicker(
context,
showTitleActions: true,
minTime: DateTime(2018, 3, 5),
maxTime: DateTime(2028, 6, 7),
onChanged: (date) {
//print('change $date');
},
onConfirm: (date) {
//print('confirm $date');
setState(() {
this._dateTime = date;
});
},
currentTime: DateTime.now(),
locale: LocaleType.zh,
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("日期选择"),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
child: Row(
children: <Widget>[
Text(
"${formatDate(_dateTime, [yyyy, '-', mm, '-', dd])}"),
Icon(Icons.arrow_drop_down)
],
),
onTap: _showDatePicker),
],
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/j_snack_bar.dart | import 'package:flutter/material.dart';
class JSnackBar extends StatelessWidget {
final BuildContext context;
const JSnackBar({Key key,this.context}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/webview_flutter_load_html.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewPageLoadHTML extends StatefulWidget {
String url;
String title;
final bool isLocalUrl;
WebViewController _webViewController;
WebViewPageLoadHTML({this.url, this.isLocalUrl = false,this.title=''});
@override
_WebViewPageLoadHTML createState() => _WebViewPageLoadHTML();
}
class _WebViewPageLoadHTML extends State<WebViewPageLoadHTML> {
JavascriptChannel jsBridge(BuildContext context) => JavascriptChannel(
name: 'jsbridge', // 与h5 端的一致 不然收不到消息
onMessageReceived: (JavascriptMessage message) async {
debugPrint(message.message);
});
@override
Widget build(BuildContext context) {
return Scaffold(appBar: _buildAppbar(), body: _buildBody());
}
_buildAppbar() {
return AppBar(
elevation: 0,
backgroundColor: Color(0xccd0d7),
title: Text(
widget.title,
style: TextStyle(color: Colors.black),
),
centerTitle: true,
leading: IconButton(
icon: Icon(
Icons.arrow_back,
color: Color(0xFF23ADE5),
),
onPressed: () {}));
}
_buildBody() {
return Column(
children: <Widget>[
SizedBox(
height: 1,
width: double.infinity,
child: const DecoratedBox(
decoration: BoxDecoration(color: Color(0xFFEEEEEE))),
),
Expanded(
flex: 1,
child: WebView(
initialUrl: widget.isLocalUrl
? Uri.dataFromString(widget.url,
mimeType: 'text/html',
encoding: Encoding.getByName('utf-8'))
.toString()
: widget.url,
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: <JavascriptChannel>[jsBridge(context)].toSet(),
onWebViewCreated: (WebViewController controller) {
widget._webViewController = controller;
if (widget.isLocalUrl) {
_loadHtmlAssets(controller);
} else {
controller.loadUrl(widget.url);
}
controller
.canGoBack()
.then((value) => debugPrint(value.toString()));
controller
.canGoForward()
.then((value) => debugPrint(value.toString()));
controller.currentUrl().then((value) => debugPrint(value));
},
onPageFinished: (url) {
widget._webViewController
.runJavascriptReturningResult("document.title")
.then((result) {
setState(() {
widget.title = result;
});
});
},
),
)
],
);
}
//加载本地文件
_loadHtmlAssets(WebViewController controller) async {
String htmlPath = await rootBundle.loadString(widget.url);
controller.loadUrl(Uri.dataFromString(htmlPath,
mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
.toString());
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/webview_flutter_2.dart | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() => runApp(MaterialApp(home: WebViewExample()));
const String kNavigationExamplePage = '''
<!DOCTYPE html><html>
<head><title>Navigation Delegate Example</title></head>
<body>
<p>
The navigation delegate is set to block navigation to the youtube website.
</p>
<ul>
<ul><a href="https://www.youtube.com/">https://www.youtube.com/</a></ul>
<ul><a href="https://www.google.cn/">https://www.google.cn/</a></ul>
</ul>
</body>
</html>
''';
class WebViewExample extends StatefulWidget {
@override
_WebViewExampleState createState() => _WebViewExampleState();
}
class _WebViewExampleState extends State<WebViewExample> {
final Completer<WebViewController> _controller =
Completer<WebViewController>();
@override
void initState() {
super.initState();
if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
NavigationControls(_controller.future),
SampleMenu(_controller.future),
],
),
// We're using a Builder here so we have a context that is below the Scaffold
// to allow calling Scaffold.of(context) so we can show a snackbar.
body: Builder(builder: (BuildContext context) {
return WebView(
initialUrl: 'https://flutter.cn',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {
_controller.complete(webViewController);
},
onProgress: (int progress) {
print("WebView is loading (progress : $progress%)");
},
javascriptChannels: <JavascriptChannel>{
_toasterJavascriptChannel(context),
},
navigationDelegate: (NavigationRequest request) {
if (request.url.startsWith('https://www.youtube.com/')) {
print('blocking navigation to $request}');
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
onPageStarted: (String url) {
print('Page started loading: $url');
},
onPageFinished: (String url) {
print('Page finished loading: $url');
},
gestureNavigationEnabled: true,
);
}),
floatingActionButton: favoriteButton(),
);
}
JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
return JavascriptChannel(
name: 'Toaster',
onMessageReceived: (JavascriptMessage message) {
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(
SnackBar(content: Text(message.message)),
);
});
}
Widget favoriteButton() {
return FutureBuilder<WebViewController>(
future: _controller.future,
builder: (BuildContext context,
AsyncSnapshot<WebViewController> controller) {
if (controller.hasData) {
return FloatingActionButton(
onPressed: () async {
final String url = (await controller.data.currentUrl());
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Favorited $url')),
);
},
child: const Icon(Icons.favorite),
);
}
return Container();
});
}
}
enum MenuOptions {
showUserAgent,
listCookies,
clearCookies,
addToCache,
listCache,
clearCache,
navigationDelegate,
}
class SampleMenu extends StatelessWidget {
SampleMenu(this.controller);
final Future<WebViewController> controller;
final CookieManager cookieManager = CookieManager();
@override
Widget build(BuildContext context) {
return FutureBuilder<WebViewController>(
future: controller,
builder:
(BuildContext context, AsyncSnapshot<WebViewController> controller) {
return PopupMenuButton<MenuOptions>(
onSelected: (MenuOptions value) {
switch (value) {
case MenuOptions.showUserAgent:
_onShowUserAgent(controller.data, context);
break;
case MenuOptions.listCookies:
_onListCookies(controller.data, context);
break;
case MenuOptions.clearCookies:
_onClearCookies(context);
break;
case MenuOptions.addToCache:
_onAddToCache(controller.data, context);
break;
case MenuOptions.listCache:
_onListCache(controller.data, context);
break;
case MenuOptions.clearCache:
_onClearCache(controller.data, context);
break;
case MenuOptions.navigationDelegate:
_onNavigationDelegateExample(controller.data, context);
break;
}
},
itemBuilder: (BuildContext context) => <PopupMenuItem<MenuOptions>>[
PopupMenuItem<MenuOptions>(
value: MenuOptions.showUserAgent,
child: const Text('Show user agent'),
enabled: controller.hasData,
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCookies,
child: Text('List cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCookies,
child: Text('Clear cookies'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.addToCache,
child: Text('Add to cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.listCache,
child: Text('List cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.clearCache,
child: Text('Clear cache'),
),
const PopupMenuItem<MenuOptions>(
value: MenuOptions.navigationDelegate,
child: Text('Navigation Delegate example'),
),
],
);
},
);
}
void _onShowUserAgent(
WebViewController controller, BuildContext context) async {
// Send a message with the user agent string to the Toaster JavaScript channel we registered
// with the WebView.
await controller.runJavascript(
'Toaster.postMessage("User Agent: " + navigator.userAgent);');
}
void _onListCookies(
WebViewController controller, BuildContext context) async {
final String cookies =
await controller.runJavascriptReturningResult('document.cookie');
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(SnackBar(
content: Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const Text('Cookies:'),
_getCookieList(cookies),
],
),
));
}
void _onAddToCache(WebViewController controller, BuildContext context) async {
await controller.runJavascript(
'caches.open("test_caches_entry"); localStorage["test_localStorage"] = "dummy_entry";');
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(const SnackBar(
content: Text('Added a test entry to cache.'),
));
}
void _onListCache(WebViewController controller, BuildContext context) async {
await controller.runJavascript('caches.keys()'
'.then((cacheKeys) => JSON.stringify({"cacheKeys" : cacheKeys, "localStorage" : localStorage}))'
'.then((caches) => Toaster.postMessage(caches))');
}
void _onClearCache(WebViewController controller, BuildContext context) async {
await controller.clearCache();
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(const SnackBar(
content: Text("Cache cleared."),
));
}
void _onClearCookies(BuildContext context) async {
final bool hadCookies = await cookieManager.clearCookies();
String message = 'There were cookies. Now, they are gone!';
if (!hadCookies) {
message = 'There are no cookies.';
}
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(message),
));
}
void _onNavigationDelegateExample(
WebViewController controller, BuildContext context) async {
final String contentBase64 =
base64Encode(const Utf8Encoder().convert(kNavigationExamplePage));
await controller.loadUrl('data:text/html;base64,$contentBase64');
}
Widget _getCookieList(String cookies) {
if (cookies == null || cookies == '""') {
return Container();
}
final List<String> cookieList = cookies.split(';');
final Iterable<Text> cookieWidgets =
cookieList.map((String cookie) => Text(cookie));
return Column(
mainAxisAlignment: MainAxisAlignment.end,
mainAxisSize: MainAxisSize.min,
children: cookieWidgets.toList(),
);
}
}
class NavigationControls extends StatelessWidget {
const NavigationControls(this._webViewControllerFuture)
: assert(_webViewControllerFuture != null);
final Future<WebViewController> _webViewControllerFuture;
@override
Widget build(BuildContext context) {
return FutureBuilder<WebViewController>(
future: _webViewControllerFuture,
builder:
(BuildContext context, AsyncSnapshot<WebViewController> snapshot) {
final bool webViewReady =
snapshot.connectionState == ConnectionState.done;
final WebViewController controller = snapshot.data;
return Row(
children: <Widget>[
IconButton(
icon: const Icon(Icons.arrow_back_ios),
onPressed: !webViewReady
? null
: () async {
if (await controller.canGoBack()) {
await controller.goBack();
} else {
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(
const SnackBar(content: Text("No back history item")),
);
return;
}
},
),
IconButton(
icon: const Icon(Icons.arrow_forward_ios),
onPressed: !webViewReady
? null
: () async {
if (await controller.canGoForward()) {
await controller.goForward();
} else {
// ignore: deprecated_member_use
Scaffold.of(context).showSnackBar(
const SnackBar(
content: Text("No forward history item")),
);
return;
}
},
),
IconButton(
icon: const Icon(Icons.replay),
onPressed: !webViewReady
? null
: () {
controller.reload();
},
),
],
);
},
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/flutter_inapp_webview.dart | import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
InAppLocalhostServer localhostServer = new InAppLocalhostServer();
void main() async {
await localhostServer.start();
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(
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> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: InAppWebView(
initialUrlRequest:
URLRequest(url: Uri.parse("http://localhost:8080/assets/index.html")),
),
);
}
@override
void dispose() {
localhostServer.close();
super.dispose();
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/player_widget.dart | import 'dart:async';
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers/notifications.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class PlayerWidget extends StatefulWidget {
final String url;
final PlayerMode mode;
const PlayerWidget({
Key key,
this.url,
this.mode = PlayerMode.MEDIA_PLAYER,
}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _PlayerWidgetState(url, mode);
}
}
class _PlayerWidgetState extends State<PlayerWidget> {
String url;
PlayerMode mode;
AudioPlayer _audioPlayer;
PlayerState _audioPlayerState;
Duration _duration;
Duration _position;
PlayerState _playerState = PlayerState.STOPPED;
PlayingRoute _playingRouteState = PlayingRoute.SPEAKERS;
StreamSubscription _durationSubscription;
StreamSubscription _positionSubscription;
StreamSubscription _playerCompleteSubscription;
StreamSubscription _playerErrorSubscription;
StreamSubscription _playerStateSubscription;
StreamSubscription<PlayerControlCommand> _playerControlCommandSubscription;
bool get _isPlaying => _playerState == PlayerState.PLAYING;
bool get _isPaused => _playerState == PlayerState.PAUSED;
String get _durationText => _duration?.toString().split('.').first ?? '';
String get _positionText => _position?.toString().split('.').first ?? '';
bool get _isPlayingThroughEarpiece =>
_playingRouteState == PlayingRoute.EARPIECE;
_PlayerWidgetState(this.url, this.mode);
@override
void initState() {
super.initState();
_initAudioPlayer();
}
@override
void dispose() {
_audioPlayer.dispose();
_durationSubscription?.cancel();
_positionSubscription?.cancel();
_playerCompleteSubscription?.cancel();
_playerErrorSubscription?.cancel();
_playerStateSubscription?.cancel();
_playerControlCommandSubscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
key: const Key('play_button'),
onPressed: _isPlaying ? null : _play,
iconSize: 64.0,
icon: const Icon(Icons.play_arrow),
color: Colors.cyan,
),
IconButton(
key: const Key('pause_button'),
onPressed: _isPlaying ? _pause : null,
iconSize: 64.0,
icon: const Icon(Icons.pause),
color: Colors.cyan,
),
IconButton(
key: const Key('stop_button'),
onPressed: _isPlaying || _isPaused ? _stop : null,
iconSize: 64.0,
icon: const Icon(Icons.stop),
color: Colors.cyan,
),
IconButton(
onPressed: _earpieceOrSpeakersToggle,
iconSize: 64.0,
icon: _isPlayingThroughEarpiece
? const Icon(Icons.volume_up)
: const Icon(Icons.hearing),
color: Colors.cyan,
),
],
),
Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(12.0),
child: Stack(
children: [
Slider(
onChanged: (v) {
final duration = _duration;
if (duration == null) {
return;
}
final Position = v * duration.inMilliseconds;
_audioPlayer
.seek(Duration(milliseconds: Position.round()));
},
value: (_position != null &&
_duration != null &&
_position.inMilliseconds > 0 &&
_position.inMilliseconds <
_duration.inMilliseconds)
? _position.inMilliseconds / _duration.inMilliseconds
: 0.0,
),
],
),
),
Text(
_position != null
? '$_positionText / $_durationText'
: _duration != null
? _durationText
: '',
style: const TextStyle(fontSize: 24.0),
),
],
),
Text('State: $_audioPlayerState'),
],
);
}
void _initAudioPlayer() {
_audioPlayer = AudioPlayer(mode: mode);
_durationSubscription = _audioPlayer.onDurationChanged.listen((duration) {
setState(() => _duration = duration);
if (Theme.of(context).platform == TargetPlatform.iOS) {
// optional: listen for notification updates in the background
_audioPlayer.notificationService.startHeadlessService();
// set at least title to see the notification bar on ios.
_audioPlayer.notificationService.setNotification(
title: 'App Name',
artist: 'Artist or blank',
albumTitle: 'Name or blank',
imageUrl: 'Image URL or blank',
forwardSkipInterval: const Duration(seconds: 30), // default is 30s
backwardSkipInterval: const Duration(seconds: 30), // default is 30s
duration: duration,
enableNextTrackButton: true,
enablePreviousTrackButton: true,
);
}
});
_positionSubscription =
_audioPlayer.onAudioPositionChanged.listen((p) => setState(() {
_position = p;
}));
_playerCompleteSubscription =
_audioPlayer.onPlayerCompletion.listen((event) {
_onComplete();
setState(() {
_position = _duration;
});
});
_playerErrorSubscription = _audioPlayer.onPlayerError.listen((msg) {
print('audioPlayer error : $msg');
setState(() {
_playerState = PlayerState.STOPPED;
_duration = const Duration();
_position = const Duration();
});
});
_playerControlCommandSubscription =
_audioPlayer.notificationService.onPlayerCommand.listen((command) {
print('command: $command');
});
_audioPlayer.onPlayerStateChanged.listen((state) {
if (mounted) {
setState(() {
_audioPlayerState = state;
});
}
});
_audioPlayer.onNotificationPlayerStateChanged.listen((state) {
if (mounted) {
setState(() => _audioPlayerState = state);
}
});
_playingRouteState = PlayingRoute.SPEAKERS;
}
Future<int> _play() async {
final playPosition = (_position != null &&
_duration != null &&
_position.inMilliseconds > 0 &&
_position.inMilliseconds < _duration.inMilliseconds)
? _position
: null;
final result = await _audioPlayer.play(url, position: playPosition);
if (result == 1) {
setState(() => _playerState = PlayerState.PLAYING);
}
return result;
}
Future<int> _pause() async {
final result = await _audioPlayer.pause();
if (result == 1) {
setState(() => _playerState = PlayerState.PAUSED);
}
return result;
}
Future<int> _earpieceOrSpeakersToggle() async {
final result = await _audioPlayer.earpieceOrSpeakersToggle();
if (result == 1) {
setState(() => _playingRouteState = _playingRouteState.toggle());
}
return result;
}
Future<int> _stop() async {
final result = await _audioPlayer.stop();
if (result == 1) {
setState(() {
_playerState = PlayerState.STOPPED;
_position = const Duration();
});
}
return result;
}
void _onComplete() {
setState(() => _playerState = PlayerState.STOPPED);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/event_bus.dart | import 'package:event_bus/event_bus.dart';
/// 创建EventBus
EventBus eventBus = EventBus();
class UserLoggedInEvent {
String text;
UserLoggedInEvent(this.text);
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/webview_flutter.dart | import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewPage extends StatefulWidget {
@override
_WebViewPageState createState() => _WebViewPageState();
}
class _WebViewPageState extends State<WebViewPage> {
WebViewController _controller;
String _title = "webview";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("$_title"),
),
body: SafeArea(
child: WebView(
initialUrl: "https://flutterchina.club/",
//JS执行模式 是否允许JS执行
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (controller) {
_controller = controller;
},
onPageFinished: (url) {
_controller
.runJavascriptReturningResult("document.title")
.then((result) {
setState(() {
_title = result;
});
});
},
navigationDelegate: (NavigationRequest request) {
if (request.url.startsWith("myapp://")) {
print("即将打开 ${request.url}");
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
javascriptChannels: <JavascriptChannel>[
JavascriptChannel(
name: "share",
onMessageReceived: (JavascriptMessage message) {
print("参数: ${message.message}");
}),
].toSet(),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/j_drawer.dart | import 'package:flutter/material.dart';
import '/pages/students.dart';
class JDrawer extends StatelessWidget {
const JDrawer({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Drawer(
child: ListView(
children: <Widget>[
Container(
height: 150,
child: UserAccountsDrawerHeader(
//设置用户名
accountName: Text('用户名'),
//设置用户邮箱
accountEmail: Text('[email protected]'),
//设置当前用户的头像
currentAccountPicture: CircleAvatar(
backgroundImage: AssetImage("assets/images/logo.jpg"),
),
//设置当前用户的头像的大小
currentAccountPictureSize: Size(50, 50),
//回调事件
onDetailsPressed: () {},
),
),
ListTile(
leading: Icon(Icons.wifi),
title: Text('我是主标题'),
subtitle: Text('我是副标题'),
),
ListTile(
leading: Icon(Icons.person),
title: Text('我是主标题'),
subtitle: Text('我是副标题'),
),
ListTile(
leading: Icon(Icons.message),
title: Text('我是主标题'),
subtitle: Text('我是副标题'),
onTap: () {
Navigator.pop(context);
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => Students(name: "jjj"),
),
);
},
),
ListTile(
leading: Icon(Icons.login),
title: Text('我是主标题'),
subtitle: Text('我是副标题'),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/coupon_shape_border.dart | import 'dart:math';
import 'package:flutter/material.dart';
class CouponShapeBorder extends ShapeBorder {
final int holeCount;
final double lineRate;
final bool dash;
final Color color;
CouponShapeBorder(
{this.holeCount = 6,
this.lineRate = 0.718,
this.dash = true,
this.color = Colors.white});
@override
EdgeInsetsGeometry get dimensions => null;
@override
Path getInnerPath(Rect rect, {TextDirection textDirection}) {
return null;
}
@override
Path getOuterPath(Rect rect, {TextDirection textDirection}) {
var w = rect.width;
var h = rect.height;
var d = h / (1 + 2 * holeCount);
var path = Path();
path.addRect(rect);
_formHoldLeft(path, d);
_formHoldRight(path, w, d);
_formHoleTop(path, rect);
_formHoleBottom(path, rect);
path.fillType = PathFillType.evenOdd;
return path;
}
void _formHoleBottom(Path path, Rect rect) {
path.addArc(
Rect.fromCenter(
center: Offset(lineRate * rect.width, rect.height),
width: 13.0,
height: 13.0),
pi,
pi);
}
void _formHoleTop(Path path, Rect rect) {
path.addArc(
Rect.fromCenter(
center: Offset(lineRate * rect.width, 0),
width: 13.0,
height: 13.0),
0,
pi);
}
_formHoldLeft(Path path, double d) {
for (int i = 0; i < holeCount; i++) {
var left = -d / 2;
var top = 0.0 + d + 2 * d * (i);
var right = left + d;
var bottom = top + d;
path.addArc(Rect.fromLTRB(left, top, right, bottom), -pi / 2, pi);
}
}
_formHoldRight(Path path, double w, double d) {
for (int i = 0; i < holeCount; i++) {
var left = -d / 2 + w;
var top = 0.0 + d + 2 * d * (i);
var right = left + d;
var bottom = top + d;
path.addArc(Rect.fromLTRB(left, top, right, bottom), pi / 2, pi);
}
}
@override
void paint(Canvas canvas, Rect rect, {TextDirection textDirection}) {
var paint = Paint()
..color = color
..strokeWidth = 1.5
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round;
var d = rect.height / (1 + 2 * holeCount);
if (dash) {
_drawDashLine(canvas, Offset(lineRate * rect.width, d / 2),
rect.height / 16, rect.height - 13, paint);
} else {
canvas.drawLine(Offset(lineRate * rect.width, d / 2),
Offset(lineRate * rect.width, rect.height - d / 2), paint);
}
}
_drawDashLine(
Canvas canvas, Offset start, double count, double length, Paint paint) {
var step = length / count / 2;
for (int i = 0; i < count; i++) {
var offset = start + Offset(0, 2 * step * i);
canvas.drawLine(offset, offset + Offset(0, step), paint);
}
}
@override
ShapeBorder scale(double t) {
// TODO: implement scale
return null;
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/widgets/btn.dart | import 'package:flutter/material.dart';
class Btn extends StatelessWidget {
final String txt;
final VoidCallback onPressed;
const Btn({Key key, this.txt, this.onPressed})
: super(key: key);
@override
Widget build(BuildContext context) {
return ButtonTheme(
minWidth: 48.0,
child: ElevatedButton(child: Text(txt), onPressed: onPressed),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/PlayingControlsSmall.dart | import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:assets_audio_player/assets_audio_player.dart';
import '../../asset_audio_player_icons.dart';
class PlayingControlsSmall extends StatelessWidget {
final bool isPlaying;
final LoopMode loopMode;
final Function() onPlay;
final Function()? onStop;
final Function()? toggleLoop;
PlayingControlsSmall({
required this.isPlaying,
required this.loopMode,
this.toggleLoop,
required this.onPlay,
this.onStop,
});
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
NeumorphicRadio(
style: NeumorphicRadioStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(12),
value: LoopMode.playlist,
groupValue: loopMode,
onChanged: (newValue) {
if (toggleLoop != null) toggleLoop!();
},
child: Icon(
Icons.loop,
size: 18,
),
),
SizedBox(
width: 12,
),
NeumorphicButton(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(16),
onPressed: onPlay,
child: Icon(
isPlaying
? AssetAudioPlayerIcons.pause
: AssetAudioPlayerIcons.play,
size: 32,
),
),
if (onStop != null)
NeumorphicButton(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(16),
onPressed: onPlay,
child: Icon(
AssetAudioPlayerIcons.stop,
size: 32,
),
),
],
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/VolumeSelector.dart | import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import 'package:assets_audio_player/assets_audio_player.dart';
class VolumeSelector extends StatelessWidget {
final double volume;
final Function(double) onChange;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Volume ',
style: TextStyle(fontWeight: FontWeight.bold),
),
Expanded(
child: NeumorphicSlider(
min: AssetsAudioPlayer.minVolume,
max: AssetsAudioPlayer.maxVolume,
value: volume,
style:
SliderStyle(variant: Colors.grey, accent: Colors.grey[500]),
onChanged: (value) {
onChange(value);
},
),
)
],
),
);
}
const VolumeSelector({
required this.volume,
required this.onChange,
});
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/PositionSeekWidget.dart | import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
class PositionSeekWidget extends StatefulWidget {
final Duration currentPosition;
final Duration duration;
final Function(Duration) seekTo;
const PositionSeekWidget({
this.currentPosition,
this.duration,
this.seekTo,
});
@override
_PositionSeekWidgetState createState() => _PositionSeekWidgetState();
}
class _PositionSeekWidgetState extends State<PositionSeekWidget> {
Duration _visibleValue;
bool listenOnlyUserInterraction = false;
double get percent => widget.duration.inMilliseconds == 0
? 0
: _visibleValue.inMilliseconds / widget.duration.inMilliseconds;
@override
void initState() {
super.initState();
_visibleValue = widget.currentPosition;
}
@override
void didUpdateWidget(PositionSeekWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (!listenOnlyUserInterraction) {
_visibleValue = widget.currentPosition;
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 40,
child: Text(durationToString(widget.currentPosition)),
),
Expanded(
child: NeumorphicSlider(
min: 0,
max: widget.duration.inMilliseconds.toDouble(),
value: percent * widget.duration.inMilliseconds.toDouble(),
style:
SliderStyle(variant: Colors.grey, accent: Colors.grey[500]),
onChangeEnd: (newValue) {
setState(() {
listenOnlyUserInterraction = false;
widget.seekTo(_visibleValue);
});
},
onChangeStart: (_) {
setState(() {
listenOnlyUserInterraction = true;
});
},
onChanged: (newValue) {
setState(() {
final to = Duration(milliseconds: newValue.floor());
_visibleValue = to;
});
},
),
),
SizedBox(
width: 40,
child: Text(durationToString(widget.duration)),
),
],
),
);
}
}
String durationToString(Duration duration) {
String twoDigits(int n) {
if (n >= 10) return '$n';
return '0$n';
}
final twoDigitMinutes =
twoDigits(duration.inMinutes.remainder(Duration.minutesPerHour));
final twoDigitSeconds =
twoDigits(duration.inSeconds.remainder(Duration.secondsPerMinute));
return '$twoDigitMinutes:$twoDigitSeconds';
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/SongsSelector.dart | import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
class SongsSelector extends StatelessWidget {
final Playing playing;
final List<Audio> audios;
final Function(Audio) onSelected;
final Function(List<Audio>) onPlaylistSelected;
SongsSelector(
{ this.playing,
this.audios,
this.onSelected,
this.onPlaylistSelected});
Widget _image(Audio item) {
if (item.metas.image == null) {
return SizedBox(height: 40, width: 40);
}
return item.metas.image?.type == ImageType.network
? Image.network(
item.metas.image.path,
height: 40,
width: 40,
fit: BoxFit.cover,
)
: Image.asset(
item.metas.image.path,
height: 40,
width: 40,
fit: BoxFit.cover,
);
}
@override
Widget build(BuildContext context) {
return Neumorphic(
style: NeumorphicStyle(
depth: -8,
boxShape: NeumorphicBoxShape.roundRect(BorderRadius.circular(9)),
),
margin: EdgeInsets.all(8),
padding: EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FractionallySizedBox(
widthFactor: 1,
child: NeumorphicButton(
onPressed: () {
onPlaylistSelected(audios);
},
child: Center(child: Text('All as playlist')),
),
),
SizedBox(
height: 10,
),
Flexible(
child: ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, position) {
final item = audios[position];
final isPlaying = item.path == playing?.audio.assetAudioPath;
return Neumorphic(
margin: EdgeInsets.all(4),
style: NeumorphicStyle(
depth: isPlaying ? -4 : 0,
boxShape:
NeumorphicBoxShape.roundRect(BorderRadius.circular(8)),
),
child: ListTile(
leading: Material(
shape: CircleBorder(),
clipBehavior: Clip.antiAlias,
child: _image(item),
),
title: Text(item.metas.title.toString(),
style: TextStyle(
color: isPlaying ? Colors.blue : Colors.black,
)),
onTap: () {
onSelected(item);
}),
);
},
itemCount: audios.length,
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/PlaySpeedSelector.dart | import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
class PlaySpeedSelector extends StatelessWidget {
final double playSpeed;
final Function(double) onChange;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Text(
'PlaySpeed ',
style: TextStyle(fontWeight: FontWeight.bold),
),
_button(0.5),
_button(1.0),
_button(2.0),
_button(4.0),
],
),
);
}
Widget _button(double value) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: NeumorphicRadio(
groupValue: playSpeed,
padding: EdgeInsets.all(12.0),
value: value,
style: NeumorphicRadioStyle(
boxShape: NeumorphicBoxShape.circle(),
),
onChanged: (double? v) {
if (v != null) onChange(v);
},
child: Text('x$value'),
),
);
}
const PlaySpeedSelector({
required this.playSpeed,
required this.onChange,
});
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/ForwardRewindSelector.dart | import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
class ForwardRewindSelector extends StatelessWidget {
final double speed;
final Function(double) onChange;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: <Widget>[
Text(
'Forward/Rewind ',
style: TextStyle(fontWeight: FontWeight.bold),
),
_button(-2),
_button(2.0),
],
),
);
}
Widget _button(double value) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: NeumorphicRadio(
groupValue: speed,
padding: EdgeInsets.all(12.0),
value: value,
style: NeumorphicRadioStyle(
boxShape: NeumorphicBoxShape.circle(),
),
onChanged: (double v) {
if (v != null) onChange(v);
},
child: Text('x$value'),
),
);
}
const ForwardRewindSelector({
this.speed,
this.onChange,
});
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets | mirrored_repositories/flutter100days/lib/widgets/player/PlayingControls.dart | import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter/material.dart';
import 'package:flutter_neumorphic/flutter_neumorphic.dart';
import '../../tool/config.dart';
class PlayingControls extends StatelessWidget {
final bool isPlaying;
final LoopMode loopMode;
final bool isPlaylist;
final Function() onPrevious;
final Function() onPlay;
final Function() onNext;
final Function() toggleLoop;
final Function() onStop;
PlayingControls({
this.isPlaying,
this.isPlaylist = false,
this.loopMode,
this.toggleLoop,
this.onPrevious,
this.onPlay,
this.onNext,
this.onStop,
});
Widget _loopIcon(BuildContext context) {
final iconSize = 34.0;
if (loopMode == LoopMode.none) {
return Icon(
Icons.loop,
size: iconSize,
color: Colors.grey,
);
} else if (loopMode == LoopMode.playlist) {
return Icon(
Icons.loop,
size: iconSize,
color: Colors.black,
);
} else {
//single
return Stack(
alignment: Alignment.center,
children: [
Icon(
Icons.loop,
size: iconSize,
color: Colors.black,
),
Center(
child: Text(
'1',
style: TextStyle(fontSize: 12, fontWeight: FontWeight.bold),
),
),
],
);
}
}
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: [
GestureDetector(
onTap: () {
if (toggleLoop != null) toggleLoop();
},
child: _loopIcon(context),
),
SizedBox(
width: 12,
),
NeumorphicButton(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(18),
onPressed: isPlaylist ? onPrevious : null,
child: Icon(AssetAudioPlayerIcons.to_start),
),
SizedBox(
width: 12,
),
NeumorphicButton(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(24),
onPressed: onPlay,
child: Icon(
isPlaying
? AssetAudioPlayerIcons.pause
: AssetAudioPlayerIcons.play,
size: 32,
),
),
SizedBox(
width: 12,
),
NeumorphicButton(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(18),
onPressed: isPlaylist ? onNext : null,
child: Icon(AssetAudioPlayerIcons.to_end),
),
SizedBox(
width: 45,
),
if (onStop != null)
NeumorphicButton(
style: NeumorphicStyle(
boxShape: NeumorphicBoxShape.circle(),
),
padding: EdgeInsets.all(16),
onPressed: onStop,
child: Icon(
AssetAudioPlayerIcons.stop,
size: 32,
),
),
],
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib/widgets/player | mirrored_repositories/flutter100days/lib/widgets/player/model/MyAudio.dart | import 'package:assets_audio_player/assets_audio_player.dart';
class MyAudio {
final Audio audio;
final String name;
final String imageUrl;
const MyAudio({
this.audio,
this.name,
this.imageUrl,
});
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tabs/tabs_pic.dart | import 'package:flutter/material.dart';
import '../data/list.dart' as newsList;
class TabsPic extends StatelessWidget {
final int index;
final String title;
const TabsPic({Key key, this.index, this.title}) : super(key: key);
Widget _itemBuilderFunc(BuildContext context, int index) {
final Map news = newsList.news[index];
return ListItem(
cover: news['imgurl'],
title: news['title'],
subTitle: news['time'],
);
}
@override
Widget build(BuildContext context) {
print(this.index);
print(this.title);
return Center(
child: ListView.builder(
itemCount: newsList.news.length,
itemBuilder: this._itemBuilderFunc,
itemExtent: 90,
),
);
}
}
class ListItem extends StatelessWidget {
ListItem({this.title, this.subTitle, this.cover});
final String title;
final String subTitle;
final String cover;
@override
Widget build(BuildContext context) {
return ListTile(
leading: Container(
child: Image.network(this.cover, fit: BoxFit.cover),
width: 60,
height: 60,
color: Colors.grey),
trailing: Icon(Icons.chevron_right),
title: Text(this.title),
subtitle: Text(this.subTitle),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tabs/tabs_news.dart | import 'package:flutter/material.dart';
import '../data/list.dart' as newsList;
class TabsNews extends StatelessWidget {
final int index;
final String title;
const TabsNews({Key key, this.index, this.title}) : super(key: key);
Widget _itemBuilderFunc(BuildContext context, int index) {
final Map news = newsList.news[index];
return ListItem(
cover: news['imgurl'],
title: news['title'],
subTitle: news['time'],
);
}
@override
Widget build(BuildContext context) {
print(this.index);
print(this.title);
return Center(
child: ListView.builder(
itemCount: newsList.news.length,
itemBuilder: this._itemBuilderFunc,
itemExtent: 90,
),
);
}
}
class ListItem extends StatelessWidget {
ListItem({this.title, this.subTitle, this.cover});
final String title;
final String subTitle;
final String cover;
@override
Widget build(BuildContext context) {
return ListTile(
leading: Container(
child: Image.network(this.cover, fit: BoxFit.cover),
width: 60,
height: 60,
color: Colors.grey),
trailing: Icon(Icons.chevron_right),
title: Text(this.title),
subtitle: Text(this.subTitle),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tabs/tabs_his.dart | import 'package:flutter/material.dart';
import '../data/list.dart' as newsList;
class TabsHis extends StatelessWidget {
final int index;
final String title;
const TabsHis({Key key, this.index, this.title}) : super(key: key);
Widget _itemBuilderFunc(BuildContext context, int index) {
final Map news = newsList.news[index];
return ListItem(
cover: news['imgurl'],
title: news['title'],
subTitle: news['time'],
);
}
@override
Widget build(BuildContext context) {
print(this.index);
print(this.title);
return Center(
child: ListView.builder(
itemCount: newsList.news.length,
itemBuilder: this._itemBuilderFunc,
itemExtent: 90,
),
);
}
}
class ListItem extends StatelessWidget {
ListItem({this.title, this.subTitle, this.cover});
final String title;
final String subTitle;
final String cover;
@override
Widget build(BuildContext context) {
return ListTile(
leading: Container(
child: Image.network(this.cover, fit: BoxFit.cover),
width: 60,
height: 60,
color: Colors.grey),
trailing: Icon(Icons.chevron_right),
title: Text(this.title),
subtitle: Text(this.subTitle),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/students.dart | import 'package:flutter/material.dart';
class Students extends StatelessWidget {
final String name;
final int age;
const Students({Key key, this.name,this.age}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: name,
home: Scaffold(
appBar: AppBar(
title: Text(name),
),
body: Center(
child: Column(
children: [
Text("name:$name --- age:$age"),
ElevatedButton(
child: Text("返回"),
onPressed: () {
Navigator.of(context).pop("这是pop返回的参数值");
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/index_page.dart | import 'package:flutter/material.dart';
import '../tool/config.dart';
import '../bottom_nav_pages/bottom_nav_pages_a.dart';
import '../bottom_nav_pages/bottom_nav_pages_b.dart';
import '../bottom_nav_pages/bottom_nav_pages_c.dart';
import '../bottom_nav_pages/bottom_nav_pages_d.dart';
import '../tool/shared_preferences_utils.dart';
class IndexPage extends StatefulWidget {
const IndexPage({Key key}) : super(key: key);
@override
_IndexPageState createState() => _IndexPageState();
}
class _IndexPageState extends State<IndexPage> {
int _currentIndex = 0; //记录当前选择的是哪一个
String title = '首页';
@override
Widget build(BuildContext context) {
final List<Widget> _pages = [
HomePage(
title: this.title,
),
BusinessPage(
title: this.title,
),
MyLocationPage(
title: this.title,
),
PersonPage(
title: this.title,
)
];
return Scaffold(
appBar: AppBar(
title: Text('底部导航'),
),
body: _pages[_currentIndex], //展示组件
bottomNavigationBar: BottomNavigationBar(
showSelectedLabels: true,
type: BottomNavigationBarType.fixed,
fixedColor: Colors.redAccent,
// unselectedLabelStyle: TextStyle(color: Colors.orange),
unselectedItemColor: Colors.grey,
// selectedItemColor: Colors.orange,
currentIndex: this._currentIndex,
onTap: (int index) {
//点击事件
setState(() {
//修改状态,会自动刷新Widget
this._currentIndex = index;
this.title = bottomNavBarList[this._currentIndex]['title'];
});
},
items: bottomNavBarList
.map((e) => BottomNavigationBarItem(
icon: Icon(e['icon']), label: e['title']))
.toList()),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/demo2.dart | import 'package:flutter/material.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:fijkplayer_skin/fijkplayer_skin.dart';
import 'package:fijkplayer_skin/schema.dart' show VideoSourceFormat;
class Demo2 extends StatefulWidget {
@override
Demo2State createState() => Demo2State();
}
class Demo2State extends State<Demo2> {
@override
Widget build(BuildContext context) {
// return VideoDetailPage();
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: VideoDetailPage(),
),
);
}
}
// 定制UI配置项
class PlayerShowConfig implements ShowConfigAbs {
@override
bool drawerBtn = false;
@override
bool nextBtn = false;
@override
bool speedBtn = true;
@override
bool topBar = true;
@override
bool lockBtn = true;
@override
bool autoNext = false;
@override
bool bottomPro = true;
@override
bool stateAuto = true;
@override
bool isAutoPlay = true;
}
class VideoDetailPage extends StatefulWidget {
@override
_VideoDetailPageState createState() => _VideoDetailPageState();
}
class _VideoDetailPageState extends State<VideoDetailPage>
with TickerProviderStateMixin {
final FijkPlayer player = FijkPlayer();
Map<String, List<Map<String, dynamic>>> videoList = {
"video": [
{
"name": "天空资源",
"list": [
{
"url": "https://v10.dious.cc/20211009/nONG14sk/index.m3u8",
"name": "一级指控",
},
]
},
]
};
VideoSourceFormat _videoSourceTabs;
int _curTabIdx = 0;
int _curActiveIdx = 0;
ShowConfigAbs vCfg = PlayerShowConfig();
@override
void dispose() {
player.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
// 格式化json转对象
_videoSourceTabs = VideoSourceFormat.fromJson(videoList);
// 这句不能省,必须有
speed = 1.0;
}
@override
Widget build(BuildContext context) {
return Column(
children: [
FijkView(
height: 260,
color: Colors.black,
fit: FijkFit.cover,
player: player,
panelBuilder: (
FijkPlayer player,
FijkData data,
BuildContext context,
Size viewSize,
Rect texturePos,
) {
/// 使用自定义的布局
/// 精简模式,可不传递onChangeVideo
return CustomFijkPanel(
player: player,
viewSize: viewSize,
texturePos: texturePos,
pageContent: context,
// 标题 当前页面顶部的标题部分
playerTitle: "标题",
// 当前视频源tabIndex
curTabIdx: _curTabIdx,
// 当前视频源activeIndex
curActiveIdx: _curActiveIdx,
// 显示的配置
showConfig: vCfg,
// json格式化后的视频数据
videoFormat: _videoSourceTabs,
);
},
),
],
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/c_page.dart | import 'package:flutter/material.dart';
class CPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'CPage';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
children: [
Text("CPage"),
ElevatedButton(
child: Text("返回"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/a_page.dart | import 'package:flutter/material.dart';
class APage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'APage';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
children: [
Text("APage"),
ElevatedButton(
child: Text("返回"),
onPressed: () {
Navigator.of(context).pop();
},
),
ElevatedButton(
child: Text("BPage"),
onPressed: () {
Navigator.of(context).pushNamed("/BPage");
},
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/demo1.dart | import 'package:flutter/material.dart';
import 'package:fijkplayer/fijkplayer.dart';
import 'package:fijkplayer_skin/fijkplayer_skin.dart';
import 'package:fijkplayer_skin/schema.dart' show VideoSourceFormat;
class Demo1 extends StatefulWidget {
@override
Demo1State createState() => Demo1State();
}
class Demo1State extends State<Demo1> {
@override
Widget build(BuildContext context) {
// return VideoDetailPage();
return Scaffold(
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: VideoDetailPage(),
),
);
}
}
// 定制UI配置项
class PlayerShowConfig implements ShowConfigAbs {
@override
bool drawerBtn = true;
@override
bool nextBtn = true;
@override
bool speedBtn = true;
@override
bool topBar = true;
@override
bool lockBtn = true;
@override
bool autoNext = true;
@override
bool bottomPro = true;
@override
bool stateAuto = true;
@override
bool isAutoPlay = false;
}
class VideoDetailPage extends StatefulWidget {
@override
_VideoDetailPageState createState() => _VideoDetailPageState();
}
class _VideoDetailPageState extends State<VideoDetailPage>
with TickerProviderStateMixin {
final FijkPlayer player = FijkPlayer();
Map<String, List<Map<String, dynamic>>> videoList = {
"video": [
{
"name": "天空资源",
"list": [
{
"url": "https://static.smartisanos.cn/common/video/t1-ui.mp4",
"name": "锤子UI-1",
},
{
"url": "https://static.smartisanos.cn/common/video/video-jgpro.mp4",
"name": "锤子UI-2",
},
{
"url": "https://v-cdn.zjol.com.cn/280443.mp4",
"name": "其他",
},
]
},
{
"name": "天空资源",
"list": [
{
"url": "https://n1.szjal.cn/20210428/lsNZ6QAL/index.m3u8",
"name": "综艺",
},
{
"url": "https://static.smartisanos.cn/common/video/t1-ui.mp4",
"name": "锤子1",
},
{
"url": "https://static.smartisanos.cn/common/video/video-jgpro.mp4",
"name": "锤子2",
}
]
},
]
};
VideoSourceFormat _videoSourceTabs;
TabController _tabController;
int _curTabIdx = 0;
int _curActiveIdx = 0;
ShowConfigAbs vCfg = PlayerShowConfig();
@override
void dispose() {
player.dispose();
_tabController.dispose();
super.dispose();
}
// 钩子函数,用于更新状态
void onChangeVideo(int curTabIdx, int curActiveIdx) {
this.setState(() {
_curTabIdx = curTabIdx;
_curActiveIdx = curActiveIdx;
});
}
@override
void initState() {
super.initState();
// 格式化json转对象
_videoSourceTabs = VideoSourceFormat.fromJson(videoList);
// tabbar初始化
_tabController = TabController(
length: _videoSourceTabs.video.length,
vsync: this,
);
// 这句不能省,必须有
speed = 1.0;
}
// build 剧集
Widget buildPlayDrawer() {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(24),
child: AppBar(
backgroundColor: Colors.black,
automaticallyImplyLeading: false,
primary: false,
elevation: 0,
title: TabBar(
tabs: _videoSourceTabs.video
.map((e) => Tab(text: e.name))
.toList(),
isScrollable: true,
controller: _tabController,
),
),
),
body: Container(
color: Colors.black87,
child: TabBarView(
controller: _tabController,
children: createTabConList(),
),
),
);
}
// 剧集 tabCon
List<Widget> createTabConList() {
List<Widget> list = [];
_videoSourceTabs.video.asMap().keys.forEach((int tabIdx) {
List<Widget> playListBtns = _videoSourceTabs.video[tabIdx].list
.asMap()
.keys
.map((int activeIdx) {
return Padding(
padding: EdgeInsets.only(left: 5, right: 5),
child: ElevatedButton(
style: ButtonStyle(
shape: MaterialStateProperty.all(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5),
),
),
elevation: MaterialStateProperty.all(0),
backgroundColor: MaterialStateProperty.all(
tabIdx == _curTabIdx && activeIdx == _curActiveIdx
? Colors.red
: Colors.blue),
),
onPressed: () async {
setState(() {
_curTabIdx = tabIdx;
_curActiveIdx = activeIdx;
});
String nextVideoUrl =
_videoSourceTabs.video[tabIdx].list[activeIdx].url;
// 切换播放源
// 如果不是自动开始播放,那么先执行stop
if (player.value.state == FijkState.completed) {
await player.stop();
}
await player.reset().then((_) async {
player.setDataSource(nextVideoUrl, autoPlay: true);
});
},
child: Text(
_videoSourceTabs.video[tabIdx].list[activeIdx].name,
style: TextStyle(
color: Colors.white,
),
),
),
);
}).toList();
//
list.add(
SingleChildScrollView(
child: Padding(
padding: EdgeInsets.only(left: 5, right: 5),
child: Wrap(
direction: Axis.horizontal,
children: playListBtns,
),
),
),
);
});
return list;
}
@override
Widget build(BuildContext context) {
return Column(
children: [
FijkView(
height: 260,
color: Colors.black,
fit: FijkFit.cover,
player: player,
panelBuilder: (
FijkPlayer player,
FijkData data,
BuildContext context,
Size viewSize,
Rect texturePos,
) {
/// 使用自定义的布局
return CustomFijkPanel(
player: player,
viewSize: viewSize,
texturePos: texturePos,
pageContent: context,
// 标题 当前页面顶部的标题部分
playerTitle: "标题",
// 当前视频改变钩子
onChangeVideo: onChangeVideo,
// 当前视频源tabIndex
curTabIdx: _curTabIdx,
// 当前视频源activeIndex
curActiveIdx: _curActiveIdx,
// 显示的配置
showConfig: vCfg,
// json格式化后的视频数据
videoFormat: _videoSourceTabs,
);
},
),
Container(
height: 300,
child: buildPlayDrawer(),
),
Container(
child: Text(
'当前tabIdx : ${_curTabIdx.toString()} 当前activeIdx : ${_curActiveIdx.toString()}'),
)
],
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/pages/b_page.dart | import 'package:flutter/material.dart';
class BPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'BPage';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
children: [
Text("BPage"),
ElevatedButton(
child: Text("返回"),
onPressed: () {
Navigator.of(context).pop();
},
),
ElevatedButton(
child: Text("CPage"),
onPressed: () {
Navigator.of(context).pushNamed("/CPage");
// Navigator.of(context).pushReplacementNamed("/CPage");
//Navigator.of(context).pushNamedAndRemoveUntil("/CPage", ModalRoute.withName("/"));
//Navigator.pushNamed("/CPage");
},
),
],
),
),
),
);
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/http/base_dio.dart | import 'package:dio/dio.dart';
var options = BaseOptions(
baseUrl: 'https://www.wanandroid.com',
connectTimeout: 5000,
receiveTimeout: 3000,
responseType: ResponseType.json);
Dio dio = Dio(options);
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/data/list.dart | List news = [
{
"title":"计算机架构宗师:996并不能够带来创新性",
"docurl":"https://tech.163.com/19/0620/07/EI3LJA1T000999D9.html",
"commenturl":"http://comment.tie.163.com/EI3LJA1T000999D9.html",
"tienum":5213,
"tlastid":"<a href='https://tech.163.com/19/0620/07/EI3LJA1T000999D9.html' class='link'>其它</a>",
"tlink":"https://tech.163.com/19/0620/07/EI3LJA1T000999D9.html",
"label":"其它",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/6/7/667a80fd624b673a/1.html",
"keyname":"智能手机"
}
],
"time":"06/20/2019 07:30:06",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/68fa7f186ffe4479ab27efabd4d94246.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"谷歌"内战":高管要利润,员工要价值观,谁是灵魂",
"docurl":"https://tech.163.com/19/0620/07/EI3K0SCC00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI3K0SCC00097U7R.html",
"tienum":926,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/8/3/8c376b4c/1.html",
"keyname":"谷歌"
},
{
"akey_link":"http://tech.163.com/keywords/5/a/5fae8f6f/1.html",
"keyname":"微软"
},
{
"akey_link":"http://tech.163.com/keywords/7/a/76ae67e54f0a/1.html",
"keyname":"皮查伊"
}
],
"time":"06/20/2019 07:02:33",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/18/cb15feda5261404593787b49bd70c622.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"FB推数字货币 美参议院:7月办听证会谈谈隐私问题",
"docurl":"https://tech.163.com/19/0620/07/EI3KRGSC000998GP.html",
"commenturl":"http://comment.tie.163.com/EI3KRGSC000998GP.html",
"tienum":22,
"tlastid":"<a href='https://tech.163.com/19/0620/07/EI3KRGSC000998GP.html' class='link'>其它</a>",
"tlink":"https://tech.163.com/19/0620/07/EI3KRGSC000998GP.html",
"label":"其它",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/6/7/65705b578d275e01/1.html",
"keyname":"数字货币"
},
{
"akey_link":"http://tech.163.com/keywords/5/c/53c28bae9662/1.html",
"keyname":"参议院"
}
],
"time":"06/20/2019 07:17:06",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/20cee67ee1a549ea8f8fb285de1f198d.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"美团王兴:Facebook发币意在替代小国央行",
"docurl":"https://tech.163.com/19/0620/11/EI42C1GM000998GP.html",
"commenturl":"http://comment.tie.163.com/EI42C1GM000998GP.html",
"tienum":189,
"tlastid":"<a href='https://tech.163.com/19/0620/11/EI42C1GM000998GP.html' class='link'>其它</a>",
"tlink":"https://tech.163.com/19/0620/11/EI42C1GM000998GP.html",
"label":"其它",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/7/8/738b5174/1.html",
"keyname":"王兴"
},
{
"akey_link":"http://tech.163.com/keywords/8/3/81384e66/1.html",
"keyname":"脸书"
},
{
"akey_link":"http://tech.163.com/keywords/7/8/7f8e56e2/1.html",
"keyname":"美团"
}
],
"time":"06/20/2019 11:13:19",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/2280e210572a4567998838dbed9770fd.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"西班牙官网宣传图抄袭,小米道歉并解雇涉事员工",
"docurl":"https://tech.163.com/19/0620/07/EI3M1VU600097U7S.html",
"commenturl":"http://comment.tie.163.com/EI3M1VU600097U7S.html",
"tienum":1812,
"tlastid":"<a href='http://tech.163.com/telecom/' class='link'>通信</a>",
"tlink":"http://tech.163.com/telecom/",
"label":"通信",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/5/0/5c0f7c73/1.html",
"keyname":"小米"
},
{
"akey_link":"http://tech.163.com/keywords/8/7/897f73ed7259/1.html",
"keyname":"西班牙"
},
{
"akey_link":"http://tech.163.com/keywords/8/f/82f9679c/1.html",
"keyname":"苹果"
}
],
"time":"06/20/2019 07:38:07",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/77456e5a07d34dfa8a2e61dec1fd32ec.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"戴尔惠普微软英特尔发布联合声明反对美国加征关税",
"docurl":"https://tech.163.com/19/0620/14/EI4D20P700097U7T.html",
"commenturl":"http://comment.tie.163.com/EI4D20P700097U7T.html",
"tienum":1,
"tlastid":"<a href='http://tech.163.com/it/' class='link'>IT业界</a>",
"tlink":"http://tech.163.com/it/",
"label":"IT业界",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/5/7/51737a0e/1.html",
"keyname":"关税"
},
{
"akey_link":"http://tech.163.com/keywords/7/8/7f8e56fd/1.html",
"keyname":"美国"
},
{
"akey_link":"http://tech.163.com/keywords/6/e/60e0666e/1.html",
"keyname":"惠普"
}
],
"time":"06/20/2019 14:20:05",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/215947bc1bef46fd800fd9d9ca1f7a9e.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"外设厂商开始生产新iPhone专用镜头保护膜",
"docurl":"https://tech.163.com/19/0620/12/EI460QKA00097U7S.html",
"commenturl":"http://comment.tie.163.com/EI460QKA00097U7S.html",
"tienum":3,
"tlastid":"<a href='http://tech.163.com/telecom/' class='link'>通信</a>",
"tlink":"http://tech.163.com/telecom/",
"label":"通信",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/4/d/4fdd62a4819c/1.html",
"keyname":"保护膜"
}
],
"time":"06/20/2019 12:17:06",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/552b931a0fe64b059664a7358cc232ed.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"京东物流618战报:非京东平台业务收入增幅超120%",
"docurl":"https://tech.163.com/19/0620/10/EI4169FI00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI4169FI00097U7R.html",
"tienum":46,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/0/3/003600310038/1.html",
"keyname":"618"
},
{
"akey_link":"http://tech.163.com/keywords/4/a/4eac4e1c/1.html",
"keyname":"京东"
},
{
"akey_link":"http://tech.163.com/keywords/7/6/72696d41/1.html",
"keyname":"物流"
}
],
"time":"06/20/2019 10:52:42",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/3e43858203da4440ae2ba756b5909733.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"任正非答美媒:华为年营收真降300亿美元也是小事",
"docurl":"https://tech.163.com/19/0620/10/EI3UBF7500097U7S.html",
"commenturl":"http://comment.tie.163.com/EI3UBF7500097U7S.html",
"tienum":2719,
"tlastid":"<a href='http://tech.163.com/telecom/' class='link'>通信</a>",
"tlink":"http://tech.163.com/telecom/",
"label":"通信",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/4/f/4efb6b63975e/1.html",
"keyname":"任正非"
},
{
"akey_link":"http://tech.163.com/keywords/5/4/534e4e3a/1.html",
"keyname":"华为"
}
],
"time":"06/20/2019 10:03:06",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/075a543838ec4cac82399dd58661d015.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"外媒:首艘载人龙飞船发射时间将晚于2019年11月",
"docurl":"https://tech.163.com/19/0620/16/EI4KMAGP00097U81.html",
"commenturl":"http://comment.tie.163.com/EI4KMAGP00097U81.html",
"tienum":1,
"tlastid":"<a href='https://tech.163.com/19/0620/16/EI4KMAGP00097U81.html' class='link'>科学探索</a>",
"tlink":"https://tech.163.com/19/0620/16/EI4KMAGP00097U81.html",
"label":"科学探索",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/9/d/98de8239/1.html",
"keyname":"飞船"
}
],
"time":"06/20/2019 16:33:30",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/e689ba068d54400abe17b10d0dae0d60.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"广州下发首批自动驾驶路测牌照 文远知行广汽等获批",
"docurl":"https://tech.163.com/19/0620/15/EI4HTU7N00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI4HTU7N00097U7R.html",
"tienum":0,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/6/8/65878fdc/1.html",
"keyname":"文远"
},
{
"akey_link":"http://tech.163.com/keywords/8/e/81ea52a89a7e9a76/1.html",
"keyname":"自动驾驶"
}
],
"time":"06/20/2019 15:45:14",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/278d61e9461d43b986399774bccdef12.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"格兰仕3天发7篇声明怼天猫 真的是因为"二选一"?",
"docurl":"https://tech.163.com/19/0620/10/EI3V32E600097U7R.html",
"commenturl":"http://comment.tie.163.com/EI3V32E600097U7R.html",
"tienum":1363,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/6/3/683c51704ed5/1.html",
"keyname":"格兰仕"
},
{
"akey_link":"http://tech.163.com/keywords/5/2/5929732b/1.html",
"keyname":"天猫"
},
{
"akey_link":"http://tech.163.com/keywords/4/a/4eac4e1c/1.html",
"keyname":"京东"
}
],
"time":"06/20/2019 10:15:59",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/f6d832856b1b490dbfa5fd48df7cb00f.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"人工智能先行,韩国欲跻身“制造业全球四强”",
"docurl":"https://tech.163.com/19/0620/12/EI47V1MS00097U7T.html",
"commenturl":"http://comment.tie.163.com/EI47V1MS00097U7T.html",
"tienum":6,
"tlastid":"<a href='http://tech.163.com/it/' class='link'>IT业界</a>",
"tlink":"http://tech.163.com/it/",
"label":"IT业界",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/5/3/523690204e1a/1.html",
"keyname":"制造业"
},
{
"akey_link":"http://tech.163.com/keywords/9/e/97e956fd/1.html",
"keyname":"韩国"
}
],
"time":"06/20/2019 12:51:05",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/8b8408673cf2486893d5a4a6c871c3d4.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"酒店、试衣间又现针孔摄像头 网友:出门要带帐篷?!",
"docurl":"https://tech.163.com/19/0620/11/EI44AETD00097U82.html",
"commenturl":"http://comment.tie.163.com/EI44AETD00097U82.html",
"tienum":25,
"tlastid":"<a href='https://tech.163.com/19/0620/11/EI44AETD00097U82.html' class='link'>社会新闻</a>",
"tlink":"https://tech.163.com/19/0620/11/EI44AETD00097U82.html",
"label":"社会新闻",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/6/4/644450cf5934/1.html",
"keyname":"摄像头"
},
{
"akey_link":"http://tech.163.com/keywords/6/0/670d88c55e97/1.html",
"keyname":"服装店"
}
],
"time":"06/20/2019 11:47:24",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/c1fd87d39e2142e0ae43ba610313713a.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"ofo回应2.5亿元诉讼无可执行财产:全力退还押金",
"docurl":"https://tech.163.com/19/0620/08/EI3NQQ3B00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI3NQQ3B00097U7R.html",
"tienum":309,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/0/6/006f0066006f/1.html",
"keyname":"ofo"
},
{
"akey_link":"http://tech.163.com/keywords/6/d/6cd59662/1.html",
"keyname":"法院"
}
],
"time":"06/20/2019 08:09:09",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/21da6217fe194c7f9b47bd0c275ab3e1.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"买了VIP却不能跳过广告 女大学生状告爱奇艺获赔偿",
"docurl":"https://tech.163.com/19/0620/12/EI45SGS700097U7R.html",
"commenturl":"http://comment.tie.163.com/EI45SGS700097U7R.html",
"tienum":98,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/7/3/72315947827a/1.html",
"keyname":"爱奇艺"
}
],
"time":"06/20/2019 12:14:45",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/0599d0364a1643758c67a1aa2f530a65.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"皮查伊发年度致股东信回应质疑:谷歌以助人为乐",
"docurl":"https://tech.163.com/19/0620/10/EI412PLQ00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI412PLQ00097U7R.html",
"tienum":4,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/7/a/76ae67e54f0a/1.html",
"keyname":"皮查伊"
},
{
"akey_link":"http://tech.163.com/keywords/8/3/8c376b4c/1.html",
"keyname":"谷歌"
},
{
"akey_link":"http://tech.163.com/keywords/4/6/4f695947/1.html",
"keyname":"佩奇"
}
],
"time":"06/20/2019 10:50:48",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/bdfd18fca1b34fee9d37e0a852044f7c.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"贝索斯:将用月球水冰制造氢气为航天器提炼燃料",
"docurl":"https://tech.163.com/19/0620/08/EI3QIBU300097U81.html",
"commenturl":"http://comment.tie.163.com/EI3QIBU300097U81.html",
"tienum":36,
"tlastid":"<a href='https://tech.163.com/19/0620/08/EI3QIBU300097U81.html' class='link'>科学探索</a>",
"tlink":"https://tech.163.com/19/0620/08/EI3QIBU300097U81.html",
"label":"科学探索",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/8/1/8d1d7d2265af/1.html",
"keyname":"贝索斯"
},
{
"akey_link":"http://tech.163.com/keywords/7/7/767b67088f66/1.html",
"keyname":"登月车"
}
],
"time":"06/20/2019 08:56:58",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/8b01f1acc3cf4fc49eed9c3828fbb924.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"加密货币Libra挑战传统金融?全球监管机构“围剿”",
"docurl":"https://tech.163.com/19/0620/08/EI3QEAG1000998GP.html",
"commenturl":"http://comment.tie.163.com/EI3QEAG1000998GP.html",
"tienum":24,
"tlastid":"<a href='https://tech.163.com/19/0620/08/EI3QEAG1000998GP.html' class='link'>其它</a>",
"tlink":"https://tech.163.com/19/0620/08/EI3QEAG1000998GP.html",
"label":"其它",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/8/2/8d275e01/1.html",
"keyname":"货币"
},
{
"akey_link":"http://tech.163.com/keywords/6/d/6bd472795e01/1.html",
"keyname":"比特币"
}
],
"time":"06/20/2019 08:54:45",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/8315979dc4534c6e9a1880ee3d087a01.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"信而富宣布退出P2P业务 网贷"老32家"仅7家健在",
"docurl":"https://tech.163.com/19/0620/07/EI3N2EDO00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI3N2EDO00097U7R.html",
"tienum":11,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/7/5/7f518d37/1.html",
"keyname":"网贷"
},
{
"akey_link":"http://tech.163.com/keywords/7/5/7f518d375e7353f0/1.html",
"keyname":"网贷平台"
}
],
"time":"06/20/2019 07:55:50",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/fd54b9eb778342caabc000ccde527439.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"5G让印度电信富豪头疼:买频谱太贵,不买没前途",
"docurl":"https://tech.163.com/19/0620/07/EI3MHV8000097U7S.html",
"commenturl":"http://comment.tie.163.com/EI3MHV8000097U7S.html",
"tienum":334,
"tlastid":"<a href='http://tech.163.com/telecom/' class='link'>通信</a>",
"tlink":"http://tech.163.com/telecom/",
"label":"通信",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/4/2/4e2d56fd75354fe1/1.html",
"keyname":"中国电信"
},
{
"akey_link":"http://tech.163.com/keywords/5/7/53705ea6/1.html",
"keyname":"印度"
}
],
"time":"06/20/2019 07:46:51",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/907b77d467a64f5db9f8d2dffa6dfd2b.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"Facebook发币最全解读:各国央行为何紧张?",
"docurl":"https://tech.163.com/19/0620/11/EI44LBOU000998GP.html",
"commenturl":"http://comment.tie.163.com/EI44LBOU000998GP.html",
"tienum":3,
"tlastid":"<a href='https://tech.163.com/19/0620/11/EI44LBOU000998GP.html' class='link'>其它</a>",
"tlink":"https://tech.163.com/19/0620/11/EI44LBOU000998GP.html",
"label":"其它",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/8/3/81384e66/1.html",
"keyname":"脸书"
},
{
"akey_link":"http://tech.163.com/keywords/6/d/6bd472795e01/1.html",
"keyname":"比特币"
},
{
"akey_link":"http://tech.163.com/keywords/5/2/592e884c/1.html",
"keyname":"央行"
}
],
"time":"06/20/2019 11:53:22",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/7de8e4760bd74dbfb9e3113b7d7066c6.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"击败动视暴雪,苹果已成为全球第四大游戏公司",
"docurl":"https://tech.163.com/19/0620/09/EI3TR7CV00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI3TR7CV00097U7R.html",
"tienum":21,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/4/f/4efb59295802/1.html",
"keyname":"任天堂"
},
{
"akey_link":"http://tech.163.com/keywords/6/b/66b496ea/1.html",
"keyname":"暴雪"
},
{
"akey_link":"http://tech.163.com/keywords/8/f/82f9679c/1.html",
"keyname":"苹果"
}
],
"time":"06/20/2019 09:54:14",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/2bd577f214b3460991b41408fc1e235b.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"中国移动发布可持续发展报告:申请5G专利超1000项",
"docurl":"https://tech.163.com/19/0620/09/EI3TGIOK00097U7S.html",
"commenturl":"http://comment.tie.163.com/EI3TGIOK00097U7S.html",
"tienum":2,
"tlastid":"<a href='http://tech.163.com/telecom/' class='link'>通信</a>",
"tlink":"http://tech.163.com/telecom/",
"label":"通信",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/4/2/4e2d56fd79fb52a8/1.html",
"keyname":"中国移动"
}
],
"time":"06/20/2019 09:48:25",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/cb8d699894b24e4cab3009cd73b61222.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"亚马逊发布Kindle Oasis第三代:售价2399元起",
"docurl":"https://tech.163.com/19/0620/08/EI3NI4M800097U7T.html",
"commenturl":"http://comment.tie.163.com/EI3NI4M800097U7T.html",
"tienum":33,
"tlastid":"<a href='http://tech.163.com/it/' class='link'>IT业界</a>",
"tlink":"http://tech.163.com/it/",
"label":"IT业界",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/0/6/006b0069006e0064006c0065/1.html",
"keyname":"kindle"
}
],
"time":"06/20/2019 08:04:25",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/0786544966a74b6288baea4037b3bb54.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"国美618战报:整体GMV同比增长68%",
"docurl":"https://tech.163.com/19/0620/10/EI4194UG00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI4194UG00097U7R.html",
"tienum":0,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/5/f/56fd7f8e/1.html",
"keyname":"国美"
},
{
"akey_link":"http://tech.163.com/keywords/0/3/003600310038/1.html",
"keyname":"618"
},
{
"akey_link":"http://tech.163.com/keywords/6/7/6d775c14/1.html",
"keyname":"海尔"
}
],
"time":"06/20/2019 10:54:16",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/b3b51372ace649a893b0f1b4332c8d5e.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"Alphabet股东大会上有人提议拆分谷歌,但遭到否决",
"docurl":"https://tech.163.com/19/0620/07/EI3MQ2EE00097U7R.html",
"commenturl":"http://comment.tie.163.com/EI3MQ2EE00097U7R.html",
"tienum":1,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/8/a/80a14e1c59274f1a/1.html",
"keyname":"股东大会"
},
{
"akey_link":"http://tech.163.com/keywords/8/3/8c376b4c/1.html",
"keyname":"谷歌"
}
],
"time":"06/20/2019 07:51:16",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/fc1c6d5289b3492cb7da56a835b8d45f.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"知否|秃头后多吃黑芝麻能生发?你可能想多了",
"docurl":"https://tech.163.com/19/0620/07/EI3K10OG000999DH.html",
"commenturl":"http://comment.tie.163.com/EI3K10OG000999DH.html",
"tienum":12,
"tlastid":"<a href='https://tech.163.com/19/0620/07/EI3K10OG000999DH.html' class='link'>其它</a>",
"tlink":"https://tech.163.com/19/0620/07/EI3K10OG000999DH.html",
"label":"其它",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/9/d/9ed1829d9ebb/1.html",
"keyname":"黑芝麻"
},
{
"akey_link":"http://tech.163.com/keywords/8/3/813153d1/1.html",
"keyname":"脱发"
},
{
"akey_link":"http://tech.163.com/keywords/7/a/76ae8102/1.html",
"keyname":"皮脂"
}
],
"time":"06/20/2019 07:02:38",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/19/fe690deb841842f5ba779c71163558b9.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"最高法:区块链利于完善电子证据应用",
"docurl":"https://tech.163.com/19/0620/11/EI43V2F500097U7R.html",
"commenturl":"http://comment.tie.163.com/EI43V2F500097U7R.html",
"tienum":0,
"tlastid":"<a href='http://tech.163.com/internet/' class='link'>互联网</a>",
"tlink":"http://tech.163.com/internet/",
"label":"互联网",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/6/0/67009ad86cd5/1.html",
"keyname":"最高法"
},
{
"akey_link":"http://tech.163.com/keywords/5/3/533a575794fe/1.html",
"keyname":"区块链"
}
],
"time":"06/20/2019 11:41:11",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/3ba0cd9426ee41c197b092394ef929f8.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
},
{
"title":"中国下一代碳纤维地铁列车成功试跑:减重13%",
"docurl":"https://tech.163.com/19/0620/08/EI3OOHUQ00097U81.html",
"commenturl":"http://comment.tie.163.com/EI3OOHUQ00097U81.html",
"tienum":29,
"tlastid":"<a href='https://tech.163.com/19/0620/08/EI3OOHUQ00097U81.html' class='link'>科学探索</a>",
"tlink":"https://tech.163.com/19/0620/08/EI3OOHUQ00097U81.html",
"label":"科学探索",
"keywords":[
{
"akey_link":"http://tech.163.com/keywords/5/3/573094c1/1.html",
"keyname":"地铁"
},
{
"akey_link":"http://tech.163.com/keywords/7/b/78b37ea47ef4/1.html",
"keyname":"碳纤维"
},
{
"akey_link":"http://tech.163.com/keywords/7/1/7f167ec4/1.html",
"keyname":"编组"
}
],
"time":"06/20/2019 08:25:23",
"newstype":"article",
"imgurl":"http://cms-bucket.ws.126.net/2019/06/20/a2850c1b15554d758e16f07bbcf54c19.png?imageView&thumbnail=190y120",
"add1":"",
"add2":"",
"add3":""
}
]; | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/model/banner.dart | class MyBanner {
List<Data> data;
int errorCode;
String errorMsg;
MyBanner({this.data, this.errorCode, this.errorMsg});
MyBanner.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = [];
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
errorCode = json['errorCode'];
errorMsg = json['errorMsg'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
data['errorCode'] = this.errorCode;
data['errorMsg'] = this.errorMsg;
return data;
}
}
class Data {
String desc;
int id;
String imagePath;
int isVisible;
int order;
String title;
int type;
String url;
Data(
{this.desc,
this.id,
this.imagePath,
this.isVisible,
this.order,
this.title,
this.type,
this.url});
Data.fromJson(Map<String, dynamic> json) {
desc = json['desc'];
id = json['id'];
imagePath = json['imagePath'];
isVisible = json['isVisible'];
order = json['order'];
title = json['title'];
type = json['type'];
url = json['url'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['desc'] = this.desc;
data['id'] = this.id;
data['imagePath'] = this.imagePath;
data['isVisible'] = this.isVisible;
data['order'] = this.order;
data['title'] = this.title;
data['type'] = this.type;
data['url'] = this.url;
return data;
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/model/News.dart | class News {
String reason;
Result result;
int errorCode;
News({this.reason, this.result, this.errorCode});
News.fromJson(Map<String, dynamic> json) {
reason = json['reason'];
result =
json['result'] != null ? new Result.fromJson(json['result']) : null;
errorCode = json['error_code'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['reason'] = this.reason;
if (this.result != null) {
data['result'] = this.result.toJson();
}
data['error_code'] = this.errorCode;
return data;
}
}
class Result {
String stat;
List<Data> data;
Result({this.stat, this.data});
Result.fromJson(Map<String, dynamic> json) {
stat = json['stat'];
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['stat'] = this.stat;
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
String uniquekey;
String title;
String date;
String category;
String authorName;
String url;
String thumbnailPicS;
String thumbnailPicS02;
String thumbnailPicS03;
Data(
{this.uniquekey,
this.title,
this.date,
this.category,
this.authorName,
this.url,
this.thumbnailPicS,
this.thumbnailPicS02,
this.thumbnailPicS03});
Data.fromJson(Map<String, dynamic> json) {
uniquekey = json['uniquekey'];
title = json['title'];
date = json['date'];
category = json['category'];
authorName = json['author_name'];
url = json['url'];
thumbnailPicS = json['thumbnail_pic_s'];
thumbnailPicS02 = json['thumbnail_pic_s02'];
thumbnailPicS03 = json['thumbnail_pic_s03'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uniquekey'] = this.uniquekey;
data['title'] = this.title;
data['date'] = this.date;
data['category'] = this.category;
data['author_name'] = this.authorName;
data['url'] = this.url;
data['thumbnail_pic_s'] = this.thumbnailPicS;
data['thumbnail_pic_s02'] = this.thumbnailPicS02;
data['thumbnail_pic_s03'] = this.thumbnailPicS03;
return data;
}
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tool/shared_preferences_utils.dart | import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SharedPreferencesUtils {
static Object savePreference( String key , Object value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if(value is int ){
await prefs.setInt(key, value);
}else if(value is double){
await prefs.setDouble(key, value);
}else if(value is bool){
await prefs.setBool(key, value);
}else if(value is String){
await prefs.setString(key, value);
}else if(value is List){
await prefs.setStringList(key, value);
} else {
throw new Exception("不能得到这种类型");
}
}
/***
* 取数据
*
*/
static Future getPreference( String key ,Object defaultValue) async{
SharedPreferences prefs = await SharedPreferences.getInstance();
if(defaultValue is int) {
return prefs.getInt(key);
}
else if(defaultValue is double) {
return prefs.getDouble(key);
}
else if(defaultValue is bool) {
return prefs.getBool(key);
}
else if(defaultValue is String) {
return prefs.getString(key);
}
else if(defaultValue is List) {
return prefs.getStringList(key);
}
else {
throw new Exception("不能得到这种类型");
}
}
static get(String key, [dynamic replace]) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var data = prefs.get(key);
return data ?? replace ?? null;
}
/***
* 删除指定数据
*/
static void remove(String key)async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.remove(key); //删除指定键
}
/***
* 清空整个缓存
*/
static void clear()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.clear(); ////清空缓存
}
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tool/app_theme.dart | import 'package:flutter/material.dart';
class AppTheme {
// 1.抽取相同的样式
static const double _titleFontSize = 20;
final ThemeData theme = ThemeData();
// 2.亮色主题
static final ThemeData lightTheme = ThemeData(
// Define the default brightness and colors.
brightness: Brightness.light,
primarySwatch: Colors.green,
fontFamily: 'Georgia',
textTheme: const TextTheme(
headline1: TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
);
// 3.暗黑主题
static final ThemeData darkTheme = ThemeData(
brightness: Brightness.dark,
fontFamily: 'Georgia',
textTheme: const TextTheme(
headline1: TextStyle(fontSize: 32.0, fontWeight: FontWeight.bold),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
);
}
| 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tool/config.dart | import 'package:flutter/material.dart';
List bottomNavBarList = [
{'title': "首页", 'icon': Icons.home},
{'title': "代码", 'icon': Icons.code},
{'title': "课程", 'icon': Icons.book},
{'title': "我的", 'icon': Icons.person},
];
class AssetAudioPlayerIcons {
AssetAudioPlayerIcons._();
static const _kFontFam = 'AssetAudioPlayer';
static const IconData play = IconData(0xe800, fontFamily: _kFontFam);
static const IconData stop = IconData(0xe801, fontFamily: _kFontFam);
static const IconData pause = IconData(0xe802, fontFamily: _kFontFam);
static const IconData to_end = IconData(0xe803, fontFamily: _kFontFam);
static const IconData to_start = IconData(0xe804, fontFamily: _kFontFam);
} | 0 |
mirrored_repositories/flutter100days/lib | mirrored_repositories/flutter100days/lib/tool/tools.dart | import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
void showWarnToast(String text) {
Fluttertoast.showToast(
msg: text,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
void showSnackBar(BuildContext context, String text, {String subTitle: '关闭'}) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(text),
backgroundColor: Colors.black54,
elevation: 10,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
behavior: SnackBarBehavior.floating,
action: SnackBarAction(
label: subTitle,
onPressed: () {
ScaffoldMessenger.of(context).removeCurrentSnackBar();
},
),
duration: Duration(seconds: 5),
onVisible: () {
print('显示');
},
),
);
}
Widget myTooltip(String s) {
return Tooltip(
message: s,
padding: EdgeInsets.all(10),
margin: EdgeInsets.only(left: 100),
verticalOffset: 10,
// preferBelow: false,
decoration: BoxDecoration(
color: Colors.amber, borderRadius: BorderRadius.circular(10)),
textStyle: TextStyle(
color: Colors.black,
fontSize: 16,
),
showDuration: Duration(seconds: 5),
child: Text(s),
);
}
Future alertDialog(BuildContext context) async {
var result = await showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text("提示信息"),
content: Text("您确定要删除吗"),
actions: <Widget>[
TextButton(
child: Text("取消"),
onPressed: () {
Navigator.pop(context, "cancel");
},
),
TextButton(
child: Text("确定"),
onPressed: () {
Navigator.pop(context, "ok");
},
),
],
);
});
return result;
}
Future alertSimpleDialog(BuildContext context) async {
var result = await showDialog(
context: context,
builder: (context) {
return SimpleDialog(
title: Text("提示"),
children: <Widget>[
TextButton(
child: Text("Option1"),
onPressed: () => Navigator.pop(context, "Option1"),
),
TextButton(
child: Text("Option2"),
onPressed: () => Navigator.pop(context, "Option2"),
),
TextButton(
child: Text("Option3"),
onPressed: () => Navigator.pop(context, "Option3"),
),
],
);
});
return result;
}
Future modeBottomDialog(BuildContext context) async {
var result = await showModalBottomSheet(
context: context,
builder: (context) {
return Container(
child: Column(
children: <Widget>[
ListTile(
title: Text("分享到 QQ"),
onTap: () {
Navigator.pop(context, "分享到 QQ");
}),
ListTile(
title: Text("分享到 微信 "),
onTap: () {
Navigator.pop(context, "分享到 微信");
}),
ListTile(
title: Text("分享到 微博"),
onTap: () {
Navigator.pop(context, "分享到 微博");
}),
ListTile(
title: Text("分享到 知乎"),
onTap: () {
Navigator.pop(context, "分享到 知乎");
}),
],
),
);
});
return result;
}
| 0 |
mirrored_repositories/flutter100days | mirrored_repositories/flutter100days/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_learn/drawer.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/Number_trivia_flutter | mirrored_repositories/Number_trivia_flutter/lib/main.dart | import 'dart:convert';
import 'dart:math';
import 'package:flutter/painting.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:giphy_client/giphy_client.dart';
import 'package:progress_dialog/progress_dialog.dart';
ProgressDialog pr;
void main() => runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: MyTriviaApp(),
theme: ThemeData(
fontFamily: 'Montserrat',
scaffoldBackgroundColor: Colors.white,
canvasColor: Colors.transparent),
));
class MyTriviaApp extends StatefulWidget {
@override
_MyTriviaAppState createState() => _MyTriviaAppState();
}
class _MyTriviaAppState extends State<MyTriviaApp> {
TextEditingController _MytextController = TextEditingController();
String query_val;
int num;
Future _fetchJson(BuildContext context) async {
num = query_val == null ? Random().nextInt(100) : int.parse(query_val);
final client = GiphyClient(apiKey: 'API_KEY');
var url = 'http://numbersapi.com/$num?json';
final a = await client.random(tag: 'amazed');
print(a);
final gif_id = a.id;
var json_data = await http.get(url);
var trivia_data = jsonDecode(json_data.body);
var img_url = "https://media.giphy.com/media/$gif_id/giphy.gif";
_showModulSheet(context, trivia_data['text'], img_url);
}
_showModulSheet(context, String text, String gif) {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topRight: Radius.circular(20.0),
topLeft: Radius.circular(20.0))),
child: Container(
padding: EdgeInsets.all(16.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'Fact about $num',
style: TextStyle(fontSize: 30.0, color: Colors.black),
),
SizedBox(
height: 10.0,
),
Text(
'$text',
style: TextStyle(fontSize: 20.0, color: Colors.black),
),
Center(
child: Container(
margin: EdgeInsets.only(top: 20.0),
decoration: BoxDecoration(),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
child: Image(
height: 150.0,
image: NetworkImage(gif),
),
)),
)
],
),
),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xFF000051),
elevation: 0.0,
title:
Text('Number Trivia', style: TextStyle(fontFamily: 'Montserrat')),
centerTitle: true,
),
body: SingleChildScrollView(
child: Column(
children: <Widget>[
Container(
width: MediaQuery.of(context).size.width,
height: 250.0,
decoration: BoxDecoration(
color: Color(0xFF000051),
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(50.0),
bottomRight: Radius.circular(50.0))),
child: Stack(
// crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding:
EdgeInsets.only(left: 15.0, top: 80.0, bottom: 0.0),
child: Text(
'Bored ?',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 60.0),
),
),
Container(
padding:
EdgeInsets.only(left: 15.0, top: 160.0, bottom: 0.0),
child: Text(
'Try this random number trivia and get amazed 😉 ',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
fontSize: 20.0),
),
),
],
),
),
Container(
margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 50.0),
width: double.infinity,
height: 50.0,
child: ClipRRect(
child: TextField(
controller: _MytextController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
border: OutlineInputBorder(),
contentPadding: EdgeInsets.all(15.0),
fillColor: Color(0xFFffffff),
hintText: "Enter any number",
hintStyle: TextStyle(
fontSize: 20.0,
)),
onSubmitted: (val) {
setState(() {
query_val = val;
});
_fetchJson(context);
},
),
),
),
Container(
margin: EdgeInsets.only(top: 10.0),
child: Text(
'Or',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
color: Colors.blue[900]),
),
),
Container(
margin: EdgeInsets.only(left: 10.0, right: 10.0, top: 10.0),
width: double.infinity,
height: 50.0,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(20.0)),
child: ElevatedButton(
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all(Color(0xFF0C35B1)),
),
onPressed: () {
if (query_val != null) {
setState(() {
query_val = null;
Future.delayed(Duration(seconds: 10)).then((onValue) {
print("PR status ${pr.isShowing()}");
if (pr.isShowing()) pr.hide();
print("PR status ${pr.isShowing()}");
});
});
}
_fetchJson(context);
},
child: Text(
'Get a random number trivia',
style: TextStyle(fontSize: 20.0, color: Colors.white),
),
),
),
),
Container(
width: 300.0,
margin: EdgeInsets.only(top: 10.0),
decoration: BoxDecoration(),
child: Image(
image: AssetImage('assets/images/numbers.jpg'),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flood | mirrored_repositories/flood/lib/main.dart | import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(App());
class App extends StatelessWidget {
@override
Widget build(ctx) =>
MaterialApp(home: Game(), debugShowCheckedModeBanner: false);
}
class Game extends StatefulWidget {
@override
_Game createState() => _Game();
}
class _Game extends State<Game> {
int siz = 14, max = 30, mov = 0, bst = 0;
List<Color> clr = [
Colors.red,
Colors.blue,
Colors.green,
Colors.orange,
Colors.purple,
Colors.yellow,
];
List<List<int>> brd = [];
dlg(w) =>
showDialog(context: context, builder: (_) => AlertDialog(content: w));
gen() {
List<List<int>> _brd = [];
Random random = new Random.secure();
for (int i = 0; i < siz; i++) {
List<int> r = [];
for (int j = 0; j < siz; j++) r.add(random.nextInt(clr.length));
_brd.add(r);
}
setState(() {
mov = 0;
brd = _brd;
});
}
los() => mov >= max;
pad(c, [p = 8.0]) => Padding(padding: EdgeInsets.all(p), child: c);
pnt(int c, int r, int color) {
int oldColor = brd[c][r];
setState(() {
brd[c][r] = color;
});
if (c - 1 >= 0 && brd[c - 1][r] == oldColor) pnt(c - 1, r, color);
if (r + 1 < siz && brd[c][r + 1] == oldColor) pnt(c, r + 1, color);
if (c + 1 < siz && brd[c + 1][r] == oldColor) pnt(c + 1, r, color);
if (r - 1 >= 0 && brd[c][r - 1] == oldColor) pnt(c, r - 1, color);
}
prf() => SharedPreferences.getInstance();
sel(int color) {
if (brd[0][0] == color || win() || los()) return false;
setState(() {
mov += 1;
});
pnt(0, 0, color);
if (win())
dlg(Image.asset('assets/images/win.png', fit: BoxFit.contain));
else if (los())
dlg(Image.asset('assets/images/lost.png', fit: BoxFit.contain));
}
txt(s, [f = 14.0]) =>
Text(s, style: TextStyle(fontSize: f, color: Colors.black));
win() {
int color = brd[0][0];
for (int i = 0; i < siz; i++)
for (int j = 0; j < siz; j++) if (color != brd[i][j]) return false;
if (bst == null || mov < bst) {
setState(() => bst = mov);
prf().then((prefs) => prefs.setInt('best', mov));
}
return true;
}
@override
void initState() {
super.initState();
gen();
prf().then((prefs) => setState(() => bst = prefs.get('best')));
}
@override
Widget build(BuildContext ctx) => Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
brightness: Platform.isIOS ? Brightness.light : Brightness.dark,
iconTheme: IconThemeData(color: Colors.black),
elevation: 0,
actions: <Widget>[
IconButton(
icon: Icon(Icons.help),
onPressed: () => dlg(
Image.asset('assets/images/help.png', fit: BoxFit.contain))),
IconButton(icon: Icon(Icons.refresh), onPressed: () => gen())
],
),
body: pad(Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Column(children: [
txt('MOVES'),
txt(mov.toString() + '/' + max.toString(), 28.0)
]),
Flexible(
child: pad(GridView.count(
primary: false,
mainAxisSpacing: 2,
crossAxisSpacing: 2,
crossAxisCount: siz,
children: brd
.expand((pair) => pair)
.toList()
.map((int v) => GridTile(child: Container(color: clr[v])))
.toList()))),
pad(Column(children: [
txt('HIGH SCORE'),
txt((bst ?? '-').toString(), 24.0)
])),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: clr
.map((color) => ButtonTheme(
minWidth: 32,
child: RaisedButton(
elevation: 0,
color: color,
shape: CircleBorder(),
onPressed: () =>
sel(clr.indexWhere((_color) => _color == color)))))
.toList(),
)
],
)));
}
| 0 |
mirrored_repositories/Magic-8-Ball | mirrored_repositories/Magic-8-Ball/lib/main.dart | import 'package:flutter/material.dart';
import 'dart:math';
void main() => runApp(
MaterialApp(
home: BallPage(),
),
);
class BallPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blue,
appBar: AppBar(
backgroundColor: Colors.blue.shade900,
title: Text('Ask Me Anything'),
),
body: Ball(),
);
}
}
class Ball extends StatefulWidget {
@override
_BallState createState() => _BallState();
}
class _BallState extends State<Ball> {
int ballNumber = 1;
@override
Widget build(BuildContext context) {
return Center(
child: FlatButton(
child: Image.asset('images/ball$ballNumber.png'),
onPressed:(){
setState(() {
ballNumber = Random().nextInt(5) + 1;
});
},
),
);
}
}
| 0 |
mirrored_repositories/digifarmer | mirrored_repositories/digifarmer/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:digi_farmer/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/whalert | mirrored_repositories/whalert/lib/generated_plugin_registrant.dart | //
// Generated file. Do not edit.
//
import 'package:audioplayers/audioplayers_web.dart';
import 'package:flutter_web_plugins/flutter_web_plugins.dart';
// ignore: public_member_api_docs
void registerPlugins(Registrar registrar) {
AudioplayersPlugin.registerWith(registrar);
registrar.registerMessageHandler();
}
| 0 |
mirrored_repositories/whalert | mirrored_repositories/whalert/lib/main.dart | import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/routes/data_logs_route.dart';
import 'package:flutter_trading_volume/utils/utils.dart';
import 'package:flutter_trading_volume/websockets/callbacks/exchange_callbacks.dart';
import 'package:flutter_trading_volume/websockets/manager/exchange_manager.dart';
import 'package:flutter_trading_volume/widgets/custom_drawer.dart';
import 'package:google_fonts/google_fonts.dart';
import 'models/trade_logs.dart';
import 'models/trades/base_trade.dart';
import 'routes/donation_route.dart';
import 'utils/decimal_text_input_formatter.dart';
final SNACKBAR_ALREADY_STARTED =
SnackBar(content: Text('Please stop recording before change pairs!'));
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Whalert',
theme: ThemeData(
fontFamily: GoogleFonts.montserrat().fontFamily,
textTheme: GoogleFonts.montserratTextTheme(Theme.of(context).textTheme),
primaryColor: Color.fromARGB(255, 14, 38, 72),
primaryColorDark: Color.fromARGB(255, 5, 22, 47),
accentColor: Color.fromARGB(255, 65, 106, 163),
),
home: TradeHomePage(title: 'Whalert'),
);
}
}
class TradeHomePage extends StatefulWidget {
TradeHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_TradeHomePageState createState() => _TradeHomePageState();
}
class _TradeHomePageState extends State<TradeHomePage> implements ExchangeCallbacks {
ExchangeManager _exchangeSockets;
AudioPlayer audioPlayer = AudioPlayer();
List<TradeLogs> _collectedTrades = [];
Map<int, double> _prices = new Map();
String _startTime = 'NoTime';
String _endTime = 'NoTime';
bool _started = false;
double _cumulativeQuantity = 0;
double _cumulativePrice = 0;
double _currentQtySliderValue = 10;
//Deltas
double _quantityDelta = 0;
double _quantityBuy = 0;
double _quantitySell = 0;
double _valueDelta = 0;
double _valueBuy = 0;
double _valueSell = 0;
SupportedPairs _currentPair = SupportedPairs.BTC_USDT;
OrderType _currentOrderType = OrderType.SELL;
//SupportedExchange _currentExchange = SupportedExchange.ALL;
final GlobalKey<DataLogsRouteState> _callDataLogs = GlobalKey<DataLogsRouteState>();
DataLogsRoute _dataLogsRoute;
void play() async {
await audioPlayer.play('beep.mp3');
}
@override
void initState() {
super.initState();
_dataLogsRoute = DataLogsRoute(
title: 'Logs', logs: _collectedTrades, key: _callDataLogs);
_exchangeSockets = ExchangeManager(_currentPair, this);
}
void _resetDeltas() {
_quantityDelta = 0;
_quantityBuy = 0;
_quantitySell = 0;
_valueDelta = 0;
_valueBuy = 0;
_valueSell = 0;
}
@override
void onTrade(BaseTrade trade, int id) {
setState(() {
_updateData(trade);
if(trade != null) {
_prices[id] = trade.price;
}
});
}
void _startStopSocket() {
if (!_started) {
setState(() {
_resetDeltas();
_prices.clear();
_cumulativeQuantity = 0;
_cumulativePrice = 0;
_endTime = '';
_startTime = DateTime.now().toString();
_started = true;
});
_exchangeSockets.connectToSocket();
} else {
setState(() {
_endTime = DateTime.now().toString();
_started = false;
});
_exchangeSockets.closeConnection();
}
}
bool _shouldLog(BaseTrade trade) {
var shouldLog = false;
switch (_currentOrderType) {
case OrderType.ALL:
shouldLog = true;
break;
case OrderType.BUY:
shouldLog = trade.orderType == OrderType.BUY;
break;
case OrderType.SELL:
shouldLog = trade.orderType == OrderType.SELL;
break;
}
return shouldLog;
}
double _averagePrice() {
double sum = 0;
int realLength = 0;
if(_prices.length == 0) {
return sum;
} else if (_prices.length == 1) {
return _prices.values.first ?? 0;
}
_prices.forEach((key, value) {
if(value > 0) {
realLength++;
sum += value;
}
});
return sum/realLength;
}
void _updateQuantityDelta(BaseTrade trade) {
setState(() {
if(trade.orderType == OrderType.BUY) {
_quantityBuy += trade.quantity;
} else if (trade.orderType == OrderType.SELL) {
_quantitySell += trade.quantity;
}
_quantityDelta = _quantityBuy-_quantitySell;
});
}
void _updateValueDelta(BaseTrade trade) {
setState(() {
if(trade.orderType == OrderType.BUY) {
_valueBuy += (trade.price*trade.quantity);
} else if (trade.orderType == OrderType.SELL) {
_valueSell += (trade.price*trade.quantity);
}
_valueDelta = _valueBuy-_valueSell;
});
}
void _updateData(BaseTrade trade) {
if (trade != null) {
if (trade.quantity >= _currentQtySliderValue && _shouldLog(trade)) {
//Set minimum qty to prevent beep on low qty orders.
if(_currentQtySliderValue >= 100) {
audioPlayer.play('assets/beep.mp3', isLocal: true);
}
setState(() {
_cumulativeQuantity += trade.quantity;
_cumulativePrice += (trade.price*trade.quantity);
var bl = new TradeLogs(
market: trade.market,
symbol: trade.symbol.isEmpty ? _currentPair.toShortString() : trade.symbol,
price: trade.price,
quantity: trade.quantity,
value: (trade.price*trade.quantity),
tradeTime: trade.tradeTime,
orderType: trade.orderType);
_collectedTrades.add(bl);
if(_callDataLogs != null && _callDataLogs.currentState != null)
_callDataLogs.currentState.addLogs(bl);
_updateQuantityDelta(trade);
_updateValueDelta(trade);
});
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
drawerEnableOpenDragGesture: false,
drawer: CustomDrawer(
onHomePressed: () {
Navigator.pop(context);
},
onDonationPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DonationRoute(title: 'Donation')));
},
),
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.white),
title: Text(
widget.title,
style: TextStyle(color: Colors.white),
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.settings,
color: Colors.white,
),
onPressed: () {
showDialog(context: context,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (context, setState) {
return Stack(
alignment: AlignmentDirectional.center,
children: [
Card(
margin: EdgeInsets.all(64),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(height: 16),
ListTile(
title: Text('Settings',
style:
TextStyle(fontWeight: FontWeight.bold, fontSize: 24)),
),
//Not enabled for now
/*Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Exchange: '),
DropdownButton<SupportedExchange>(
value: _currentExchange,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Theme.of(context).primaryColor),
underline: Container(
height: 2,
color: Theme.of(context).accentColor,
),
onChanged: (SupportedExchange newValue) {
setState(() {
if (_started) {
ScaffoldMessenger.of(context)
.showSnackBar(snackBar_alreadyStarted);
} else {
_currentExchange = newValue;
}
});
},
items: SupportedExchange.values
.map<DropdownMenuItem<SupportedExchange>>((SupportedExchange value) {
return DropdownMenuItem<SupportedExchange>(
value: value,
child: Text(value.toShortString()),
);
}).toList(),
),
],
),
),*/
Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Order Type: '),
DropdownButton<OrderType>(
value: _currentOrderType,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Theme.of(context).primaryColor),
underline: Container(
height: 2,
color: Theme.of(context).accentColor,
),
onChanged: (OrderType newValue) {
setState(() {
if (_started) {
ScaffoldMessenger.of(context)
.showSnackBar(SNACKBAR_ALREADY_STARTED);
} else {
_currentOrderType = newValue;
}
});
},
items: OrderType.values
.map<DropdownMenuItem<OrderType>>((OrderType value) {
return DropdownMenuItem<OrderType>(
value: value,
child: Text(value.toShortString()),
);
}).toList(),
),
],
),
),
Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Current Pair: '),
DropdownButton<SupportedPairs>(
value: _currentPair,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Theme.of(context).primaryColor),
underline: Container(
height: 2,
color: Theme.of(context).accentColor,
),
onChanged: (SupportedPairs newValue) {
setState(() {
if (_started) {
ScaffoldMessenger.of(context)
.showSnackBar(SNACKBAR_ALREADY_STARTED);
} else {
_currentPair = newValue;
_exchangeSockets.updatePairs(newValue);
}
});
},
items: SupportedPairs.values
.map<DropdownMenuItem<SupportedPairs>>((SupportedPairs value) {
return DropdownMenuItem<SupportedPairs>(
value: value,
child: Text(value.toShortString()),
);
}).toList(),
),
],
),
),
Padding(
padding: EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Text('Min Log Volume ($_currentQtySliderValue): '),
SizedBox(
width: 75,
child: TextFormField(
initialValue: _currentQtySliderValue.toString(),
inputFormatters: [DecimalTextInputFormatter(decimalRange: 6)],
keyboardType: TextInputType.numberWithOptions(decimal: true),
onChanged: (value) {
setState(() {
_currentQtySliderValue = double.parse(value);
});
},// Only numbers can be entered
),
),
]),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.end,
children: [
ButtonTheme(
minWidth: 100.0,
height: 50.0,
child: OutlineButton(
child: Text('Close', style: TextStyle(color: Theme.of(context).primaryColor)),
borderSide: BorderSide(
color: Theme.of(context).primaryColor,
style: BorderStyle.solid,
),
onPressed: () {
Navigator.pop(context);
},
),
),
SizedBox(width: 16),
],
),
SizedBox(height: 16),
],
),
)
],
);
},
);
}
);
},
)
],
),
body: ListView(
children: [
Card(
margin: EdgeInsets.all(16),
color: Colors.grey[200],
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(height: 16),
Text('Current supported exchange\n\nBinance, FTX, ByBit, BitMEX, Bitfinex, Kraken, Bitstamp, Coinbase, OKEx',
style: TextStyle(fontSize: 20),
textAlign: TextAlign.center),
SizedBox(height: 16),
],
),
),
Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Card(
margin: EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
SizedBox(height: 32),
Text(
_currentPair.toShortString(),
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 32),
),
SizedBox(height: 16),
Text(
'Price: ${_averagePrice().toStringAsFixed(4) ?? 0}\$',
style: TextStyle(fontSize: 18)),
SizedBox(height: 8),
Text(
'Quantity executed: ${humanReadableNumberGenerator(_cumulativeQuantity)}',
style: TextStyle(fontSize: 18)),
SizedBox(height: 8),
Text(
'Cumulative Value: ${humanReadableNumberGenerator(_cumulativePrice)}\$',
style: TextStyle(fontSize: 18)),
SizedBox(height: 32),
Text(
'Started At: ' + _startTime,
),
Text(
'Ended At: ' + _endTime,
),
SizedBox(height: 56),
],
),
),
),
Expanded(
child: Card(
margin: EdgeInsets.all(16),
child: Column(
mainAxisSize: MainAxisSize.max,
children: [
SizedBox(height: 32),
Text('Analysis',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 32),),
SizedBox(height: 16),
RichText(
text: TextSpan(
text: "Quantity Delta (Buy-Sell): ",
style: TextStyle(color: Colors.black, fontFamily: GoogleFonts.montserrat().fontFamily, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: '${humanReadableNumberGenerator(_quantityDelta)}',
style: TextStyle(color: _quantityDelta.isNegative ? Colors.red : Colors.green,
fontFamily: GoogleFonts.montserrat().fontFamily)),
],
),
),
SizedBox(height: 8),
RichText(
text: TextSpan(
text: "Value Delta (Buy-Sell): ",
style: TextStyle(color: Colors.black, fontFamily: GoogleFonts.montserrat().fontFamily, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: '${humanReadableNumberGenerator(_valueDelta)}\$',
style: TextStyle(color: _valueDelta.isNegative ? Colors.red : Colors.green,
fontFamily: GoogleFonts.montserrat().fontFamily)),
],
),
),
SizedBox(height: 16),
RichText(
text: TextSpan(
text: "Quantity Buy: ",
style: TextStyle(color: Colors.black, fontFamily: GoogleFonts.montserrat().fontFamily, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: '${humanReadableNumberGenerator(_quantityBuy)}',
style: TextStyle(color: Colors.green,
fontFamily: GoogleFonts.montserrat().fontFamily)),
],
),
),
SizedBox(height: 8),
RichText(
text: TextSpan(
text: "Value Buy: ",
style: TextStyle(color: Colors.black, fontFamily: GoogleFonts.montserrat().fontFamily, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: '${humanReadableNumberGenerator(_valueBuy)}\$',
style: TextStyle(color: Colors.green,
fontFamily: GoogleFonts.montserrat().fontFamily)),
],
),
),
SizedBox(height: 16),
RichText(
text: TextSpan(
text: "Quantity Sell: ",
style: TextStyle(color: Colors.black, fontFamily: GoogleFonts.montserrat().fontFamily, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: '${humanReadableNumberGenerator(_quantitySell)}',
style: TextStyle(color: Colors.red,
fontFamily: GoogleFonts.montserrat().fontFamily)),
],
),
),
SizedBox(height: 8),
RichText(
text: TextSpan(
text: "Value Sell: ",
style: TextStyle(color: Colors.black, fontFamily: GoogleFonts.montserrat().fontFamily, fontSize: 18),
children: <TextSpan>[
TextSpan(
text: '${humanReadableNumberGenerator(_valueSell)}\$',
style: TextStyle(color: Colors.red,
fontFamily: GoogleFonts.montserrat().fontFamily)),
],
),
),
SizedBox(height: 16),
],
),
),
)
],
)
],
),
floatingActionButton: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => _dataLogsRoute),
);
},
backgroundColor: Colors.white,
child: Icon(Icons.list,
color: Theme.of(context).accentColor,
),
),
SizedBox(height: 16),
FloatingActionButton(
heroTag: null,
onPressed: _startStopSocket,
backgroundColor: Theme.of(context).accentColor,
child: Icon(
_started ? Icons.pause : Icons.play_arrow,
color: Colors.white,
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/widgets/custom_drawer.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_trading_volume/utils/constants.dart';
import 'package:yaml/yaml.dart';
import 'package:universal_html/html.dart' as html;
class CustomDrawer extends StatelessWidget {
final VoidCallback onHomePressed;
final VoidCallback onDonationPressed;
CustomDrawer({ @required this.onHomePressed, @required this.onDonationPressed});
@override
Widget build(BuildContext context) {
return Drawer(
child: Container(
child: Column(
children: <Widget>[
DrawerHeader(
padding: EdgeInsets.zero,
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('/graphics/drawer_header.jpg'),
fit: BoxFit.cover
),
),
),
Expanded(
child: Column(children: <Widget>[
ListTile(
leading: Icon(Icons.home),
title: Text('Home'),
onTap: () {
onHomePressed.call();
},
),
ListTile(
leading: Icon(Icons.favorite),
title: Text('Donation'),
onTap: () {
onDonationPressed.call();
},
),
]),
),
Container(
child: Align(
alignment: FractionalOffset.bottomCenter,
child: Column(
children: <Widget>[
ListTile(
leading: Icon(Icons.account_tree),
title: Text('Github'),
onTap: () {
html.window.open(GITHUB_URL, 'Github');
},
),
Divider(),
ListTile(
title: FutureBuilder(
future: rootBundle.loadString("pubspec.yaml"),
builder: (context, snapshot) {
String version = "Unknown";
if (snapshot.hasData) {
var yaml = loadYaml(snapshot.data);
version = yaml["version"];
}
return Container(
child: Text('Version: $version'),
);
}),
),
],
))),
],
),
),
);
}
}
| 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/routes/data_logs_route.dart | import 'package:csv/csv.dart';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'package:flutter_trading_volume/models/trade_logs.dart';
import 'package:flutter_trading_volume/utils/utils.dart';
class DataLogsSource extends DataTableSource {
final List<TradeLogs> logs;
int _selectedCount = 0;
DataLogsSource({this.logs});
void updateLogs(List<TradeLogs> updated) {
logs.addAll(updated);
notifyListeners();
}
void _sort<T>(Comparable<T> getField(TradeLogs d), bool ascending) {
logs.sort((TradeLogs a, TradeLogs b) {
if (!ascending) {
final TradeLogs c = a;
a = b;
b = c;
}
final Comparable<T> aValue = getField(a);
final Comparable<T> bValue = getField(b);
return Comparable.compare(aValue, bValue);
});
notifyListeners();
}
@override
DataRow getRow(int index) {
assert(index >= 0);
if (index >= logs.length)
return null;
final TradeLogs element = logs[index];
return new DataRow.byIndex(
index: index,
cells: <DataCell>[
DataCell(Text(element.market)),
DataCell(Text(element.symbol)),
DataCell(Text(element.orderType.toShortString(),
style: TextStyle(
color:
element.orderType == OrderType.SELL
? Colors.red
: Colors.green))),
DataCell(Text(element.price.toString())),
DataCell(Text(humanReadableNumberGenerator(element.quantity))),
DataCell(Text(humanReadableNumberGenerator(element.value))),
DataCell(Text(element.tradeTime)),
]
);
}
@override
int get rowCount => logs.length;
@override
bool get isRowCountApproximate => false;
@override
int get selectedRowCount => _selectedCount;
}
class DataLogsRoute extends StatefulWidget {
final String title;
final List<TradeLogs> logs;
DataLogsRoute({Key key, this.title, this.logs}) : super(key: key);
@override
DataLogsRouteState createState() => DataLogsRouteState();
}
class DataLogsRouteState extends State<DataLogsRoute> {
bool _sortAscending = false;
List<TradeLogs> internalLog = [];
DataLogsSource _logsDataSource;
int _sortColumnIndex;
@override
void initState(){
super.initState();
_logsDataSource = new DataLogsSource(logs: widget.logs);
}
void addLogs(TradeLogs log) {
internalLog.add(log);
if(internalLog.length == 10) {
setState(() {
/*if(widget.logs.length == 200) {
widget.logs.clear();
}*/
widget.logs.addAll(internalLog);
_logsDataSource.updateLogs(internalLog);
_sort<String>((TradeLogs t) => t.tradeTime, 0, false);
internalLog.clear();
});
}
}
void _sort<T>(Comparable<T> getField(TradeLogs d), int columnIndex, bool ascending) {
_logsDataSource._sort<T>(getField, ascending);
setState(() {
_sortColumnIndex = columnIndex;
_sortAscending = ascending;
});
}
void _exportAsCsv() {
List<List<dynamic>> rows = [[]];
//Adding header, maybe we can improve this...
List<dynamic> row = [];
row.add('Exchange');
row.add('Pair');
row.add('Order Type');
row.add('Price');
row.add('Quantity');
row.add('Value');
row.add('Time');
rows.add(row);
//Adding rows.
widget.logs.forEach((element) {
List<dynamic> row = [];
row.add(element.market);
row.add(element.symbol);
row.add(element.orderType.toShortString());
row.add(element.price);
row.add(element.quantity);
row.add(element.value);
row.add(element.tradeTime);
rows.add(row);
});
final csv = const ListToCsvConverter().convert(rows);
downloadStringAsCsv(csv);
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton(
onPressed: _exportAsCsv,
backgroundColor: Theme.of(context).accentColor,
child: Icon(Icons.download_outlined,
color: Colors.white,
),
),
body: ListView(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
PaginatedDataTable(
rowsPerPage: 15,
sortColumnIndex: _sortColumnIndex,
sortAscending: _sortAscending,
columns: [
DataColumn(
numeric: false,
label: Text(
'Exchange',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.market, columnIndex, ascending)
),
DataColumn(
numeric: false,
label: Text(
'Pair',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.symbol, columnIndex, ascending),
),
DataColumn(
numeric: false,
label: Text(
'Type',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.orderType.toShortString(), columnIndex, ascending),
),
DataColumn(
numeric: true,
label: Text(
'Price (\$)',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.price.toString(), columnIndex, ascending),
),
DataColumn(
numeric: true,
label: Text(
'Quantity',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.quantity.toString(), columnIndex, ascending),
),
DataColumn(
numeric: true,
label: Text(
'Value (\$)',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.value.toString(), columnIndex, ascending),
),
DataColumn(
numeric: false,
label: Text(
'Time',
style: TextStyle(fontStyle: FontStyle.italic),
),
onSort: (columnIndex, ascending) => _sort<String>((TradeLogs t) => t.tradeTime, columnIndex, ascending),
),
],
source: _logsDataSource,
),
],
)
],
),
);
}
}
| 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/routes/donation_route.dart | import 'package:clipboard/clipboard.dart';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/utils/constants.dart';
import 'package:flutter_trading_volume/widgets/custom_drawer.dart';
import '../main.dart';
final snackBar = SnackBar(
content: Text('Copied to Clipboard'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {},
),
);
class DonationRoute extends StatefulWidget {
DonationRoute({Key key, this.title}) : super(key: key);
final String title;
@override
_DonationRouteState createState() => _DonationRouteState();
}
class _DonationRouteState extends State<DonationRoute> {
@override
Widget build(BuildContext context) {
return Scaffold(
drawer: CustomDrawer(
onHomePressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => TradeHomePage(title: 'Home')),
);
},
onDonationPressed: () {
Navigator.pop(context);
},
),
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.white),
title: Text(
widget.title,
style: TextStyle(color: Colors.white),
),
),
body: ListView(children: [
Card(
margin: EdgeInsets.all(32),
child: InkWell(
onTap: () {
FlutterClipboard.copy(WALLET_PUBLIC_ADDR).then((value) =>
{ScaffoldMessenger.of(context).showSnackBar(snackBar)});
},
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(height: 64),
Text(
'If you like this project and you want to contribute, there is a BTC wallet address, thanks!',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 24)),
SizedBox(height: 32),
Image(image: AssetImage('graphics/qr_code.png')),
SizedBox(height: 64),
Text(WALLET_PUBLIC_ADDR),
SizedBox(height: 64),
],
),
),
),
]),
);
}
}
| 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/models/supported_exchange.dart | enum SupportedExchange {
ALL,
FTX,
BINANCE
}
extension toString on SupportedExchange {
String toShortString() {
return this.toString().split('.').last;
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/models/supported_pairs.dart | enum SupportedPairs {
BTC_USDT,
ETH_USDT,
BNB_USDT,
YFI_USDT,
XRP_USDT,
ADA_USDT,
LINK_USDT,
SUSHI_USDT,
UNI_USDT,
DOT_USDT,
}
extension toString on SupportedPairs {
String toShortString() {
return this.toString().split('.').last.replaceAll('_', '');
}
String toStringWithCustomReplace(String char) {
return this.toString().split('.').last.replaceAll('_', char);
}
String toStringUSD() {
return this.toString().split('.').last.replaceAll('_', '').replaceAll('USDT', 'USD');
}
String toStringCustomUSD(String char) {
return this.toString().split('.').last.replaceAll('_', char).replaceAll('USDT', 'USD');
}
String toStringXBT() {
return this.toString().split('.').last.replaceAll('_', '').replaceAll('USDT', 'USD').replaceAll('BTC', 'XBT');
}
String toStringCustomXBT(String char) {
return this.toString().split('.').last.replaceAll('_', char).replaceAll('USDT', 'USD').replaceAll('BTC', 'XBT');
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/models/trade_logs.dart | import 'package:flutter_trading_volume/models/order_type.dart';
class TradeLogs {
final String market;
final String symbol;
final double price;
final double quantity;
final double value;
final String tradeTime;
final OrderType orderType;
TradeLogs({
this.market,
this.symbol,
this.price,
this.quantity,
this.value,
this.tradeTime,
this.orderType});
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/models/order_type.dart | enum OrderType {
ALL,
BUY,
SELL
}
extension toString on OrderType {
String toShortString() {
return this.toString().split('.').last;
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/okex_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class OkExData {
final double price;
final double size;
final OrderType side;
final String time;
OkExData(
{this.price, this.size, this.side, this.time});
factory OkExData.fromJson(dynamic jsonData) {
return OkExData(
price: double.parse(jsonData['price'] ?? '0'),
size: double.parse(jsonData['size'] ?? '0'),
side: (jsonData['side'] as String).contains('buy') ? OrderType.BUY : OrderType.SELL,
time: jsonData['timestamp'] as String
);
}
}
class OkExTrade extends BaseTrade{
OkExTrade({
symbol,
price,
quantity,
orderType,
tradeTime}) : super(market: 'OKEx', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
{
"table":"spot/trade",
"data":[{
"side":"sell",
"trade_id":"129747847",
"price":"18404.1",
"size":"0.01",
"instrument_id":"BTC-USDT",
"timestamp":"2020-12-12T09:11:41.044Z"}]
}
*/
static List<OkExTrade> fromJson(String jsonAsString) {
final List<OkExTrade> resultTrade = [];
if(jsonAsString == null || jsonAsString.contains('subscribe')) return null;
final jsonData = json.decode(jsonAsString);
final dataJson = jsonData['data'] as List;
List<OkExData> tradeData = dataJson.map((okExJson) => OkExData.fromJson(okExJson)).toList();
if(tradeData.isEmpty) {
return null;
}
tradeData.forEach((element) {
resultTrade.add(new OkExTrade(
symbol: (jsonData['instrument_id'] as String ?? '').replaceAll('-', ''),
price: tradeData != null ? element.price ?? 0 : 0,
quantity: tradeData != null ? (element.size) ?? 0 : 0,
orderType: tradeData != null ? element.side : OrderType.ALL,
tradeTime: tradeData != null ? element.time : '0',
));
});
return resultTrade;
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/binance_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class BinanceTrade extends BaseTrade {
final String eventType;
final int eventTime;
final int tradeId;
final int buyerOrderId;
final int sellerOrderId;
BinanceTrade({
this.eventType,
this.eventTime,
symbol,
this.tradeId,
price,
quantity,
this.buyerOrderId,
this.sellerOrderId,
tradeTime,
orderType}) : super(market: 'Binance', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
/**
* {
"e": "trade", // Event type
"E": 123456789, // Event time
"s": "BNBBTC", // Symbol
"t": 12345, // Trade ID
"p": "0.001", // Price
"q": "100", // Quantity
"b": 88, // Buyer order ID
"a": 50, // Seller order ID
"T": 123456785, // Trade time
"m": true, // Is the buyer the market maker?
"M": true // Ignore
}
*/
factory BinanceTrade.fromJson(String jsonAsString) {
if(jsonAsString == null) return null;
final jsonData = json.decode(jsonAsString);
return BinanceTrade(
eventType: jsonData['e'] as String,
eventTime: jsonData['E'] as int,
symbol: jsonData['s'] as String,
tradeId: jsonData['t'] as int,
price: double.parse(jsonData['p'] ?? '0'),
quantity: double.parse(jsonData['q'] ?? '0'),
buyerOrderId: jsonData['b'] as int,
sellerOrderId: jsonData['a'] as int,
tradeTime: (jsonData['T'] != null ? DateTime.fromMillisecondsSinceEpoch((jsonData['T'] as int)).toString() : '0'),
orderType: jsonData['m'] != null ? (jsonData['m'] as bool ? OrderType.SELL : OrderType.BUY) : OrderType.ALL,
);
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/coinbase_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class CoinbaseTrade extends BaseTrade {
CoinbaseTrade({
symbol,
price,
quantity,
tradeTime,
orderType}) : super(market: 'Coinbase', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
{
"type": "ticker",
"trade_id": 20153558,
"sequence": 3262786978,
"time": "2017-09-02T17:05:49.250000Z",
"product_id": "BTC-USD",
"price": "4388.01000000",
"side": "buy", // Taker side
"last_size": "0.03000000",
"best_bid": "4388",
"best_ask": "4388.01"
}
*/
factory CoinbaseTrade.fromJson(String jsonAsString) {
if(jsonAsString == null) return null;
final jsonData = json.decode(jsonAsString);
return CoinbaseTrade(
symbol: jsonData['product_id'] as String,
price: double.parse(jsonData['price'] ?? '0'),
quantity: double.parse(jsonData['last_size'] ?? '0'),
tradeTime: jsonData['time'] as String,
orderType: jsonData['side'] != null ? (jsonData['side'].toString().contains('buy') ? OrderType.BUY : OrderType.SELL) : OrderType.ALL,
);
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/bitmex_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class BitmexData {
final String symbol;
final double price;
final double size;
final String side;
final String time;
BitmexData(
{this.symbol, this.price, this.size, this.side, this.time});
factory BitmexData.fromJson(dynamic jsonData) {
return BitmexData(
symbol: jsonData['symbol'] as String,
price: jsonData['price'] ?? 0,
size: jsonData['size'] ?? 0,
side: jsonData['side'] as String,
time: jsonData['timestamp'] as String
);
}
}
class BitmexTrade extends BaseTrade{
BitmexTrade({
symbol,
price,
quantity,
orderType,
tradeTime}) : super(market: 'BitMEX', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
{
"data":[
{
"timestamp":"2020-12-08T16:06:13.580Z",
"symbol":"XBTUSD",
"side":"Buy",
"size":1500, // 1 USD of BTC
"price":18813,
"tickDirection":"PlusTick",
"trdMatchID":"3539a9fa-ef88-4c25-6634-92997c69ec31",
"grossValue":7972500,
"homeNotional":0.079725,
"foreignNotional":1500
}
]
}
*/
factory BitmexTrade.fromJson(String jsonAsString) {
if(jsonAsString == null || jsonAsString.contains('subscribe') || jsonAsString.contains('info')) return null;
final jsonData = json.decode(jsonAsString);
var dataJson = jsonData['data'] as List;
List<BitmexData> tradeData = dataJson.map((bitmexJson) => BitmexData.fromJson(bitmexJson)).toList();
return BitmexTrade(
symbol: tradeData != null ? tradeData[0].symbol : '',
price: tradeData != null ? tradeData[0].price ?? 0 : 0,
quantity: tradeData != null ? (tradeData[0].size/tradeData[0].price) ?? 0 : 0,
orderType: tradeData != null ? (tradeData[0].side.contains('Buy') ? OrderType.BUY : OrderType.SELL) : OrderType.ALL,
tradeTime: tradeData != null ? tradeData[0].time : '0',
);
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/bitfinex_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class BitfinexTrade extends BaseTrade{
BitfinexTrade({
symbol,
price,
quantity,
orderType,
tradeTime}) : super(market: 'Bitfinex', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
* //CHANNEL_ID, te, SEQ, TIMESTAMP, AMOUNT, PRICE
[6702,"te",[540102695,1607537836202,0.0077,18377]]
*/
static List<BitfinexTrade> fromJson(String jsonAsString) {
final List<BitfinexTrade> resultTrade = [];
if(jsonAsString == null || jsonAsString.contains('subscribe')
|| jsonAsString.contains('info') || jsonAsString.contains('tu') ||
!jsonAsString.contains('te')) return null;
final jsonData = json.decode(jsonAsString) as List;
final dataArray = jsonData[2] as List;
if(dataArray.isEmpty) {
return null;
}
if(dataArray.length == 4) {
final tradeTime = jsonData[2][1] != null ? DateTime.fromMillisecondsSinceEpoch(jsonData[2][1] as int).toString() : '0';
final quantity = jsonData[2][2] != null ? jsonData[2][2] as double : 0;
final orderType = jsonData[2][2] != null ? ((jsonData[2][2] as double).isNegative ? OrderType.SELL : OrderType.BUY) : OrderType.ALL;
final price = jsonData[2][3] != null ? jsonData[2][3] as double : 0;
resultTrade.add(BitfinexTrade(
symbol: '',
price: price,
quantity: quantity,
orderType: orderType,
tradeTime: tradeTime,
));
} else if (dataArray.length > 4){
dataArray.forEach((element) {
final tradeTime = element[1] != null ? DateTime.fromMillisecondsSinceEpoch(element[1] as int).toString() : '0';
final quantity = element[2] != null ? double.parse(element[2]) : 0;
final orderType = element[2] != null ? ((element[2] as double).isNegative ? OrderType.SELL : OrderType.BUY) : OrderType.ALL;
final price = element[3] != null ? double.parse(element[3]) : 0;
resultTrade.add(BitfinexTrade(
symbol: '',
price: price,
quantity: quantity,
orderType: orderType,
tradeTime: tradeTime,
));
});
} else return null;
return resultTrade;
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/bybit_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class ByBitData {
final String symbol;
final double price;
final double size;
final String side;
final String time;
ByBitData(
{this.symbol, this.price, this.size, this.side, this.time});
factory ByBitData.fromJson(dynamic jsonData) {
return ByBitData(
symbol: jsonData['symbol'] as String,
price: jsonData['price'] ?? 0,
size: jsonData['size'] ?? 0,
side: jsonData['side'] as String,
time: jsonData['timestamp'] as String
);
}
}
class ByBitTrade extends BaseTrade{
ByBitTrade({
symbol,
price,
quantity,
orderType,
tradeTime}) : super(market: 'ByBit', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
* {
* "topic":"trade.BTCUSD",
"data": [
{
"trade_time_ms":1607440944799,
"timestamp":"2020-12-08T15:22:24.000Z",
"symbol":"BTCUSD",
"side":"Buy",
"size":1000, // 1 USD of BTC
"price":18836.5,
"tick_direction":"ZeroPlusTick",
"trade_id":"6706df9b-ca18-5625-8f8c-801f58496f0c",
"cross_seq":2699618710}
]
}
*/
factory ByBitTrade.fromJson(String jsonAsString) {
if(jsonAsString == null || jsonAsString.contains('subscribe')) return null;
final jsonData = json.decode(jsonAsString);
var dataJson = jsonData['data'] as List;
List<ByBitData> tradeData = dataJson.map((byBitJson) => ByBitData.fromJson(byBitJson)).toList();
return ByBitTrade(
symbol: tradeData != null ? tradeData[0].symbol : '',
price: tradeData != null ? tradeData[0].price ?? 0 : 0,
quantity: tradeData != null ? (tradeData[0].size/tradeData[0].price) ?? 0 : 0,
orderType: tradeData != null ? (tradeData[0].side.contains('Buy') ? OrderType.BUY : OrderType.SELL) : OrderType.ALL,
tradeTime: tradeData != null ? tradeData[0].time : '0',
);
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/bitstamp_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class BitstampData {
final double price;
final double size;
final OrderType side;
final String time;
BitstampData(
{this.price, this.size, this.side, this.time});
factory BitstampData.fromJson(dynamic jsonData) {
return BitstampData(
price: jsonData['price'] ?? 0,
size: jsonData['amount'] ?? 0,
side: jsonData['type'] as int == 0 ? OrderType.BUY : OrderType.SELL,
time: DateTime.fromMillisecondsSinceEpoch(int.parse(jsonData['timestamp'] as String)*1000).toString()
);
}
}
class BitstampTrade extends BaseTrade{
BitstampTrade({
symbol,
price,
quantity,
orderType,
tradeTime}) : super(market: 'Bitstamp', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
{"data":
{
"buy_order_id": 1305761191571458,
"amount_str": "0.02358000",
"timestamp": "1607624328",
"microtimestamp": "1607624328069000",
"id": 133112193,
"amount": 0.02358,
"sell_order_id": 1305761152376834,
"price_str": "18260.48",
"type": 0,
"price": 18260.48
},
"event": "trade", "channel": "live_trades_btcusd"}
*/
factory BitstampTrade.fromJson(String jsonAsString) {
if(jsonAsString == null || jsonAsString.contains('subscription')) return null;
final jsonData = json.decode(jsonAsString);
BitstampData tradeData = BitstampData.fromJson(jsonData['data']);
return BitstampTrade(
symbol: jsonData['channel'] != null ? jsonData['channel'].toString().replaceAll('live_trades_', '').toUpperCase() : '',
price: tradeData != null ? tradeData.price ?? 0 : 0,
quantity: tradeData != null ? (tradeData.size) ?? 0 : 0,
orderType: tradeData != null ? tradeData.side : OrderType.ALL,
tradeTime: tradeData != null ? tradeData.time : '0',
);
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/ftx_trade.dart | import 'dart:convert';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class FtxTradeData {
final int id;
final double price;
final double size;
final String side;
final bool liquidation;
final String time;
FtxTradeData(
{this.id, this.price, this.size, this.side, this.liquidation, this.time});
factory FtxTradeData.fromJson(dynamic jsonData) {
return FtxTradeData(
id: jsonData['id'] as int,
price: jsonData['price'] ?? 0,
size: jsonData['size'] ?? 0,
side: jsonData['side'] as String,
liquidation: jsonData['liquidation'] != null ? jsonData['liquidation'] as bool : false,
time: jsonData['time'] as String
);
}
}
class FtxTrade extends BaseTrade{
final bool liquidation;
FtxTrade({
symbol,
price,
quantity,
orderType,
this.liquidation,
tradeTime}) : super(market: 'FTX', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
* { "channel": "trades",
"market": "BTC/USDT",
"type": "update",
"data": [
{
"id": 218720629,
"price": 19144.0,
"size": 0.0002,
"side": "buy",
"liquidation": false,
"time": "2020-12-06T22:55:22.570088+00:00"
}
]
}
*/
static List<FtxTrade> fromJson(String jsonAsString) {
final List<FtxTrade> resultTrade = [];
if(jsonAsString == null || jsonAsString.contains('subscribed')) return null;
final jsonData = json.decode(jsonAsString);
var dataJson = jsonData['data'] as List;
List<FtxTradeData> tradeData = dataJson.map((ftxJson) => FtxTradeData.fromJson(ftxJson)).toList();
if(tradeData.isEmpty) {
return null;
}
tradeData.forEach((element) {
resultTrade.add(FtxTrade(
symbol: jsonData['market'] as String,
price: element != null ? element.price ?? 0 : 0,
quantity: element != null ? element.size ?? 0 : 0,
orderType: element != null ? (element.side.contains('buy') ? OrderType.BUY : OrderType.SELL) : OrderType.ALL,
liquidation: element != null ? (element.liquidation != null ? element.liquidation : false) : false,
tradeTime: element != null ? element.time : '0',
));
});
return resultTrade;
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/kraken_trade.dart | import 'dart:convert';
import 'dart:io';
import 'package:flutter_trading_volume/models/order_type.dart';
import 'base_trade.dart';
class KrakenTrade extends BaseTrade{
KrakenTrade({
symbol,
price,
quantity,
orderType,
tradeTime}) : super(market: 'Kraken', symbol: symbol, price: price,
quantity: quantity, tradeTime: tradeTime, orderType: orderType);
// ignore: slash_for_doc_comments
/**
[
0,
[
["5541.20000","0.15850568","1534614057.321597","s","l",""],
["6060.00000","0.02455000","1534614057.324998","b","l",""]
],
"trade",
"XBT/USD"
]
*/
static List<KrakenTrade> fromJson(String jsonAsString) {
final List<KrakenTrade> resultTrade = [];
if(jsonAsString == null || jsonAsString.contains('subscription')
|| jsonAsString.contains('event') || jsonAsString.contains('subscribe')) return null;
final jsonData = json.decode(jsonAsString) as List;
final dataArray = jsonData[1] as List;
final symbol = jsonData[3];
if(dataArray.isEmpty) {
return null;
}
dataArray.forEach((element) {
final price = element[0] != null ? double.parse(element[0]) : 0;
final quantity = element[1] != null ? double.parse(element[1]) : 0;
final tradeTime = element[2] != null ? DateTime.fromMillisecondsSinceEpoch(
int.parse(element[2].toString().split('.')[0])*1000).toString() : '0';
final orderType = element[3] != null ? (element[3].toString().contains('s') ? OrderType.SELL : OrderType.BUY) : OrderType.ALL;
resultTrade.add(KrakenTrade(
symbol: symbol,
price: price,
quantity: quantity,
orderType: orderType,
tradeTime: tradeTime,
));
});
return resultTrade;
}
} | 0 |
mirrored_repositories/whalert/lib/models | mirrored_repositories/whalert/lib/models/trades/base_trade.dart | import '../order_type.dart';
class BaseTrade {
final String market;
final String symbol;
final double price;
final double quantity;
final String tradeTime;
final OrderType orderType;
BaseTrade({
this.market,
this.symbol,
this.price,
this.quantity,
this.tradeTime,
this.orderType});
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/kraken_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class KrakenSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
KrakenSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://ws.kraken.com';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'event': subscribe ? 'subscribe' : 'unsubscribe',
'pair': ['${pair.toStringCustomXBT('/')}'],
'subscription': {
'name': 'trade'
}
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/bitfinex_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class BitfinexSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
BitfinexSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://api-pub.bitfinex.com/ws/2';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
if(!subscribe) {
return json.encode({
'event': 'unsubscribe',
'chanId': 0,
});
}
return json.encode({
'event': 'subscribe',
'channel': 'trades',
'symbol': '${pair.toStringUSD()}'
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/bybit_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class ByBitSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
ByBitSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://stream.bybit.com/realtime';
}
@override
//Unsubscribe not present in doc...
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'op': subscribe ? 'subscribe' : 'unsubscribe',
'args': ['trade.${pair.toStringUSD()}']
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/base_socket.dart | import 'package:web_socket_channel/html.dart';
abstract class BaseSocket {
HtmlWebSocketChannel connect();
void closeConnection();
String wsUrl();
String wsSubscribeUnsubscribeMessage({bool subscribe = true});
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/binance_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class BinanceSocket extends BaseSocket{
SupportedPairs pair;
HtmlWebSocketChannel socket;
BinanceSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://stream.binance.com:9443/ws/${pair.toShortString()}@trade';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'method': subscribe ? 'SUBSCRIBE' : 'UNSUBSCRIBE',
'params': ['${pair.toShortString().toLowerCase()}@trade'],
'id': 1
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/huobi_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class HuobiSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
HuobiSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
//socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://api-aws.huobi.pro/ws/v2/';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
if(!subscribe) {
return json.encode({
'unsub': 'market.${pair.toStringUSD()}.trade.detail',
'id': '1'
});
}
return json.encode({
'sub': 'market.${pair.toStringUSD()}.trade.detail',
'id': '1'
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/bitmex_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class BitmexSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
BitmexSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://www.bitmex.com/realtime';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'op': subscribe ? 'subscribe' : 'unsubscribe',
'args': ['trade:${pair.toStringXBT()}']
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/ftx_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class FtxSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
FtxSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://ftx.com/ws/';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'op': subscribe ? 'subscribe' : 'unsubscribe',
'channel': 'trades',
'market': '${pair.toStringWithCustomReplace('/')}'
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/okex_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class OkExSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
OkExSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://real.okex.com:8443/ws/v3';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'op': subscribe ? 'subscribe' : 'unsubscribe',
'args': ['spot/trade:${pair.toStringWithCustomReplace('-')}']
});
}
} | 0 |
mirrored_repositories/whalert/lib | mirrored_repositories/whalert/lib/websockets/coinbase_socket.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_trading_volume/models/supported_pairs.dart';
import 'package:flutter_trading_volume/websockets/base_socket.dart';
import 'package:web_socket_channel/html.dart';
class CoinbaseSocket implements BaseSocket {
SupportedPairs pair;
HtmlWebSocketChannel socket;
CoinbaseSocket({@required this.pair});
@override
HtmlWebSocketChannel connect() {
if(socket == null) {
socket = HtmlWebSocketChannel.connect(wsUrl());
}
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage());
}
return socket;
}
@override
void closeConnection() {
if(socket != null && socket.sink != null) {
socket.sink.add(wsSubscribeUnsubscribeMessage(subscribe: false));
socket.sink.close();
}
socket = null;
}
@override
String wsUrl() {
return 'wss://ws-feed.pro.coinbase.com';
}
@override
String wsSubscribeUnsubscribeMessage({bool subscribe = true}) {
return json.encode({
'type': subscribe ? 'subscribe' : 'unsubscribe',
'channels': [ {
'name': 'ticker',
'product_ids': ['${pair.toStringCustomUSD('-')}']
}]
});
}
} | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.