repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/100-Days-of-Flutter/intro_scaffold | mirrored_repositories/100-Days-of-Flutter/intro_scaffold/lib/main.dart | import 'package:flutter/material.dart';
import 'package:intro_scaffold/UI/home.dart';
void main() {
runApp(new MaterialApp(
title: "Scaffold",
home: new Home(),
));
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/intro_scaffold/lib | mirrored_repositories/100-Days-of-Flutter/intro_scaffold/lib/UI/home.dart | import 'package:flutter/material.dart';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
void _onPress(String text) {
debugPrint("$text Tapped!");
}
void _onTap() {
debugPrint("Button Tapped!");
}
// TODO: implement build
return new Scaffold(
appBar: new AppBar(
backgroundColor: Colors.deepPurpleAccent,
title: new Text(
"Hello Bar",
),
actions: <Widget>[
new IconButton(
icon: new Icon(Icons.send), onPressed: () => _onPress("Send")),
new IconButton(
icon: new Icon(Icons.search),
onPressed: () => _onPress("Search")),
],
),
backgroundColor: Colors.grey.shade100,
body: new Container(
alignment: Alignment.center,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
"The Blacklist",
style: new TextStyle(
fontSize: 34,
fontWeight: FontWeight.w400,
color: Colors.grey),
),
new InkWell(
child: new Text(
"Press Me!",
style: TextStyle(fontSize: 24),
),
onTap: () => _onTap(),
)
],
),
),
bottomNavigationBar: BottomNavigationBar(
selectedItemColor: Colors.deepPurple,
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text("Home")),
BottomNavigationBarItem(
icon: Icon(Icons.rss_feed), title: Text("Feed")),
BottomNavigationBarItem(
icon: Icon(Icons.settings), title: Text("Settings")),
],
onTap: (int i) => debugPrint("Selected Index $i"),
),
floatingActionButton: FloatingActionButton(
onPressed: () => debugPrint("Floating Action Button Tapped!"),
backgroundColor: Colors.green,
tooltip: 'Going Up!',
child: Icon(Icons.add),
),
);
}
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/intro_scaffold | mirrored_repositories/100-Days-of-Flutter/intro_scaffold/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:intro_scaffold/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/intro_layouts_containers | mirrored_repositories/100-Days-of-Flutter/intro_layouts_containers/lib/main.dart |
import 'package:flutter/material.dart';
import 'package:intro_layouts_containers/UI/home.dart';
void main() {
runApp(new MaterialApp(
title: "Layouts",
home: new Home(),
));
} | 0 |
mirrored_repositories/100-Days-of-Flutter/intro_layouts_containers/lib | mirrored_repositories/100-Days-of-Flutter/intro_layouts_containers/lib/UI/home.dart | import 'package:flutter/material.dart';
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
alignment: Alignment.center,
child: new Stack(
children: <Widget>[
Container(
width: 200,
height: 200,
color: Colors.red,
),
Container(
width: 150,
height: 150,
color: Colors.green,
),
Container(
width: 100,
height: 100,
color: Colors.blue,
),
],
),
// child: new Row(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// new Text("Item 1", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.white, fontSize: 12),),
// new Text("Item 2", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.white, fontSize: 12),),
// const Expanded(
// child: const Text("Item 3"),
// )
// new Text("Item 4", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.white, fontSize: 12),),
//
// ],
//),
// child: new Column(
// mainAxisAlignment: MainAxisAlignment.center,
// children: <Widget>[
// new Text("First Item", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.white),),
// new Text("Second Item", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.orangeAccent),),
// new Text("Third Item", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.yellow),),
// new Container(
// color: Colors.deepOrange.shade600,
// alignment: Alignment.bottomLeft,
// child: new Text("Fourth Item", textDirection: TextDirection.ltr, style: new TextStyle(color: Colors.white),),
// )
// ],
// )
// child: new Text(
// "Hello, Container!",
// textDirection: TextDirection.ltr,
// style: new TextStyle(
// color: Colors.white,
// fontWeight: FontWeight.w900,
// fontSize: 34
// ),
// ),
);
}
} | 0 |
mirrored_repositories/100-Days-of-Flutter/time_world | mirrored_repositories/100-Days-of-Flutter/time_world/lib/main.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
"Time World",
style: TextStyle(color: Colors.black38),
),
backgroundColor: Colors.yellow,
),
backgroundColor: Colors.white,
body: Center(
child: Text(
"London : 3:14 PM",
style: TextStyle(fontSize: 34, fontWeight: FontWeight.w400),
),
),
),
));
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/time_world | mirrored_repositories/100-Days-of-Flutter/time_world/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:time_world/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/make_it_rain | mirrored_repositories/100-Days-of-Flutter/make_it_rain/lib/main.dart | import 'package:flutter/material.dart';
import 'package:make_it_rain/UI/make_it_rain.dart';
void main() {
String title = "Make it Rain!";
runApp(MaterialApp(
title: title,
home: MakeItRain(),
));
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/make_it_rain/lib | mirrored_repositories/100-Days-of-Flutter/make_it_rain/lib/UI/make_it_rain.dart | import 'package:flutter/material.dart';
import 'package:make_it_rain/UI/make_it_rain_state.dart';
class MakeItRain extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MakeItRainState();
}
}
| 0 |
mirrored_repositories/100-Days-of-Flutter/make_it_rain/lib | mirrored_repositories/100-Days-of-Flutter/make_it_rain/lib/UI/make_it_rain_state.dart | import 'package:flutter/material.dart';
import 'package:make_it_rain/UI/make_it_rain.dart';
class MakeItRainState extends State<MakeItRain> {
int _moneyCounter = 0;
void _rainMoney() {
setState(() {
_moneyCounter += 1000;
});
}
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: Text("Make It Rain!"),
backgroundColor: Colors.green,
),
backgroundColor: Colors.white,
body: Center(
child: Container(
child: Column(
children: <Widget>[
Expanded(
child: Center(
child: Text(
"Get Rich!",
style: TextStyle(color: Colors.grey, fontSize: 34),
),
),
),
Expanded(
child: Center(
child: Text(
"\$ $_moneyCounter",
style: TextStyle(
color: _moneyCounter > 10000 ? Colors.green : Colors.greenAccent,
fontSize: 34,
fontWeight: FontWeight.w800),
),
),
),
Expanded(
child: Center(
child: FlatButton(
color: Colors.lightGreen,
textColor: Colors.white,
child: Text(
"Make It Rain!",
style: TextStyle(fontSize: 19),
),
onPressed: _rainMoney,
),
))
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter | mirrored_repositories/WanAndroid_Flutter/lib/main.dart | // Flutter code sample for material.AppBar.1
// This sample shows an [AppBar] with two simple actions. The first action
// opens a [SnackBar], while the second action navigates to a new page.
import 'package:bloc/bloc.dart';
import 'package:data_plugin/bmob/bmob.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/drawer/about_page.dart';
import 'package:wanandroid_flutter/page/home/drawer/rank_page.dart';
import 'package:wanandroid_flutter/page/home/drawer/support_author.dart';
import 'package:wanandroid_flutter/page/home/home/home_page.dart';
import 'package:wanandroid_flutter/page/home/project/project_detail_page.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/page/search/search_page.dart';
import 'package:wanandroid_flutter/page/todo/todo_create.dart';
import 'package:wanandroid_flutter/page/todo/todo_main.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'entity/project_entity.dart';
import 'http/index.dart';
///在拿不到context的地方通过navigatorKey进行路由跳转:
///https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app
final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>();
final Map<String, WidgetBuilder> routes = {
LoginWanandroidPage.ROUTER_NAME: (context) => new LoginWanandroidPage(),
HomePage.ROUTER_NAME: (context) => new HomePage(),
TodoPage.ROUTER_NAME: (context) => new TodoPage(),
TodoCreatePage.ROUTER_NAME: (context) => new TodoCreatePage(),
ProjectDetailPage.ROUTER_NAME: (context) => new ProjectDetailPage(),
WebViewPage.ROUTER_NAME: (context) => WebViewPage(),
SupportAuthorPage.ROUTER_NAME: (context) => SupportAuthorPage(),
AboutPage.ROUTER_NAME: (context) => AboutPage(),
RankPage.ROUTER_NAME: (c) => RankPage(),
SearchPage.ROUTER_NAME: (_) => SearchPage(),
};
///开源版本我不会上传appkey相关数据,bmob相关操作禁用。
bool bmobEnable = false;
bool _blocDebug = true;
class GlobalBlocDel extends BlocDelegate {
@override
void onEvent(Bloc bloc, Object event) {
if (_blocDebug) {
print('Bloc-event : $event');
}
}
@override
void onError(Bloc bloc, Object error, StackTrace stacktrace) {
if (_blocDebug) {
print('Bloc-error : $error ; $stacktrace');
}
}
@override
void onTransition(Bloc bloc, Transition transition) {
if (_blocDebug) {
print('Bloc-Transition : $transition');
}
}
}
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations(
[DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
BlocSupervisor.delegate = GlobalBlocDel();
//SDK初始化
Bmob.initMasterKey('', '', '');
await DioUtil.init();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.light().copyWith(
primaryColor: WColors.theme_color,
),
routes: routes,
title: res.appName,
navigatorKey: navigatorKey,
home: HomePage(),
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/test/nested_test_page.dart |
import 'package:flutter/material.dart';
class NestedTestPage extends StatelessWidget {
List<String> _tabs = ['1','22','333','4444','55555'];
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: _tabs.length,
child: Scaffold(
body: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
return <Widget>[
SliverOverlapAbsorber(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
child: SliverAppBar(
title: const Text('Books'),
pinned: true,
expandedHeight: 150.0,
forceElevated: innerBoxIsScrolled,
bottom: TabBar(
tabs: _tabs.map((String name) => Tab(text: name)).toList(),
),
),
),
];
},
body: TabBarView(
children: _tabs.map((String name) {
return TestSubPage(name);
}).toList(),
),
),
),
);
}
}
class TestSubPage extends StatefulWidget {
String name;
TestSubPage(this.name);
@override
_TestSubPageState createState() => _TestSubPageState();
}
class _TestSubPageState extends State<TestSubPage> with AutomaticKeepAliveClientMixin {
List<String> _tabs = ['1','22','333','4444','55555'];
@override
Widget build(BuildContext context) {
super.build(context);
return SafeArea(
top: false,
bottom: false,
child: Builder(
builder: (BuildContext context) {
return CustomScrollView(
key: PageStorageKey<String>(widget.name),
slivers: <Widget>[
SliverOverlapInjector(
handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
),
SliverAppBar(
backgroundColor: Colors.red,
title: const Text('123123'),
pinned: true,
expandedHeight: 150.0,
// forceElevated: innerBoxIsScrolled,
bottom: TabBar(
tabs: _tabs.map((String name) => Tab(text: name)).toList(),
),
),
SliverPadding(
padding: const EdgeInsets.all(8.0),
sliver: SliverFixedExtentList(
itemExtent: 48.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) {
return ListTile(
title: Text('Item $index'),
);
},
childCount: 30,
),
),
),
],
);
},
),
);
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/test/test_page.dart | import 'dart:io';
import 'package:data_plugin/bmob/bmob_query.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:wanandroid_flutter/entity/bmob_feedback_entity.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/shared_preference_util.dart';
class TestPage extends StatefulWidget {
@override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
TextEditingController userNameController;
TextEditingController psdController;
TextEditingController _tc;
String appName;
String packageName;
String version;
String buildNumber;
var datas;
int level = 0;
CounterModel counterModel = CounterModel();
@override
void initState() {
super.initState();
// SystemChrome.setEnabledSystemUIOverlays([]);
userNameController = TextEditingController();
psdController = TextEditingController();
_tc = TextEditingController();
pkif();
}
Future pkif() async {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
appName = packageInfo.appName;
packageName = packageInfo.packageName;
version = packageInfo.version;
buildNumber = packageInfo.buildNumber;
setState(() {});
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<CounterModel>.value(
value: counterModel,
child: ListView.builder(
// ignore: missing_return
itemBuilder: (BuildContext context, int index) {
if (index == 0) {
return accountWidget();
}
if (index == 1) {
return accountTest();
}
if (index == 2) {
return TodoTest();
}
if (index == 3) {
return BmboTest();
}
if (index == 4) {
// return getLevelWidgets(level);
print('1');
return Consumer<CounterModel>(
builder:
(BuildContext context, CounterModel value, Widget child) {
return GestureDetector(
onTap: () {
value.increment();
},
child: Container(
width: 100,
height: 200,
child: Column(
children: <Widget>[
Text('va = ${value.value}'),
child,
],
),
),
);
},
child: AStful(),
);
}
},
itemCount: 5,
),
);
}
Widget accountWidget() {
return Column(
children: <Widget>[
Row(
children: <Widget>[
Text('账号 = '),
Expanded(
child: TextField(
controller: userNameController,
decoration: InputDecoration(hintText: '账号'),
),
),
],
),
Row(
children: <Widget>[
Text('密码 = '),
Expanded(
child: TextField(
controller: psdController,
decoration: InputDecoration(hintText: '密码'),
),
),
],
),
Padding(
padding: EdgeInsets.only(top: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
RaisedButton(
color: WColors.theme_color,
textColor: Colors.white,
child: Text('登录'),
onPressed: () {
login(userNameController.text, psdController.text);
},
),
RaisedButton(
color: WColors.theme_color,
textColor: Colors.white,
child: Text('注册'),
onPressed: () {
regist(userNameController.text, psdController.text);
},
),
],
),
)
],
);
}
Widget accountTest() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
RaisedButton(
child: Text('退出登录'),
onPressed: () {
logout();
},
),
RaisedButton(
onPressed: () {
collectTest();
},
child: Text('测试收藏'),
),
RaisedButton(
onPressed: () {
printCookieFile();
},
child: Text('打印cookie本地文件'),
),
RaisedButton(
onPressed: () {
printSPisLogin();
},
child: Text('打印SP是否登录'),
),
],
),
);
}
Future collectTest() async {
try {
await dio.post("/lg/collect/1165/json");
print("collect success");
} catch (e) {
print(e);
}
}
Future login(String username, String password) async {
try {
Response response = await AccountApi.login(username, password);
await SPUtil.setLogin(true);
print("login success");
} catch (e) {
print(DioUtil.parseError(e));
}
}
Future regist(String username, String password) async {
try {
await AccountApi.regist(username, password, password);
print("regist success");
} catch (e) {
print(DioUtil.parseError(e));
}
}
Future logout() async {
try {
await AccountApi.logout();
await SPUtil.setLogin(false);
print('logout success');
} catch (e) {
print(DioUtil.parseError(e));
}
}
Future printCookieFile() async {
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path + "/dioCookie";
Directory dire = Directory(tempPath);
bool ex = await dire.exists();
print('exists = $ex');
flatPrintFiles(dire);
// String s = await file.readAsString();
// print('[[[[${s}');
}
flatPrintFiles(Directory dire) {
dire.list().listen((f) {
if (f is File) {
print('f.name = ${f.toString()}');
print('file = ${f.readAsStringSync()}');
} else {
flatPrintFiles(f);
}
});
}
Future printSPisLogin() async {
bool islogin = await SPUtil.isLogin();
print('isLogin = $islogin');
}
Widget BmboTest() {
return Row(
children: <Widget>[
RaisedButton(
onPressed: () {
createOne();
},
child: Text('创建一条'),
),
RaisedButton(
onPressed: () {
updateOne();
},
child: Text('更新一条'),
),
RaisedButton(
onPressed: () {
queryOne();
},
child: Text('查询'),
),
RaisedButton(
onPressed: () {
String t = '2019-07-28 18:44:19';
DateTime d1 = DateTime.parse(t);
DateTime now = DateTime.now();
DateTime d2 = DateTime(now.year, now.month, now.day + 1);
if (d1.isAfter(d2)) {
print('之后');
} else {
print('之前');
}
setState(() {
level++;
});
},
child: Text('同一天?'),
),
],
);
}
}
Future createOne() async {
BmobUserEntity userEntity = BmobUserEntity.empty();
userEntity.userName = 'ccy0122';
userEntity.signature = 'asdasdas';
userEntity.level = 100;
userEntity.save().then((value) {
print('save success:${value.objectId},${value.createdAt}');
}, onError: (e, s) {
print('save filed $e;$s');
});
BmobFeedbackEntity feedbackEntity = BmobFeedbackEntity.empty();
feedbackEntity.userName = 'asd';
feedbackEntity.feedback = '你好啊';
feedbackEntity.save();
}
Future queryOne() async {
BmobQuery<BmobUserEntity> query = BmobQuery();
query.addWhereEqualTo('userName', 'ccy01221');
query.queryObjects().then((results) {
print('query size = ${results.length}');
if (results != null && results.length >= 1) {
print('query success ${(BmobUserEntity.fromJson(results[0])).userName}');
}
}, onError: (e, s) {
print('query filed $e;$s');
});
}
Future updateOne() async {
BmobQuery<BmobUserEntity> query = BmobQuery();
query.addWhereEqualTo('userName', 'ccy0122');
query.queryObjects().then((results) {
print('query size = ${results.length}');
if (results != null && results.length >= 1) {
BmobUserEntity entity = BmobUserEntity.fromJson(results[0]);
entity.level = 110;
entity.update().then((value) {
print('update success = ${value.updatedAt}');
});
}
}, onError: (e, s) {
print('query filed $e;$s');
});
}
class TodoTest extends StatefulWidget {
@override
_TodoTestState createState() => _TodoTestState();
}
class _TodoTestState extends State<TodoTest> {
@override
Widget build(BuildContext context) {
return Wrap(
children: <Widget>[
RaisedButton(
child: Text('add'),
onPressed: () {
// TodoApi.addTodo(
// 'test2',
// 'test content2',
// completeDateMilli: DateTime.now().millisecondsSinceEpoch,
// type: 1,
// ).then((result) {
// print('success:${result.toString()}');
// }).catchError((e) {
// print('failed:$e');
// });
},
),
RaisedButton(
child: Text('DELETE'),
onPressed: () {
TodoApi.deleteTodo(11511);
},
)
],
);
}
}
class AStful extends StatefulWidget {
@override
_AStfulState createState() => _AStfulState();
AStful(){
print('constar');
}
}
class _AStfulState extends State<AStful> {
@override
Widget build(BuildContext context) {
//结论,只第一次build 后续不会
print('_AStfulState : build');
return Container(
child: Text('asdasd'),
);
}
}
class CounterModel with ChangeNotifier {
int _count = 0;
int get value => _count;
void increment() {
_count++;
notifyListeners();
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/badge_view.dart | import 'package:flutter/material.dart';
///Created by ccy(17022) on ${DATE} ${TIME}
///角标与布局的相对位置
enum BadgeAlignment {
topLeft,
topRight,
bottomLeft,
bottomRight,
}
enum BadgeLocation {
///角标在布局内部,offsetX、offsetY会让角标向布局内偏移。
inside,
///角标可以超出布局,offsetX、offsetY会让角标向布局外偏移。
outside,
}
///角标控件
class Badge extends StatefulWidget {
final BadgeAlignment badgeAlignment;
final BadgeLocation badgeLocation;
///角标背景颜色
final Color color;
///角标内偏移。
///ps:当[badge]为null,[shape]为圆形时,该值即圆点角标的半径
final EdgeInsetsGeometry padding;
///角标相对位置偏移量。受[BadgeLocation]影响
double offsetX;
///角标相对位置偏移量。受[BadgeLocation]影响
double offsetY;
///角标形状。一般都是圆形或者圆角矩形。默认圆形
final ShapeBorder shape;
///角标z轴值
final double elevation;
///角标内容。可以为null
Widget badge;
///布局
final Widget child;
///角标是否可见
final bool visible;
Badge({
Key key,
this.badgeAlignment = BadgeAlignment.topRight,
this.badgeLocation = BadgeLocation.outside,
this.color = const Color(0xFFE84E40),
this.padding = const EdgeInsets.all(5),
this.offsetX,
this.offsetY,
this.shape = const CircleBorder(),
this.elevation = 0.0,
this.badge,
this.child,
this.visible = true,
}) : super(key: key) {
//当没有设置offsetX、Y时,若是圆点角标且位置可以超出布局,那么默认超出的偏移量为圆点半径。
//这样效果正好圆心在布局矩形的角上
bool isCircleAndOutSide = (badge == null &&
shape is CircleBorder &&
badgeLocation == BadgeLocation.outside &&
padding is EdgeInsets);
offsetX ??= (isCircleAndOutSide
? (padding as EdgeInsets).left
: getSuitableDefaultOffset(true));
offsetY ??= (isCircleAndOutSide
? (padding as EdgeInsets).left
: getSuitableDefaultOffset(false));
}
double getSuitableDefaultOffset(bool isOffsetX) {
//经测试,如果是text且形状为圆形,圆形上下空间会有一定padding。为了视觉上更好,Y偏移量要比X少一点
if (badge != null && badge is Text && shape is CircleBorder) {
if (isOffsetX) {
return badgeLocation == BadgeLocation.inside ? 3 : 8;
} else {
return badgeLocation == BadgeLocation.inside ? 0 : 11; //比X少偏移3
}
} else {
//其他正常情况。
return badgeLocation == BadgeLocation.inside ? 3 : 8;
}
}
@override
_BadgeState createState() => _BadgeState();
}
class _BadgeState extends State<Badge> {
@override
Widget build(BuildContext context) {
double left, top, right, bottom;
switch (widget.badgeAlignment) {
case BadgeAlignment.topLeft:
left = widget.badgeLocation == BadgeLocation.inside
? widget.offsetX
: -widget.offsetX;
top = widget.badgeLocation == BadgeLocation.inside
? widget.offsetY
: -widget.offsetY;
break;
case BadgeAlignment.topRight:
right = widget.badgeLocation == BadgeLocation.inside
? widget.offsetX
: -widget.offsetX;
top = widget.badgeLocation == BadgeLocation.inside
? widget.offsetY
: -widget.offsetY;
break;
case BadgeAlignment.bottomLeft:
left = widget.badgeLocation == BadgeLocation.inside
? widget.offsetX
: -widget.offsetX;
bottom = widget.badgeLocation == BadgeLocation.inside
? widget.offsetY
: -widget.offsetY;
break;
case BadgeAlignment.bottomRight:
right = widget.badgeLocation == BadgeLocation.inside
? widget.offsetX
: -widget.offsetX;
bottom = widget.badgeLocation == BadgeLocation.inside
? widget.offsetY
: -widget.offsetY;
break;
}
if (widget.child == null) {
return Offstage(
offstage: !widget.visible,
child: createBadgeView(),
);
} else {
return Stack(
overflow: Overflow.visible,
children: <Widget>[
widget.child,
Positioned(
child: Offstage(
offstage: !widget.visible,
child: createBadgeView(),
),
left: left,
top: top,
right: right,
bottom: bottom,
)
],
);
}
}
Widget createBadgeView() {
return Material(
type: MaterialType.canvas,
elevation: widget.elevation,
shape: widget.shape,
color: widget.color,
child: Padding(
padding: widget.padding,
child: widget.badge,
),
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/load_more_footer.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
Widget getLoadMoreFooter(bool hasMore,{Color color = WColors.gray_background}) {
return Container(
width: double.infinity,
height: pt(45),
color: color,
alignment: Alignment.center,
child: hasMore
? CupertinoActivityIndicator()
: Text(
res.isBottomst,
style: TextStyle(color: WColors.hint_color),
),
);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/flat_pagination.dart | import 'package:flutter/material.dart';
import 'package:flutter_page_indicator/flutter_page_indicator.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
///参考了[DotSwiperPaginationBuilder]
///
class FlatDotSwiperPaginationBuilder extends SwiperPlugin {
///color when current index,if set null , will be Theme.of(context).primaryColor
final Color activeColor;
///,if set null , will be Theme.of(context).scaffoldBackgroundColor
final Color color;
///Size of the dot when activate
final double activeSize;
///Size of the dot
final double size;
/// Space between dots
final double space;
final Key key;
const FlatDotSwiperPaginationBuilder(
{this.activeColor,
this.color,
this.key,
this.size: 10.0,
this.activeSize: 10.0,
this.space: 3.0});
@override
Widget build(BuildContext context, SwiperPluginConfig config) {
if (config.itemCount > 20) {
print(
"The itemCount is too big, we suggest use FractionPaginationBuilder instead of DotSwiperPaginationBuilder in this sitituation");
}
Color activeColor = this.activeColor;
Color color = this.color;
if (activeColor == null || color == null) {
ThemeData themeData = Theme.of(context);
activeColor = this.activeColor ?? themeData.primaryColor;
color = this.color ?? themeData.scaffoldBackgroundColor;
}
if (config.indicatorLayout != PageIndicatorLayout.NONE &&
config.layout == SwiperLayout.DEFAULT) {
return new PageIndicator(
count: config.itemCount,
controller: config.pageController,
layout: config.indicatorLayout,
size: size,
activeColor: activeColor,
color: color,
space: space,
);
}
List<Widget> list = [];
int itemCount = config.itemCount;
int activeIndex = config.activeIndex;
for (int i = 0; i < itemCount; ++i) {
bool active = i == activeIndex;
list.add(Container(
key: Key("pagination_$i"),
margin: EdgeInsets.all(space),
child: active
? ClipRRect(
borderRadius: BorderRadius.circular(activeSize / 2),
child: Container(
color: activeColor,
width: activeSize * 2,
height: activeSize,
),
)
: ClipOval(
child: Container(
color: active ? activeColor : color,
width: active ? activeSize : size,
height: active ? activeSize : size,
),
),
));
}
if (config.scrollDirection == Axis.vertical) {
return new Column(
key: key,
mainAxisSize: MainAxisSize.min,
children: list,
);
} else {
return new Row(
key: key,
mainAxisSize: MainAxisSize.min,
children: list,
);
}
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/level_view.dart | import 'package:flutter/material.dart';
Widget getLevelWidgets(int level) {
if (level == null || level < 1) {
level = 1;
}
int crown = level ~/ (4 * 4 * 4);
level %= (4 * 4 * 4);
int sun = level ~/ (4 * 4);
level %= (4 * 4);
int moon = level ~/ (4);
level %= (4);
int star = level;
// print('level.$crown,$sun,$moon,$star');
List<Widget> icons = List<Widget>();
icons.addAll(List.generate(crown, (index) {
return Image.asset(
'images/lv_crown.png',
width: 20,
height: 20,
color: Colors.orangeAccent,
);
}).toList());
icons.addAll(List.generate(sun, (index) {
return Image.asset(
'images/lv_sun.png',
width: 20,
height: 20,
color: Colors.orangeAccent,
);
}).toList());
icons.addAll(List.generate(moon, (index) {
return Image.asset(
'images/lv_moon.png',
width: 20,
height: 20,
color: Colors.orangeAccent,
);
}).toList());
icons.addAll(List.generate(star, (index) {
return Image.asset(
'images/lv_star.png',
width: 20,
height: 20,
color: Colors.orangeAccent,
);
}).toList());
return Row(
children: icons,
);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/article_type_view.dart | import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class ArticleTypeView {
///折叠时的type view
static Widget collaspTypesView({
@required Key key,
@required List<ArticleTypeEntity> types,
@required int selectId,
@required VoidCallback onExpanded,
@required ValueChanged<int> onSelected,
ScrollController collaspTypeScrollController,
}) {
return Row(
key: key,
children: <Widget>[
Expanded(
child: SingleChildScrollView(
controller: collaspTypeScrollController,
physics: BouncingScrollPhysics(),
scrollDirection: Axis.horizontal,
child: Row(
children: List.generate(
types.length,
(index) {
return typeItem(
id: types[index].id,
name: types[index].name,
selected: types[index].id == selectId,
onSelected: onSelected,
);
},
),
),
),
),
GestureDetector(
onTap: () {
onExpanded();
},
child: Container(
width: pt(30),
height: pt(30),
child: Icon(
Icons.keyboard_arrow_down,
size: pt(30),
color: Colors.white,
),
),
),
],
);
}
///展开时的type view
static Widget expandedTypesView({
@required List<ArticleTypeEntity> types,
@required int selectId,
@required VoidCallback onExpanded,
@required ValueChanged<int> onSelected,
}) {
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
)),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Wrap(
children: List.generate(
types.length,
(index) {
return typeItem(
id: types[index].id,
name: types[index].name,
selected: types[index].id == selectId,
onSelected: onSelected,
);
},
),
),
),
GestureDetector(
onTap: () {
onExpanded();
},
child: Container(
width: pt(30),
height: pt(30),
child: Icon(
Icons.keyboard_arrow_up,
size: pt(30),
color: Colors.white,
),
),
),
],
),
);
}
///type 单元
static Widget typeItem({
@required int id,
@required String name,
@required bool selected,
@required ValueChanged<int> onSelected,
}) {
return Padding(
padding: EdgeInsets.symmetric(vertical: pt(4), horizontal: pt(2)),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
//只可选中,不可取消
if (!selected) {
onSelected(id);
}
},
child: Container(
height: pt(28),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: selected ? Border.all(color: Colors.white) : null,
),
// 这里为什么用stack呢?因为我想让child居中。
// 那居中为什么不直接给父container设置alignment呢?因为这会使Container约束变尽可能大,
// 导致width占满剩余空间(height已经固定给了pt(28),而width我不希望给固定值,它应当根据文字长度自动调整),
// 最终导致expandedTypesView中的wrap是一行一个typeItem。所以换用stack来实现文字居中。
// 如果你还不理解,去掉stack,给Container加上Alignment.center,运行看效果。
// 为什么height要给固定值?因为不同文字的高度其实是不一样的,不给固定值的话他们基线不一样
child: Stack(
alignment: Alignment.center,
children: [
Text(
name,
style: TextStyle(color: Colors.white),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/loading_view.dart | import 'package:flare_flutter/flare_actor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/res/index.dart';
Widget getLoading({bool start = true}) {
return IgnorePointer(
child: Container(
alignment: Alignment.center,
color: Colors.transparent,
child: FlareActor(
'assets/loading.flr',
animation: 'start', //该动画定义的名字
color: WColors.theme_color_dark,
isPaused: start != true,
),
),
);
}
Widget getLoadingParent({@required Widget child,Key key, bool isLoading = false}) {
return Stack(
key: key,
children: <Widget>[
child,
Offstage(
offstage: !isLoading,
child: getLoading(start: isLoading),
),
],
);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/views/saerch_bar.dart | import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class SearchBar extends StatefulWidget {
double height;
double width;
Widget child;
Color color;
Color iconColor;
Widget icon;
SearchBar({this.height, this.width, this.child, this.color, this.iconColor,this.icon});
@override
_SearchBarState createState() => _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
@override
Widget build(BuildContext context) {
return Container(
height: widget.height,
width: widget.width,
decoration: BoxDecoration(
borderRadius: widget.height != null
? BorderRadius.circular(widget.height / 2)
: null,
color: widget.color,
),
alignment: Alignment.centerLeft,
child: Row(
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(
horizontal: pt(5),
),
child: widget.icon ?? Icon(
Icons.search,
color: widget.iconColor,
),
),
Expanded(
child: widget.child ?? Container(),
)
],
),
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/page/notifications.dart |
import 'package:flutter/material.dart';
class UpdateNotification extends Notification {
bool update;
UpdateNotification(this.update);
} | 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/account/login_wanandroid_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
///页面的模式
enum LoginMode {
///登录账户
LOGIN,
///注册账户
REGIST,
}
class LoginModeNotification extends Notification {
final LoginMode mode;
LoginModeNotification(this.mode);
}
///wanAndroid登录
class LoginWanandroidPage extends StatefulWidget {
static const String ROUTER_NAME = "/LoginWanandroidPage";
@override
_LoginWanandroidPageState createState() => _LoginWanandroidPageState();
}
class _LoginWanandroidPageState extends State<LoginWanandroidPage> with SingleTickerProviderStateMixin {
LoginMode mode;
AnimationController animationController;
CurvedAnimation curvedAnimation;
@override
void initState() {
super.initState();
mode = LoginMode.LOGIN;
animationController = AnimationController(vsync: this,duration: Duration(seconds: 1));
curvedAnimation = CurvedAnimation(parent: animationController, curve: Curves.elasticOut);
animationController.forward();
}
@override
void dispose() {
super.dispose();
animationController.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: WColors.theme_color_dark,
elevation: 0,
centerTitle: true,
title: Text(mode == LoginMode.LOGIN ? res.login : res.regist),
),
body: NotificationListener<LoginModeNotification>(
onNotification: (notification) {
setState(() {
mode = notification.mode;
});
},
child: Container(
color: WColors.gray_background,
width: double.infinity,
height: double.infinity,
child: SingleChildScrollView(
child: Stack(
alignment: Alignment.topCenter,
children: <Widget>[
Container(
height: pt(200),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
WColors.theme_color_dark,
WColors.theme_color,
WColors.theme_color_light
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
),
Positioned(
top: pt(50),
child: Image.asset(
'images/ic_launcher.png',
color: Colors.white,
),
),
ScaleTransition(
scale: curvedAnimation,
child: Container(
margin: EdgeInsets.only(top: pt(170)),
child: LoginCard(
mode: mode,
),
),
),
],
),
),
),
),
);
}
}
class LoginCard extends StatefulWidget {
bool isLogining;
LoginMode mode;
LoginCard({
this.isLogining = false,
this.mode = LoginMode.LOGIN,
});
@override
_LoginCardState createState() => _LoginCardState();
}
class _LoginCardState extends State<LoginCard> {
TextEditingController userController;
TextEditingController pwdController;
TextEditingController pwdAgainController;
FocusNode pwdFocus;
FocusNode pwdAgainFocus;
@override
void initState() {
super.initState();
userController = TextEditingController();
pwdController = TextEditingController();
pwdAgainController = TextEditingController();
pwdFocus = FocusNode();
pwdAgainFocus = FocusNode();
}
@override
Widget build(BuildContext context) {
return Container(
decoration: ShapeDecoration(
color: Colors.white,
shadows: <BoxShadow>[
DisplayUtil.lightElevation(),
],
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(1),
bottomRight: Radius.circular(1),
topRight: Radius.elliptical(25, 25),
bottomLeft: Radius.elliptical(25, 25),
),
),
),
child: Container(
width: pt(310),
padding: EdgeInsets.all(
pt(20),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
//用户名
Row(
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: pt(16)),
child: Icon(
Icons.account_circle,
color: WColors.theme_color,
),
),
Expanded(
child: TextField(
onSubmitted: (String str) {
FocusScope.of(context).requestFocus(pwdFocus);
},
textInputAction: TextInputAction.next,
controller: userController,
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w300,
),
decoration: InputDecoration(
hintText: res.username,
hintStyle: TextStyle(
fontSize: 16,
color: WColors.hint_color,
),
contentPadding: EdgeInsets.only(
top: pt(10),
bottom: pt(4),
),
),
),
)
],
),
SizedBox(
height: pt(20),
),
//密码
Row(
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: pt(16)),
child: Icon(
Icons.lock,
color: WColors.theme_color,
),
),
Expanded(
child: TextField(
onSubmitted: (String str) {
if (widget.mode == LoginMode.REGIST) {
FocusScope.of(context).requestFocus(pwdAgainFocus);
}
},
textInputAction: widget.mode == LoginMode.LOGIN
? TextInputAction.done
: TextInputAction.next,
focusNode: pwdFocus,
controller: pwdController,
style: TextStyle(
fontSize: pt(22), fontWeight: FontWeight.w300),
decoration: InputDecoration(
hintText: res.password,
hintStyle: TextStyle(
fontSize: 16,
color: WColors.hint_color,
),
contentPadding: EdgeInsets.only(
top: pt(10),
bottom: pt(4),
),
),
),
)
],
),
//确认密码
AnimatedContainer(
duration: Duration(milliseconds: 200),
padding: EdgeInsets.only(
top: widget.mode == LoginMode.LOGIN ? 0 : pt(20)),
child: Offstage(
offstage: widget.mode != LoginMode.REGIST,
child: Padding(
padding: EdgeInsets.only(
top: pt(0),
),
child: Row(
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: pt(16)),
child: Icon(
Icons.lock,
color: WColors.theme_color,
),
),
Expanded(
child: TextField(
focusNode: pwdAgainFocus,
controller: pwdAgainController,
style: TextStyle(
fontSize: pt(22), fontWeight: FontWeight.w300),
decoration: InputDecoration(
hintText: res.rePassword,
hintStyle: TextStyle(
fontSize: 16,
color: WColors.hint_color,
),
contentPadding: EdgeInsets.only(
top: pt(10),
bottom: pt(4),
),
),
),
)
],
),
),
),
),
SizedBox(
height: pt(30),
),
//登录注册按钮
Container(
width: double.infinity,
margin: EdgeInsets.symmetric(horizontal: pt(20)),
child: RaisedButton(
elevation: 1,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(1),
topRight: Radius.elliptical(14, 14),
bottomLeft: Radius.elliptical(14, 14),
bottomRight: Radius.circular(1)),
),
onPressed: widget.isLogining
? null
: () {
if (widget.mode == LoginMode.LOGIN) {
login(userController.text, pwdController.text);
} else {
regist(userController.text, pwdController.text,
pwdAgainController.text);
}
},
textColor: Colors.white,
color: WColors.theme_color,
child: Padding(
padding: EdgeInsets.symmetric(vertical: pt(8)),
child: widget.isLogining
? CupertinoActivityIndicator()
: Text(
widget.mode == LoginMode.LOGIN
? res.login
: res.regist,
style: TextStyle(fontSize: 18),
),
)),
),
SizedBox(
height: pt(15),
),
//登录注册切换按钮
Container(
alignment: Alignment.centerRight,
child: GestureDetector(
child: Text(
widget.mode == LoginMode.LOGIN ? res.regist : res.login,
style: TextStyle(
decoration: TextDecoration.underline,
color: Colors.grey,
),
),
onTap: () {
if (widget.isLogining) {
return;
}
LoginModeNotification(widget.mode == LoginMode.LOGIN
? LoginMode.REGIST
: LoginMode.LOGIN)
.dispatch(context);
}),
),
],
)),
);
}
///登录
Future login(String username, String password) async {
setState(() {
widget.isLogining = true;
});
try {
await AccountApi.login(username, password);
await SPUtil.setLogin(true);
await SPUtil.setUserName(username);
print('_LoginCardState : login success');
Navigator.of(context).pop(true);
return;
} catch (e) {
DisplayUtil.showMsg(context, exception: e);
}
setState(() {
widget.isLogining = false;
});
}
///注册并登录
Future regist(String username, String password, String rePassword) async {
setState(() {
widget.isLogining = true;
});
try {
await AccountApi.regist(username, password, rePassword);
print('_LoginCardState : regist success');
await AccountApi.login(username, password);
await SPUtil.setLogin(true);
await SPUtil.setUserName(username);
print('_LoginCardState : login success');
Navigator.of(context).pop(true);
return;
} catch (e) {
DisplayUtil.showMsg(context, exception: e);
}
setState(() {
widget.isLogining = false;
});
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/home/web_view.dart | import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
class WebViewPage extends StatefulWidget {
static const ROUTER_NAME = '/WebViewPage';
@override
_WebViewPageState createState() => _WebViewPageState();
}
class _WebViewPageState extends State<WebViewPage> {
String title;
String url;
FlutterWebviewPlugin flutterWebviewPlugin;
bool showLoading = false;
@override
void initState() {
super.initState();
flutterWebviewPlugin = FlutterWebviewPlugin();
//initialChild只有第一网页加载时会显示,网页内部页面跳转不会再显示,所以要手动加上页面内跳转监听
flutterWebviewPlugin.onStateChanged.listen((state) {
print('_WebViewPageState.initState state = ${state.type}');
if (state.type == WebViewState.shouldStart) {
setState(() {
showLoading = true;
});
} else if (state.type == WebViewState.finishLoad ||
state.type == WebViewState.abortLoad) {
setState(() {
showLoading = false;
});
}
});
}
@override
Widget build(BuildContext context) {
var args = ModalRoute.of(context).settings.arguments;
if (args is Map) {
title = decodeString(args['title']);
url = args['url'];
}
return WebviewScaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: Row(
children: <Widget>[
GestureDetector(
behavior: HitTestBehavior.opaque,
child: Container(
child: Icon(
Icons.close,
color: Colors.white,
),
),
onTap: () {
Navigator.pop(context);
},
),
GestureDetector(
behavior: HitTestBehavior.opaque,
child: Container(
padding: EdgeInsets.only(left: 10, right: 8),
child: Icon(
Icons.arrow_back,
color: Colors.white,
),
),
onTap: () {
flutterWebviewPlugin.goBack();
},
),
Expanded(
child: Text(
title,
style: TextStyle(fontSize: 16),
),
),
],
),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.open_in_browser,
color: Colors.white,
),
tooltip: res.openBrowser,
onPressed: () {
_launchURL();
},
)
],
bottom: PreferredSize(
child: showLoading
? LinearProgressIndicator(
backgroundColor: Colors.grey,
)
: Container(),
preferredSize: Size(double.infinity, 1),
),
),
url: url,
hidden: true,
initialChild: getLoading(),
withZoom: true,
withLocalStorage: true,
);
}
_launchURL() async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle/wx_article_page.dart | import 'dart:math' as Math;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/Article_type_view.dart';
import 'package:wanandroid_flutter/views/load_more_footer.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
import '../web_view.dart';
import 'bloc/wxArticle_index.dart';
///公众号页.
///BloC模式
///如法炮制博文页[ArticleSubPage],但是多了公众号搜索功能逻辑
class WXArticleSubPage extends StatefulWidget {
PageStorageKey pageStorageKey;
WXArticleSubPage(this.pageStorageKey);
@override
_WXArticleSubPageState createState() => _WXArticleSubPageState();
}
class _WXArticleSubPageState extends State<WXArticleSubPage>
with AutomaticKeepAliveClientMixin {
WXArticleBloc wXArticleBloc;
List<ArticleTypeEntity> types;
List<ProjectEntity> wXArticleDatas;
int currentProjectPage;
int totalProjectPage;
int selectTypeId;
ScrollController collaspTypeScrollController;
bool typeIsExpanded;
String searchKey;
///不能直接使用[WXArticleLoading]作为是否在加载的依据
bool isLoading = false;
GlobalKey rootKey;
GlobalKey typeKey;
@override
void initState() {
super.initState();
wXArticleBloc = WXArticleBloc(BlocProvider.of<HomeBloc>(context));
types ??= [];
wXArticleDatas ??= [];
currentProjectPage ??= 1;
totalProjectPage ??= 1;
selectTypeId = 408; //408是'鸿洋'公众号分类id
typeIsExpanded = false;
rootKey = GlobalKey();
typeKey = GlobalKey();
collaspTypeScrollController = ScrollController();
}
@override
Widget build(BuildContext context) {
super.build(context);
return BlocProviderTree(
key: rootKey,
blocProviders: [
BlocProvider<WXArticleBloc>(builder: (context) => wXArticleBloc),
],
child: BlocListenerTree(
blocListeners: [
BlocListener<HomeEvent, HomeState>(
bloc: BlocProvider.of<HomeBloc>(context),
listener: (context, state) {
if (state is HomeSearchStarted) {
if (state.isSearchWXArticle && !isLoading) {
searchKey = state.searchKey;
wXArticleBloc.dispatch(LoadMoreWXArticleDatas(
originDatas: [],
id: selectTypeId,
page: 1,
searchKey: searchKey,
));
}
}
},
),
BlocListener<WXArticleEvent, WXArticleState>(
bloc: wXArticleBloc,
listener: (context, state) {
if (state is WXArticleLoading) {
isLoading = true;
} else if (state is WXArticleLoaded ||
state is WXArticleLoadError) {
isLoading = false;
}
if (state is WXArticleTypesloaded) {
types = state.WXArticleTypes;
} else if (state is WXArticleDatasLoaded) {
wXArticleDatas = state.datas;
currentProjectPage = state.curretnPage;
totalProjectPage = state.totalPage;
} else if (state is WXArticleCollectChanged) {
wXArticleDatas
.where((e) => e.id == state.id)
.map((e) => e.collect = state.collect)
.toList();
} else if (state is WXArticleLoadError) {
DisplayUtil.showMsg(context, exception: state.exception);
}
},
)
],
child: BlocBuilder<WXArticleEvent, WXArticleState>(
bloc: wXArticleBloc,
builder: (context, state) {
return NotificationListener(
onNotification: (notification) {
//不要在这里检测加载更多,因为子树可能有多个垂直滚动widget
//so问题来了:如何在NotificationListener确定一个ScrollNotification是由哪个scrollable widget发来的?
},
child: Stack(
children: <Widget>[
NotificationListener(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
//确定是公众号列表发出来的滚动,而不是公众号分类栏发出来的滚动
if (notification.metrics.axis == Axis.vertical) {
//确定是否到达了底部
if (notification.metrics.pixels >=
notification.metrics.maxScrollExtent) {
//确定当前允许加载更多
if (state is WXArticleLoaded &&
currentProjectPage < totalProjectPage) {
wXArticleBloc.dispatch(
LoadMoreWXArticleDatas(
originDatas: wXArticleDatas,
page: currentProjectPage + 1,
id: selectTypeId,
searchKey: searchKey,
),
);
}
return false;
}
}
}
return false;
},
child: RefreshIndicator(
color: WColors.theme_color,
onRefresh: () async {
if (!isLoading) {
searchKey = null; //下拉刷新时取消掉搜索key
wXArticleBloc.dispatch(LoadWXArticle(selectTypeId));
}
//app有自己的加载框样式,不使用RefreshIndicator拉出来的圆球作为加载框。所以onRefresh立即返回,让圆球立即消失
return;
},
child: CustomScrollView(
key: widget.pageStorageKey,
//在NestedScrollView的文档注释里有这句话:
// The "controller" and "primary" members should be left
// unset, so that the NestedScrollView can control this
// inner scroll view.
// If the "controller" property is set, then this scroll
// view will not be associated with the NestedScrollView.
// 所以这里不能设置controller
// controller: _scrollController,
physics: AlwaysScrollableScrollPhysics(
parent: ClampingScrollPhysics()),
slivers: <Widget>[
//头部分类栏
SliverToBoxAdapter(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
//分类
Padding(
padding: EdgeInsets.only(
left: pt(16), top: pt(16)),
child: Text(
res.author,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold),
),
),
ArticleTypeView.collaspTypesView(
collaspTypeScrollController:
collaspTypeScrollController,
key: typeKey,
types: types,
selectId: selectTypeId,
onExpanded: () {
setState(() {
typeIsExpanded = true;
});
},
onSelected: (selectId) {
if (!isLoading) {
setState(() {
selectTypeId = selectId;
wXArticleBloc.dispatch(
LoadMoreWXArticleDatas(
originDatas: [],
page: 1,
id: selectTypeId,
searchKey: searchKey,
),
);
});
}
},
),
],
),
),
),
//文章列表
SliverPadding(
padding: EdgeInsets.only(
top: pt(10),
),
sliver: WXArticleList(datas: wXArticleDatas)),
//底部footer
SliverToBoxAdapter(
child: getLoadMoreFooter(
currentProjectPage < totalProjectPage,
color: Colors.white,
),
),
],
),
),
),
//展开的分类
Positioned(
top: _getExpandedViewMarginTop(typeKey),
left: 0,
right: 0,
child: Offstage(
offstage: !typeIsExpanded,
child: AnimatedOpacity(
opacity: typeIsExpanded ? 1 : 0,
duration: Duration(milliseconds: 400),
child: ArticleTypeView.expandedTypesView(
types: types,
selectId: selectTypeId,
onExpanded: () {
setState(() {
typeIsExpanded = false;
});
},
onSelected: (selectId) {
if (!isLoading) {
setState(() {
typeIsExpanded = false;
selectTypeId = selectId;
wXArticleBloc.dispatch(
LoadMoreWXArticleDatas(
originDatas: [],
page: 1,
id: selectTypeId,
searchKey: searchKey,
),
);
});
}
},
),
),
),
),
//加载框
Offstage(
offstage: !isLoading,
child: getLoading(start: isLoading),
)
],
),
);
},
),
),
);
}
double _getExpandedViewMarginTop(GlobalKey relativeViewkey) {
if (rootKey.currentContext?.findRenderObject() == null ||
relativeViewkey.currentContext?.findRenderObject() == null) {
return 0.0;
}
RenderBox renderBox = rootKey.currentContext.findRenderObject();
double rootGlobalY = renderBox.localToGlobal(Offset.zero).dy;
renderBox = relativeViewkey.currentContext.findRenderObject();
double relativeViewGlobalY = renderBox.localToGlobal(Offset.zero).dy;
return Math.max(0.0, relativeViewGlobalY - rootGlobalY);
}
///公众号列表
Widget WXArticleList({List<ProjectEntity> datas = const []}) {
return SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
ProjectEntity data = datas[index];
return WXArticleItem(data, isLoading);
}, childCount: datas.length),
);
}
@override
bool get wantKeepAlive => true;
}
class WXArticleItem extends StatefulWidget {
ProjectEntity data;
bool isLoading;
WXArticleItem(
this.data,
this.isLoading,
);
@override
_WXArticleItemState createState() => _WXArticleItemState();
}
class _WXArticleItemState extends State<WXArticleItem>
with SingleTickerProviderStateMixin {
bool lastCollectState;
AnimationController _collectController;
Animation _collectAnim;
@override
void initState() {
super.initState();
_collectController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
CurvedAnimation curvedAnimation =
CurvedAnimation(parent: _collectController, curve: Curves.easeOut);
_collectAnim = Tween<double>(begin: 1, end: 1.8).animate(curvedAnimation);
}
@override
void dispose() {
_collectController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (lastCollectState == false && lastCollectState != widget.data.collect) {
_collectController.forward(from: 0).then((_) {
_collectController.reverse();
});
}
lastCollectState = widget.data.collect;
return Column(
children: [
ListTile(
dense: true,
contentPadding: EdgeInsets.only(right: pt(8), left: pt(8)),
leading: GestureDetector(
behavior: HitTestBehavior.opaque,
child: Container(
alignment: Alignment.center,
width: 40, //查看源码,这是leading的最小宽高
height: 40,
child: ScaleTransition(
scale: _collectAnim,
child: Icon(
widget.data.collect ? Icons.favorite : Icons.favorite_border,
color:
widget.data.collect ? WColors.warning_red : Colors.grey,
size: 24,
),
),
),
onTap: () {
if (!widget.isLoading) {
if (BlocProvider.of<HomeBloc>(context).isLogin) {
BlocProvider.of<WXArticleBloc>(context).dispatch(
CollectWXArticle(widget.data.id, !widget.data.collect),
);
} else {
Navigator.pushNamed(context, LoginWanandroidPage.ROUTER_NAME)
.then((_) {
BlocProvider.of<HomeBloc>(context).dispatch(LoadHome());
});
}
}
},
),
title: Text(
decodeString(widget.data.title),
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
children: [
widget.data.type == 1 //目前本人通过对比json差异猜测出type=1表示置顶类型
? Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.red[700])),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.stickTop,
style: TextStyle(
color: Colors.red[700],
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.fresh
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.warning_red)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.New,
style: TextStyle(
color: WColors.warning_red,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
///WanAndroid文档原话:superChapterId其实不是一级分类id,因为要拼接跳转url,内容实际都挂在二级分类下,所以该id实际上是一级分类的第一个子类目的id,拼接后故可正常跳转
widget.data.superChapterId == 294 //项目
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.theme_color_dark)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.project,
style: TextStyle(
color: WColors.theme_color_dark,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.superChapterId == 440 //问答
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.theme_color)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.QA,
style: TextStyle(
color: WColors.theme_color,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
Expanded(
child: Text(
'${res.author}:${widget.data.author} ${res.time}:${widget.data.niceDate}'),
),
],
),
onTap: () {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': widget.data.title,
'url': widget.data.link,
},
);
},
),
Divider(
height: 10,
),
],
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle | mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle/bloc/wxarticle_index.dart | export 'wxarticle_bloc.dart';
export 'wxarticle_event.dart';
export 'wxarticle_state.dart'; | 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle | mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle/bloc/wxarticle_state.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
abstract class WXArticleState extends Equatable {
WXArticleState([List props = const []]) : super(props);
}
class WXArticleUnready extends WXArticleState {
@override
String toString() {
return 'WXArticleUnready{}';
}
}
class WXArticleLoading extends WXArticleState {
@override
String toString() {
return 'WXArticleLoading{}';
}
}
class WXArticleTypesloaded extends WXArticleState {
List<ArticleTypeEntity> WXArticleTypes;
WXArticleTypesloaded(this.WXArticleTypes) : super([WXArticleTypes]);
@override
String toString() {
return 'WXArticleTypesloaded{WXArticleTypes: $WXArticleTypes}';
}
}
class WXArticleDatasLoaded extends WXArticleState {
List<ProjectEntity> datas;
int curretnPage;
int totalPage;
WXArticleDatasLoaded(this.datas, this.curretnPage, this.totalPage)
: super([datas, curretnPage, totalPage]);
@override
String toString() {
return 'WXArticleDatasLoaded{datas: $datas, curretnPage: $curretnPage, totalPage: $totalPage}';
}
}
///收藏状态变化
class WXArticleCollectChanged extends WXArticleState {
int id;
bool collect;
WXArticleCollectChanged(this.id, this.collect);
@override
String toString() {
return 'WXArticleCollectChanged{id: $id, collect: $collect}';
}
}
class WXArticleLoaded extends WXArticleState {
@override
String toString() {
return 'WXArticleLoaded{}';
}
}
class WXArticleLoadError extends WXArticleState {
Exception exception;
WXArticleLoadError(this.exception) : super([exception]);
@override
String toString() {
return 'WXArticleLoadError{exception: $exception}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle | mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle/bloc/wxarticle_event.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
abstract class WXArticleEvent extends Equatable {
WXArticleEvent([List props = const []]) : super(props);
}
///加载全部
class LoadWXArticle extends WXArticleEvent {
int id;
String searchKey;
LoadWXArticle(this.id, {this.searchKey}) : super([id, searchKey]);
@override
String toString() {
return 'LoadWXArticle{id: $id, searchKey: $searchKey}';
}
}
///加载(更多)公众号
class LoadMoreWXArticleDatas extends WXArticleEvent {
List<ProjectEntity> originDatas;
int id;
int page;
String searchKey;
LoadMoreWXArticleDatas({this.originDatas, this.id, this.page, this.searchKey})
: super([originDatas, id, page, searchKey]);
@override
String toString() {
return 'LoadMoreWXArticleDatas{originDatas: $originDatas, id: $id, page: $page, searchKey: $searchKey}';
}
}
///收藏、取消收藏
class CollectWXArticle extends WXArticleEvent {
int id;
bool collect;
CollectWXArticle(this.id, this.collect) : super([id, collect]);
@override
String toString() {
return 'CollectWXArticle{id: $id, collect: $collect}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle | mirrored_repositories/WanAndroid_Flutter/lib/page/home/wxarticle/bloc/wxarticle_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'WXArticle_index.dart';
class WXArticleBloc extends Bloc<WXArticleEvent, WXArticleState> {
HomeBloc homeBloc;
StreamSubscription subscription;
WXArticleBloc(this.homeBloc) {
print('WXArticle bloc constra');
///等主页的基础数据加载完了后,子页再开始加载数据
subscription = homeBloc.state.listen((state) {
if (state is HomeLoaded) {
print('微信公众号子页:主页加载完成,开始加载子页');
dispatch(LoadWXArticle(408)); //408是'鸿洋'公众号分类id
} else if (homeBloc.alredyHomeloaded &&
currentState == WXArticleUnready()) {
print('微信公众号子页:在构造函数之前主页就已经加载完成并可能已经发送了其他bloc state,开始加载子页');
dispatch(LoadWXArticle(408));
}
});
}
@override
void dispose() {
subscription?.cancel();
super.dispose();
}
@override
WXArticleState get initialState => WXArticleUnready();
@override
Stream<WXArticleState> mapEventToState(WXArticleEvent event) async* {
if (event is LoadWXArticle) {
yield* _mapLoadWXArticleToState(event.id, event.searchKey);
} else if (event is LoadMoreWXArticleDatas) {
yield* _mapLoadMoreWXArticleDatasToState(
datas: event.originDatas,
id: event.id,
page: event.page,
searchKey: event.searchKey);
} else if (event is CollectWXArticle) {
yield* _mapCollectWXArticleToState(event.id, event.collect);
}
}
Stream<WXArticleState> _mapLoadWXArticleToState(
int id, String searchKey) async* {
try {
yield WXArticleLoading();
List<ArticleTypeEntity> types = await _getTypes();
yield WXArticleTypesloaded(types);
WXArticleDatasLoaded datasState = await _getWXArticleDatasState(
datas: [],
id: id,
page: 1,
searchKey: searchKey,
);
yield datasState;
yield WXArticleLoaded();
} catch (e) {
yield WXArticleLoadError(e);
}
}
Stream<WXArticleState> _mapLoadMoreWXArticleDatasToState(
{List<ProjectEntity> datas, int id, int page, String searchKey}) async* {
try {
yield WXArticleLoading();
WXArticleDatasLoaded datasState = await _getWXArticleDatasState(
datas: datas,
id: id,
page: page,
searchKey: searchKey,
);
yield datasState;
yield WXArticleLoaded();
} catch (e) {
print(e);
yield WXArticleLoadError(e);
}
}
Stream<WXArticleState> _mapCollectWXArticleToState(
int id, bool collect) async* {
try {
yield WXArticleLoading();
if (collect) {
await CollectApi.collect(id);
} else {
await CollectApi.unCollect(id);
}
yield WXArticleCollectChanged(id, collect);
yield WXArticleLoaded();
} catch (e) {
yield WXArticleLoadError(e);
}
}
Future<List<ArticleTypeEntity>> _getTypes() async {
Response response = await WXArticleApi.getWXArticleTypes();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
List<ArticleTypeEntity> parentTypes =
baseEntity.data.map((e) => ArticleTypeEntity.fromJson(e)).toList();
// parentTypes.map((parent) {
// parent.children =
// parent.children.map((e) => ArticleTypeEntity.fromJson(e)).toList();
// }).toList();
return parentTypes;
}
//页码从1开始
Future<WXArticleDatasLoaded> _getWXArticleDatasState({
List<ProjectEntity> datas,
int id,
int page,
String searchKey,
}) async {
Response response;
response = await WXArticleApi.getWXArticleList(
page,
id,
searchKey: searchKey,
);
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
if (datas == null || datas.length == 0) {
datas =
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList();
} else {
datas.addAll(
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList());
}
return WXArticleDatasLoaded(
datas, baseListEntity.curPage, baseListEntity.pageCount);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/drawer/about_page.dart | import 'package:data_plugin/bmob/bmob_query.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wanandroid_flutter/entity/bmob_update_entity.dart';
import 'package:wanandroid_flutter/main.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class AboutPage extends StatefulWidget {
static const ROUTER_NAME = '/AboutPage';
@override
_AboutPageState createState() => _AboutPageState();
}
class _AboutPageState extends State<AboutPage> {
String appName;
String packageName;
String version;
String buildNumber;
@override
void initState() {
super.initState();
getPackageInfo();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(res.about),
),
body: Container(
color: WColors.gray_background,
child: ListView.builder(
itemBuilder: (context, index) {
if (index == 0) return _logo();
if (index == 1) {
return DecoratedBox(
decoration: BoxDecoration(color: Colors.white),
child: ListTile(
title: Text('GitHub'),
trailing: Icon(Icons.navigate_next),
onTap: (() {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': 'GitHub',
'url': 'https://github.com/CCY0122/WanAndroid_Flutter'
},
);
}),
),
);
}
if (index == 2) {
return DecoratedBox(
decoration: BoxDecoration(color: Colors.white),
child: ListTile(
title: Text('Blog'),
trailing: Icon(Icons.navigate_next),
onTap: (() {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': 'Blog',
'url': 'https://blog.csdn.net/ccy0122'
},
);
}),
),
);
}
return DecoratedBox(
decoration: BoxDecoration(color: Colors.white),
child: ListTile(
title: Text(res.checkUpdate),
trailing: Icon(Icons.navigate_next),
onTap: (() {
if (!bmobEnable) {
DisplayUtil.showMsg(context, text: '仅官方正式版支持检测升级');
return;
}
checkUpdate(context);
}),
),
);
},
itemCount: 4,
),
),
);
}
Widget _logo() {
return Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(
top: pt(70),
bottom: pt(20),
),
child: Image.asset(
'images/ic_launcher.png',
color: WColors.theme_color,
),
),
Padding(
padding: EdgeInsets.only(bottom: pt(30)),
child: Text('v.$version'),
),
],
);
}
Future getPackageInfo() async {
PackageInfo packageInfo = await PackageInfo.fromPlatform();
appName = packageInfo.appName;
packageName = packageInfo.packageName;
version = packageInfo.version;
buildNumber = packageInfo.buildNumber;
print('版本信息:$appName,$packageName,$version,$buildNumber');
setState(() {});
}
Future checkUpdate(BuildContext context) async{
try {
DisplayUtil.showMsg(context,text: 'checking...',duration: Duration(seconds: 1));
BmobQuery<BmobUpdateEntity> query = BmobQuery();
dynamic result = await query.queryObject('ed22ca3838');
BmobUpdateEntity entity = BmobUpdateEntity.fromJson(result);
print('$entity');
if (version != null) {
int cur = int.parse(version.replaceAll('.', ''));
int news = int.parse(entity.versionName.replaceAll('.', ''));
if (cur < news) {
if (mounted) {
showDialog(
context: context,
builder: (c) {
return AlertDialog(
title: Text(entity.versionName),
content: Text(entity.updateMsg),
actions: <Widget>[
FlatButton(
onPressed: () {
_launchURL(entity.downloadUrl);
},
child: Text(res.go),
),
],
);
});
return;
}
}
}
} catch (e) {
print(e);
if (mounted) {
DisplayUtil.showMsg(context, text: 'check update failed');
return;
}
}
if (mounted) {
DisplayUtil.showMsg(context, text: res.isNewestVersion);
}
}
_launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/drawer/rank_page.dart | import 'package:data_plugin/bmob/bmob_query.dart';
import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/views/level_view.dart';
class RankPage extends StatefulWidget {
static const ROUTER_NAME = '/RankPage';
@override
_RankPageState createState() => _RankPageState();
}
class _RankPageState extends State<RankPage> {
List<BmobUserEntity> datas;
@override
void initState() {
super.initState();
_getDatas();
}
@override
Widget build(BuildContext context) {
if (datas == null) {
return Scaffold(
appBar: AppBar(
title: Text(res.levelRank),
),
body: Center(
child: Text(res.isLoading),
),
);
}
if (datas.length == 0) {
return Scaffold(
appBar: AppBar(
title: Text(res.levelRank),
),
body: Center(
child: Text(res.allEmpty),
),
);
}
return Scaffold(
appBar: AppBar(
title: Text(res.levelRank),
),
body: ListView.builder(
itemBuilder: (c, i) {
return _item(datas[i], i);
},
itemCount: datas.length,
),
);
}
Widget _item(BmobUserEntity entity, int index) {
Color color;
Widget rank;
TextStyle style;
if (index == 0) {
color = Colors.red;
rank = Image.asset(
'images/no1.png',
width: pt(22),
height: pt(22),
color: color,
);
style = TextStyle(fontWeight: FontWeight.w700, color: color);
} else if (index == 1) {
color = Colors.orange;
rank = Image.asset(
'images/no2.png',
width: pt(22),
height: pt(22),
color: color,
);
style = TextStyle(fontWeight: FontWeight.w600, color: color);
} else if (index == 2) {
color = Colors.purple;
rank = Image.asset(
'images/no3.png',
width: pt(22),
height: pt(22),
color: color,
);
style = TextStyle(fontWeight: FontWeight.w500, color: color);
} else {
color = Colors.black;
rank = Container(
decoration: ShapeDecoration(
shape: CircleBorder(side: BorderSide(color: Colors.red))),
padding: EdgeInsets.all(pt(2.5)),
child: Text(
'${index + 1}',
style: TextStyle(color: Colors.red, fontSize: 12),
),
);
style = TextStyle(fontWeight: FontWeight.normal, color: color);
}
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
),
child: Padding(
padding: EdgeInsets.symmetric(horizontal: pt(16), vertical: pt(10)),
child: Row(
children: <Widget>[
Padding(
padding: EdgeInsets.only(right: pt(8)),
child: rank,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
entity.userName ?? 'unknow',
style: TextStyle(
fontSize: 18,
fontWeight: style.fontWeight,
color: style.color),
),
Text(
entity.signature ?? '',
style: TextStyle(
fontSize: 12,
fontWeight: style.fontWeight,
color: style.color),
),
],
),
),
getLevelWidgets(entity.level),
],
),
),
);
}
Future _getDatas() async {
try {
BmobQuery<BmobUserEntity> query = BmobQuery();
query.setOrder('-level');
List<dynamic> results = await query.queryObjects();
datas = results.map((e) => BmobUserEntity.fromJson(e)).toList();
setState(() {});
} catch (e) {
print(e);
}
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/drawer/support_author.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class SupportAuthorPage extends StatefulWidget {
static const ROUTER_NAME = '/SupportAuthorPage';
@override
_SupportAuthorPageState createState() => _SupportAuthorPageState();
}
class _SupportAuthorPageState extends State<SupportAuthorPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(res.supportAuthor),
),
body: Builder(
builder: (context) {
return SingleChildScrollView(
child: Column(
children: <Widget>[
//问题:如何保存asset文件到本地呢?
Image.asset('images/ccy_pay_qr.jpeg'),
RaisedButton(
onPressed: () {
_launchURL();
},
color: WColors.theme_color,
padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Text(
'去网页版打赏作者',
style: TextStyle(fontSize: 16, color: Colors.white),
),
),
Padding(
padding:
EdgeInsets.only(top: 16, left: 16, right: 16, bottom: 16),
child: Row(
children: <Widget>[
Expanded(
child: Text(
'微信:ccy01220122',
style: TextStyle(fontSize: 20),
),
),
RaisedButton(
onPressed: () {
Clipboard.setData(
ClipboardData(text: 'ccy01220122'),
);
DisplayUtil.showMsg(context, text: '已复制微信号');
},
color: WColors.theme_color_dark,
padding:
EdgeInsets.symmetric(vertical: 5, horizontal: 10),
child: Text(
'点击复制',
style: TextStyle(fontSize: 20, color: Colors.white),
),
)
],
),
),
Image.asset(
'images/nice_xiongdei.jpeg',
width: 150,
height: 150,
),
],
),
);
},
),
);
}
_launchURL() async {
var url = 'https://github.com/CCY0122/WanAndroid_Flutter/blob/master/WechatIMG34.jpeg';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/project/project_page.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:wanandroid_flutter/entity/banner_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/entity/project_type_entity.dart';
import 'package:wanandroid_flutter/entity/todo_entity.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/page/home/project/bloc/project_index.dart';
import 'package:wanandroid_flutter/page/home/project/project_detail_page.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/page/todo/todo_main.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/flat_pagination.dart';
import 'package:wanandroid_flutter/views/load_more_footer.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
///项目页
///BloC模式
class ProjectSubPage extends StatefulWidget {
PageStorageKey pageStorageKey;
ProjectSubPage(this.pageStorageKey);
@override
_ProjectSubPageState createState() => _ProjectSubPageState();
}
class _ProjectSubPageState extends State<ProjectSubPage>
with AutomaticKeepAliveClientMixin {
ProjectBloc projectBloc;
List<BannerEntity> banners;
List<ProjectTypeEntity> projectTypes;
List<ProjectEntity> projectDatas;
List<TodoEntity> todoDatas;
int currentProjectPage;
int totalProjectPage;
///不能直接使用[ProjectLoading]作为是否在加载的依据,原因见[ProjectBloc]
bool isLoading = false;
@override
void initState() {
super.initState();
projectBloc = ProjectBloc(BlocProvider.of<HomeBloc>(context));
banners ??= [];
projectTypes ??= [];
todoDatas ??= [];
projectDatas ??= [];
currentProjectPage ??= 1;
totalProjectPage ??= 1;
}
@override
void dispose() {
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
return BlocProviderTree(
blocProviders: [
BlocProvider<ProjectBloc>(
builder: (context) => projectBloc,
),
],
child: BlocListenerTree(
blocListeners: [
BlocListener<ProjectEvent, ProjectState>(
bloc: projectBloc,
listener: (context, state) {
if (state is ProjectLoading) {
isLoading = true;
} else if (state is ProjectLoaded || state is ProjectLoadError) {
isLoading = false;
}
if (state is ProjectBannerLoaded) {
banners = state.banners;
} else if (state is ProjectTypesLoaded) {
projectTypes = state.types;
} else if (state is ProjectTodoLoaded) {
todoDatas = state.todos;
} else if (state is ProjectDatasLoaded) {
currentProjectPage = state.curretnPage;
totalProjectPage = state.totalPage;
projectDatas = state.datas;
} else if (state is ProjectCollectChanged) {
projectDatas
.where((e) => e.id == state.id)
.map((e) => e.collect = state.collect)
.toList();
} else if (state is ProjectLoadError) {
DisplayUtil.showMsg(context, exception: state.exception);
}
},
),
],
child: BlocBuilder<ProjectEvent, ProjectState>(
bloc: projectBloc,
builder: (context, state) {
return NotificationListener(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
// print('scroll key = ${widget.pageStorageKey}');
//确定是项目列表发出来的滚动,而不是项目分类栏发出来的滚动
if (notification.metrics.axis == Axis.vertical) {
//确定是否到达了底部
if (notification.metrics.pixels >=
notification.metrics.maxScrollExtent) {
//确定当前允许加载更多
if (state is ProjectLoaded &&
currentProjectPage < totalProjectPage) {
projectBloc.dispatch(LoadMoreProjectDatas(
projectDatas, currentProjectPage + 1));
}
return false;
}
}
}
return false;
},
child: Stack(
children: <Widget>[
RefreshIndicator(
color: WColors.theme_color,
onRefresh: () async {
///鉴于flutter关于NestedScrollView的这个bug:https://github.com/flutter/flutter/issues/36419。
///所以当本页的下拉被拉出来时,实际上其他页(如articlePage)的下拉也被拉出来了。导致其他页也会触发刷新。
if (!isLoading) {
projectBloc.dispatch(LoadProject());
}
//app有自己的加载框样式,不使用RefreshIndicator拉出来的圆球作为加载框。所以onRefresh立即返回,让圆球立即消失
return;
},
child: CustomScrollView(
key: widget.pageStorageKey,
//在NestedScrollView的文档注释里有这句话:
// The "controller" and "primary" members should be left
// unset, so that the NestedScrollView can control this
// inner scroll view.
// If the "controller" property is set, then this scroll
// view will not be associated with the NestedScrollView.
// 所以这里不能设置controller
// controller: _scrollController,
physics: AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics()),
slivers: <Widget>[
//banner
SliverToBoxAdapter(
child: bannerView(
datas: banners.map((entity) {
return BannerModel(
entity.title ?? '',
entity.imagePath ?? '',
entity.url ?? '',
);
}).toList()),
),
//分类
SliverToBoxAdapter(
child: typesGridView(
datas: projectTypes
.asMap()
.map<int, ProjectTypesModel>((index, entity) {
return MapEntry(
index,
ProjectTypesModel(
entity.id,
entity.name,
Image.asset(
MyImage.animals[
index % MyImage.animals.length],
width: pt(40),
height: pt(40),
),
),
);
})
.values
.toList(),
),
),
//to-do轮播栏
SliverToBoxAdapter(
child: todoViewFlipper(datas: todoDatas),
),
//最新项目标题
SliverToBoxAdapter(
child: Container(
color: WColors.gray_background,
padding: EdgeInsets.only(left: pt(16), top: pt(8)),
child: Row(
children: <Widget>[
Image.asset(
'images/new.png',
width: pt(30),
height: pt(30),
),
SizedBox(
width: pt(10),
),
Text(
res.newestProject,
style: TextStyle(
color: Colors.black,
fontSize: 17,
fontWeight: FontWeight.bold),
)
],
),
),
),
//项目列表
projectGrid(datas: projectDatas),
//底部footer
SliverToBoxAdapter(
child: getLoadMoreFooter(
currentProjectPage < totalProjectPage),
),
],
),
),
Offstage(
offstage: !isLoading,
child: getLoading(start: isLoading),
)
],
),
);
},
),
),
);
}
///banner
Widget bannerView({List<BannerModel> datas = const []}) {
return Container(
height: pt(140 + 16 * 2.0),
padding: EdgeInsets.all(pt(16)),
child: ClipRRect(
borderRadius: BorderRadius.circular(pt(6)),
child: (datas == null || datas.length == 0)
? Container(
color: Colors.grey[300],
)
: Swiper(
itemCount: datas.length,
itemBuilder: (context, index) {
BannerModel data = datas[index];
return CachedNetworkImage(
imageUrl: data.imagePath,
fit: BoxFit.cover,
placeholder: (context, url) {
return DecoratedBox(
decoration: BoxDecoration(color: Colors.grey[300]),
);
},
);
},
autoplay: datas.length > 1,
pagination: SwiperPagination(
builder: FlatDotSwiperPaginationBuilder(
color: Colors.white,
activeColor: WColors.theme_color_light,
size: 5,
activeSize: 5,
space: 2.5,
),
alignment: Alignment.bottomRight,
),
onTap: (index) {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': datas[index].title,
'url': datas[index].url,
},
);
},
),
),
);
}
///项目分类网格布局,固定两行
Widget typesGridView({List<ProjectTypesModel> datas = const []}) {
if (datas == null || datas.length == 0) {
//占位view
return GridView.builder(
physics: NeverScrollableScrollPhysics(),
shrinkWrap: true,
itemBuilder: (context, index) {
return Container(
color: Colors.grey[300],
margin:
EdgeInsets.symmetric(horizontal: pt(9.375), vertical: pt(6)),
);
},
itemCount: 8,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 4, childAspectRatio: 1.25),
);
}
//这里无法用table实现。
//一行最多item
int maxOneRowCount = (datas.length / 2).ceil();
if (datas.length == 1) {
maxOneRowCount = 1;
}
//一行的一屏内最多可显示item
int maxOnScreenCount = 5;
double itemWidth;
if (maxOneRowCount <= maxOnScreenCount) {
//一屏放得下,均分屏幕宽
itemWidth = pt(375) / maxOneRowCount;
} else {
//一屏放不下,可横向滚动,末尾露出一半item让用户好发现这是可以横向滚动的
itemWidth = pt(375) / (maxOnScreenCount + 0.5);
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: Iterable.generate(maxOneRowCount, (index) {
ProjectTypesModel data = datas[index];
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, ProjectDetailPage.ROUTER_NAME,
arguments: {
'id': data.id,
'name': decodeString(data.title)
}).then((_) {
HomeBloc homeBloc = BlocProvider.of<HomeBloc>(context);
if (!homeBloc.isLogin) {
homeBloc.dispatch(LoadHome());
}
});
},
child: Container(
alignment: Alignment.center,
width: itemWidth,
height: pt(75),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
data.icon,
Text(
decodeString(data.title),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: WColors.hint_color_dark, fontSize: 11.5),
),
],
),
),
);
}).toList(),
),
datas.length == 1
? Container()
: Row(
children:
Iterable.generate(datas.length - maxOneRowCount, (index) {
ProjectTypesModel data = datas[index + maxOneRowCount];
return GestureDetector(
onTap: () {
Navigator.pushNamed(
context, ProjectDetailPage.ROUTER_NAME, arguments: {
'id': data.id,
'name': decodeString(data.title)
}).then((_) {
HomeBloc homeBloc =
BlocProvider.of<HomeBloc>(context);
if (!homeBloc.isLogin) {
homeBloc.dispatch(LoadHome());
}
});
},
child: Container(
alignment: Alignment.center,
width: itemWidth,
height: pt(75),
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
data.icon,
Text(
decodeString(data.title),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: WColors.hint_color_dark,
fontSize: 11.5),
),
],
),
),
);
}).toList(),
),
],
),
);
}
///to-do轮播栏
Widget todoViewFlipper({List<TodoEntity> datas = const []}) {
if (datas == null || datas.length == 0) {
return Container();
}
return Column(
children: <Widget>[
Divider(
height: 1,
),
Container(
height: pt(35),
alignment: Alignment.center,
padding: EdgeInsets.symmetric(horizontal: pt(16)),
child: Swiper(
physics: NeverScrollableScrollPhysics(),
onTap: (index) {
Navigator.pushNamed(context, TodoPage.ROUTER_NAME);
},
autoplayDelay: 5000,
duration: 1000,
scrollDirection: Axis.vertical,
itemCount: datas.length,
autoplay: datas.length > 1,
itemBuilder: (context, index) {
TodoEntity data = datas[index];
return Row(
children: <Widget>[
Icon(
Icons.alarm,
size: 20,
),
Expanded(
child: Container(
margin: EdgeInsets.symmetric(horizontal: pt(5)),
child: Text(
data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
Padding(
padding: EdgeInsets.only(right: pt(5)),
child: Text(
data.completeDateStr,
style: TextStyle(
fontSize: 12,
color: WColors.hint_color_dark,
),
),
),
Container(
decoration: BoxDecoration(
border: Border.all(
color: data.status == 1
? WColors.theme_color
: WColors.warning_red),
borderRadius: BorderRadius.circular(4)),
padding: EdgeInsets.symmetric(
horizontal: pt(4), vertical: pt(1)),
child: Text(
data.status == 1 ? res.done : res.undone,
style: TextStyle(
fontSize: 12,
color: data.status == 1
? WColors.theme_color
: WColors.warning_red),
),
),
],
);
},
),
)
],
);
}
///项目列表
Widget projectGrid({List<ProjectEntity> datas = const []}) {
return SliverGrid(
delegate: SliverChildBuilderDelegate(
(context, index) {
//问题:没有类似SliverDecoration这种控件,那么怎么独立设置sliver的背景颜色呢?暂时通过改变每个item的颜色来实现吧
return Container(
color: WColors.gray_background,
padding: index % 2 == 0
? EdgeInsets.only(
left: pt(12), right: pt(6), top: pt(6), bottom: pt(6))
: EdgeInsets.only(
left: pt(6), right: pt(12), top: pt(6), bottom: pt(6)),
child: projectItem(datas[index]),
);
},
childCount: datas.length,
),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 0.9,
),
);
}
///项目item
Widget projectItem(ProjectEntity data) {
return ProjectItem(data, isLoading);
}
@override
bool get wantKeepAlive => true;
}
class ProjectItem extends StatefulWidget {
ProjectEntity data;
bool isLoading;
ProjectItem(this.data, this.isLoading);
@override
_ProjectItemState createState() => _ProjectItemState();
}
class _ProjectItemState extends State<ProjectItem>
with SingleTickerProviderStateMixin {
bool lastCollectState;
AnimationController _collectController;
Animation _collectAnim;
@override
void initState() {
super.initState();
_collectController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
CurvedAnimation curvedAnimation =
CurvedAnimation(parent: _collectController, curve: Curves.easeOut);
_collectAnim = Tween<double>(begin: 1, end: 1.8).animate(curvedAnimation);
}
@override
void dispose() {
_collectController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (lastCollectState == false && lastCollectState != widget.data.collect) {
_collectController.forward(from: 0).then((_) {
_collectController.reverse();
});
}
lastCollectState = widget.data.collect;
return Card(
elevation: 0.5,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(pt(6))),
clipBehavior: Clip.antiAlias,
child: GestureDetector(
onTap: () {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': widget.data.title,
'url': widget.data.link,
},
);
},
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Stack(
children: <Widget>[
CachedNetworkImage(
imageUrl: widget.data.envelopePic,
width: double.infinity,
alignment: Alignment(0.0, -0.95),
fit: BoxFit.cover,
placeholder: (BuildContext context, String url) {
return Container(
color: Colors.grey[300],
);
},
errorWidget:
(BuildContext context, String url, Object error) {
return Container(
color: Colors.grey[300],
);
},
),
Positioned(
bottom: 0,
left: 0,
right: 0,
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
Colors.transparent,
Colors.black26,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
)),
padding: EdgeInsets.only(
left: pt(4),
bottom: pt(2),
top: pt(10),
),
child: Text(
widget.data.author,
style: TextStyle(color: Colors.white, fontSize: 11),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
],
),
),
Padding(
padding: EdgeInsets.symmetric(vertical: pt(4), horizontal: pt(4)),
child: Text(
widget.data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
),
),
GestureDetector(
// behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.pushNamed(context, ProjectDetailPage.ROUTER_NAME,
arguments: {
'id': widget.data.chapterId,
'name': decodeString(widget.data.chapterName)
}).then((_) {
HomeBloc homeBloc = BlocProvider.of<HomeBloc>(context);
if (!homeBloc.isLogin) {
homeBloc.dispatch(LoadHome());
}
});
},
child: Padding(
padding:
EdgeInsets.only(bottom: pt(6), left: pt(4), right: pt(4)),
child: Row(
children: <Widget>[
Text(
widget.data.chapterName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: 11,
color: WColors.hint_color_dark,
),
),
Icon(
Icons.chevron_right,
color: WColors.hint_color_dark,
size: pt(12),
),
Expanded(
child: Align(
alignment: Alignment(0.9, 0),
child: GestureDetector(
child: ScaleTransition(
scale: _collectAnim,
child: Icon(
widget.data.collect
? Icons.favorite
: Icons.favorite_border,
color: widget.data.collect
? WColors.warning_red
: Colors.grey,
size: 18,
),
),
onTap: () {
if (!widget.isLoading) {
if (BlocProvider.of<HomeBloc>(context).isLogin) {
BlocProvider.of<ProjectBloc>(context).dispatch(
CollectProject(
widget.data.id, !widget.data.collect),
);
} else {
Navigator.pushNamed(
context, LoginWanandroidPage.ROUTER_NAME)
.then((_) {
BlocProvider.of<HomeBloc>(context)
.dispatch(LoadHome());
});
}
}
},
),
))
],
),
),
),
],
),
),
);
}
}
class BannerModel {
BannerModel(
this.title,
this.imagePath,
this.url,
);
String title;
String imagePath;
String url;
}
class ProjectTypesModel {
int id;
String title;
Widget icon;
ProjectTypesModel(this.id, this.title, this.icon);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/project/project_detail_page.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/load_more_footer.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
///项目细分页
class ProjectDetailPage extends StatefulWidget {
static const ROUTER_NAME = '/ProjectDetailPage';
@override
_ProjectDetailPageState createState() => _ProjectDetailPageState();
}
class _ProjectDetailPageState extends State<ProjectDetailPage>
with TickerProviderStateMixin {
int typeId;
String typeName;
List<ProjectEntity> datas;
int currentPage;
int totalPage;
bool isloading;
ScrollController _scrollController;
BuildContext innerContext;
double lastOffsetPixels = 0;
@override
void initState() {
super.initState();
currentPage = 1;
totalPage = 1;
isloading = false;
datas = [];
_scrollController = ScrollController();
}
@override
Widget build(BuildContext context) {
if (typeId == null || typeName == null) {
Map args = ModalRoute.of(context).settings.arguments;
typeId = args['id'];
typeName = args['name'];
getProjects(id: typeId);
_scrollController.addListener(() {
if (_scrollController.position.pixels >=
_scrollController.position.maxScrollExtent) {
if (currentPage < totalPage &&
!isloading &&
_scrollController.position.pixels !=
lastOffsetPixels /*这个是为了避免没网时连续重复触发*/) {
lastOffsetPixels = _scrollController.position.pixels;
getProjects(page: currentPage + 1, id: typeId);
}
}
});
}
return Scaffold(
appBar: AppBar(
title: Text(typeName),
),
backgroundColor: WColors.gray_background,
body: Builder(
builder: (context) {
innerContext = context;
return getLoadingParent(
child: ListView.builder(
physics: ClampingScrollPhysics(),
//考虑到没网时下拉到底部会无限触发"加载更多->加载失败"的循环,_scrollController里做了特殊判断,所以这里不适合使用BouncingScrollPhysics这种可以overScroller的效果
itemBuilder: (context, index) {
if (index < datas.length) {
return Container(
margin: EdgeInsets.symmetric(
horizontal: pt(16), vertical: pt(8)),
height: pt(180),
child: ProjectItem(datas[index], isloading),
);
} else {
return getLoadMoreFooter(currentPage < totalPage);
}
},
itemCount: datas.length + 1,
controller: _scrollController,
),
isLoading: isloading,
);
},
),
);
}
Future getProjects({int page = 1, @required int id}) async {
isloading = true;
setState(() {});
try {
Response response = await ProjectApi.getProjectList(page, id);
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
currentPage = baseListEntity.curPage;
totalPage = baseListEntity.pageCount;
if (datas == null || datas.length == 0) {
datas =
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList();
} else {
datas.addAll(baseListEntity.datas
.map((e) => ProjectEntity.fromJson(e))
.toList());
}
} catch (e) {
if (innerContext != null) {
DisplayUtil.showMsg(innerContext, exception: e);
}
}
isloading = false;
setState(() {});
}
}
class ProjectItem extends StatefulWidget {
ProjectEntity data;
bool isLoading;
ProjectItem(this.data, this.isLoading);
@override
_ProjectItemState createState() => _ProjectItemState();
}
class _ProjectItemState extends State<ProjectItem>
with SingleTickerProviderStateMixin {
bool lastCollectState;
AnimationController _collectController;
Animation _collectAnim;
@override
void initState() {
super.initState();
_collectController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
CurvedAnimation curvedAnimation =
CurvedAnimation(parent: _collectController, curve: Curves.easeOut);
_collectAnim = Tween<double>(begin: 1, end: 1.8).animate(curvedAnimation);
}
@override
void dispose() {
_collectController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (lastCollectState == false && lastCollectState != widget.data.collect) {
_collectController.forward(from: 0).then((_) {
_collectController.reverse();
});
}
lastCollectState = widget.data.collect;
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
boxShadow: [DisplayUtil.lightElevation(baseColor: Colors.grey[300])],
),
child: GestureDetector(
onTap: () {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': widget.data.title,
'url': widget.data.link,
},
);
},
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
CachedNetworkImage(
imageUrl: widget.data.envelopePic,
height: double.infinity,
width: pt(100),
alignment: Alignment(0.0, -0.95),
fit: BoxFit.cover,
placeholder: (BuildContext context, String url) {
return Container(
width: pt(100),
color: Colors.grey[300],
alignment: Alignment.center,
child: CupertinoActivityIndicator(),
);
},
errorWidget: (BuildContext context, String url, Object error) {
return Container(
width: pt(100),
color: Colors.grey[300],
);
},
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: EdgeInsets.symmetric(
vertical: pt(4), horizontal: pt(4)),
child: Text(
decodeString(widget.data.title),
style:
TextStyle(fontSize: 14, fontWeight: FontWeight.w500),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.symmetric(
vertical: pt(2), horizontal: pt(4)),
child: Text(
decodeString(widget.data.desc),
overflow: TextOverflow.fade,
style: TextStyle(
fontSize: 13, color: WColors.hint_color_dark),
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(pt(4), pt(4), pt(8), pt(4)),
child: Row(
children: [
Expanded(
child: Text(
'${widget.data.niceDate} ${widget.data.author}',
overflow: TextOverflow.ellipsis,
style: TextStyle(color: WColors.hint_color_dark),
),
),
GestureDetector(
child: ScaleTransition(
scale: _collectAnim,
child: Icon(
widget.data.collect
? Icons.favorite
: Icons.favorite_border,
color: widget.data.collect
? WColors.warning_red
: Colors.grey,
size: 22,
),
),
onTap: () {
if (widget.isLoading) {
return;
}
SPUtil.isLogin().then(
(isLogin) {
if (isLogin) {
collect(widget.data.id, !widget.data.collect);
} else {
Navigator.pushNamed(
context, LoginWanandroidPage.ROUTER_NAME);
}
},
);
},
),
],
),
),
],
),
),
],
),
),
);
}
Future collect(int id, bool collect) async {
try {
if (collect) {
await CollectApi.collect(id);
} else {
await CollectApi.unCollect(id);
}
widget.data.collect = collect;
} catch (e) {
print(e);
DisplayUtil.showMsg(context, exception: e);
}
setState(() {});
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/project | mirrored_repositories/WanAndroid_Flutter/lib/page/home/project/bloc/project_state.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/banner_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/entity/project_type_entity.dart';
import 'package:wanandroid_flutter/entity/todo_entity.dart';
abstract class ProjectState extends Equatable {
ProjectState([List props = const []]) : super(props);
}
class ProjectUnready extends ProjectState {
@override
String toString() {
return 'ProjectUnready{}';
}
}
class ProjectLoading extends ProjectState {
@override
String toString() {
return 'ProjectLoading{}';
}
}
///banner数据加载完成
class ProjectBannerLoaded extends ProjectState {
List<BannerEntity> banners;
ProjectBannerLoaded(this.banners) : super([banners]);
@override
String toString() {
return 'ProjectBannerLoaded{banners: ${banners?.length}}';
}
}
///项目分类加载完成
class ProjectTypesLoaded extends ProjectState {
List<ProjectTypeEntity> types;
ProjectTypesLoaded(this.types) : super([types]);
@override
String toString() {
return 'ProjectTypesLoaded{types: ${types?.length}}';
}
}
///to-do数据加载完成
class ProjectTodoLoaded extends ProjectState {
List<TodoEntity> todos;
ProjectTodoLoaded(this.todos) : super([todos]);
@override
String toString() {
return 'ProjectTodoLoaded{todos: ${todos?.length}';
}
}
///最新项目加载完成
class ProjectDatasLoaded extends ProjectState {
List<ProjectEntity> datas;
int curretnPage;
int totalPage;
ProjectDatasLoaded(this.datas, this.curretnPage, this.totalPage)
: super([datas, curretnPage, totalPage]);
@override
String toString() {
return 'ProjectDatasLoaded{datas: ${datas?.length}, curretnPage: $curretnPage, totalPage: $totalPage}';
}
}
///收藏状态变化
class ProjectCollectChanged extends ProjectState {
int id;
bool collect;
ProjectCollectChanged(this.id, this.collect);
@override
String toString() {
return 'ProjectCollectChanged{id: $id, collect: $collect}';
}
}
///页面加载完成
class ProjectLoaded extends ProjectState {
@override
String toString() {
return 'ProjectLoaded{}';
}
}
class ProjectLoadError extends ProjectState {
Exception exception;
ProjectLoadError(this.exception) : super([exception]);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/project | mirrored_repositories/WanAndroid_Flutter/lib/page/home/project/bloc/project_event.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
abstract class ProjectEvent extends Equatable {
ProjectEvent([List props = const []]) : super(props);
}
///加载全部
class LoadProject extends ProjectEvent {
@override
String toString() {
return 'LoadProject{}';
}
}
///加载更多项目
class LoadMoreProjectDatas extends ProjectEvent {
List<ProjectEntity> originDatas;
int page;
LoadMoreProjectDatas(this.originDatas, this.page)
: super([originDatas, page]);
@override
String toString() {
return 'LoadMoreProjectDatas{originDatas: ${originDatas?.length}, page: $page}';
}
}
///收藏、取消收藏
class CollectProject extends ProjectEvent {
int id;
bool collect;
CollectProject(this.id, this.collect) : super([id, collect]);
@override
String toString() {
return 'CollectProject{id: $id, collect: $collect}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/project | mirrored_repositories/WanAndroid_Flutter/lib/page/home/project/bloc/project_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:wanandroid_flutter/entity/banner_entity.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/entity/project_type_entity.dart';
import 'package:wanandroid_flutter/entity/todo_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'project_index.dart';
class ProjectBloc extends Bloc<ProjectEvent, ProjectState> {
HomeBloc homeBloc;
StreamSubscription subscription;
ProjectBloc(this.homeBloc) {
print('project bloc constra');
///等主页的基础数据加载完了后,子页再开始加载数据
///因为state使用的是BehaviorSubject,即粘性广播,所以即使ProjectBloc在HomeBloc发送了HomeLoaded之后才被实例,listen依然能接收到该事件。这也是为什么不用blocListener的原因(它会skip(1))
subscription = homeBloc.state.listen((state) {
if (state is HomeLoaded) {
print('项目子页:主页加载完成,开始加载子页');
dispatch(LoadProject());
}
});
}
@override
void dispose() {
subscription?.cancel();
super.dispose();
}
@override
ProjectState get initialState => ProjectUnready();
@override
Stream<ProjectState> mapEventToState(ProjectEvent event) async* {
if (event is LoadProject) {
yield* _mapLoadProjectToState();
} else if (event is LoadMoreProjectDatas) {
yield* _mapLoadMoreProjectDatasToState(event.originDatas, event.page);
} else if (event is CollectProject) {
yield* _mapCollectProjectToState(event.id, event.collect);
}
}
Stream<ProjectState> _mapLoadProjectToState() async* {
try {
///从这里可知,UI层是否显示加载框不能依赖于ProjectLoading状态,因为在ProjectLoaded之前还有一些中间状态,
///所以UI层要自己记录isLoading,即ProjectLoading时置为true,直到ProjectLoaded或ProjectLoadError时置为false
yield ProjectLoading();
List<BannerEntity> bannerEntitys = await _getBanners();
yield ProjectBannerLoaded(bannerEntitys);
List<ProjectTypeEntity> types = await _getProjectTypes();
yield ProjectTypesLoaded(types);
///获取to-do列表需要已登录
if (homeBloc.isLogin) {
List<TodoEntity> todos = await _getTodos();
yield ProjectTodoLoaded(todos);
} else {
yield ProjectTodoLoaded([]);
}
ProjectDatasLoaded datasState = await _getProjectDatasState([], 1);
yield datasState;
yield ProjectLoaded();
} catch (e) {
yield ProjectLoadError(e);
}
}
Stream<ProjectState> _mapLoadMoreProjectDatasToState(
List<ProjectEntity> datas, int page) async* {
try {
yield ProjectLoading();
ProjectDatasLoaded datasState = await _getProjectDatasState(datas, page);
yield datasState;
yield ProjectLoaded();
} catch (e) {
yield ProjectLoadError(e);
}
}
Stream<ProjectState> _mapCollectProjectToState(int id, bool collect) async* {
try {
yield ProjectLoading();
if (collect) {
await CollectApi.collect(id);
} else {
await CollectApi.unCollect(id);
}
yield ProjectCollectChanged(id, collect);
yield ProjectLoaded();
} catch (e) {
yield ProjectLoadError(e);
}
}
//不用加try-catch,调用层已捕获了
Future<List<BannerEntity>> _getBanners() async {
Response response = await ProjectApi.getBanners();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
List<BannerEntity> bannerEntitys = baseEntity.data.map((e) {
return BannerEntity.fromJson(e);
}).toList();
return bannerEntitys;
}
Future<List<ProjectTypeEntity>> _getProjectTypes() async {
Response response = await ProjectApi.getProjectTree();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
List<ProjectTypeEntity> types = baseEntity.data.map((e) {
return ProjectTypeEntity.fromJson(e);
}).toList();
return types;
}
//获取未完成的to-do
Future<List<TodoEntity>> _getTodos() async {
Response response = await TodoApi.getTodoList(1);
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
List<TodoEntity> newDatas = baseListEntity.datas.map((json) {
return TodoEntity.fromJson(json);
}).toList();
return newDatas;
}
//页码从1开始
Future<ProjectDatasLoaded> _getProjectDatasState(
List<ProjectEntity> datas, int page) async {
Response response = await ProjectApi.getNewProjects(page);
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
if (datas == null || datas.length == 0) {
datas =
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList();
} else {
datas.addAll(
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList());
}
return ProjectDatasLoaded(
datas, baseListEntity.curPage, baseListEntity.pageCount);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/project | mirrored_repositories/WanAndroid_Flutter/lib/page/home/project/bloc/project_index.dart | export 'project_event.dart';
export 'project_state.dart';
export 'project_bloc.dart'; | 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/article/article_page.dart | import 'dart:math' as Math;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/article/bloc/article_index.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/article_type_view.dart';
import 'package:wanandroid_flutter/views/load_more_footer.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
///博文页
///BloC模式
class ArticleSubPage extends StatefulWidget {
PageStorageKey pageStorageKey;
ArticleSubPage(this.pageStorageKey);
@override
_ArticleSubPageState createState() => _ArticleSubPageState();
}
class _ArticleSubPageState extends State<ArticleSubPage>
with AutomaticKeepAliveClientMixin {
ArticleBloc articleBloc;
List<ArticleTypeEntity> types;
List<ProjectEntity> articleDatas;
int currentProjectPage;
int totalProjectPage;
int selectParentId;
int selectChildId;
ScrollController collaspTypeScrollController;
bool parentTypeIsExpanded;
bool childTypeIsExpanded;
///不能直接使用[ArticleLoading]作为是否在加载的依据
bool isLoading = false;
GlobalKey rootKey;
GlobalKey parentTypeKey;
GlobalKey childTypeKey;
@override
void initState() {
super.initState();
articleBloc = ArticleBloc(BlocProvider.of<HomeBloc>(context));
types ??= [];
articleDatas ??= [];
currentProjectPage ??= 1;
totalProjectPage ??= 1;
selectParentId = -1;
selectChildId = -1;
parentTypeIsExpanded = false;
childTypeIsExpanded = false;
rootKey = GlobalKey();
parentTypeKey = GlobalKey();
childTypeKey = GlobalKey();
collaspTypeScrollController = ScrollController();
}
@override
Widget build(BuildContext context) {
super.build(context);
return BlocProviderTree(
key: rootKey,
blocProviders: [
BlocProvider<ArticleBloc>(builder: (context) => articleBloc),
],
child: BlocListenerTree(
blocListeners: [
BlocListener<ArticleEvent, ArticleState>(
bloc: articleBloc,
listener: (context, state) {
if (state is ArticleLoading) {
isLoading = true;
} else if (state is ArticleLoaded || state is ArticleLoadError) {
isLoading = false;
}
if (state is ArticleTypesloaded) {
types = state.articleTypes;
//插入'最新博文'类别
types.insert(
0,
ArticleTypeEntity.simple(
res.newestArticle,
-1,
<ArticleTypeEntity>[
ArticleTypeEntity.simple(
res.newestArticle,
-1,
[],
),
],
),
);
} else if (state is ArticleDatasLoaded) {
articleDatas = state.datas;
currentProjectPage = state.curretnPage;
totalProjectPage = state.totalPage;
} else if (state is ArticleCollectChanged) {
articleDatas
.where((e) => e.id == state.id)
.map((e) => e.collect = state.collect)
.toList();
} else if (state is ArticleLoadError) {
DisplayUtil.showMsg(context, exception: state.exception);
}
},
)
],
child: BlocBuilder<ArticleEvent, ArticleState>(
bloc: articleBloc,
builder: (context, state) {
return NotificationListener(
onNotification: (notification) {
//不要在这里检测加载更多,因为子树可能有多个垂直滚动widget
//so问题来了:如何在NotificationListener确定一个ScrollNotification是由哪个scrollable widget发来的?
},
child: Stack(
children: <Widget>[
NotificationListener(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
//确定是博文列表发出来的滚动,而不是博文分类栏发出来的滚动
if (notification.metrics.axis == Axis.vertical) {
//确定是否到达了底部
if (notification.metrics.pixels >=
notification.metrics.maxScrollExtent) {
//确定当前允许加载更多
if (state is ArticleLoaded &&
currentProjectPage < totalProjectPage) {
articleBloc.dispatch(
LoadMoreArticleDatas(
originDatas: articleDatas,
page: currentProjectPage + 1,
id: selectChildId,
),
);
}
return false;
}
}
}
return false;
},
child: RefreshIndicator(
color: WColors.theme_color,
onRefresh: () async {
if (!isLoading) {
articleBloc.dispatch(LoadArticle(selectChildId));
}
//app有自己的加载框样式,不使用RefreshIndicator拉出来的圆球作为加载框。所以onRefresh立即返回,让圆球立即消失
return;
},
child: CustomScrollView(
// key: widget.pageStorageKey,
//在NestedScrollView的文档注释里有这句话:
// The "controller" and "primary" members should be left
// unset, so that the NestedScrollView can control this
// inner scroll view.
// If the "controller" property is set, then this scroll
// view will not be associated with the NestedScrollView.
// 所以这里不能设置controller
// controller: _scrollController,
physics: AlwaysScrollableScrollPhysics(
parent: ClampingScrollPhysics()),
slivers: <Widget>[
//头部分类栏
SliverToBoxAdapter(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
//一级分类
Padding(
padding: EdgeInsets.only(
left: pt(16), top: pt(16)),
child: Text(
res.typeLevel1,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold),
),
),
ArticleTypeView.collaspTypesView(
collaspTypeScrollController:
collaspTypeScrollController,
key: parentTypeKey,
types: types,
selectId: selectParentId,
onExpanded: () {
setState(() {
parentTypeIsExpanded = true;
childTypeIsExpanded = false;
});
},
onSelected: (selectId) {
if (!isLoading) {
setState(() {
selectParentId = selectId;
selectChildId =
_getChildTypes()[0].id;
articleBloc.dispatch(
LoadMoreArticleDatas(
originDatas: [],
page: 1,
id: selectChildId,
),
);
});
}
},
),
//二级分类
Padding(
padding: EdgeInsets.only(
left: pt(16),
),
child: Text(
res.typeLevel2,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold),
),
),
ArticleTypeView.collaspTypesView(
collaspTypeScrollController:
collaspTypeScrollController,
key: childTypeKey,
types: _getChildTypes(),
selectId: selectChildId,
onExpanded: () {
setState(() {
parentTypeIsExpanded = false;
childTypeIsExpanded = true;
});
},
onSelected: (selectId) {
if (!isLoading) {
setState(() {
selectChildId = selectId;
articleBloc.dispatch(
LoadMoreArticleDatas(
originDatas: [],
page: 1,
id: selectChildId,
),
);
});
}
},
),
],
),
),
),
//文章列表
SliverPadding(
padding: EdgeInsets.only(
top: pt(10),
),
sliver: articleList(datas: articleDatas)),
//底部footer
SliverToBoxAdapter(
child: getLoadMoreFooter(
currentProjectPage < totalProjectPage,
color: Colors.white,
),
),
],
),
),
),
//展开的一级分类
Positioned(
top: _getExpandedViewMarginTop(parentTypeKey),
left: 0,
right: 0,
child: Offstage(
offstage: !parentTypeIsExpanded,
child: AnimatedOpacity(
opacity: parentTypeIsExpanded ? 1 : 0,
duration: Duration(milliseconds: 400),
child: ArticleTypeView.expandedTypesView(
types: types,
selectId: selectParentId,
onExpanded: () {
setState(() {
parentTypeIsExpanded = false;
});
},
onSelected: (selectId) {
if (!isLoading) {
setState(() {
parentTypeIsExpanded = false;
selectParentId = selectId;
selectChildId = _getChildTypes()[0].id;
articleBloc.dispatch(
LoadMoreArticleDatas(
originDatas: [],
page: 1,
id: selectChildId,
),
);
});
}
},
),
),
),
),
//展开的二级分类
Positioned(
top: _getExpandedViewMarginTop(childTypeKey),
left: 0,
right: 0,
child: Offstage(
offstage: !childTypeIsExpanded,
child: AnimatedOpacity(
opacity: childTypeIsExpanded ? 1 : 0,
duration: Duration(milliseconds: 400),
child: ArticleTypeView.expandedTypesView(
types: _getChildTypes(),
selectId: selectChildId,
onExpanded: () {
setState(() {
childTypeIsExpanded = false;
});
},
onSelected: (selectId) {
if (!isLoading) {
setState(() {
childTypeIsExpanded = false;
selectChildId = selectId;
articleBloc.dispatch(
LoadMoreArticleDatas(
originDatas: [],
page: 1,
id: selectChildId,
),
);
});
}
},
),
),
),
),
//加载框
Offstage(
offstage: !isLoading,
child: getLoading(start: isLoading),
)
],
),
);
},
),
),
);
}
List<ArticleTypeEntity> _getChildTypes() {
List<ArticleTypeEntity> list =
types.where((e) => e.id == selectParentId).toList();
if (list.length >= 1) {
return list[0].children;
} else {
return <ArticleTypeEntity>[
ArticleTypeEntity.simple(
res.newestArticle,
-1,
[],
),
];
}
}
double _getExpandedViewMarginTop(GlobalKey relativeViewkey) {
if (rootKey.currentContext?.findRenderObject() == null ||
relativeViewkey.currentContext?.findRenderObject() == null) {
return 0.0;
}
RenderBox renderBox = rootKey.currentContext.findRenderObject();
double rootGlobalY = renderBox.localToGlobal(Offset.zero).dy;
renderBox = relativeViewkey.currentContext.findRenderObject();
double relativeViewGlobalY = renderBox.localToGlobal(Offset.zero).dy;
return Math.max(0.0, relativeViewGlobalY - rootGlobalY);
}
///博文列表
Widget articleList({List<ProjectEntity> datas = const []}) {
return SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
ProjectEntity data = datas[index];
return ArticleItem(data, isLoading);
}, childCount: datas.length),
);
}
@override
bool get wantKeepAlive => true;
}
class ArticleItem extends StatefulWidget {
ProjectEntity data;
bool isLoading;
ArticleItem(
this.data,
this.isLoading,
);
@override
_ArticleItemState createState() => _ArticleItemState();
}
class _ArticleItemState extends State<ArticleItem>
with SingleTickerProviderStateMixin {
bool lastCollectState;
AnimationController _collectController;
Animation _collectAnim;
@override
void initState() {
super.initState();
_collectController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
CurvedAnimation curvedAnimation =
CurvedAnimation(parent: _collectController, curve: Curves.easeOut);
_collectAnim = Tween<double>(begin: 1, end: 1.8).animate(curvedAnimation);
}
@override
void dispose() {
_collectController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (lastCollectState == false && lastCollectState != widget.data.collect) {
_collectController.forward(from: 0).then((_) {
_collectController.reverse();
});
}
lastCollectState = widget.data.collect;
return Column(
children: [
ListTile(
dense: true,
contentPadding: EdgeInsets.only(right: pt(8), left: pt(8)),
leading: GestureDetector(
behavior: HitTestBehavior.opaque,
child: Container(
alignment: Alignment.center,
width: 40, //查看源码,这是leading的最小宽高
height: 40,
child: ScaleTransition(
scale: _collectAnim,
child: Icon(
widget.data.collect ? Icons.favorite : Icons.favorite_border,
color:
widget.data.collect ? WColors.warning_red : Colors.grey,
size: 24,
),
),
),
onTap: () {
if (!widget.isLoading) {
if (BlocProvider.of<HomeBloc>(context).isLogin) {
BlocProvider.of<ArticleBloc>(context).dispatch(
CollectArticle(widget.data.id, !widget.data.collect),
);
} else {
Navigator.pushNamed(context, LoginWanandroidPage.ROUTER_NAME)
.then((_) {
BlocProvider.of<HomeBloc>(context).dispatch(LoadHome());
});
}
}
},
),
title: Text(
decodeString(widget.data.title),
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
children: [
widget.data.type == 1 //目前本人通过对比json差异猜测出type=1表示置顶类型
? Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.red[700])),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.stickTop,
style: TextStyle(
color: Colors.red[700],
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.fresh
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.warning_red)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.New,
style: TextStyle(
color: WColors.warning_red,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
///WanAndroid文档原话:superChapterId其实不是一级分类id,因为要拼接跳转url,内容实际都挂在二级分类下,所以该id实际上是一级分类的第一个子类目的id,拼接后故可正常跳转
widget.data.superChapterId == 294 //项目
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.theme_color_dark)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.project,
style: TextStyle(
color: WColors.theme_color_dark,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.superChapterId == 440 //问答
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.theme_color)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.QA,
style: TextStyle(
color: WColors.theme_color,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.superChapterId == 408 //公众号
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.theme_color_light)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.vxArticle,
style: TextStyle(
color: WColors.theme_color_light,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
Expanded(
child: Text(
'${res.author}:${widget.data.author} ${res.time}:${widget.data.niceDate}',),
),
],
),
onTap: () {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': widget.data.title,
'url': widget.data.link,
},
);
},
),
Divider(
height: 10,
),
],
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/article | mirrored_repositories/WanAndroid_Flutter/lib/page/home/article/bloc/article_state.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
abstract class ArticleState extends Equatable {
ArticleState([List props = const []]) : super(props);
}
class ArticleUnready extends ArticleState {
@override
String toString() {
return 'ArticleUnready{}';
}
}
class ArticleLoading extends ArticleState {
@override
String toString() {
return 'ArticleLoading{}';
}
}
class ArticleTypesloaded extends ArticleState {
List<ArticleTypeEntity> articleTypes;
ArticleTypesloaded(this.articleTypes) : super([articleTypes]);
@override
String toString() {
return 'ArticleTypesloaded{articleTypes: ${articleTypes?.length}';
}
}
class ArticleDatasLoaded extends ArticleState {
List<ProjectEntity> datas;
int curretnPage;
int totalPage;
ArticleDatasLoaded(this.datas, this.curretnPage, this.totalPage)
: super([datas, curretnPage, totalPage]);
@override
String toString() {
return 'ArticleDatasLoaded{datas: ${datas?.length}, curretnPage: $curretnPage, totalPage: $totalPage}';
}
}
///收藏状态变化
class ArticleCollectChanged extends ArticleState {
int id;
bool collect;
ArticleCollectChanged(this.id, this.collect);
@override
String toString() {
return 'ArticleCollectChanged{id: $id, collect: $collect}';
}
}
class ArticleLoaded extends ArticleState {
@override
String toString() {
return 'ArticleLoaded{}';
}
}
class ArticleLoadError extends ArticleState {
Exception exception;
ArticleLoadError(this.exception) : super([exception]);
@override
String toString() {
return 'ArticleLoadError{exception: $exception}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/article | mirrored_repositories/WanAndroid_Flutter/lib/page/home/article/bloc/article_event.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
abstract class ArticleEvent extends Equatable {
ArticleEvent([List props = const []]) : super(props);
}
///加载全部
class LoadArticle extends ArticleEvent {
///如果为-1,则加载最新博文,否则加载对应id类型的博文
int id;
LoadArticle(this.id) : super([id]);
@override
String toString() {
return 'LoadArticle{id: $id}';
}
}
///加载(更多)博文
class LoadMoreArticleDatas extends ArticleEvent {
List<ProjectEntity> originDatas;
int id;
int page;
LoadMoreArticleDatas({this.originDatas, this.id, this.page})
: super([originDatas, id, page]);
@override
String toString() {
return 'LoadMoreArticleDatas{originDatas: ${originDatas?.length}, id: $id, page: $page}';
}
}
///收藏、取消收藏
class CollectArticle extends ArticleEvent {
int id;
bool collect;
CollectArticle(this.id, this.collect) : super([id, collect]);
@override
String toString() {
return 'CollectArticle{id: $id, collect: $collect}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/article | mirrored_repositories/WanAndroid_Flutter/lib/page/home/article/bloc/article_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:wanandroid_flutter/entity/article_type_entity.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'article_index.dart';
class ArticleBloc extends Bloc<ArticleEvent, ArticleState> {
HomeBloc homeBloc;
StreamSubscription subscription;
ArticleBloc(this.homeBloc) {
print('article bloc constra');
///等主页的基础数据加载完了后,子页再开始加载数据
subscription = homeBloc.state.listen((state) {
if (state is HomeLoaded) {
print('博文子页:主页加载完成,开始加载子页');
dispatch(LoadArticle(-1));
}else if(homeBloc.alredyHomeloaded && currentState == ArticleUnready()){
print('博文子页:在构造函数之前主页就已经加载完成并可能已经发送了其他bloc state,开始加载子页');
dispatch(LoadArticle(-1));
}
});
}
@override
void dispose() {
subscription?.cancel();
super.dispose();
}
@override
ArticleState get initialState => ArticleUnready();
@override
Stream<ArticleState> mapEventToState(ArticleEvent event) async* {
if (event is LoadArticle) {
yield* _mapLoadArticleToState(event.id);
} else if (event is LoadMoreArticleDatas) {
yield* _mapLoadMoreArticleDatasToState(
datas: event.originDatas,
id: event.id,
page: event.page,
);
} else if (event is CollectArticle) {
yield* _mapCollectArticleToState(event.id, event.collect);
}
}
Stream<ArticleState> _mapLoadArticleToState(int id) async* {
try {
yield ArticleLoading();
List<ArticleTypeEntity> types = await _getTypes();
yield ArticleTypesloaded(types);
ArticleDatasLoaded datasState = await _getArticleDatasState(
datas: [],
id: id,
page: 1,
);
yield datasState;
yield ArticleLoaded();
} catch (e) {
yield ArticleLoadError(e);
}
}
Stream<ArticleState> _mapLoadMoreArticleDatasToState(
{List<ProjectEntity> datas, int id, int page}) async* {
try {
yield ArticleLoading();
ArticleDatasLoaded datasState = await _getArticleDatasState(
datas: datas,
id: id,
page: page,
);
yield datasState;
yield ArticleLoaded();
} catch (e) {
yield ArticleLoadError(e);
}
}
Stream<ArticleState> _mapCollectArticleToState(int id, bool collect) async* {
try {
yield ArticleLoading();
if (collect) {
await CollectApi.collect(id);
} else {
await CollectApi.unCollect(id);
}
yield ArticleCollectChanged(id, collect);
yield ArticleLoaded();
} catch (e) {
yield ArticleLoadError(e);
}
}
Future<List<ArticleTypeEntity>> _getTypes() async {
Response response = await ArticleApi.getArticleTypes();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
List<ArticleTypeEntity> parentTypes =
baseEntity.data.map((e) => ArticleTypeEntity.fromJson(e)).toList();
parentTypes.map((parent) {
parent.children =
parent.children.map((e) => ArticleTypeEntity.fromJson(e)).toList();
}).toList();
return parentTypes;
}
///页码从1开始
///id : 如果为-1,则加载最新博文,否则加载对应id类型的博文
Future<ArticleDatasLoaded> _getArticleDatasState(
{List<ProjectEntity> datas, int id, int page}) async {
Response response;
if (id == -1) {
response = await ArticleApi.getNewArticle(page);
} else {
response = await ArticleApi.getArticleList(page, id);
}
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
if (datas == null || datas.length == 0) {
datas =
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList();
} else {
datas.addAll(
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList());
}
if (id == -1 && page == 1) {
//如果是最新博文的第一页,插入置顶文章
Response response2 = await ArticleApi.getTopArticles();
BaseEntity<List> baseEntity2 = BaseEntity.fromJson(response2.data);
List<ProjectEntity> topArticles =
baseEntity2.data.map((e) => ProjectEntity.fromJson(e)).toList();
datas.insertAll(0, topArticles);
}
return ArticleDatasLoaded(
datas, baseListEntity.curPage, baseListEntity.pageCount);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/article | mirrored_repositories/WanAndroid_Flutter/lib/page/home/article/bloc/article_index.dart | export 'article_bloc.dart';
export 'article_event.dart';
export 'article_state.dart'; | 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/navigation/navigation_page.dart | import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
///导航子页。
class NavigationSubPage extends StatefulWidget {
@override
_NavigationSubPageState createState() => _NavigationSubPageState();
}
class _NavigationSubPageState extends State<NavigationSubPage>
with AutomaticKeepAliveClientMixin {
Map<String, List<ProjectEntity>> datas;
Map<String, GlobalKey> itemKeys;
bool isLoading;
ScrollController typeScrollController;
ScrollController contentScrollController;
GlobalKey rootKey;
int currentTypeIndex;
bool shouldReloadKeys = true;
@override
void initState() {
super.initState();
datas = {};
itemKeys = {};
currentTypeIndex = 0;
rootKey = GlobalKey();
typeScrollController = ScrollController();
contentScrollController = ScrollController();
contentScrollController.addListener(() {
int newTypeIndex = getCurrentTypeIndex();
if (newTypeIndex != currentTypeIndex) {
currentTypeIndex = newTypeIndex;
typeScrollController.animateTo(
(math.max(0, currentTypeIndex - 3)) * pt(50),
duration: Duration(milliseconds: 500),
curve: Curves.decelerate);
setState(() {});
}
});
getDatas();
}
@override
void dispose() {
typeScrollController.dispose();
contentScrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
if (shouldReloadKeys) {
itemKeys.clear();
}
Widget widget = getLoadingParent(
key: rootKey,
isLoading: isLoading,
child: RefreshIndicator(
onRefresh: () async {
if (!isLoading) {
getDatas();
}
//app有自己的加载框样式,不使用RefreshIndicator拉出来的圆球作为加载框。所以onRefresh立即返回,让圆球立即消失
return;
},
///为了实现listView滚动到指定位置,下面两个listView都指定了scrollController,因此与主页面的NestedScrollView的联动关系失效了。
///第一个listView因为所有item固定高度为pt(50),所以滚动到指定位置很简单;
///第二个listView的item高度不固定,因此要借助globalKey去获取每个item的位置,还是有点点耗性能的。
child: Row(
children: <Widget>[
Expanded(
flex: 3,
child: Container(
color: Colors.grey[200],
child: ListView.builder(
physics: ClampingScrollPhysics(),
controller: typeScrollController,
itemBuilder: (c, i) {
String type = datas.keys.elementAt(i);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
if (i == currentTypeIndex) {
return;
}
double scrollerOffset = getOffsetForTagetTypeIndex(
contentScrollController.offset, i);
if (scrollerOffset != 0) {
contentScrollController.animateTo(scrollerOffset,
duration: Duration(
milliseconds: math.min(
600, 150 * (i - currentTypeIndex).abs())),
//离得越远动画时间越久,最久600ms
curve: Curves.linear);
}
},
child: Container(
alignment: Alignment.center,
color: i == currentTypeIndex ? Colors.white : null,
padding: EdgeInsets.all(pt(5)),
child: Text(
type,
style: TextStyle(
color: i == currentTypeIndex
? WColors.theme_color_dark
: Colors.black),
),
),
);
},
itemExtent: pt(50),
itemCount: datas.length,
),
),
),
Expanded(
flex: 10,
//为了保存globalKey,所有item需一次性加载,这里不使用ListView
//(实测发现,即使使用的是ListView无参构造,虽然item也是一次性全加载,但屏幕外的item的GlobalKey是获取不到context的
child: SingleChildScrollView(
physics: ClampingScrollPhysics(),
controller: contentScrollController,
child: Column(
children: List.generate(datas.length, (i) {
if (shouldReloadKeys) {
GlobalKey itemKey = GlobalKey();
itemKeys[datas.keys.elementAt(i)] = itemKey;
}
return Padding(
key: itemKeys.values.elementAt(i),
padding: EdgeInsets.all(pt(8)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Offstage(
offstage: i != 0,
child: Text(
res.longPressToCopyUrl,
style: TextStyle(
color: WColors.hint_color_dark, fontSize: 12),
),
),
Padding(
padding:
EdgeInsets.only(top: pt(10), bottom: pt(5)),
child: Align(
alignment: Alignment.center,
child: Row(
children: <Widget>[
Expanded(
child: Divider(
height: 1,
),
),
Padding(
padding: EdgeInsets.symmetric(
horizontal: pt(10)),
child: Text(
datas.keys.elementAt(i),
style: TextStyle(
color: WColors.hint_color_dark),
),
),
Expanded(
child: Divider(
height: 1,
),
),
],
),
),
),
Wrap(
children: List.generate(
datas.values.elementAt(i).length, (innerIndex) {
ProjectEntity item =
datas.values.elementAt(i)[innerIndex];
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.pushNamed(
context, WebViewPage.ROUTER_NAME,
arguments: {
'title': item.title,
'url': item.link
});
},
onLongPress: () {
Clipboard.setData(
ClipboardData(text: item.link),
);
DisplayUtil.showMsg(context,
text: res.hasCopied);
},
//可用chip代替
child: Container(
margin: EdgeInsets.symmetric(
horizontal: pt(5), vertical: pt(5)),
padding: EdgeInsets.symmetric(
horizontal: pt(12), vertical: pt(6)),
decoration: ShapeDecoration(
shape: StadiumBorder(),
color: getColors(innerIndex)),
child: Text(
item.title,
style: TextStyle(color: Colors.white),
),
),
);
}),
),
],
),
);
}).toList(),
),
),
),
],
),
),
);
shouldReloadKeys = false;
return widget;
}
///获取当前在列表上第一个可见的导航分类序号
int getCurrentTypeIndex() {
try {
if (itemKeys.length != datas.length) {
return 0;
}
RenderBox root = rootKey.currentContext.findRenderObject();
if (root == null) {
return 0;
}
double rootDy = root.localToGlobal(Offset.zero).dy;
for (int i = 0; i < itemKeys.length; i++) {
BuildContext context = itemKeys.values.elementAt(i).currentContext;
if (context == null) {
return 0;
}
RenderBox renderBox = context.findRenderObject();
if (renderBox == null) {
return 0;
}
if (i < itemKeys.length - 1) {
BuildContext contextNext =
itemKeys.values.elementAt(i + 1).currentContext;
if (context == null) {
return 0;
}
RenderBox renderBoxNext = contextNext.findRenderObject();
if (renderBoxNext == null) {
return 0;
}
if ((renderBox.localToGlobal(Offset.zero).dy - rootDy) <= 0 &&
(renderBoxNext.localToGlobal(Offset.zero).dy - rootDy) > 0) {
return i;
}
} else {
if ((renderBox.localToGlobal(Offset.zero).dy - rootDy) <= 0) {
return i;
}
}
}
} catch (e) {
print(e);
}
return 0;
}
///获取指定导航分类需要滚动到列表最上方所需的偏移量
double getOffsetForTagetTypeIndex(double currentOffset, int typeIndex) {
try {
if (itemKeys.length != datas.length || typeIndex >= itemKeys.length) {
return 0;
}
RenderBox root = rootKey.currentContext.findRenderObject();
if (root == null) {
return 0;
}
double rootDy = root.localToGlobal(Offset.zero).dy;
BuildContext context =
itemKeys.values.elementAt(typeIndex).currentContext;
if (context == null) {
return 0;
}
RenderBox renderBox = context.findRenderObject();
if (renderBox == null) {
return 0;
}
double offset = renderBox.localToGlobal(Offset.zero).dy - rootDy;
return currentOffset + offset + 1;
} catch (e) {
print(e);
}
return 0;
}
Color getColors(int i) {
List pool = [
WColors.theme_color_dark,
WColors.theme_color,
WColors.theme_color_light,
WColors.warning_red.withAlpha(0x99)
];
return pool[i % (pool.length)];
}
Future getDatas() async {
isLoading = true;
setState(() {});
try {
Response response = await CommonApi.getNavigations();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
///data的json 结构为:
/// [
/// {
/// "articles":Array[23],
/// "cid":272,
/// "name":"常用网站"
/// },
/// ....
/// ]
///Array结构为ProjectEntity
///
baseEntity.data.map(
(e) {
datas ??= {};
datas[e['name']] = (e['articles'] as List)
.map((e) => ProjectEntity.fromJson(e))
.toList();
},
).toList();
shouldReloadKeys = true;
} catch (e) {
print(e);
if (mounted) {
DisplayUtil.showMsg(context, exception: e);
}
}
isLoading = false;
if (mounted) {
setState(() {});
}
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/home/home_page.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
import 'package:wanandroid_flutter/page/base/custom_sliver_app_bar_delegate.dart';
import 'package:wanandroid_flutter/page/home/article/article_page.dart';
import 'package:wanandroid_flutter/page/home/collect/collect_page.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/page/home/home/home_drawer.dart';
import 'package:wanandroid_flutter/page/home/navigation/navigation_page.dart';
import 'package:wanandroid_flutter/page/home/project/project_page.dart';
import 'package:wanandroid_flutter/page/home/wxarticle/wx_article_page.dart';
import 'package:wanandroid_flutter/page/search/search_page.dart';
import 'package:wanandroid_flutter/page/todo/todo_main.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
import 'package:wanandroid_flutter/views/saerch_bar.dart';
///主页
///BloC模式
///本页结构存在该问题:【flutter关于NestedScrollView的这个bug:https://github.com/flutter/flutter/issues/36419】
class HomePage extends StatefulWidget {
static const ROUTER_NAME = '/HomePage';
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
BuildContext innerContext;
HomeBloc homeBloc = HomeBloc();
bool isLogin = false;
String userName;
BmobUserEntity bmobUserEntity;
TabController _tabController;
ScrollController _scrollController;
bool isSearchWXArticle = false;
bool showFAB = true;
TextEditingController _searchTextContriller;
static List<PageStorageKey<String>> keys = [
PageStorageKey<String>('1'),
PageStorageKey<String>('2'),
PageStorageKey<String>('3'),
PageStorageKey<String>('4'),
PageStorageKey<String>('5'),
];
//实际上如果子页已经AutomaticKeepAliveClientMixin了,那也没必要再用PageStorageKey去保存滚动状态了,因为切换tab时页面根本不会被销毁
Map<String, Widget> tabs = {
res.project: ProjectSubPage(keys[0]),
res.article: ArticleSubPage(keys[1]),
res.vxArticle: WXArticleSubPage(keys[2]),
res.navigation: NavigationSubPage(),
res.collect: CollectSubPage(),
};
@override
void initState() {
super.initState();
_tabController = TabController(length: tabs.length, vsync: this);
_tabController.addListener(() {
if (_tabController.index == 2) {
setState(() {
isSearchWXArticle = true;
});
} else {
setState(() {
isSearchWXArticle = false;
});
}
if (_tabController.index == 3) {
setState(() {
showFAB = false;
});
} else {
setState(() {
showFAB = true;
});
}
});
_scrollController = ScrollController();
_searchTextContriller = TextEditingController();
homeBloc.dispatch(LoadHome());
}
@override
Widget build(BuildContext context) {
return BlocProviderTree(
blocProviders: [
BlocProvider<HomeBloc>(
builder: (context) => homeBloc,
),
],
child: BlocListener(
bloc: homeBloc,
listener: (context, state) {
if (state is HomeLoadError) {
if (innerContext != null) {
DisplayUtil.showMsg(innerContext, exception: state.exception);
}
}
if (state is HomeLoaded) {
isLogin = state.isLogin;
userName = state.userName;
}
if (state is HomeSearchStarted) {
if (!state.isSearchWXArticle) {
Navigator.pushNamed(context, SearchPage.ROUTER_NAME,
arguments: _searchTextContriller.text).then((_){
if(!isLogin){
homeBloc.dispatch(LoadHome());
}
});
}
}
if (state is HomeBmobLoaded) {
bmobUserEntity = state.bmobUserEntity;
}
},
child: BlocBuilder<HomeEvent, HomeState>(
bloc: homeBloc,
builder: (context, state) {
return Stack(
children: <Widget>[
Scaffold(
body: Builder(builder: (context) {
innerContext = context;
return Stack(
children: <Widget>[
DecoratedBox(
decoration: _themeGradientDecoration(),
child: SafeArea(
child: NestedScrollView(
controller: _scrollController,
headerSliverBuilder: (BuildContext context,
bool innerBoxIsScrolled) {
//为了练习代码,并不是直接使用SliverAppBar来实现头部
return <Widget>[
SliverToBoxAdapter(
child: Container(
decoration: _themeGradientDecoration(),
child: appBarHeader(),
),
),
//因为子页TabBarView不一定都会用CustomScrollView,放弃使用SliverOverlapAbsorber + SliverOverlapInjector
//影响是滑到顶部后子页还能继续上滑一小段距离(我的tabBarView是包了一层上面有圆角的DecoratedBox的,滑动列表时可发现圆角背景还会上滑而不是固定住,但影响不大,页面和它内部滚动widget的滚动衔接还是在的,所以看上去都是在滑动)
SliverPersistentHeader(
pinned: true,
floating: true,
delegate: CustomSliverAppBarDelegate(
minHeight: pt(40),
maxHeight: pt(40),
child: Container(
height: pt(40),
decoration:
_themeGradientDecoration(),
child: appBarTab(_tabController),
),
),
),
];
},
body: DecoratedBox(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(pt(10)),
topRight: Radius.circular(pt(10)),
),
),
child: TabBarView(
controller: _tabController,
children: tabs.values
.map((page) => page)
.toList(),
),
),
),
),
),
],
);
}),
drawer: Drawer(
child: HomeDrawer(isLogin, userName, bmobUserEntity),
),
floatingActionButton: Offstage(
offstage: !showFAB,
child: FloatingActionButton(
onPressed: () {
//本打算监听_scrollController,当滑动距离较大时再显示"返回顶部"按钮,但实际发现在NestedScrollView头部被收起后就收不到监听了。
//那么只能在TabBarView子页中监听它们自己的滚动距离,然后再通知到主页(可以用bloc发一个event、也可以发一个自定义Notification)显示"返回顶部"按钮。(嫌麻烦,不做了,永久显示吧)
_scrollController.animateTo(1,
duration: Duration(seconds: 1),
curve: Curves.decelerate);
},
child: Padding(
padding: const EdgeInsets.all(4.0),
child: Image.asset('images/rocket.png'),
),
mini: true,
backgroundColor: WColors.theme_color,
),
),
),
Offstage(
offstage: state is! HomeLoading,
child: getLoading(start: state is HomeLoading),
)
],
);
}),
),
);
}
Decoration _themeGradientDecoration() {
return BoxDecoration(
gradient: LinearGradient(
colors: [
// WColors.theme_color_dark,
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
));
}
///头部标题栏
Widget appBarHeader() {
return Container(
height: pt(60),
alignment: Alignment.centerLeft,
child: Row(
children: <Widget>[
GestureDetector(
onTap: () {
Scaffold.of(innerContext).openDrawer();
},
child: Container(
width: pt(34),
height: pt(34),
alignment: Alignment.center,
margin: EdgeInsets.symmetric(horizontal: pt(12)),
child: ClipRRect(
borderRadius: BorderRadius.circular(pt(17)),
child: isLogin
? Image.asset(
'images/user_icon.jpeg',
fit: BoxFit.cover,
width: pt(34),
height: pt(34),
)
: Icon(
Icons.account_circle,
color: Colors.white,
size: pt(34),
),
),
),
),
Expanded(
child: Hero(
tag: 'searchBar',
//hero的child中若有material系widget(如TextField),则父需要为Material系layout(如Scaffold、Material),否则在页面跳转期间会看到报错UI,提示祖先不是material
child: Material(
type: MaterialType.transparency,
child: SearchBar(
height: pt(30),
color: Colors.grey[50],
child: TextField(
controller: _searchTextContriller,
textInputAction: TextInputAction.search,
onSubmitted: (text) {
if (_searchTextContriller.text != null) {
homeBloc.dispatch(
StartSearchEvent(
isSearchWXArticle, _searchTextContriller.text),
);
}
},
style: TextStyle(fontSize: 14),
decoration: InputDecoration(
hintText: isSearchWXArticle
? res.searchWXArticleTips
: res.searchTips,
border: InputBorder.none,
contentPadding: EdgeInsets.only(),
isDense: true,
hintStyle: TextStyle(
fontSize: 12,
color: isSearchWXArticle
? WColors.wechat_green
: WColors.hint_color_dark,
)),
),
iconColor: isSearchWXArticle
? WColors.wechat_green
: WColors.hint_color_dark,
icon: isSearchWXArticle
? Image.asset(
'images/wechat.png',
width: 24,
height: 24,
)
: null,
),
),
),
),
GestureDetector(
onTap: () {
Navigator.pushNamed(context, TodoPage.ROUTER_NAME).then((_){
if(!isLogin){
homeBloc.dispatch(LoadHome());
}
});
},
child: Container(
alignment: Alignment.center,
margin: EdgeInsets.only(left: pt(12), right: pt(6)),
child: Icon(
Icons.assignment,
color: Colors.white,
),
),
),
],
),
);
}
///头部tab栏
Widget appBarTab(TabController tabController) {
return TabBar(
isScrollable: true,
controller: tabController,
indicatorSize: TabBarIndicatorSize.label,
indicatorColor: Colors.white,
tabs: tabs.keys.map((title) {
return Padding(
padding: EdgeInsets.symmetric(vertical: 0, horizontal: pt(6)),
child: Text(
title,
style: TextStyle(fontSize: 15),
),
);
}).toList(),
);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/home/home_drawer.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wanandroid_flutter/entity/bmob_feedback_entity.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/main.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/drawer/about_page.dart';
import 'package:wanandroid_flutter/page/home/drawer/rank_page.dart';
import 'package:wanandroid_flutter/page/home/drawer/support_author.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/views/level_view.dart';
///主页侧滑菜单
class HomeDrawer extends StatefulWidget {
bool isLogin = false;
String userName;
BmobUserEntity bmobUserEntity;
HomeDrawer(this.isLogin, this.userName, this.bmobUserEntity);
@override
_HomeDrawerState createState() => _HomeDrawerState();
}
class _HomeDrawerState extends State<HomeDrawer> {
HomeBloc homeBloc;
bool hasSignin = false;
@override
void initState() {
super.initState();
homeBloc = BlocProvider.of<HomeBloc>(context);
if (widget.bmobUserEntity != null) {
checkTodayHasSignin(DateTime.parse(widget.bmobUserEntity.updatedAt));
} else {
hasSignin = true;
}
}
@override
Widget build(BuildContext context) {
return BlocListener<HomeEvent, HomeState>(
bloc: homeBloc,
listener: (context, state) {
//这里监听状态并赋值属性不合适。因为侧滑菜单在直到第一次展开时才被初始化。此时监听为时已晚
},
child: BlocBuilder<HomeEvent, HomeState>(
bloc: homeBloc,
builder: (context, state) {
return Column(
children: <Widget>[
Container(
height: pt(200),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('images/drawer_bg.jpeg'),
fit: BoxFit.cover,
alignment: Alignment.center)),
alignment: Alignment.center,
child: SafeArea(
child: Stack(
children: <Widget>[
Positioned(
left: pt(10),
top: pt(15),
child: widget.bmobUserEntity == null
? Container()
: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
if (!hasSignin) {
hasSignin = true;
BmobUserEntity copy = widget.bmobUserEntity
.copyWith(
level: widget.bmobUserEntity.level +
1);
homeBloc.dispatch(UpdateBmobInfo(copy));
}
},
child: Row(
children: <Widget>[
Text(
!hasSignin ? res.signin : res.signined,
style: TextStyle(color: Colors.white),
),
SizedBox(
width: pt(5),
),
Image.asset(
'images/signin.png',
color: Colors.white,
width: 25,
height: 25,
)
],
),
),
),
Positioned(
right: pt(10),
top: pt(15),
child: widget.bmobUserEntity == null
? Container()
: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.pushNamed(
context, RankPage.ROUTER_NAME);
},
child: Image.asset(
'images/rank.png',
color: Colors.white,
width: 30,
height: 30,
),
),
),
Positioned(
left: pt(10),
bottom: pt(10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Row(
children: <Widget>[
ClipRRect(
borderRadius: BorderRadius.circular(pt(17)),
child: widget.isLogin
? Image.asset(
'images/user_icon.jpeg',
fit: BoxFit.cover,
width: pt(34),
height: pt(34),
)
: Icon(
Icons.account_circle,
color: Colors.white,
size: pt(34),
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
if (!widget.isLogin) {
Navigator.pushNamed(context,
LoginWanandroidPage.ROUTER_NAME)
.then((_) {
homeBloc.dispatch(LoadHome());
});
}
},
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: pt(10)),
child: Text(
widget.userName ?? res.login,
style: TextStyle(
fontSize: 26,
color: Colors.white,
fontWeight: FontWeight.w500),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
)
],
),
Padding(
padding: const EdgeInsets.only(top: 5),
child: widget.bmobUserEntity == null
? Container()
: GestureDetector(
onTap: () {
showSignatureDialog();
},
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
(widget.bmobUserEntity.signature ==
null ||
widget.bmobUserEntity
.signature.length ==
0)
? res.initSignature
: widget
.bmobUserEntity.signature,
style:
TextStyle(color: Colors.white),
overflow: TextOverflow.ellipsis,
maxLines: 1,
),
getLevelWidgets(
widget.bmobUserEntity.level),
],
),
),
),
],
),
),
],
),
),
),
Offstage(
offstage: !bmobEnable,
child: _menuItem(Icon(Icons.feedback), res.feedback, () {
showFeedbackDialog();
}),
),
_menuItem(Icon(Icons.attach_money), res.supportAuthor, () {
Navigator.pushNamed(context, SupportAuthorPage.ROUTER_NAME);
}),
_menuItem(Icon(Icons.error_outline), res.about, () {
Navigator.pushNamed(context, AboutPage.ROUTER_NAME);
}),
_menuItem(Icon(Icons.account_circle),
widget.isLogin ? res.logout : res.login, () {
Navigator.pop(context);
if (widget.isLogin) {
homeBloc.dispatch(LogoutHome());
} else {
Navigator.pushNamed(context, LoginWanandroidPage.ROUTER_NAME)
.then((_) {
homeBloc.dispatch(LoadHome());
});
}
}),
// FlatButton(
// child: Text('去测试页'),
// onPressed: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) {
// return Scaffold(
// body: TestPage(),
// );
// },
// ),
// );
// },
// ),
// FlatButton(
// child: Text('去nest'),
// onPressed: () {
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) {
// return Scaffold(
// body: NestedTestPage(),
// );
// },
// ),
// );
// },
// ),
],
);
},
),
);
}
Widget _menuItem(Widget icon, String title, VoidCallback onTap) {
return ListTile(
leading: icon,
title: Text(title),
onTap: onTap,
);
}
Future checkTodayHasSignin(DateTime updateTime) async {
///为防止打卡作弊,当前时间从网络上获取
DateTime now;
try {
Response response = await dio.get(
'http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp');
Map<String, dynamic> data =
(response.data as Map<String, dynamic>)['data'];
String todayMills = data['t'];
now = DateTime.fromMillisecondsSinceEpoch(int.parse(todayMills),
isUtc: true);
} catch (e) {
print(e);
hasSignin = true;
setState(() {});
return;
}
DateTime today = DateTime(
now.year,
now.month,
now.day,
);
// print('$updateTime,$today');
hasSignin = updateTime.isAfter(today.toUtc());
setState(() {});
}
showSignatureDialog() {
showDialog(
context: context,
builder: (context) {
TextEditingController controller =
TextEditingController(text: widget.bmobUserEntity.signature);
if (widget.bmobUserEntity.signature != null) {
controller.selection = TextSelection(
baseOffset: widget.bmobUserEntity.signature.length,
extentOffset: widget.bmobUserEntity.signature.length);
}
return AlertDialog(
contentPadding: EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 0),
content: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
contentPadding: EdgeInsets.symmetric(
horizontal: pt(5),
vertical: pt(8),
),
),
controller: controller,
autofocus: true,
),
actions: <Widget>[
FlatButton(
child: Text(res.cancel),
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text(res.confirm),
onPressed: () {
BmobUserEntity copy = widget.bmobUserEntity
.copyWith(signature: controller.text);
homeBloc.dispatch(UpdateBmobInfo(copy));
Navigator.of(context).pop();
},
),
],
);
});
}
showFeedbackDialog() {
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
TextEditingController controller = TextEditingController();
return AlertDialog(
contentPadding: EdgeInsets.fromLTRB(24.0, 20.0, 24.0, 0),
content: Container(
height: pt(200),
decoration: BoxDecoration(
border: Border.all(),
),
child: TextField(
maxLines: null,
textAlign: TextAlign.start,
decoration: InputDecoration(
hintText: res.feedbackTips,
border: InputBorder.none,
contentPadding: EdgeInsets.symmetric(
horizontal: pt(5),
vertical: pt(8),
),
),
controller: controller,
autofocus: true,
),
),
actions: <Widget>[
FlatButton(
child: Text(res.cancel),
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text(res.confirm),
onPressed: () {
BmobFeedbackEntity feedback = BmobFeedbackEntity(
widget.userName ?? '未登录用户', controller.text ?? '空');
feedback.save().then((_) {
print('feedback send success');
});
Navigator.of(context).pop();
},
),
],
);
});
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/home/bloc/home_bloc.dart | import 'package:bloc/bloc.dart';
import 'package:data_plugin/bmob/bmob_query.dart';
import 'package:data_plugin/bmob/response/bmob_saved.dart';
import 'package:data_plugin/bmob/response/bmob_updated.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/main.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
bool isLogin = false;
String userName;
bool alredyHomeloaded = false;
@override
HomeState get initialState => HomeLoading();
@override
Stream<HomeState> mapEventToState(HomeEvent event) async* {
if (event is LoadHome) {
yield* _mapLoadHomeToState();
} else if (event is LogoutHome) {
yield* _mapLogoutHomeToState();
} else if (event is StartSearchEvent) {
yield HomeSearchStarted(event.isSearchWXArticle, event.searchKey);
} else if (event is LoadBmobInfo) {
yield* _mapLoadBmobInfoToState(event.userName);
} else if (event is UpdateBmobInfo) {
yield* _mapUpdateBmobInfoToState(event.bmobUserEntity);
}
}
Stream<HomeState> _mapLoadHomeToState() async* {
try {
alredyHomeloaded = false;
yield HomeLoading();
isLogin = await SPUtil.isLogin();
if (isLogin) {
userName = await SPUtil.getUserName();
} else {
userName = null;
}
yield HomeLoaded(isLogin, userName: userName);
alredyHomeloaded = true;
if (bmobEnable && isLogin && userName != null) {
dispatch(LoadBmobInfo(userName));
}
} catch (e) {
yield HomeLoadError(e);
}
}
Stream<HomeState> _mapLogoutHomeToState() async* {
try {
alredyHomeloaded = false;
yield HomeLoading();
await AccountApi.logout();
await SPUtil.setLogin(false);
yield HomeLoaded(isLogin);
alredyHomeloaded = true;
yield HomeBmobLoaded(null);
dispatch(LoadHome());
} catch (e) {
yield HomeLoadError(e);
}
}
Stream<HomeState> _mapLoadBmobInfoToState(String userName) async* {
try {
BmobQuery<BmobUserEntity> query = BmobQuery();
query.addWhereEqualTo('userName', userName);
List<dynamic> results = await query.queryObjects();
if (results == null || results.length == 0) {
print('HomeBloc._mapLoadBmobInfoToState 新用户,创建bmob行');
BmobUserEntity initUser = BmobUserEntity.empty();
initUser.userName = userName;
initUser.level = 1;
initUser.signature = res.initSignature;
initUser.strWhat = '';
initUser.numWhat = 0;
BmobSaved saved = await initUser.save();
initUser.objectId = saved.objectId;
initUser.createdAt = initUser.updatedAt = saved.createdAt;
yield HomeBmobLoaded(initUser);
} else {
yield HomeBmobLoaded(BmobUserEntity.fromJson(results[0]));
}
} catch (e) {
print('HomeBloc._mapLoadBmobInfoToState $e');
//不报错
}
}
Stream<HomeState> _mapUpdateBmobInfoToState(BmobUserEntity entity) async* {
try {
yield HomeLoading();
BmobUpdated updated = await entity.update();
entity.updatedAt = updated.updatedAt;
yield HomeBmobLoaded(entity);
} catch (e) {
print('HomeBloc._mapUpdateBmobInfoToState $e');
yield HomeLoadError(e);
}
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/home/bloc/home_state.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
abstract class HomeState extends Equatable {
HomeState([List props = const []]) : super(props);
}
class HomeLoading extends HomeState {
@override
String toString() {
return 'HomeLoading';
}
}
///主页基础数据已加载完成的state,主页内的所有子页需等待主页基础数据完成后再加载各自的数据,即有依赖关系。
///如果后面还想做如"检测升级"等逻辑,由于子页面没必要依赖"检测升级",
///所以主页到时候的状态顺序应当类似这样:加载子页需要依赖的数据(如登录状态)-> 发送HomeLoaded -> 静默加载子页不依赖的数据(如检测升级)-> 发送类似如HomeBackgroundTaskLoaded的state。
///而不应该是这样:加载子页需要依赖的数据(如登录状态)同时加载子页不依赖的数据(如检测升级)-> 发送HomeLoaded
class HomeLoaded extends HomeState {
bool isLogin;
String userName;
HomeLoaded(this.isLogin, {this.userName}) : super([isLogin, userName]);
@override
String toString() {
return 'HomeLoaded{isLogin: $isLogin, userName: $userName}';
}
}
class HomeLoadError extends HomeState {
Exception exception;
HomeLoadError(this.exception) : super([exception]);
@override
String toString() {
return 'HomeLoadError';
}
}
class HomeSearchStarted extends HomeState {
bool isSearchWXArticle;
String searchKey;
HomeSearchStarted(this.isSearchWXArticle, this.searchKey)
: super([isSearchWXArticle, searchKey,new Object()/*每次都实例一个新obj,这样可以被认为每次都是新的state即使内容都一样。*/]);
@override
String toString() {
return 'HomeSearchStarted{isSearchWXArticle: $isSearchWXArticle, searchKey: $searchKey}';
}
}
///bmob用户信息获取
class HomeBmobLoaded extends HomeState {
BmobUserEntity bmobUserEntity;
HomeBmobLoaded(this.bmobUserEntity) : super([bmobUserEntity]);
@override
String toString() {
return 'HomeBmobLoaded{bmobUserEntity: $bmobUserEntity}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/home/bloc/home_event.dart | import 'package:equatable/equatable.dart';
import 'package:wanandroid_flutter/entity/bmob_user_entity.dart';
abstract class HomeEvent extends Equatable {
HomeEvent([List props = const []]) : super(props);
}
///加载主页数据
class LoadHome extends HomeEvent {
@override
String toString() {
return 'LoadHome';
}
}
class LogoutHome extends HomeEvent {
@override
String toString() {
return 'LogoutHome';
}
}
class StartSearchEvent extends HomeEvent {
bool isSearchWXArticle;
String searchKey;
StartSearchEvent(this.isSearchWXArticle, this.searchKey)
: super([isSearchWXArticle, searchKey]);
@override
String toString() {
return 'StartSearchEvent{isSearchWXArticle: $isSearchWXArticle, searchKey: $searchKey}';
}
}
///加载bmob用户信息
class LoadBmobInfo extends HomeEvent {
String userName;
LoadBmobInfo(this.userName) : super([userName]);
@override
String toString() {
return 'LoadBmobInfo{userName: $userName}';
}
}
class UpdateBmobInfo extends HomeEvent{
BmobUserEntity bmobUserEntity;
UpdateBmobInfo(this.bmobUserEntity) : super([bmobUserEntity]);
@override
String toString() {
return 'UpdateBmobInfo{bmobUserEntity: $bmobUserEntity}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/home/bloc/home_index.dart | export 'package:wanandroid_flutter/page/home/home/bloc/home_bloc.dart';
export 'package:wanandroid_flutter/page/home/home/bloc/home_event.dart';
export 'package:wanandroid_flutter/page/home/home/bloc/home_state.dart'; | 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/collect/collect_page.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wanandroid_flutter/page/home/home/bloc/home_index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'collect_list_view.dart';
import 'collect_web_view.dart';
///收藏子页
class CollectSubPage extends StatefulWidget {
@override
_CollectSubPageState createState() => _CollectSubPageState();
}
class _CollectSubPageState extends State<CollectSubPage>
with AutomaticKeepAliveClientMixin {
GlobalKey<AnimatedListState> animatedListKey;
bool isLogin = false;
StreamSubscription subscription;
@override
void initState() {
super.initState();
animatedListKey = GlobalKey();
}
@override
void dispose() {
subscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
if (subscription == null) {
HomeBloc homeBloc = BlocProvider.of<HomeBloc>(context);
subscription = homeBloc.state.listen((state) {
if (state is HomeLoaded) {
print('收藏子页:主页加载完成,获取最新登录状态');
setState(() {
isLogin = state.isLogin;
});
} else if (homeBloc.alredyHomeloaded) {
print('收藏子页:在构造函数之前主页就已经加载完成并可能已经发送了其他bloc state,获取最新登录状态');
setState(() {
isLogin = homeBloc.isLogin;
});
}
});
}
return !isLogin
? Center(
child: Text(res.loginFirst),
)
: Column(
children: <Widget>[
//两个子布局相互独立,各自拥有各自的provider
CollectWebView(),
Expanded(
child: CollectListView(),
),
],
);
}
@override
bool get wantKeepAlive => true;
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/collect/collect_web_view.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:wanandroid_flutter/entity/collect_web_entity.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/views/badge_view.dart';
import '../web_view.dart';
import 'collect_web_model.dart';
typedef OnAddWeb = void Function(String name, String link);
///网址收藏栏
///Provider模式
///为了List增减有动画,使用了AnimatedList,注意写法区别
class CollectWebView extends StatelessWidget {
GlobalKey<AnimatedListState> animListKey;
@override
Widget build(BuildContext context) {
animListKey = GlobalKey();
return ChangeNotifierProvider(
builder: (_) => CollectWebModel((Exception e) {
DisplayUtil.showMsg(context, exception: e);
})
..getDatas(),
child: Consumer<CollectWebModel>(
builder: (context, value, _) {
if (value.isFirst && value.datas.length == 0) {
//加这段代码是因为列表使用的是AnimatedList,如果当datas为空时就构建它,那么后面datas获取后就得一个一个的调用animListKey.currentState.insertItem来添加
return CupertinoActivityIndicator();
}
return Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
),
),
height: pt(100),
width: double.infinity,
child: Stack(
alignment: Alignment.center,
children: <Widget>[
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding:
EdgeInsets.fromLTRB(pt(16), pt(16), pt(16), pt(0)),
child: Row(
children: [
Text(
res.collectWeb,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
Expanded(
child: Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: () {
value.toggleEdit();
},
child: Text(
value.isEditMode ? res.finish : res.editor,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
)
],
),
),
Expanded(
child: AnimatedList(
key: animListKey,
itemBuilder: (context, index, animation) {
if (index < value.datas.length) {
//网址收藏item
CollectWebEntity entity = value.datas[index];
return Container(
child: item(
animation: animation,
isEditMode: value.isEditMode,
title: entity.name,
onTap: () {
Navigator.pushNamed(
context, WebViewPage.ROUTER_NAME,
arguments: {
'title': entity.name,
'url': entity.link,
});
},
onDelete: () {
if (value.isLoading) {
return;
}
value.deleteWeb(
entity.id,
onDeleteSuccess: () {
//构建list的删除动画
animListKey.currentState.removeItem(
index,
(context, animation) {
return item(
animation: animation,
title: entity.name,
isEditMode: true);
},
);
},
);
},
),
);
} else {
//添加网址收藏按钮
return item(
animation: animation,
title: '+',
isEditMode: false,
onTap: () {
if (value.isLoading) {
return;
}
showAddWebDialog(context,
onAddWeb: (name, link) {
value.addWeb(
name: name,
link: link,
onAddSuccess: () {
//构建list添加动画
animListKey.currentState.insertItem(
value.datas.length - 1,
);
});
});
});
}
},
initialItemCount: value.datas.length + 1,
scrollDirection: Axis.horizontal,
),
),
],
),
Offstage(
offstage: !value.isLoading,
child: CupertinoActivityIndicator(),
),
],
),
);
},
),
);
}
Widget item({
Key key,
@required Animation<double> animation,
VoidCallback onTap,
bool isEditMode = false,
VoidCallback onDelete,
@required String title,
}) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: isEditMode ? null : onTap, //编辑模式下暂屏蔽点击
child: ScaleTransition(
scale: animation,
child: Padding(
padding: EdgeInsets.only(top: pt(10)),
child: Badge(
visible: isEditMode,
badge: GestureDetector(
onTap: onDelete,
child: Icon(
Icons.cancel,
color: WColors.warning_red,
size: 20,
),
),
offsetX: 6,
offsetY: 6,
color: Colors.transparent,
child: Container(
margin: EdgeInsets.symmetric(horizontal: pt(8), vertical: pt(8)),
padding:
EdgeInsets.symmetric(horizontal: pt(12), vertical: pt(6)),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
border: Border.all(color: Colors.white),
),
child: Text(
title,
style: TextStyle(color: Colors.white),
),
),
),
),
),
);
}
void showAddWebDialog(BuildContext context, {OnAddWeb onAddWeb}) {
TextEditingController nameC = TextEditingController();
TextEditingController linkC = TextEditingController();
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
elevation: 1,
content: SingleChildScrollView(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: () => Navigator.pop(context),
child: Icon(
Icons.close,
size: 20,
),
),
),
TextField(
controller: nameC,
decoration: InputDecoration(hintText: res.enterWebName),
autofocus: true,
),
SizedBox(
height: pt(20),
),
TextField(
controller: linkC,
decoration: InputDecoration(hintText: res.enterWebLink),
),
],
),
),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
actions: <Widget>[
FlatButton(
onPressed: () {
onAddWeb?.call(
nameC.text.isEmpty ? 'ccy' : nameC.text,
linkC.text.isEmpty
? 'https://github.com/CCY0122/WanAndroid_Flutter'
: linkC.text);
Navigator.pop(context);
},
child: Text(res.add))
],
);
});
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/collect/collect_web_model.dart | import 'package:flutter/foundation.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/collect_web_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
///收藏网址提供者
class CollectWebModel extends ChangeNotifier {
bool isFirst;
bool isEditMode;
bool isLoading;
Function(Exception e) onError;
List<CollectWebEntity> _datas;
List<CollectWebEntity> get datas => _datas;
CollectWebModel(this.onError) {
isFirst = true;
isEditMode = false;
isLoading = false;
_datas = [];
}
//收藏网址的增删改查方法:
getDatas() async {
isLoading = true;
notifyListeners();
try {
Response response = await CollectWebApi.getCollectWebList();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
_datas =
baseEntity.data.map((e) => CollectWebEntity.fromJson(e)).toList();
} catch (e) {
print(e);
onError(e);
}
isFirst = false;
isLoading = false;
notifyListeners();
}
addWeb(
{String name,
String link,
VoidCallback onAddSuccess}) async {
isLoading = true;
notifyListeners();
try {
Response response =
await CollectWebApi.collectWeb(name: name, link: link);
CollectWebEntity entity =
CollectWebEntity.fromJson(response.data['data']);
_datas.add(entity);
onAddSuccess?.call();
} catch (e) {
print(e);
onError(e);
}
isLoading = false;
notifyListeners();
}
deleteWeb(int id, {VoidCallback onDeleteSuccess}) async {
isLoading = true;
notifyListeners();
try {
await CollectWebApi.deleteWeb(id);
datas.removeWhere((e) => e.id == id);
onDeleteSuccess?.call();
} catch (e) {
print(e);
onError(e);
}
isLoading = false;
notifyListeners();
}
toggleEdit() {
isEditMode = !isEditMode;
notifyListeners();
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/collect/collect_list_view.dart | import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter/cupertino.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/load_more_footer.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
import '../web_view.dart';
import 'collect_list_model.dart';
typedef OnCollect = void Function(String title, String author, String link);
///收藏列表
///Provider模式
///为了List增减有动画,使用了AnimatedList,注意写法区别
class CollectListView extends StatefulWidget {
@override
_CollectListViewState createState() => _CollectListViewState();
}
class _CollectListViewState extends State<CollectListView> {
GlobalKey<AnimatedListState> animListKey;
@override
Widget build(BuildContext context) {
animListKey = GlobalKey();
return ChangeNotifierProvider(
builder: (_) => CollectListModel((Exception e) {
DisplayUtil.showMsg(context, exception: e);
})
..getDatas(1),
child: Consumer<CollectListModel>(
builder: (context, value, _) {
if (value.isFirst && value.datas.length == 0) {
//加这段代码是因为列表使用的是AnimatedList,如果当datas为空时就构建它,那么后面datas获取后就得一个一个的调用animListKey.currentState.insertItem来添加
return getLoadingParent(
child: Container(),
isLoading: value.isLoading,
);
}
return RefreshIndicator(
onRefresh: () async {
value.getDatas(1, clearData: true, onSuccess: () {
//AnimatedList根普通listview不一样,它的item需要自己手动insert进去,但是对于刷新来说是全部item都变了,所以直接重建根布局
setState(() {});
});
return;
},
child: getLoadingParent(
child: NotificationListener(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
if (notification.metrics.axis == Axis.vertical) {
//确定是否到达了底部
if (notification.metrics.pixels >=
notification.metrics.maxScrollExtent) {
//确定当前允许加载更多
if (!value.isLoading && value.hasMore()) {
value.getDatas(value.currentPage + 1,
onSuccess: () {
setState(() {});
});
}
return false;
}
}
}
return false;
},
child: AnimatedList(
key: animListKey,
physics: AlwaysScrollableScrollPhysics(),
itemBuilder: (context, index, animation) {
if (index == 0) {
return Padding(
padding:
EdgeInsets.fromLTRB(pt(16), pt(8), pt(16), pt(8)),
child: Row(
children: [
Expanded(
child: Text(
res.collectArticle,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Row(
children: <Widget>[
FlatButton(
padding: EdgeInsets.all(0),
onPressed: () {
if (value.isLoading) {
return;
}
showAddCollectDialog(context,
onCollect: (title, author, link) {
value.addCollect(
title: title,
author: author,
link: link,
onAddSuccess: () {
//构建list添加动画
animListKey.currentState
.insertItem(1);
});
});
},
child: Text(
res.add,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
FlatButton(
padding: EdgeInsets.all(0),
onPressed: () {
value.toggleEdit();
},
child: Text(
value.isEditMode
? res.finish
: res.editor,
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
],
)
],
),
);
} else if (index == value.datas.length + 1) {
return getLoadMoreFooter(value.hasMore(),
color: Colors.white);
} else {
if (value.datas.length == 0) {
return null;
}
ProjectEntity entity = value.datas[index - 1];
return item(
animation: animation,
data: entity,
isEditMode: value.isEditMode,
onTap: () {
Navigator.pushNamed(
context, WebViewPage.ROUTER_NAME,
arguments: {
'title': entity.title,
'url': entity.link,
});
},
onDelete: () {
if (value.isLoading) {
return;
}
value.unCollect(
entity.id,
onUncollectSuccess: () {
//构建list的删除动画
animListKey.currentState.removeItem(
index,
(context, animation) {
return item(
animation: animation,
data: entity,
isEditMode: true,
);
},
);
},
);
});
}
},
initialItemCount: value.datas.length + 2,
),
),
isLoading: value.isLoading),
);
},
),
);
}
Widget item({
Key key,
@required Animation<double> animation,
VoidCallback onTap,
bool isEditMode = false,
VoidCallback onDelete,
@required ProjectEntity data,
}) {
return SizeTransition(
sizeFactor: animation,
child: Column(
children: <Widget>[
ListTile(
onTap: isEditMode ? null : onTap,
dense: true,
contentPadding: EdgeInsets.only(right: pt(16), left: pt(16)),
title: Text(
decodeString(data.title),
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
children: [
Expanded(
child: Text(
'${res.author}:${data.author ?? '-'} ${res.type}:${data.chapterName ?? '-'} ${res.time}:${data.niceDate ?? '-'}'),
),
],
),
trailing: isEditMode
? GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onDelete,
child: Icon(
Icons.cancel,
color: WColors.warning_red,
),
)
: null,
),
Divider(
height: 10,
),
],
),
);
}
void showAddCollectDialog(BuildContext context, {OnCollect onCollect}) {
TextEditingController nameC = TextEditingController();
TextEditingController authorC = TextEditingController();
TextEditingController linkC = TextEditingController();
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return AlertDialog(
elevation: 1,
content: SingleChildScrollView(
child: Column(
children: <Widget>[
Align(
alignment: Alignment.centerRight,
child: GestureDetector(
onTap: () => Navigator.pop(context),
child: Icon(
Icons.close,
size: 20,
),
),
),
TextField(
controller: nameC,
decoration: InputDecoration(hintText: res.enterTitle),
autofocus: true,
),
SizedBox(
height: pt(20),
),
TextField(
controller: authorC,
decoration: InputDecoration(hintText: res.enterAuthor),
autofocus: true,
),
SizedBox(
height: pt(20),
),
TextField(
controller: linkC,
decoration: InputDecoration(hintText: res.enterLink),
),
],
),
),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
actions: <Widget>[
FlatButton(
onPressed: () {
onCollect?.call(
nameC.text.isEmpty ? 'ccy is best!' : nameC.text,
authorC.text.isEmpty ? 'ccy' : authorC.text,
linkC.text.isEmpty
? 'https://github.com/CCY0122/WanAndroid_Flutter'
: linkC.text);
Navigator.pop(context);
},
child: Text(res.add))
],
);
});
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page/home | mirrored_repositories/WanAndroid_Flutter/lib/page/home/collect/collect_list_model.dart | import 'package:flutter/foundation.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
///收藏提供者
class CollectListModel extends ChangeNotifier {
bool isFirst;
bool isEditMode;
bool isLoading;
Function(Exception e) onError;
int currentPage;
int totalPage;
List<ProjectEntity> _datas;
List<ProjectEntity> get datas => _datas;
CollectListModel(this.onError)
: isFirst = true,
isEditMode = false,
isLoading = false,
currentPage = 1,
totalPage = 1,
_datas = [] {}
//收藏的增删改查方法:
getDatas(int page, {bool clearData = false, VoidCallback onSuccess}) async {
isLoading = true;
notifyListeners();
try {
Response response = await CollectApi.getCollectList(page);
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
currentPage = baseListEntity.curPage;
totalPage = baseListEntity.pageCount;
if (clearData) {
_datas.clear();
}
if (_datas == null || _datas.length == 0) {
_datas =
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList();
} else {
_datas.addAll(baseListEntity.datas
.map((e) => ProjectEntity.fromJson(e))
.toList());
}
onSuccess?.call();
} catch (e) {
print(e);
onError(e);
_datas = [];
}
isFirst = false;
isLoading = false;
notifyListeners();
}
addCollect(
{String title,
String author,
String link,
VoidCallback onAddSuccess}) async {
isLoading = true;
notifyListeners();
try {
Response response = await CollectApi.collectOutter(
title: title, author: author, link: link);
ProjectEntity entity = ProjectEntity.fromJson(response.data['data']);
_datas.insert(0, entity);
onAddSuccess?.call();
} catch (e) {
print(e);
onError(e);
}
isLoading = false;
notifyListeners();
}
unCollect(int id, {int originId, VoidCallback onUncollectSuccess}) async {
isLoading = true;
notifyListeners();
try {
//感觉有bug,明明取消收藏了,在其他地方获取的数据collect仍为true
await CollectApi.unCollectWithOriginId(id, originId: originId);
datas.removeWhere((e) => e.id == id);
onUncollectSuccess?.call();
} catch (e) {
print(e);
onError(e);
}
isLoading = false;
notifyListeners();
}
toggleEdit() {
isEditMode = !isEditMode;
notifyListeners();
}
bool hasMore() {
return currentPage < totalPage;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/todo/todo_list.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/todo_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/page/notifications.dart';
import 'package:wanandroid_flutter/page/todo/todo_create.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class DataChangeNotification extends Notification {
TodoEntity data;
bool removed;
DataChangeNotification(this.data, {this.removed = false});
}
///to-do 列表页
class TodoListPage extends StatefulWidget {
int type;
int priority;
int order;
bool forceUpdate;
TodoListPage(
this.type,
this.priority,
this.order, {
this.forceUpdate = false,
}) {
if (type == 0) {
type = null;
}
if (priority == 0) {
priority = null;
}
if (order == 0) {
order = null;
}
}
@override
_TodoListPageState createState() => _TodoListPageState();
}
class _TodoListPageState extends State<TodoListPage> {
List<TodoEntity> datas;
int currentPage;
int totalPage;
ScrollController _scrollController;
bool isLoading;
bool isFirst = true;
bool _isGetTodoListError = false;
@override
void initState() {
super.initState();
isLoading = false;
currentPage ??= 1;
totalPage ??= 1;
_getTodoList(currentPage);
_scrollController = ScrollController();
_scrollController.addListener(() {
// 如果下拉的当前位置到scroll的最下面
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
if (currentPage < totalPage && !isLoading) {
_getTodoList(currentPage + 1);
}
}
});
}
@override
void didUpdateWidget(TodoListPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.priority != widget.priority ||
oldWidget.type != widget.type ||
oldWidget.order != widget.order ||
widget.forceUpdate) {
_refreshAuto();
}
}
@override
Widget build(BuildContext context) {
return NotificationListener(
onNotification: (Notification notification) {
switch (notification.runtimeType) {
case UpdateNotification:
if ((notification as UpdateNotification).update) {
_refreshAuto();
}
return true; //没必要继续冒泡到todo_main
case DataChangeNotification:
if ((notification as DataChangeNotification).removed) {
_deleteTodo((notification as DataChangeNotification).data);
}
return true;
}
return false;
},
child: RefreshIndicator(
color: WColors.theme_color,
child: ListView.builder(
controller: _scrollController,
physics:
AlwaysScrollableScrollPhysics(parent: BouncingScrollPhysics()),
shrinkWrap: false,
itemBuilder: (BuildContext context, int index) {
if (datas == null || datas.length == 0 || _isGetTodoListError) {
return Container(
height: pt(400),
alignment: Alignment.center,
child: _isGetTodoListError
? Text(
res.pullToRetry,
style: TextStyle(fontSize: 18),
)
: datas == null
? CupertinoActivityIndicator()
: Text(
res.allEmpty,
style: TextStyle(fontSize: 18),
),
);
} else {
if (index != datas.length) {
return TodoItem(
index,
datas[index],
);
} else {
return Container(
width: double.infinity,
height: pt(45),
alignment: Alignment.center,
child: (currentPage < totalPage)
? CupertinoActivityIndicator()
: Text(
res.isBottomst,
style: TextStyle(color: WColors.hint_color),
),
);
}
}
},
itemCount:
(datas == null || datas.length == 0 || _isGetTodoListError)
? 1
: datas.length + 1,
),
onRefresh: _refreshAuto),
);
}
Future<void> _refreshAuto() async {
datas = null;
currentPage = 1;
totalPage = 1;
await _getTodoList(currentPage);
}
///获取todo列表
Future _getTodoList(int page) async {
isLoading = true;
try {
Response response = await TodoApi.getTodoList(
page,
type: widget.type,
priority: widget.priority,
orderby: widget.order,
);
BaseEntity<Map<String, dynamic>> baseEntity = BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity = BaseListEntity.fromJson(baseEntity.data);
List<TodoEntity> newDatas = baseListEntity.datas.map((json){
return TodoEntity.fromJson(json);
}).toList();
if (datas == null) {
datas = newDatas;
} else {
datas.addAll(newDatas);
}
currentPage = baseListEntity.curPage;
totalPage = baseListEntity.pageCount;
print('_TodoListPageState : 获取todo列表成功');
if (isFirst) {
isFirst = false;
DisplayUtil.showMsg(context,
text: res.todoTips, duration: Duration(seconds: 4));
}
_isGetTodoListError = false;
} catch (e) {
_isGetTodoListError = true;
DisplayUtil.showMsg(context, exception: e);
}
if (mounted) {
setState(() {});
}
isLoading = false;
}
Future _deleteTodo(TodoEntity data) async {
isLoading = true;
try {
await TodoApi.deleteTodo(data.id);
datas.remove(data);
print('_TodoListPageState : 删除todo成功');
} catch (e) {
DisplayUtil.showMsg(context, exception: e);
}
if (mounted) {
setState(() {});
}
isLoading = false;
}
}
class TodoItem extends StatefulWidget {
int index;
TodoEntity data;
TodoItem(this.index, this.data);
@override
_TodoItemState createState() => _TodoItemState();
}
class _TodoItemState extends State<TodoItem> with TickerProviderStateMixin {
ItemDragData _dragData;
AnimationController _finishDragController;
BuildContext contentContext;
bool isLoading = false;
@override
void initState() {
super.initState();
_dragData = ItemDragData();
_dragData.initPosition = -pt(45 / 2.0 + 70); //一个圆角半径+日期widget所占长度
_dragData.totalDragLength = pt(375); //屏幕宽
_dragData.alreadyDragLength = 0;
}
@override
void dispose() {
_finishDragController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.pushNamed(context, TodoCreatePage.ROUTER_NAME,
arguments: widget.data)
.then((needUpdate) {
if (needUpdate ?? false) {
//告诉_TodoListPageState要刷新列表
UpdateNotification(true).dispatch(context);
}
});
},
onLongPress: () {
showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Text(res.ensureDelete),
actions: <Widget>[
FlatButton(
child: Text(res.cancel),
onPressed: () => Navigator.of(context).pop(),
),
FlatButton(
child: Text(res.confirm),
onPressed: () {
DataChangeNotification(widget.data, removed: true)
.dispatch(this.context);
Navigator.of(context).pop();
},
),
],
);
},
);
},
onHorizontalDragUpdate: (DragUpdateDetails details) {
if (isLoading) {
return;
}
setState(() {
_dragData.alreadyDragLength += details.primaryDelta;
});
},
onHorizontalDragCancel: () {
if (isLoading) {
return;
}
onFinishDrag();
},
onHorizontalDragEnd: (DragEndDetails details) {
if (isLoading) {
return;
}
onFinishDrag(velocity: details.primaryVelocity);
},
child: Container(
alignment: Alignment.center,
width: double.infinity,
height: pt(65),
margin: EdgeInsets.only(top: widget.index == 0 ? pt(30) : 0),
child: Stack(
overflow: Overflow.visible,
alignment: Alignment.center,
children: <Widget>[
Positioned(
left: widget.data.status == 1
? null
: _dragData.initPosition + _dragData.alreadyDragLength,
// 一个圆角半径+日期widget所占长度
right: widget.data.status == 1
? _dragData.initPosition - _dragData.alreadyDragLength
: null,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: pt(60),
alignment: Alignment.centerRight,
margin: EdgeInsets.only(right: pt(10)),
child: Text(
widget.data.completeDateStr,
maxLines: 1,
style: TextStyle(fontSize: 10, color: WColors.hint_color),
),
),
Builder(builder: (context) {
contentContext = context;
return Container(
//一个疑问:一旦给contatiner加上alignment后,它的宽就固定为maxWidth了,这不是我想要的,所以目前只好给他的child再套上一个stack来实现内容垂直居中
constraints: BoxConstraints(
maxWidth: pt(375 - 70.0), //屏幕宽 - 日期widget长度
minWidth: pt(375 / 2.0 + 45 / 2.0), //一半屏幕宽 + 一个圆角半径
maxHeight: pt(45),
minHeight: pt(45),
),
decoration: ShapeDecoration(
color: widget.data.status == 1
? WColors.theme_color_light
: WColors.theme_color_dark,
shadows: <BoxShadow>[
DisplayUtil.supreLightElevation(
baseColor: widget.data.status == 1
? WColors.theme_color_light.withAlpha(0xaa)
: WColors.theme_color_dark.withAlpha(0xaa),
),
],
shape: StadiumBorder(),
),
child: Stack(
alignment: widget.data.status == 1
? Alignment.centerLeft
: Alignment.centerRight,
children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(
horizontal: pt(45 / 2.0 + 5),
),
child: Text(
widget.data.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style:
TextStyle(color: Colors.white, fontSize: 16),
),
),
Positioned(
right: 0,
child: isLoading
? CupertinoActivityIndicator()
: RotatedBox(
child: Image.asset(
'images/pull.png',
width: pt(20),
height: pt(20),
color: Colors.white30,
),
quarterTurns: 3,
),
),
Positioned(
left: 0,
child: isLoading
? CupertinoActivityIndicator()
: RotatedBox(
child: Image.asset(
'images/pull.png',
width: pt(20),
height: pt(20),
color: Colors.white30,
),
quarterTurns: 1,
),
),
],
),
);
}),
Container(
width: pt(60),
margin: EdgeInsets.only(left: pt(10)),
alignment: Alignment.centerLeft,
child: Text(
widget.data.completeDateStr,
maxLines: 1,
style: TextStyle(fontSize: 10, color: WColors.hint_color),
),
),
],
),
),
],
),
),
);
}
///拖动结束,触发位置互换或恢复位置动画
void onFinishDrag({double velocity = 0}) {
if (_finishDragController != null && _finishDragController.isAnimating) {
return;
}
if (contentContext == null ||
contentContext.findRenderObject() is! RenderBox) {
return;
}
//内容item宽度
double itemWidth =
(contentContext.findRenderObject() as RenderBox).size.width;
//是否是初始位置在右侧的item(即已完成的todo)
bool isRightItem = (widget.data.status == 1);
//是否最终拖动方向是向右
bool isDragToRight = _dragData.alreadyDragLength > 0;
//是否达到了互换左右侧item的阈值(拖动超过一半item距离或者滑动速度够大)
bool isReachedThreshold =
(_dragData.alreadyDragLength.abs() >= itemWidth / 2.0) ||
velocity.abs() > 60;
_finishDragController =
AnimationController(vsync: this, duration: Duration(milliseconds: 400));
Animation animation;
bool leftChangeToRight =
!isRightItem && isDragToRight && isReachedThreshold;
bool rightChangeToLeft =
isRightItem && !isDragToRight && isReachedThreshold;
if (leftChangeToRight || rightChangeToLeft) {
//交换位置
animation = Tween<double>(
begin: _dragData.alreadyDragLength,
end: (leftChangeToRight ? 1 : -1) *
(pt(375) - itemWidth + pt(70 - 45 / 2.0)), //画图计算出来的
).animate(CurvedAnimation(
parent: _finishDragController, curve: Curves.easeOutBack));
animation.addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) {
changeTodoStatus(widget.data);
}
});
animation.addListener(() {
setState(() {
_dragData.alreadyDragLength = animation.value;
});
});
_finishDragController.forward();
} else {
//恢复原始位置
animation = Tween<double>(
begin: _dragData.alreadyDragLength,
end: 0,
).animate(CurvedAnimation(
parent: _finishDragController, curve: Curves.easeOutBack));
animation.addListener(() {
setState(() {
_dragData.alreadyDragLength = animation.value;
});
});
_finishDragController.forward();
}
}
Future changeTodoStatus(TodoEntity data, {int status}) async {
setState(() {
isLoading = true;
});
try {
await TodoApi.updateTodoStatus(
data.id, status ?? (data.status == 1 ? 0 : 1));
data.status = status ?? (data.status == 1 ? 0 : 1);
} catch (e) {
DisplayUtil.showMsg(context, exception: e);
}
if (mounted) {
setState(() {});
_dragData.alreadyDragLength = 0;
isLoading = false;
}
}
}
class ItemDragData {
///item初始位置
double initPosition;
///总可拖动长度
double totalDragLength;
///item当前已拖动长度
double alreadyDragLength;
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/todo/todo_main.dart | import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/page/notifications.dart';
import 'package:wanandroid_flutter/page/todo/todo_console.dart';
import 'package:wanandroid_flutter/page/todo/todo_list.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
class TodoFilterNotification extends Notification {
//0或null视为不过滤。
int type;
int priority;
int order;
TodoFilterNotification(this.type, this.priority, this.order);
}
///to-do 主页
class TodoPage extends StatefulWidget {
static const String ROUTER_NAME = "/TodoPage";
@override
_TodoPageState createState() => _TodoPageState();
}
class _TodoPageState extends State<TodoPage> {
TextEditingController addTodoC;
int type;
int priority;
int order = 4;
bool forceRegetList = false;
@override
void initState() {
super.initState();
addTodoC = TextEditingController();
}
@override
Widget build(BuildContext context) {
Widget widget = Scaffold(
appBar: AppBar(
backgroundColor: WColors.theme_color,
title: Text(
res.todo,
),
centerTitle: true,
elevation: 0,
),
body: NotificationListener(
onNotification: (Notification notification) {
switch (notification.runtimeType) {
case TodoFilterNotification:
setState(() {
this.type = (notification as TodoFilterNotification).type;
this.priority =
(notification as TodoFilterNotification).priority;
this.order = (notification as TodoFilterNotification).order;
});
return true;
case UpdateNotification:
if ((notification as UpdateNotification).update) {
setState(() {
forceRegetList = true;
});
}
return true;
}
return false;
},
child: DecoratedBox(
decoration: BoxDecoration(
color: WColors.gray_background,
),
child: Stack(
children: <Widget>[
Column(
children: <Widget>[
Container(
height: pt(130),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
// WColors.theme_color_dark,
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
),
Expanded(
child: TodoListPage(
this.type,
this.priority,
this.order,
forceUpdate: this.forceRegetList,
),
),
],
),
Positioned(
top: pt(10),
left: 0,
right: 0,
child: TodoConsole(),
)
],
),
),
),
);
forceRegetList = false;
return widget;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/todo/todo_create.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/todo_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
typedef OnSelect<T> = void Function(T item);
class TodoCreateNotification extends Notification {
int type;
int priority;
int template;
TodoCreateNotification(this.type, this.priority, this.template);
}
///to-do创建页
class TodoCreatePage extends StatefulWidget {
static const String ROUTER_NAME = "/TodoCreatePage";
TodoCreatePage() {}
@override
_TodoCreatePageState createState() => _TodoCreatePageState();
}
class _TodoCreatePageState extends State<TodoCreatePage> {
bool isFirst = true;
TodoEntity data;
DateTime planFinishDate;
int type;
int priority;
int template;
TextEditingController titleController;
TextEditingController detailController;
bool isLoading = false;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
if (isFirst) {
isFirst = false;
data = ModalRoute.of(context).settings.arguments;
planFinishDate = data?.completeDate != null
? DateTime.fromMillisecondsSinceEpoch(data.completeDate)
: DateTime.now();
titleController ??= TextEditingController(text: data?.title);
detailController ??= TextEditingController(text: data?.content);
if (data != null) {
type = data.type;
priority = data.priority;
}
}
return Scaffold(
appBar: AppBar(
backgroundColor: WColors.theme_color,
elevation: 0,
title: Text(
data == null ? res.create : res.editor,
),
centerTitle: true,
),
//下面接口调用必须使用这个属于Scaffold中的子widget的context,这样才能弹snackbar
body: Builder(builder: (context) {
return NotificationListener<TodoCreateNotification>(
onNotification: (TodoCreateNotification notification) {
this.type = notification.type;
this.priority = notification.priority;
if (this.template != notification.template) {
this.template = notification.template;
changeTextByTemplate();
}
return true;
},
child: Container(
height: double.infinity,
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
// WColors.theme_color_dark,
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(children: <Widget>[
TodoConsole(
callback: () {
addOrUpdateTodo(context);
},
isLoading: isLoading,
),
Container(
height: pt(50),
width: double.infinity,
alignment: Alignment.center,
margin:
EdgeInsets.only(left: pt(16), right: pt(16), top: pt(16)),
padding: EdgeInsets.only(left: pt(8), right: pt(8)),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
DisplayUtil.supreLightElevation(),
],
),
child: TextField(
controller: titleController,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
decoration: InputDecoration(
hintText: res.title,
hintStyle: TextStyle(color: WColors.hint_color),
border: InputBorder.none,
),
),
),
Container(
height: pt(250),
width: double.infinity,
margin: EdgeInsets.only(
left: pt(16), right: pt(16), top: pt(16), bottom: pt(16)),
padding: EdgeInsets.only(
left: pt(8), right: pt(8), top: pt(8), bottom: pt(8)),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
DisplayUtil.lightElevation(),
],
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Text(
res.planFinishTime,
style: TextStyle(color: Colors.grey),
),
SizedBox(
width: pt(10),
),
GestureDetector(
child: Text(
TodoApi.dateFormat(
planFinishDate,
),
style: TextStyle(
color: WColors.theme_color,
decoration: TextDecoration.underline,
),
),
onTap: () {
showDatePicker(
context: context,
initialDate: DateTime.now(),
firstDate: DateTime(2019),
lastDate: DateTime(2035),
).then((DateTime date) {
if (date != null && mounted) {
setState(() {
planFinishDate = date;
});
}
});
},
),
],
),
Expanded(
child: TextField(
controller: detailController,
maxLines: null,
style: TextStyle(fontSize: 18),
decoration: InputDecoration(
hintText: res.detail,
hintStyle: TextStyle(color: WColors.hint_color),
border: InputBorder.none,
),
),
),
],
),
),
]),
),
),
);
}),
);
}
void changeTextByTemplate() {
if (template == null || template == 0) {
titleController.text = '';
detailController.text = '';
} else if (template == 1) {
titleController.value = detailController.value = TextEditingValue(
text: res.getExpressDetail,
selection: TextSelection(baseOffset: 6, extentOffset: 8),
);
} else if (template == 2) {
titleController.value = detailController.value = TextEditingValue(
text: res.repayDetail,
selection: TextSelection(baseOffset: 0, extentOffset: 1),
);
}
}
Future addOrUpdateTodo(BuildContext context) async {
setState(() {
isLoading = true;
});
try {
if (data == null) {
await TodoApi.addTodo(
titleController.text,
detailController.text,
completeDate: TodoApi.dateFormat(planFinishDate),
type: type,
priority: priority,
);
print('_TodoCreatePageState : add todo success');
Navigator.pop(context, true);
} else {
await TodoApi.updateTodo(
data.id,
titleController.text,
detailController.text,
data.dateStr,
completeDate: TodoApi.dateFormat(planFinishDate),
status: data.status,
type: type,
priority: priority,
);
print('_TodoCreatePageState : update todo success');
Navigator.pop(context, true);
}
} catch (e) {
DisplayUtil.showMsg(context, exception: e);
}
if (mounted) {
setState(() {
isLoading = false;
});
}
}
}
///to-do控制台
class TodoConsole extends StatefulWidget {
Function callback;
bool isLoading;
TodoConsole({this.callback, this.isLoading});
@override
_TodoConsoleState createState() => _TodoConsoleState();
}
class _TodoConsoleState extends State<TodoConsole> {
List<FilterEntry> types = [
FilterEntry(0, res.all),
FilterEntry(1, res.work),
FilterEntry(2, res.life),
FilterEntry(3, res.play),
];
FilterEntry currentType;
List<FilterEntry> prioritys = [
FilterEntry(0, res.all),
FilterEntry(1, res.important),
FilterEntry(2, res.normal),
FilterEntry(3, res.relaxed),
];
FilterEntry currentPriority;
List<FilterEntry> templates = [
FilterEntry(0, res.noTemplate),
FilterEntry(1, res.getExpress),
FilterEntry(2, res.repay),
// FilterEntry(3, res.readbook),
];
FilterEntry currentTemplate;
@override
void initState() {
super.initState();
currentType ??= types[0];
currentPriority ??= prioritys[0];
currentTemplate ??= templates[0];
}
@override
Widget build(BuildContext context) {
return Container(
height: pt(150),
margin: EdgeInsets.only(
left: pt(16),
right: pt(16),
top: pt(8),
),
padding: EdgeInsets.only(left: pt(8)),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
DisplayUtil.supreLightElevation(),
],
),
child: Row(
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
filterTypesWidget(),
filterPriorityWidget(),
filterTemplateWidget(),
],
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
if (widget.isLoading) {
return;
}
widget.callback?.call();
},
child: Padding(
padding: EdgeInsets.symmetric(horizontal: pt(8)),
child: Center(
child: Container(
alignment: Alignment.center,
child: widget.isLoading
? CupertinoActivityIndicator()
: Image.asset(
'images/finish.png',
color: WColors.theme_color,
width: pt(55),
height: pt(55),
),
),
),
),
),
],
));
}
Widget filterTypesWidget() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Row(
children: types.map((entry) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: pt(3)),
child: myFilterChip(
entry,
currentType == null
? types.indexOf(entry) == 0
: currentType == entry, (f) {
setState(() {
currentType = f;
TodoCreateNotification(
currentType?.value,
currentPriority?.value,
currentTemplate?.value,
).dispatch(context);
});
}),
);
}).toList(),
),
);
}
Widget filterPriorityWidget() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Row(
children: prioritys.map((entry) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: pt(3)),
child: myFilterChip(
entry,
currentPriority == null
? prioritys.indexOf(entry) == 0
: currentPriority == entry, (f) {
setState(() {
currentPriority = f;
TodoCreateNotification(
currentType?.value,
currentPriority?.value,
currentTemplate?.value,
).dispatch(context);
});
}),
);
}).toList(),
),
);
}
Widget filterTemplateWidget() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Row(
children: templates.map((entry) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: pt(3)),
child: myFilterChip(
entry,
currentTemplate == null
? templates.indexOf(entry) == 0
: currentTemplate == entry, (f) {
setState(() {
currentTemplate = f;
TodoCreateNotification(
currentType?.value,
currentPriority?.value,
currentTemplate?.value,
).dispatch(context);
});
}),
);
}).toList(),
),
);
}
Widget myFilterChip(
FilterEntry data, bool isSelect, OnSelect<FilterEntry> onSelect) {
return Container(
child: FilterChip(
// backgroundColor: Colors.white,
selectedColor: WColors.theme_color,
shape: isSelect
? null
: StadiumBorder(side: BorderSide(color: WColors.hint_color)),
label: Text(
data.text,
style: TextStyle(fontSize: 12),
),
selected: isSelect,
onSelected: (bool value) {
if (value) {
onSelect(data);
} else {
onSelect(null);
}
},
),
);
}
}
class FilterEntry {
int value;
String text;
FilterEntry(this.value, this.text);
@override
bool operator ==(other) {
if (other is! FilterEntry) {
return false;
}
return this.value == (other as FilterEntry).value;
}
@override
String toString() {
return 'value = $value ,text = $text';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/todo/todo_console.dart | import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/page/notifications.dart';
import 'package:wanandroid_flutter/page/todo/todo_create.dart';
import 'package:wanandroid_flutter/page/todo/todo_main.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
typedef OnSelect<T> = void Function(T item);
///to-do控制台
class TodoConsole extends StatefulWidget {
@override
_TodoConsoleState createState() => _TodoConsoleState();
}
class _TodoConsoleState extends State<TodoConsole> {
List<FilterEntry> types = [
FilterEntry(0, res.all),
FilterEntry(1, res.work),
FilterEntry(2, res.life),
FilterEntry(3, res.play),
];
FilterEntry currentType;
List<FilterEntry> prioritys = [
FilterEntry(0, res.all),
FilterEntry(1, res.important),
FilterEntry(2, res.normal),
FilterEntry(3, res.relaxed),
];
FilterEntry currentPriority;
//排序接口有bug,没有正常排序:https://github.com/hongyangAndroid/wanandroid/issues/138
List<FilterEntry> orders = [
FilterEntry(4, res.orderByCreateTime),
FilterEntry(2, res.orderByFinishTime),
];
FilterEntry currentOrder;
@override
void initState() {
super.initState();
currentType = types[0];
currentPriority = prioritys[0];
currentOrder = orders[0];
}
@override
Widget build(BuildContext context) {
return Container(
height: pt(150),
margin: EdgeInsets.symmetric(horizontal: pt(16)),
padding: EdgeInsets.only(left: pt(8)),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
DisplayUtil.supreLightElevation(),
],
),
child: Row(
children: <Widget>[
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
filterTypesWidget(),
filterPriorityWidget(),
filterOrderWidget(),
],
),
),
GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.pushNamed(context, TodoCreatePage.ROUTER_NAME).then(
(needUpdate) {
if (needUpdate ?? false) {
//告诉_TodoPageState要让_TodoListPageState重新获取列表
UpdateNotification(true).dispatch(context);
}
},
);
// Navigator.push(context, PopupRoute())
},
child: Padding(
padding: EdgeInsets.symmetric(horizontal: pt(8)),
child: Center(
child: Container(
decoration: BoxDecoration(border: Border()),
child: Image.asset(
'images/add.png',
color: Colors.grey[350],
width: pt(55),
height: pt(55),
)),
),
),
),
],
));
}
Widget filterTypesWidget() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Row(
children: types.map((entry) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: pt(3)),
child: myFilterChip(
entry,
currentType == null
? types.indexOf(entry) == 0
: currentType == entry, (f) {
setState(() {
currentType = f;
TodoFilterNotification(
currentType?.value,
currentPriority?.value,
currentOrder?.value,
).dispatch(context);
});
}),
);
}).toList(),
),
);
}
Widget filterPriorityWidget() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Row(
children: prioritys.map((entry) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: pt(3)),
child: myFilterChip(
entry,
currentPriority == null
? prioritys.indexOf(entry) == 0
: currentPriority == entry, (f) {
setState(() {
currentPriority = f;
TodoFilterNotification(
currentType?.value,
currentPriority?.value,
currentOrder?.value,
).dispatch(context);
});
}),
);
}).toList(),
),
);
}
Widget filterOrderWidget() {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
physics: BouncingScrollPhysics(),
child: Row(
children: orders.map((entry) {
return Padding(
padding: EdgeInsets.symmetric(horizontal: pt(3)),
child: myFilterChip(
entry,
currentOrder == null
? orders.indexOf(entry) == 0
: currentOrder == entry, (f) {
setState(() {
currentOrder = f;
TodoFilterNotification(
currentType?.value,
currentPriority?.value,
currentOrder?.value,
).dispatch(context);
});
}),
);
}).toList(),
),
);
}
Widget myFilterChip(
FilterEntry data, bool isSelect, OnSelect<FilterEntry> onSelect) {
return Container(
child: FilterChip(
// backgroundColor: Colors.white,
selectedColor: WColors.theme_color,
shape: isSelect
? null
: StadiumBorder(side: BorderSide(color: WColors.hint_color)),
label: Text(
data.text,
style: TextStyle(fontSize: 12),
),
selected: isSelect,
onSelected: (bool value) {
if (value) {
onSelect(data);
} else {
onSelect(null);
}
},
),
);
}
}
class FilterEntry {
int value;
String text;
FilterEntry(this.value, this.text);
@override
bool operator ==(other) {
if (other is! FilterEntry) {
return false;
}
return this.value == (other as FilterEntry).value;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/base/custom_sliver_app_bar_delegate.dart | import 'dart:math' as math;
import 'package:flutter/material.dart';
///放在NestedScrollView中配合SliverPersistentHeader使用
///当[SliverAppBar]不满足使用时(比如希望自定义内容视图),就用这个。
///SliverPersistentHeader的pinned为true前提下,maxExtent即最大展开高度,minExtent即收缩到最小时留存的高度。
///(floating属性没做实现,失效了)
class CustomSliverAppBarDelegate extends SliverPersistentHeaderDelegate {
CustomSliverAppBarDelegate({
@required this.minHeight,
@required this.maxHeight,
@required this.child,
});
final double minHeight;
final double maxHeight;
final Widget child;
@override
Widget build(
BuildContext context, double shrinkOffset, bool overlapsContent) {
return child;
}
@override
double get maxExtent => math.max(minHeight, maxHeight);
@override
double get minExtent => minHeight;
// @override
// FloatingHeaderSnapConfiguration get snapConfiguration => _snapConfiguration;
@override
bool shouldRebuild(CustomSliverAppBarDelegate oldDelegate) {
return maxHeight != oldDelegate.maxHeight ||
minHeight != oldDelegate.minHeight ||
child != oldDelegate.child;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/search/search_results_model.dart | import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/base_list_entity.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
///搜索结果提供者
class SearchResultsModel with ChangeNotifier {
bool isLoading = false;
int currentPage = 1;
int totalPage = 1;
String searchKey;
List<ProjectEntity> _datas = [];
Function(Exception e) onError;
List<ProjectEntity> get datas => _datas;
SearchResultsModel(this.searchKey, this.onError);
///获取搜索结果
getResults(String searchKey, {int page = 1}) async {
if (searchKey == null || searchKey.length == 0) {
return;
}
try {
isLoading = true;
if (this.searchKey != searchKey) {
this.searchKey = searchKey;
_datas = [];
}
notifyListeners();
Response response =
await CommonApi.searchArticles(page, searchKey);
BaseEntity<Map<String, dynamic>> baseEntity =
BaseEntity.fromJson(response.data);
BaseListEntity<List> baseListEntity =
BaseListEntity.fromJson(baseEntity.data);
currentPage = baseListEntity.curPage;
totalPage = baseListEntity.pageCount;
if (_datas == null || _datas.length == 0) {
_datas =
baseListEntity.datas.map((e) => ProjectEntity.fromJson(e)).toList();
} else {
_datas.addAll(baseListEntity.datas
.map((e) => ProjectEntity.fromJson(e))
.toList());
}
} catch (e) {
print(e);
onError(e);
_datas = [];
}
isLoading = false;
notifyListeners();
}
///收藏、取消收藏
collect(int id, bool collect) async {
try {
isLoading = true;
notifyListeners();
if (collect) {
await CollectApi.collect(id);
} else {
await CollectApi.unCollect(id);
}
datas.where((e) => e.id == id).map((e) => e.collect = collect).toList();
} catch (e) {
print(e);
onError(e);
}
isLoading = false;
notifyListeners();
}
bool hasMore() {
return currentPage < totalPage;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/search/hot_key_model.dart | import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/entity/base_entity.dart';
import 'package:wanandroid_flutter/entity/hot_key_entity.dart';
import 'package:wanandroid_flutter/http/index.dart';
import 'dart:math' as math;
///热搜词提供者
class HotKeyModel with ChangeNotifier {
bool isLoading = false;
List<HotKeyEntity> _datas = [];
List<HotKeyEntity> get datas => _datas;
///更新
updateHotkeys() async {
try {
isLoading = true;
notifyListeners();
Response response = await CommonApi.getHotKey();
BaseEntity<List> baseEntity = BaseEntity.fromJson(response.data);
_datas = baseEntity.data.map((e) => HotKeyEntity.fromJson(e)).toList();
//随机排序一下,以此证明刷新成功
_datas.sort((a,b){
return - 1 + math.Random().nextInt(3); //返回随机的-1、0、1值随机排序。
},);
} catch (e) {
print(e);
_datas = [];
}
isLoading = false;
notifyListeners();
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/page | mirrored_repositories/WanAndroid_Flutter/lib/page/search/search_page.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:wanandroid_flutter/entity/project_entity.dart';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import 'package:wanandroid_flutter/page/home/web_view.dart';
import 'package:wanandroid_flutter/page/search/hot_key_model.dart';
import 'package:wanandroid_flutter/page/search/search_results_model.dart';
import 'package:wanandroid_flutter/res/index.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import 'package:wanandroid_flutter/utils/string_decode.dart';
import 'package:wanandroid_flutter/views/load_more_footer.dart';
import 'package:wanandroid_flutter/views/loading_view.dart';
import 'package:wanandroid_flutter/views/saerch_bar.dart';
///搜索页。
///使用Provider模式,重点关注刷新颗粒度
class SearchPage extends StatefulWidget {
static const ROUTER_NAME = '/SearchPage';
@override
_SearchPageState createState() => _SearchPageState();
}
class _SearchPageState extends State<SearchPage> {
String searchKey;
BuildContext innerContext;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
if (searchKey == null) {
searchKey = ModalRoute.of(context).settings.arguments;
if (searchKey == null) {
//不可能进入的case
searchKey = 'RxJava';
}
}
print('根页面被刷新');
return Scaffold(
body: Builder(
builder: (context) {
return MultiProvider(
providers: [
ChangeNotifierProvider(
builder: (context) => SearchResultsModel(
searchKey,
(Exception e) {
DisplayUtil.showMsg(context, exception: e);
},
)..getResults(searchKey))
],
child: Builder(
builder: (innerContext) {
this.innerContext = innerContext;
return DecoratedBox(
decoration: _themeGradientDecoration(),
child: SafeArea(
child: DecoratedBox(
decoration: BoxDecoration(
color: WColors.gray_background,
),
child: Column(
children: <Widget>[
SearchAppBar(),
HotKeyBanner(),
Expanded(child: ResultsList()),
],
),
),
),
);
},
),
);
},
),
);
}
}
///搜索栏
class SearchAppBar extends StatelessWidget {
TextEditingController _searchTextContriller = TextEditingController();
@override
Widget build(BuildContext context) {
return Consumer<SearchResultsModel>(builder:
(BuildContext context, SearchResultsModel value, Widget child) {
print('【搜索框】被刷新');
_searchTextContriller.value = TextEditingValue(
text: value.searchKey,
selection: TextSelection.collapsed(offset: value.searchKey.length),
);
return DecoratedBox(
decoration: _themeGradientDecoration(),
child: Padding(
padding: EdgeInsets.symmetric(vertical: pt(10)),
child: Row(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.pop(context);
},
child: Padding(
padding: EdgeInsets.symmetric(horizontal: pt(16)),
child: Icon(
Icons.arrow_back,
color: Colors.white,
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(right: pt(16)),
child: Hero(
tag: 'searchBar',
//hero的child中若有material系widget(如TextField),则父需要为Material系layout(如Scaffold、Material),否则在页面跳转期间会看到报错UI,提示祖先不是material
child: Material(
type: MaterialType.transparency,
child: SearchBar(
height: pt(30),
color: Colors.grey[50],
child: TextField(
controller: _searchTextContriller,
textInputAction: TextInputAction.search,
onSubmitted: (text) {
if (_searchTextContriller.text != null &&
!value.isLoading) {
print('刷新颗粒度测试:全部刷新(因为涉及键盘弹出收起,整个根布局会被刷新)');
value.getResults(_searchTextContriller.text);
}
},
style: TextStyle(fontSize: 14),
decoration: InputDecoration(
hintText: res.searchTips,
border: InputBorder.none,
contentPadding: EdgeInsets.only(),
hintStyle: TextStyle(
fontSize: 12,
color: WColors.hint_color_dark,
),
),
),
iconColor: WColors.hint_color_dark,
),
),
),
),
),
],
),
),
);
});
}
}
///热搜栏
class HotKeyBanner extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
builder: (context) => HotKeyModel()..updateHotkeys(),
child: DecoratedBox(
decoration: _themeGradientDecoration(),
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: pt(16),
),
child: Column(
children: <Widget>[
Row(
children: [
Text(
res.peopleAreSearching,
style: TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.w600),
),
SizedBox(width: pt(5)),
Consumer<HotKeyModel>(
builder: (context, value, child) {
print('【刷新按钮】被刷新');
return value.isLoading
? CupertinoActivityIndicator()
: GestureDetector(
onTap: () {
print('刷新颗粒度测试:期望只刷新【刷新按钮】【热搜栏】');
value.updateHotkeys();
},
child: Icon(
Icons.refresh,
color: Colors.white,
size: 20,
),
);
},
),
],
),
SizedBox(
height: pt(5),
),
Consumer<HotKeyModel>(
builder: (context, hotkeyValue, child) {
print('【热搜栏】被刷新');
return Wrap(
children: List.generate(hotkeyValue.datas.length, (index) {
return _hotKeyItem(hotkeyValue.datas[index].name, () {
//获取搜索结果,并不需要刷新【热搜栏】,即当前builder不需要刷新,所以listen = false;
SearchResultsModel searchValue =
Provider.of<SearchResultsModel>(context,
listen: false);
if (!searchValue.isLoading) {
print('刷新颗粒度测试:期望只刷新【搜索框】【结果列表】');
searchValue.getResults(hotkeyValue.datas[index].name);
}
});
}),
);
},
),
SizedBox(
height: pt(5),
),
],
),
),
),
);
}
Widget _hotKeyItem(String title, onTap) {
return Padding(
padding: EdgeInsets.only(bottom: pt(5)),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
height: pt(24),
padding: EdgeInsets.symmetric(horizontal: pt(5)),
// 这里为什么用stack呢?因为我想让child居中。
// 那居中为什么不直接给父container设置alignment呢?因为这会使Container约束变尽可能大,
// 导致width占满剩余空间(height已经固定给了pt(24),而width我不希望给固定值,它应当根据文字长度自动调整),
// 最终导致HotKeyBanner中的wrap是一行一个typeItem。所以换用stack来实现文字居中。
// 如果你还不理解,去掉stack,给Container加上Alignment.center,运行看效果。
// 为什么height要给固定值?因为不同文字的高度其实是不一样的,不给固定值的话他们基线不一样
child: Stack(
alignment: Alignment.center,
children: [
Text(
title,
style: TextStyle(
color: Colors.white,
fontSize: 13,
decoration: TextDecoration.underline),
),
],
),
),
),
);
}
}
///结果列表
class ResultsList extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Consumer<SearchResultsModel>(
builder: (context, value, child) {
print('【结果列表】被刷新');
return NotificationListener(
onNotification: (notification) {
if (notification is ScrollUpdateNotification) {
if (notification.metrics.axis == Axis.vertical) {
//确定是否到达了底部
if (notification.metrics.pixels >=
notification.metrics.maxScrollExtent) {
//确定当前允许加载更多
if (!value.isLoading && value.hasMore()) {
print('刷新颗粒度测试:期望只刷新【搜索框】【结果列表】');
value.getResults(value.searchKey,
page: value.currentPage + 1);
}
return false;
}
}
}
return false;
},
child: Container(
child: getLoadingParent(
child: ListView.builder(
itemBuilder: (context, index) {
if (index < value.datas.length) {
return ArticleItem(value.datas[index], value.isLoading,
() {
if (value.isLoading) {
return;
}
SPUtil.isLogin().then((islogin) {
if (islogin) {
print('刷新颗粒度测试:期望只刷新【搜索框】【结果列表】');
value.collect(value.datas[index].id,
!value.datas[index].collect);
} else {
Navigator.pushNamed(
context, LoginWanandroidPage.ROUTER_NAME);
}
});
});
} else {
return getLoadMoreFooter(value.hasMore(),
color: Colors.white);
}
},
itemCount: value.datas.length + 1,
),
isLoading: value.isLoading),
),
);
},
);
}
}
class ArticleItem extends StatefulWidget {
ProjectEntity data;
bool isLoading;
var onTap;
ArticleItem(this.data, this.isLoading, this.onTap);
@override
_ArticleItemState createState() => _ArticleItemState();
}
class _ArticleItemState extends State<ArticleItem>
with SingleTickerProviderStateMixin {
bool lastCollectState;
AnimationController _collectController;
Animation _collectAnim;
@override
void initState() {
super.initState();
_collectController =
AnimationController(vsync: this, duration: Duration(milliseconds: 300));
CurvedAnimation curvedAnimation =
CurvedAnimation(parent: _collectController, curve: Curves.easeOut);
_collectAnim = Tween<double>(begin: 1, end: 1.8).animate(curvedAnimation);
}
@override
void dispose() {
_collectController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
if (lastCollectState == false && lastCollectState != widget.data.collect) {
_collectController.forward(from: 0).then((_) {
_collectController.reverse();
});
}
lastCollectState = widget.data.collect;
return Container(
color: Colors.white,
child: Column(
children: [
ListTile(
dense: true,
contentPadding: EdgeInsets.only(right: pt(8), left: pt(8)),
leading: GestureDetector(
behavior: HitTestBehavior.opaque,
child: Container(
alignment: Alignment.center,
width: 40, //查看源码,这是leading的最小宽高
height: 40,
child: ScaleTransition(
scale: _collectAnim,
child: Icon(
widget.data.collect
? Icons.favorite
: Icons.favorite_border,
color:
widget.data.collect ? WColors.warning_red : Colors.grey,
size: 24,
),
),
),
onTap: widget.onTap,
),
title: Text(
decodeString(widget.data.title)
.replaceAll("<em class='highlight'>", '')
.replaceAll("\</em>", ''), //去掉HTML语法
style: TextStyle(
fontSize: 15,
),
),
subtitle: Row(
children: [
//搜索页不需要显示"置顶"
// widget.data.type == 1 //目前本人通过对比json差异猜测出type=1表示置顶类型
// ? Container(
// decoration: BoxDecoration(
// border: Border.all(color: Colors.red[700])),
// margin: EdgeInsets.only(right: pt(6)),
// padding: EdgeInsets.symmetric(horizontal: pt(4)),
// child: Text(
// res.stickTop,
// style: TextStyle(
// color: Colors.red[700],
// fontWeight: FontWeight.w600,
// fontSize: 10),
// ),
// )
// : Container(),
widget.data.fresh
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.warning_red)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.New,
style: TextStyle(
color: WColors.warning_red,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
///WanAndroid文档原话:superChapterId其实不是一级分类id,因为要拼接跳转url,内容实际都挂在二级分类下,所以该id实际上是一级分类的第一个子类目的id,拼接后故可正常跳转
widget.data.superChapterId == 294 //项目
? Container(
decoration: BoxDecoration(
border:
Border.all(color: WColors.theme_color_dark)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.project,
style: TextStyle(
color: WColors.theme_color_dark,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.superChapterId == 440 //问答
? Container(
decoration: BoxDecoration(
border: Border.all(color: WColors.theme_color)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.QA,
style: TextStyle(
color: WColors.theme_color,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
widget.data.superChapterId == 408 //公众号
? Container(
decoration: BoxDecoration(
border:
Border.all(color: WColors.theme_color_light)),
margin: EdgeInsets.only(right: pt(6)),
padding: EdgeInsets.symmetric(horizontal: pt(4)),
child: Text(
res.vxArticle,
style: TextStyle(
color: WColors.theme_color_light,
fontWeight: FontWeight.w600,
fontSize: 10),
),
)
: Container(),
Expanded(
child: Text(
'${res.author}:${widget.data.author} ${res.time}:${widget.data.niceDate}'),
),
],
),
onTap: () {
Navigator.pushNamed(
context,
WebViewPage.ROUTER_NAME,
arguments: {
'title': widget.data.title,
'url': widget.data.link,
},
);
},
),
Divider(
height: 10,
),
],
),
);
}
}
Decoration _themeGradientDecoration() {
return BoxDecoration(
gradient: LinearGradient(
colors: [
// WColors.theme_color_dark,
WColors.theme_color,
WColors.theme_color_light,
],
begin: Alignment.centerLeft,
end: Alignment.centerRight,
));
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/res/my_images.dart | class MyImage {
static const String baitu = 'images/baitu.png';
static const String bianfu = 'images/bianfu.png';
static const String bianselong = 'images/bianselong.png';
static const String daishu = 'images/daishu.png';
static const String daxiang = 'images/daxiang.png';
static const String eyu = 'images/eyu.png';
static const String gongji = 'images/gongji.png';
static const String gou = 'images/gou.png';
static const String hainiu = 'images/hainiu.png';
static const String haiyaoyu = 'images/haiyaoyu.png';
static const String hashiqi = 'images/hashiqi.png';
static const String hema = 'images/hema.png';
static const String houzi = 'images/houzi.png';
static const String huanxiong = 'images/huanxiong.png';
static const String hudie = 'images/hudie.png';
static const String jiakechong = 'images/jiakechong.png';
static const String jingangyingwu = 'images/jingangyingwu.png';
static const String jingyu = 'images/jingyu.png';
static const String juzuiniao = 'images/juzuiniao.png';
static const String laohu = 'images/laohu.png';
static const String laoshu = 'images/laoshu.png';
static const String luotuo = 'images/luotuo.png';
static const String mao = 'images/mao.png';
static const String maotouying = 'images/maotouying.png';
static const String mianyang = 'images/mianyang.png';
static const String milu = 'images/milu.png';
static const String nainiu = 'images/nainiu.png';
static const String pangxie = 'images/pangxie.png';
static const String qie = 'images/qie.png';
static const String qingwa = 'images/qingwa.png';
static const String shayu = 'images/shayu.png';
static const String she = 'images/she.png';
static const String shiyishou = 'images/shiyishou.png';
static const String shizi = 'images/shizi.png';
static const String shuta = 'images/shuta.png';
static const String songshu = 'images/songshu.png';
static const String tiane = 'images/tiane.png';
static const String tihu = 'images/tihu.png';
static const String tuoniao = 'images/tuoniao.png';
static const String wugui = 'images/wugui.png';
static List<String> animals = [
baitu,
hashiqi,
tihu,
huanxiong,
bianselong,
bianfu,
daishu,
daxiang,
eyu,
tuoniao,
wugui,
gongji,
hudie,
mao,
tiane,
jingyu,
juzuiniao,
laohu,
laoshu,
luotuo,
maotouying,
mianyang,
milu,
nainiu,
pangxie,
qie,
qingwa,
shayu,
she,
shiyishou,
hema,
houzi,
shizi,
shuta,
jiakechong,
jingangyingwu,
songshu,
hainiu,
haiyaoyu,
gou,
];
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/res/strings_zh.dart | import 'package:wanandroid_flutter/res/strings.dart';
///语言集具体实现类:中文
class StringsZh extends BaseStrings {
@override
get login => '登录';
@override
get password => '密码';
@override
get regist => '注册';
@override
get username => '用户名';
@override
get netConnectFailed => '网络连接超时或者服务器未响应';
@override
get rePassword => '再次输入密码';
@override
get createNew => '新建';
@override
get todo => '便笺';
@override
get allEmpty => '空空如也';
@override
get life => '生活';
@override
get play => '娱乐';
@override
get work => '工作';
@override
get all => '全部';
@override
get important => '重要';
@override
get normal => '一般';
@override
get relaxed => '宽松';
@override
get orderByCreateTime => '按创建日期排序';
@override
get orderByFinishTime => '按完成日期排序';
@override
get isLoading => '加载中';
@override
get create => '创建';
@override
get detail => '详情';
@override
get title => '标题';
@override
get finishTime => '完成日期';
@override
get planFinishTime => '计划完成日期';
@override
get getExpress => '取快递';
@override
get noTemplate => '无模板';
@override
get getExpressDetail => '回家前记得去丰巢取快递';
@override
get readbook => '读书计划';
@override
get readbookDetail => '一个月内看完《-》';
@override
get repay => '还钱';
@override
get repayDetail => '9号之前记得还花呗!!!!!';
@override
get editor => '编辑';
@override
get isBottomst => '———我是有底线的———';
@override
get cancel => '取消';
@override
get confirm => '确定';
@override
get ensureDelete => '确定删除?';
@override
get markDone => '标记为已完成';
@override
get markUndo => '标记为未完成';
@override
get todoTips => '横向拖动便笺切换完成状态,长按便笺删除';
@override
get pullToRefresh => '下拉刷新';
@override
get pullToRetry => '下拉重试';
@override
get project => '项目';
@override
get searchTips => '搜索关键词以空格形式隔开';
@override
get ensureLogout => '确定登出?';
@override
get logout => '登出';
@override
get newestProject => '最新项目';
@override
get article => '博文';
@override
get navigation => '导航';
@override
get vxArticle => '公众号';
@override
get collect => '收藏';
@override
get newestArticle => '最新博文';
@override
get typeLevel1 => '一级分类';
@override
get typeLevel2 => '二级分类';
@override
get author => '作者';
@override
get time => '时间';
@override
get QA => '问答';
@override
get New => '新';
@override
get done => '已完成';
@override
get undone => '未完成';
@override
get openBrowser => '浏览器打开';
@override
get about => '关于';
@override
get feedback => '反馈';
@override
get supportAuthor => '支持作者';
@override
get searchWXArticleTips => '搜索公众号文章';
@override
get checkUpdate => '检测升级';
@override
get initSignature => '编辑个性签名';
@override
get rank => '排行';
@override
get signin => '打卡';
@override
get signined => '已打卡';
@override
get levelRank => '打卡等级排行榜';
@override
get feedbackTips => '反馈BUG、建议、想对作者说的话 :)';
@override
get peopleAreSearching => '大家都在搜';
@override
get stickTop => '置顶';
@override
get longPressToCopyUrl => '*长按标签可复制链接';
@override
get hasCopied => '已复制';
@override
get collectWeb => '收藏的网址';
@override
get enterAuthor => '请输入作者';
@override
get enterLink => '请输入链接';
@override
get enterTitle => '请输入标题';
@override
get enterWebLink => '请输入网站链接';
@override
get enterWebName => '请输入网站名称';
@override
get add => '添加';
@override
get noEmpty => '不许为空';
@override
get collectArticle => '收藏的文章';
@override
get type => '分类';
@override
get finish => '完成';
@override
get loginFirst => '请先登录';
@override
get isNewestVersion => '已是最新版';
@override
get go => '前往';
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/res/my_icons.dart | import 'package:flutter/widgets.dart';
class MyIcon {
}
class _MyIconData extends IconData {
const _MyIconData(int codePoint)
: super(
codePoint,
fontFamily: 'Animals',
);
} | 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/res/index.dart | export 'strings.dart';
export 'colors.dart';
export 'my_icons.dart';
export 'my_images.dart'; | 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/res/colors.dart | import 'dart:ui';
import 'package:flutter/material.dart';
class WColors {
static const Color theme_color = Color(0xFF7CB4EF);
static const Color theme_color_light = Color(0xFF7EDDFF);
static const Color theme_color_dark = Color(0xFF9A99E8);
static const Color gray_background = Color(0xFFF6F6F6);
static const Color warning_red = Color(0xFFFB5858);
static const Color line_color = Color(0xFFEFEFEF);
static const Color hint_color = Color(0xFFD0D0D0);
static const Color hint_color_dark = Color(0xFF8E8E93);
static const Color wechat_green = Color(0xFF62b900);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/res/strings.dart | import 'strings_zh.dart';
///当前语言:中文
Strings _res = StringsZh();
Strings get res => _res;
///语言集接口。方便统一管理字符串。也为未来多语言做准备
///ps:实际开发中发现,这样写无法赋值方法默认值(因为默认值要求为const)
abstract class Strings {
//'get'关键字可加可不加。加上的话能够快速跳转具体实现:快捷键option + command + 左键
get appName;
get username;
get password;
get regist;
get login;
get netConnectFailed;
get rePassword;
get todo;
get createNew;
get allEmpty;
get work;
get life;
get play;
get all;
get important;
get normal;
get relaxed;
get orderByCreateTime;
get orderByFinishTime;
get isLoading;
get create;
get title;
get detail;
get finishTime;
get planFinishTime;
get noTemplate;
get getExpress;
get repay;
get readbook;
get getExpressDetail;
get repayDetail;
get readbookDetail;
get editor;
get isBottomst;
get confirm;
get cancel;
get ensureDelete;
get markDone;
get markUndo;
get todoTips;
get pullToRefresh;
get pullToRetry;
get searchTips;
get project;
get ensureLogout;
get logout;
get newestProject;
get article;
get vxArticle;
get navigation;
get collect;
get typeLevel1;
get typeLevel2;
get newestArticle;
get author;
get time;
get QA;
get New;
get undone;
get done;
get openBrowser;
get about;
get feedback;
get supportAuthor;
get searchWXArticleTips;
get checkUpdate;
get initSignature;
get signin;
get signined;
get rank;
get levelRank;
get feedbackTips;
get peopleAreSearching;
get stickTop;
get longPressToCopyUrl;
get hasCopied;
get collectWeb;
get enterWebName;
get enterWebLink;
get enterTitle;
get enterAuthor;
get enterLink;
get add;
get noEmpty;
get collectArticle;
get type;
get finish;
get loginFirst;
get isNewestVersion;
get go;
}
///通用的语言,直接这里实现。
///非通用的语言,各自子类继承它来实现。如中文语言:[StringsZh]
abstract class BaseStrings implements Strings {
@override
get appName => '玩儿Android';
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/http/api.dart | import 'dio_util.dart';
import 'index.dart';
class Api {
static const String BASE_URL = "https://www.wanandroid.com";
static const int ERROR_CODE_UN_LOGIN = -1001;
}
///对于调用层涉及传入页码的,统一从1开始。
///账户相关接口
class AccountApi {
static const String LOGIN_PATH = "/user/login";
static const String REGIST_PATH = "/user/register";
static const String LOGOUT_PATH = "/user/logout/json";
static Future<Response> login(String username, String password) {
return dio.post(LOGIN_PATH, queryParameters: {
"username": username,
"password": password,
});
}
static Future<Response> regist(
String username, String password, String repassword) {
return dio.post(REGIST_PATH, queryParameters: {
"username": username,
"password": password,
"repassword": repassword,
});
}
static Future<Response> logout() {
return dio.get(LOGOUT_PATH);
}
}
///to-do相关接口
class TodoApi {
static const String ADD_TODO = "/lg/todo/add/json";
static String UPDATE_TODO(int id) => "/lg/todo/update/$id/json";
static String DELETE_TODO(int id) => "/lg/todo/delete/$id/json";
static String UPDATE_TODO_STATUS(int id) => "/lg/todo/done/$id/json";
static String TODO_LIST(int page) => "/lg/todo/v2/list/$page/json";
static String dateFormat(DateTime date) {
//yyyy-MM-dd
String timestamp =
"${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
// String timestamp =
// "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}:${date.second.toString().padLeft(2, '0')}";
return timestamp;
}
//新增
//title: 新增标题(必须)
// content: 新增详情(必须)
// date: 2018-08-01 预定完成时间(不传默认当天,建议传)
// type: 大于0的整数(可选);
// priority 大于0的整数(可选);
static Future<Response> addTodo(
String title,
String content, {
String completeDate,
int type,
int priority,
}) {
Map<String, dynamic> query = {
'title': title,
'content': content,
};
query['date'] = dateFormat(DateTime.now());
if (completeDate != null) {
query['completeDate'] = completeDate;
}
if (type != null) {
query['type'] = type;
}
if (priority != null) {
query['priority'] = priority;
}
return dio.post(ADD_TODO, queryParameters: query);
}
//更新
// id: 拼接在链接上,为唯一标识,列表数据返回时,每个todo 都会有个id标识 (必须)
// title: 更新标题 (必须)
// content: 新增详情(必须)
// date: 2018-08-01(必须)
// status: 0 // 0为未完成,1为完成
// type: ;
// priority: ;
static Future<Response> updateTodo(
int id,
String title,
String content,
String date, {
String completeDate,
int status,
int type,
int priority,
}) {
Map<String, dynamic> query = {
'title': title,
'content': content,
};
if (date != null) {
query['date'] = date;
}
if (completeDate != null) {
query['completeDate'] = completeDate;
}
if (type != null) {
query['type'] = type;
}
if (status != null) {
query['status'] = status;
}
if (priority != null) {
query['priority'] = priority;
}
return dio.post(UPDATE_TODO(id), queryParameters: query);
}
//删除
//id: 拼接在链接上,为唯一标识
static Future<Response> deleteTodo(int id) {
return dio.post(DELETE_TODO(id));
}
//仅更新完成状态
//id: 拼接在链接上,为唯一标识
// status: 0或1,传1代表未完成到已完成,反之则反之。
static Future<Response> updateTodoStatus(int id, int status) {
return dio.post(UPDATE_TODO_STATUS(id), queryParameters: {
'status': status,
});
}
//获取
// 页码从1开始,拼接在url 上
// status 状态, 1-完成;0未完成; 默认全部展示;
// type 创建时传入的类型, 默认全部展示
// priority 创建时传入的优先级;默认全部展示
// orderby 1:完成日期顺序;2.完成日期逆序;3.创建日期顺序;4.创建日期逆序(默认);
static Future<Response> getTodoList(
int page, {
int status,
int type,
int priority,
int orderby,
}) {
Map<String, dynamic> query = Map();
if (type != null) {
query['type'] = type;
}
if (status != null) {
query['status'] = status;
}
if (priority != null) {
query['priority'] = priority;
}
if (orderby != null) {
query['orderby'] = orderby;
}
return dio.get(TODO_LIST(page), queryParameters: query);
}
}
///项目相关接口
class ProjectApi {
static const PROJECT_TREE = '/project/tree/json';
static String NEW_PROJECTS(int page) => '/article/listproject/$page/json';
static String PROJECT_LIST(int page, int id) =>
'/project/list/$page/json?cid=$id';
///页码从1开始
static Future<Response> getNewProjects(int page) {
//老接口原因,实际输入页码是从0开始
return dio.get(NEW_PROJECTS(page - 1));
}
static Future<Response> getProjectTree() {
return dio.get(PROJECT_TREE);
}
///页码从1开始
static Future<Response> getProjectList(int page, int id) {
return dio.get(PROJECT_LIST(page, id));
}
static Future<Response> getBanners() {
return dio.get('/banner/json');
}
}
///博文(体系)相关接口
class ArticleApi {
static const ARTICLE_TREE = '/tree/json';
static String NEW_ARTICLES(int page) => '/article/list/$page/json';
static String ARTICLE_LIST(int page, int id) =>
'/article/list/$page/json?cid=$id';
///置顶文章
static String TOP_ARTICLE = '/article/top/json';
///页码从1开始
static Future<Response> getNewArticle(int page) {
//老接口原因,实际输入页码是从0开始
return dio.get(NEW_ARTICLES(page - 1));
}
static Future<Response> getArticleTypes() {
return dio.get(ARTICLE_TREE);
}
///页码从1开始
static Future<Response> getArticleList(int page, int id) {
//老接口原因,实际输入页码是从0开始
return dio.get(ARTICLE_LIST(page - 1, id));
}
static Future<Response> getTopArticles() {
return dio.get(TOP_ARTICLE);
}
}
///公众号相关接口
class WXArticleApi {
static const WXARTICLE_TREE = '/wxarticle/chapters/json';
static String WXARTICLE_LIST(int page, int id) =>
'/wxarticle/list/$id/$page/json';
static Future<Response> getWXArticleTypes() {
return dio.get(WXARTICLE_TREE);
}
///页码从1开始
static Future<Response> getWXArticleList(int page, int id,
{String searchKey}) {
if (searchKey != null) {
Map<String, dynamic> query = {'k': searchKey};
return dio.get(WXARTICLE_LIST(page, id), queryParameters: query);
}
return dio.get(WXARTICLE_LIST(page, id));
}
}
///收藏相关接口
class CollectApi {
static String COLLECT(int id) => '/lg/collect/$id/json';
///收藏站外文章
static String COLLECT_OUTTER = '/lg/collect/add/json';
static String UN_COLLECT(int id) => '/lg/uncollect_originId/$id/json';
static String UN_COLLECT_WITH_ORIGIN_ID(int id) => '/lg/uncollect/$id/json';
static String COLLECT_LIST(int page) => '/lg/collect/list/$page/json';
static Future<Response> collect(int id) {
return dio.post(COLLECT(id));
}
static Future<Response> unCollect(int id) {
return dio.post(UN_COLLECT(id));
}
///originId:列表页下发,无则为-1
static Future<Response> unCollectWithOriginId(int id, {int originId}) {
return dio.post(
UN_COLLECT_WITH_ORIGIN_ID(id),
queryParameters: {'originId': originId ?? -1},
);
}
///获取收藏列表,page从1开始
static Future<Response> getCollectList(int page) {
//老接口原因,实际输入页码是从0开始
return dio.get(COLLECT_LIST(page - 1));
}
///收藏站外网址
static Future<Response> collectOutter(
{String title, String author, String link}) {
Map<String, dynamic> query = {};
if (title != null) {
query['title'] = title;
}
if (author != null) {
query['author'] = author;
}
if (link != null) {
query['link'] = link;
}
return dio.post(COLLECT_OUTTER, queryParameters: query);
}
}
class CollectWebApi {
static const String COLLECT_WEB_LIST = '/lg/collect/usertools/json';
static const String COLLECT_WEB = '/lg/collect/addtool/json';
static const String UPDATE_WEB = '/lg/collect/updatetool/json';
static const String DELETE_WEB = '/lg/collect/deletetool/json';
static Future<Response> getCollectWebList() {
return dio.get(COLLECT_WEB_LIST);
}
static Future<Response> collectWeb({String name, String link}) {
Map<String, dynamic> query = {};
if (name != null) {
query['name'] = name;
}
if (link != null) {
query['link'] = link;
}
return dio.post(COLLECT_WEB, queryParameters: query);
}
static Future<Response> updateWeb({int id, String name, String link}) {
Map<String, dynamic> query = {};
if (id != null) {
query['id'] = id;
}
if (name != null) {
query['name'] = name;
}
if (link != null) {
query['link'] = link;
}
return dio.post(UPDATE_WEB, queryParameters: query);
}
static Future<Response> deleteWeb(int id) {
return dio.post(DELETE_WEB, queryParameters: {'id': id});
}
}
///其他接口
class CommonApi {
static String SEARCH(int page) => '/article/query/$page/json';
static String HOT_SEARCH_KEY = '/hotkey/json';
static String NAVIGATION = '/navi/json';
///搜索文章。页码从1开始
static Future<Response> searchArticles(int page, String searchKey) {
//老接口原因,实际输入页码是从0开始
return dio.post(SEARCH(page - 1), queryParameters: {'k': searchKey});
}
///热搜词
static Future<Response> getHotKey() {
return dio.get(HOT_SEARCH_KEY);
}
///导航
static Future<Response> getNavigations() {
return dio.get(NAVIGATION);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/http/index.dart | export 'package:dio/dio.dart';
export 'dio_util.dart';
export 'api.dart'; | 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/http/dio_util.dart | import 'dart:io';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
import 'api.dart';
import 'interceptors/log_interceptors.dart';
import 'interceptors/wanandroid_error_interceptors.dart';
Dio _dio = Dio();
Dio get dio => _dio;
class DioUtil {
static Future init() async {
dio.options.baseUrl = Api.BASE_URL;
dio.options.connectTimeout = 5 * 1000;
dio.options.sendTimeout = 5 * 1000;
dio.options.receiveTimeout = 3 * 1000;
//todo 网络环境监听
dio.interceptors.add(LogsInterceptors());
dio.interceptors.add(WanAndroidErrorInterceptors());
Directory tempDir = await getTemporaryDirectory();
String tempPath = tempDir.path + "/dioCookie";
print('DioUtil : http cookie path = $tempPath');
CookieJar cj = PersistCookieJar(dir: tempPath);
dio.interceptors.add(CookieManager(cj));
}
static String parseError(error, {String defErrorString = '网络连接超时或者服务器未响应'}) {
String errStr;
if (error is DioError) {
if (error.type == DioErrorType.CONNECT_TIMEOUT ||
error.type == DioErrorType.SEND_TIMEOUT ||
error.type == DioErrorType.RECEIVE_TIMEOUT) {
errStr = defErrorString;
} else {
errStr = error.message;
}
}
return errStr ?? defErrorString;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/http | mirrored_repositories/WanAndroid_Flutter/lib/http/interceptors/log_interceptors.dart | import 'package:dio/dio.dart';
import 'package:wanandroid_flutter/utils/index.dart';
import '../dio_util.dart';
bool isDebug = true;
///用于Dio的请求日志拦截器
class LogsInterceptors extends InterceptorsWrapper {
@override
onRequest(RequestOptions options) {
if (isDebug) {
print("┌────────────────────────Begin Request────────────────────────");
print("uri = ${options.uri}");
print("method = ${options.method}");
// print("请求url:${options.baseUrl}");
// print("请求path:${options.path}");
// print("query参数:${options.queryParameters}");
print('headers: ' + options.headers.toString());
if (options.data != null) {
printLong('body: ' + options.data.toString());
}
print("└————————————————————————End Request——————————————————————————\n\n");
}
return options;
}
@override
onResponse(Response response) {
if (isDebug) {
if (response != null) {
print("┌────────────────────────Begin Response————————————————————————");
print('status ${response.statusCode}');
// print(' ┌───────────header——————');
// print('${response.headers.toString()}');
// print(' └——————————————————————');
printLong('response: ' + response.toString());
print("└————————————————————————End Response——————————————————————————\n\n");
}
}
return response; // continue
}
@override
onError(DioError err) {
if (isDebug) {
print("┌────────────────────────Begin Dio Error————————————————————————");
print('请求异常: ' + err.toString());
print('请求异常信息: ' + (err.response?.toString() ?? ""));
print("└————————————————————————End Dio Error——————————————————————————\n\n");
}
return err;
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib/http | mirrored_repositories/WanAndroid_Flutter/lib/http/interceptors/wanandroid_error_interceptors.dart | import 'dart:convert';
import 'package:wanandroid_flutter/page/account/login_wanandroid_page.dart';
import '../../main.dart';
import '../index.dart';
/// ```
/// {
/// "data": ...,
/// "errorCode": 0,
/// "errorMsg":
/// }
/// ```
///wanAndroid统一接口返回格式错误检测
class WanAndroidErrorInterceptors extends InterceptorsWrapper {
@override
onRequest(RequestOptions options) {
return options;
}
@override
onError(DioError err) {
return err;
}
@override
onResponse(Response response) {
var data = response.data;
if (data is String) {
try {
data = json.decode(data);
} catch (e) {}
}
if (data is Map) {
int errorCode = data['errorCode'] ?? 0;
String errorMsg = data['errorMsg'] ?? '请求失败[$errorCode]';
if (errorCode == -1001 /*未登录错误码*/) {
dio.clear();
goLogin();
return dio.reject(errorMsg);
} else if (errorCode < 0) {
return dio.reject(errorMsg);
} else {
return response;
}
}
return response;
}
void goLogin() {
///在拿不到context的地方通过navigatorKey进行路由跳转:
///https://stackoverflow.com/questions/52962112/how-to-navigate-without-context-in-flutter-app
navigatorKey.currentState.pushNamed(LoginWanandroidPage.ROUTER_NAME);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/banner_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'banner_entity.g.dart';
@JsonSerializable()
class BannerEntity extends Object {
@JsonKey(name: 'desc')
String desc;
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'imagePath')
String imagePath;
@JsonKey(name: 'isVisible')
int isVisible;
@JsonKey(name: 'order')
int order;
@JsonKey(name: 'title')
String title;
@JsonKey(name: 'type')
int type;
@JsonKey(name: 'url')
String url;
BannerEntity(this.desc,this.id,this.imagePath,this.isVisible,this.order,this.title,this.type,this.url,);
factory BannerEntity.fromJson(Map<String, dynamic> srcJson) => _$BannerEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$BannerEntityToJson(this);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/collect_web_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'collect_web_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
CollectWebEntity _$CollectWebEntityFromJson(Map<String, dynamic> json) {
return CollectWebEntity(
json['desc'] as String,
json['icon'] as String,
json['id'] as int,
json['link'] as String,
json['name'] as String,
json['order'] as int,
json['userId'] as int,
json['visible'] as int,
);
}
Map<String, dynamic> _$CollectWebEntityToJson(CollectWebEntity instance) =>
<String, dynamic>{
'desc': instance.desc,
'icon': instance.icon,
'id': instance.id,
'link': instance.link,
'name': instance.name,
'order': instance.order,
'userId': instance.userId,
'visible': instance.visible,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/bmob_update_entity.dart | import 'package:data_plugin/bmob/table/bmob_object.dart';
import 'package:json_annotation/json_annotation.dart';
part 'bmob_update_entity.g.dart';
@JsonSerializable()
class BmobUpdateEntity extends BmobObject {
int deviceType; //1:android
String versionName;
String updateMsg;
String downloadUrl;
BmobUpdateEntity(
this.deviceType, this.versionName, this.updateMsg, this.downloadUrl);
BmobUpdateEntity.empty();
factory BmobUpdateEntity.fromJson(Map<String, dynamic> json) =>
_$BmobUpdateEntityFromJson(json);
Map<String, dynamic> toJson() => _$BmobUpdateEntityToJson(this);
@override
Map getParams() {
return toJson();
}
@override
String toString() {
return 'BmobUpdateEntity{deviceType: $deviceType, versionName: $versionName, updateMsg: $updateMsg, downloadUrl: $downloadUrl}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/todo_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'todo_entity.g.dart';
//生成命令:flutter packages pub run build_runner build
// flutter packages pub run build_runner build --delete-conflicting-outputs
@JsonSerializable()
class TodoEntity extends Object {
@JsonKey(name: 'completeDate')
int completeDate;
@JsonKey(name: 'completeDateStr')
String completeDateStr;
@JsonKey(name: 'content')
String content;
@JsonKey(name: 'date')
int date;
@JsonKey(name: 'dateStr')
String dateStr;
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'priority')
int priority;
@JsonKey(name: 'status')
int status;
@JsonKey(name: 'title')
String title;
@JsonKey(name: 'type')
int type;
@JsonKey(name: 'userId')
int userId;
TodoEntity(
this.completeDate,
this.completeDateStr,
this.content,
this.date,
this.dateStr,
this.id,
this.priority,
this.status,
this.title,
this.type,
this.userId,
);
factory TodoEntity.fromJson(Map<String, dynamic> srcJson) =>
_$TodoEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$TodoEntityToJson(this);
@override
String toString() {
return 'TodoEntity{completeDate: $completeDate, completeDateStr: $completeDateStr, content: $content, date: $date, dateStr: $dateStr, id: $id, priority: $priority, status: $status, title: $title, type: $type, userId: $userId}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/project_type_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'project_type_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ProjectTypeEntity _$ProjectTypeEntityFromJson(Map<String, dynamic> json) {
return ProjectTypeEntity(
json['children'] as List,
json['courseId'] as int,
json['id'] as int,
json['name'] as String,
json['order'] as int,
json['parentChapterId'] as int,
json['userControlSetTop'] as bool,
json['visible'] as int,
);
}
Map<String, dynamic> _$ProjectTypeEntityToJson(ProjectTypeEntity instance) =>
<String, dynamic>{
'children': instance.children,
'courseId': instance.courseId,
'id': instance.id,
'name': instance.name,
'order': instance.order,
'parentChapterId': instance.parentChapterId,
'userControlSetTop': instance.userControlSetTop,
'visible': instance.visible,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/project_type_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'project_type_entity.g.dart';
@JsonSerializable()
class ProjectTypeEntity extends Object {
@JsonKey(name: 'children')
List<dynamic> children;
@JsonKey(name: 'courseId')
int courseId;
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'order')
int order;
@JsonKey(name: 'parentChapterId')
int parentChapterId;
@JsonKey(name: 'userControlSetTop')
bool userControlSetTop;
@JsonKey(name: 'visible')
int visible;
ProjectTypeEntity(this.children,this.courseId,this.id,this.name,this.order,this.parentChapterId,this.userControlSetTop,this.visible,);
factory ProjectTypeEntity.fromJson(Map<String, dynamic> srcJson) => _$ProjectTypeEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$ProjectTypeEntityToJson(this);
} | 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/article_type_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'article_type_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ArticleTypeEntity _$ArticleTypeEntityFromJson(Map<String, dynamic> json) {
return ArticleTypeEntity(
json['children'] as List,
json['courseId'] as int,
json['id'] as int,
json['name'] as String,
json['order'] as int,
json['parentChapterId'] as int,
json['userControlSetTop'] as bool,
json['visible'] as int,
);
}
Map<String, dynamic> _$ArticleTypeEntityToJson(ArticleTypeEntity instance) =>
<String, dynamic>{
'children': instance.children,
'courseId': instance.courseId,
'id': instance.id,
'name': instance.name,
'order': instance.order,
'parentChapterId': instance.parentChapterId,
'userControlSetTop': instance.userControlSetTop,
'visible': instance.visible,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/collect_web_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'collect_web_entity.g.dart';
@JsonSerializable()
class CollectWebEntity extends Object {
@JsonKey(name: 'desc')
String desc;
@JsonKey(name: 'icon')
String icon;
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'link')
String link;
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'order')
int order;
@JsonKey(name: 'userId')
int userId;
@JsonKey(name: 'visible')
int visible;
CollectWebEntity(this.desc,this.icon,this.id,this.link,this.name,this.order,this.userId,this.visible,);
factory CollectWebEntity.fromJson(Map<String, dynamic> srcJson) => _$CollectWebEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$CollectWebEntityToJson(this);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/bmob_user_entity.dart | import 'package:data_plugin/bmob/table/bmob_object.dart';
import 'package:json_annotation/json_annotation.dart';
part 'bmob_user_entity.g.dart';
@JsonSerializable()
class BmobUserEntity extends BmobObject {
String userName; //用户名
String signature; //个性签名
int level; //等级
//预留
String strWhat;
double numWhat;
BmobUserEntity(this.userName, this.signature, this.level, this.strWhat,
this.numWhat);
BmobUserEntity.empty();
BmobUserEntity copyWith({userName, signature, level, strWhat, numWhat}) {
BmobUserEntity copy = BmobUserEntity(userName ?? this.userName, signature ?? this.signature,
level ?? this.level, strWhat ?? this.strWhat, numWhat ?? this.numWhat,);
copy.objectId = this.objectId;
copy.updatedAt = this.updatedAt;
copy.createdAt = this.createdAt;
copy.ACL = this.ACL;
return copy;
}
factory BmobUserEntity.fromJson(Map<String, dynamic> json) =>
_$BmobUserEntityFromJson(json);
Map<String, dynamic> toJson() => _$BmobUserEntityToJson(this);
@override
Map getParams() {
return toJson();
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/bmob_user_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bmob_user_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BmobUserEntity _$BmobUserEntityFromJson(Map<String, dynamic> json) {
return BmobUserEntity(
json['userName'] as String,
json['signature'] as String,
json['level'] as int,
json['strWhat'] as String,
(json['numWhat'] as num)?.toDouble(),
)
..createdAt = json['createdAt'] as String
..updatedAt = json['updatedAt'] as String
..objectId = json['objectId'] as String
..ACL = json['ACL'] as Map<String, dynamic>;
}
Map<String, dynamic> _$BmobUserEntityToJson(BmobUserEntity instance) =>
<String, dynamic>{
'createdAt': instance.createdAt,
'updatedAt': instance.updatedAt,
'objectId': instance.objectId,
'ACL': instance.ACL,
'userName': instance.userName,
'signature': instance.signature,
'level': instance.level,
'strWhat': instance.strWhat,
'numWhat': instance.numWhat,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/bmob_feedback_entity.dart | import 'package:data_plugin/bmob/table/bmob_object.dart';
import 'package:json_annotation/json_annotation.dart';
part 'bmob_feedback_entity.g.dart';
@JsonSerializable()
class BmobFeedbackEntity extends BmobObject{
String userName;//用户名
String feedback;
BmobFeedbackEntity(this.userName, this.feedback);
BmobFeedbackEntity.empty();
factory BmobFeedbackEntity.fromJson(Map<String, dynamic> json) =>
_$BmobFeedbackEntityFromJson(json);
Map<String, dynamic> toJson() => _$BmobFeedbackEntityToJson(this);
@override
Map getParams() {
return toJson();
}
} | 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/bmob_feedback_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bmob_feedback_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BmobFeedbackEntity _$BmobFeedbackEntityFromJson(Map<String, dynamic> json) {
return BmobFeedbackEntity(
json['userName'] as String,
json['feedback'] as String,
)
..createdAt = json['createdAt'] as String
..updatedAt = json['updatedAt'] as String
..objectId = json['objectId'] as String
..ACL = json['ACL'] as Map<String, dynamic>;
}
Map<String, dynamic> _$BmobFeedbackEntityToJson(BmobFeedbackEntity instance) =>
<String, dynamic>{
'createdAt': instance.createdAt,
'updatedAt': instance.updatedAt,
'objectId': instance.objectId,
'ACL': instance.ACL,
'userName': instance.userName,
'feedback': instance.feedback,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/base_list_entity.dart | class BaseListEntity<T> {
int curPage;
T datas;
int offset;
bool over;
int pageCount;
int size;
int total;
BaseListEntity(
{this.curPage,
this.datas,
this.offset,
this.over,
this.pageCount,
this.size,
this.total});
BaseListEntity.fromJson(Map<String, dynamic> json) {
curPage = json['curPage'];
if (json['datas'] != null) {
datas = json['datas'];
}
offset = json['offset'];
over = json['over'];
pageCount = json['pageCount'];
size = json['size'];
total = json['total'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['curPage'] = this.curPage;
//泛型成员手动put进去
// if (this.datas != null) {
// data['datas'] = this.datas.map((v) => v.toJson()).toList();
// }
data['offset'] = this.offset;
data['over'] = this.over;
data['pageCount'] = this.pageCount;
data['size'] = this.size;
data['total'] = this.total;
return data;
}
@override
String toString() {
return 'BaseListEntity{curPage: $curPage, datas: $datas, offset: $offset, over: $over, pageCount: $pageCount, size: $size, total: $total}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/project_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'project_entity.g.dart';
@JsonSerializable()
class ProjectEntity extends Object {
@JsonKey(name: 'apkLink')
String apkLink;
@JsonKey(name: 'author')
String author;
@JsonKey(name: 'chapterId')
int chapterId;
@JsonKey(name: 'chapterName')
String chapterName;
@JsonKey(name: 'collect')
bool collect;
@JsonKey(name: 'courseId')
int courseId;
@JsonKey(name: 'desc')
String desc;
@JsonKey(name: 'envelopePic')
String envelopePic;
@JsonKey(name: 'fresh')
bool fresh;
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'link')
String link;
@JsonKey(name: 'niceDate')
String niceDate;
@JsonKey(name: 'origin')
String origin;
@JsonKey(name: 'originId')
int originId;
@JsonKey(name: 'prefix')
String prefix;
@JsonKey(name: 'projectLink')
String projectLink;
@JsonKey(name: 'publishTime')
int publishTime;
@JsonKey(name: 'superChapterId')
int superChapterId;
@JsonKey(name: 'superChapterName')
String superChapterName;
@JsonKey(name: 'tags')
List<Tags> tags;
@JsonKey(name: 'title')
String title;
@JsonKey(name: 'type')
int type;
@JsonKey(name: 'userId')
int userId;
@JsonKey(name: 'visible')
int visible;
@JsonKey(name: 'zan')
int zan;
ProjectEntity(this.apkLink,this.author,this.chapterId,this.chapterName,this.collect,this.courseId,this.desc,this.envelopePic,this.fresh,this.id,this.link,this.niceDate,this.origin,this.originId,this.prefix,this.projectLink,this.publishTime,this.superChapterId,this.superChapterName,this.tags,this.title,this.type,this.userId,this.visible,this.zan,);
factory ProjectEntity.fromJson(Map<String, dynamic> srcJson) => _$ProjectEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$ProjectEntityToJson(this);
}
@JsonSerializable()
class Tags extends Object {
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'url')
String url;
Tags(this.name,this.url,);
factory Tags.fromJson(Map<String, dynamic> srcJson) => _$TagsFromJson(srcJson);
Map<String, dynamic> toJson() => _$TagsToJson(this);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/bmob_update_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'bmob_update_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BmobUpdateEntity _$BmobUpdateEntityFromJson(Map<String, dynamic> json) {
return BmobUpdateEntity(
json['deviceType'] as int,
json['versionName'] as String,
json['updateMsg'] as String,
json['downloadUrl'] as String,
)
..createdAt = json['createdAt'] as String
..updatedAt = json['updatedAt'] as String
..objectId = json['objectId'] as String
..ACL = json['ACL'] as Map<String, dynamic>;
}
Map<String, dynamic> _$BmobUpdateEntityToJson(BmobUpdateEntity instance) =>
<String, dynamic>{
'createdAt': instance.createdAt,
'updatedAt': instance.updatedAt,
'objectId': instance.objectId,
'ACL': instance.ACL,
'deviceType': instance.deviceType,
'versionName': instance.versionName,
'updateMsg': instance.updateMsg,
'downloadUrl': instance.downloadUrl,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/base_entity.dart |
class BaseEntity<T>{
T data;
int errorCode;
String errorMsg;
BaseEntity({this.data, this.errorCode, this.errorMsg});
BaseEntity.fromJson(Map<String, dynamic> json) {
data = json['data'] != null ? json['data'] : null;
errorCode = json['errorCode'];
errorMsg = json['errorMsg'];
}
@override
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
//泛型成员手动put进去
// if (this.data != null) {
// data['data'] = this.data.toJson();
// }
data['errorCode'] = this.errorCode;
data['errorMsg'] = this.errorMsg;
return data;
}
@override
String toString() {
return 'BaseEntity{data: $data, errorCode: $errorCode, errorMsg: $errorMsg}';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/hot_key_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'hot_key_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
HotKeyEntity _$HotKeyEntityFromJson(Map<String, dynamic> json) {
return HotKeyEntity(
json['id'] as int,
json['link'] as String,
json['name'] as String,
json['order'] as int,
json['visible'] as int,
);
}
Map<String, dynamic> _$HotKeyEntityToJson(HotKeyEntity instance) =>
<String, dynamic>{
'id': instance.id,
'link': instance.link,
'name': instance.name,
'order': instance.order,
'visible': instance.visible,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/project_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'project_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
ProjectEntity _$ProjectEntityFromJson(Map<String, dynamic> json) {
return ProjectEntity(
json['apkLink'] as String,
json['author'] as String,
json['chapterId'] as int,
json['chapterName'] as String,
json['collect'] as bool,
json['courseId'] as int,
json['desc'] as String,
json['envelopePic'] as String,
json['fresh'] as bool,
json['id'] as int,
json['link'] as String,
json['niceDate'] as String,
json['origin'] as String,
json['originId'] as int,
json['prefix'] as String,
json['projectLink'] as String,
json['publishTime'] as int,
json['superChapterId'] as int,
json['superChapterName'] as String,
(json['tags'] as List)
?.map(
(e) => e == null ? null : Tags.fromJson(e as Map<String, dynamic>))
?.toList(),
json['title'] as String,
json['type'] as int,
json['userId'] as int,
json['visible'] as int,
json['zan'] as int,
);
}
Map<String, dynamic> _$ProjectEntityToJson(ProjectEntity instance) =>
<String, dynamic>{
'apkLink': instance.apkLink,
'author': instance.author,
'chapterId': instance.chapterId,
'chapterName': instance.chapterName,
'collect': instance.collect,
'courseId': instance.courseId,
'desc': instance.desc,
'envelopePic': instance.envelopePic,
'fresh': instance.fresh,
'id': instance.id,
'link': instance.link,
'niceDate': instance.niceDate,
'origin': instance.origin,
'originId': instance.originId,
'prefix': instance.prefix,
'projectLink': instance.projectLink,
'publishTime': instance.publishTime,
'superChapterId': instance.superChapterId,
'superChapterName': instance.superChapterName,
'tags': instance.tags,
'title': instance.title,
'type': instance.type,
'userId': instance.userId,
'visible': instance.visible,
'zan': instance.zan,
};
Tags _$TagsFromJson(Map<String, dynamic> json) {
return Tags(
json['name'] as String,
json['url'] as String,
);
}
Map<String, dynamic> _$TagsToJson(Tags instance) => <String, dynamic>{
'name': instance.name,
'url': instance.url,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/hot_key_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'hot_key_entity.g.dart';
@JsonSerializable()
class HotKeyEntity extends Object {
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'link')
String link;
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'order')
int order;
@JsonKey(name: 'visible')
int visible;
HotKeyEntity(this.id,this.link,this.name,this.order,this.visible,);
factory HotKeyEntity.fromJson(Map<String, dynamic> srcJson) => _$HotKeyEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$HotKeyEntityToJson(this);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/article_type_entity.dart | import 'package:json_annotation/json_annotation.dart';
part 'article_type_entity.g.dart';
@JsonSerializable()
class ArticleTypeEntity extends Object {
@JsonKey(name: 'children')
List<dynamic> children;
@JsonKey(name: 'courseId')
int courseId;
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'order')
int order;
@JsonKey(name: 'parentChapterId')
int parentChapterId;
@JsonKey(name: 'userControlSetTop')
bool userControlSetTop;
@JsonKey(name: 'visible')
int visible;
ArticleTypeEntity(this.children,this.courseId,this.id,this.name,this.order,this.parentChapterId,this.userControlSetTop,this.visible,);
ArticleTypeEntity.simple(this.name,this.id,this.children);
factory ArticleTypeEntity.fromJson(Map<String, dynamic> srcJson) => _$ArticleTypeEntityFromJson(srcJson);
Map<String, dynamic> toJson() => _$ArticleTypeEntityToJson(this);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/banner_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'banner_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BannerEntity _$BannerEntityFromJson(Map<String, dynamic> json) {
return BannerEntity(
json['desc'] as String,
json['id'] as int,
json['imagePath'] as String,
json['isVisible'] as int,
json['order'] as int,
json['title'] as String,
json['type'] as int,
json['url'] as String,
);
}
Map<String, dynamic> _$BannerEntityToJson(BannerEntity instance) =>
<String, dynamic>{
'desc': instance.desc,
'id': instance.id,
'imagePath': instance.imagePath,
'isVisible': instance.isVisible,
'order': instance.order,
'title': instance.title,
'type': instance.type,
'url': instance.url,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/entity/todo_entity.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'todo_entity.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
TodoEntity _$TodoEntityFromJson(Map<String, dynamic> json) {
return TodoEntity(
json['completeDate'] as int,
json['completeDateStr'] as String,
json['content'] as String,
json['date'] as int,
json['dateStr'] as String,
json['id'] as int,
json['priority'] as int,
json['status'] as int,
json['title'] as String,
json['type'] as int,
json['userId'] as int,
);
}
Map<String, dynamic> _$TodoEntityToJson(TodoEntity instance) =>
<String, dynamic>{
'completeDate': instance.completeDate,
'completeDateStr': instance.completeDateStr,
'content': instance.content,
'date': instance.date,
'dateStr': instance.dateStr,
'id': instance.id,
'priority': instance.priority,
'status': instance.status,
'title': instance.title,
'type': instance.type,
'userId': instance.userId,
};
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/utils/string_decode.dart | //将被转义的字符变换原符号
String decodeString(String str) {
return str
.replaceAll('&', '/')
.replaceAll(""", "\"")
.replaceAll("“", "“")
.replaceAll("”", "”")
.replaceAll("<br>", "\n")
.replaceAll(">", ">")
.replaceAll("<", "<");
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/utils/shared_preference_util.dart | import 'package:shared_preferences/shared_preferences.dart';
///一些通用SharedPreferences key声明处
class SPKey {
static const String LOGIN = "key_is_login";
static const String USER_NAME = "user_name";
}
class SPUtil {
static Future<bool> isLogin() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.get(SPKey.LOGIN) ?? false;
}
static Future setLogin(bool isLogin) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setBool(SPKey.LOGIN, isLogin ?? false);
}
static Future setUserName(String userName) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.setString(SPKey.USER_NAME, userName);
}
static Future getUserName()async{
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.get(SPKey.USER_NAME) ?? '';
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/utils/screen_utils.dart | import 'dart:ui' as ui;
import 'package:flutter/material.dart';
//系统默认的appBar等高度
//位于Dart Packages/flutter/src/material/constans.dart
///默认设计稿尺寸
double _designW = 375.0;
double _designH = 667.0;
/**
* 配置设计稿尺寸
* w 宽
* h 高
*/
/// 配置设计稿尺寸 屏幕 宽,高
void setDesignWHD(double w, double h) {
_designW = w;
_designH = h;
}
///--------------屏幕适配。按【宽】适配。------------------
/// Screen Util.
class ScreenUtils {
double _screenWidth = 0.0;
double _screenHeight = 0.0;
double _screenDensity = 0.0;
double _statusBarHeight = 0.0;
double _bottomBarHeight = 0.0;
double _appBarHeight = 0.0;
MediaQueryData _mediaQueryData;
static final ScreenUtils _singleton = ScreenUtils._internal();
ScreenUtils._internal();
static ScreenUtils getInstance() {
_singleton._init();
return _singleton;
}
///类似屏幕旋转等窗口变化时,需重新init以获取新的MediaQueryData
_init() {
MediaQueryData mediaQuery = MediaQueryData.fromWindow(ui.window);
if (mediaQuery == null) {
throw Exception("获取MediaQueryData失败");
}
if (_mediaQueryData != mediaQuery) {
_mediaQueryData = mediaQuery;
_screenWidth = mediaQuery.size.width;
_screenHeight = mediaQuery.size.height;
_screenDensity = mediaQuery.devicePixelRatio;
_statusBarHeight = mediaQuery.padding.top;
_bottomBarHeight = mediaQuery.padding.bottom;
_appBarHeight = kToolbarHeight;
}
}
_initByMedia(MediaQueryData mediaQuery) {
if (_mediaQueryData != mediaQuery) {
_mediaQueryData = mediaQuery;
_screenWidth = mediaQuery.size.width;
_screenHeight = mediaQuery.size.height;
_screenDensity = mediaQuery.devicePixelRatio;
_statusBarHeight = mediaQuery.padding.top;
_bottomBarHeight = mediaQuery.padding.bottom;
_appBarHeight = kToolbarHeight;
}
}
/// 屏幕 宽
double get screenWidth => _screenWidth;
/// 屏幕 高
double get screenHeight => _screenHeight;
/// appBar(标题栏) 默认高
double get appBarHeight => _appBarHeight;
/// 屏幕 像素密度
double get screenDensity => _screenDensity;
/// 状态栏高度
double get statusBarHeight => _statusBarHeight;
/// 底部栏高度(如android底部虚拟按键区域)
double get bottomBarHeight => _bottomBarHeight;
/// media Query Data
MediaQueryData get mediaQueryData => _mediaQueryData;
/// 按宽度适配时。
/// 返回适配后尺寸
/// size 即设计稿上使用的单位
double getWidth(double size) {
//屏幕实际总宽度 : 设计稿总宽度 = 适配宽度 : 传入的size
return _screenWidth == 0.0 ? size : (size * _screenWidth / _designW);
}
/// 按高度适配时。
/// 返回适配后尺寸
/// size 即设计稿上使用的单位
double getHeight(double size) {
return _screenHeight == 0.0 ? size : (size * _screenHeight / _designH);
}
/// 返回根据屏幕宽适配后字体尺寸
/// fontSize 字体尺寸
double getSp(double fontSize) {
if (_screenDensity == 0.0) return fontSize;
return getWidth(fontSize);
}
///-------------快捷方法---------------
double pt(double size) {
return getWidth(size);
}
}
///-------------快捷静态方法。-----------------
double pt(double size) {
// MediaQueryData mediaQuery = MediaQuery.of(context);
MediaQueryData mediaQuery = MediaQueryData.fromWindow(ui.window);
double _screenWidth = mediaQuery.size.width;
return _screenWidth == 0.0 ? size : (size * _screenWidth / _designW);
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/utils/print_long.dart | ///print打印日志有长度限制,超出部分会自动别截断。
///本方法可以打印长日志。
///经测试,print一次最多打印1023长度。大部分中文占3字节。因此使用最保险的最大长度 1023 / 3 = 341
///同时这也说明如果日志里没有中文或只有部分中文时,直接用print其实是比printLong一次打印更多内容的,
///所以你日常打印还是应该尽量用print,只有真的不确定打印会不会很多时再用printLong
int maxLength = 340;
void printLong(String log) {
if (log.length < maxLength) {
print(log);
} else {
while (log.length > maxLength) {
print(log.substring(0, maxLength));
log = log.substring(maxLength);
}
//打印剩余部分
print(log);
}
}
| 0 |
mirrored_repositories/WanAndroid_Flutter/lib | mirrored_repositories/WanAndroid_Flutter/lib/utils/index.dart | export 'print_long.dart';
export 'screen_utils.dart';
export 'display_util.dart';
export 'shared_preference_util.dart'; | 0 |
Subsets and Splits