build: code format

This commit is contained in:
zymxxxs
2019-11-08 01:30:34 +08:00
parent c337f72c49
commit 728f4e20a2
373 changed files with 6283 additions and 5259 deletions

View File

@ -1,36 +1,36 @@
class Api{
class Api {
// static const String BASE_URL = 'http://flutter-go.alibaba.net/';
static const String BASE_URL = 'https://flutter-go.pub/api/';
static const String DO_LOGIN = BASE_URL+'doLogin';//登陆
static const String DO_LOGIN = BASE_URL + 'doLogin'; //登陆
static const String CHECK_LOGIN = BASE_URL+'checkLogin';//验证登陆
static const String CHECK_LOGIN = BASE_URL + 'checkLogin'; //验证登陆
static const String LOGOUT = BASE_URL+'logout';//退出登陆
static const String LOGOUT = BASE_URL + 'logout'; //退出登陆
static const String GET_USER_INFO = BASE_URL+'getUserInfo';//获取用户信息
static const String GET_USER_INFO = BASE_URL + 'getUserInfo'; //获取用户信息
static const String VERSION = BASE_URL + 'getAppVersion'; //检查版本
static const String VERSION = BASE_URL+'getAppVersion';//检查版本
static const String FEEDBACK = BASE_URL+'auth/feedback';//建议反馈
static const String FEEDBACK = BASE_URL + 'auth/feedback'; //建议反馈
// static const String LOTOUT = BASE_URL+'logout';//退出登陆
static const String GET_ALL_COLLECTION = BASE_URL+'auth/getAllUserCollection';//获取全部收藏
static const String GET_ALL_COLLECTION =
BASE_URL + 'auth/getAllUserCollection'; //获取全部收藏
static const String REMOVE_COLLECTION = BASE_URL+'auth/removeCollection';//移除收藏
static const String REMOVE_COLLECTION =
BASE_URL + 'auth/removeCollection'; //移除收藏
static const String ADD_COLLECTION = BASE_URL+'auth/addCollection';//添加收藏
static const String ADD_COLLECTION = BASE_URL + 'auth/addCollection'; //添加收藏
static const String CHECK_COLLECTED = BASE_URL+'checkCollected';//校验收藏
static const String CHECK_COLLECTED = BASE_URL + 'checkCollected'; //校验收藏
static const String SET_THEMECOLOR = BASE_URL+'auth/setThemeColor';//设置主题颜色
static const String SET_THEMECOLOR = BASE_URL + 'auth/setThemeColor'; //设置主题颜色
static const String GET_THEMECOLOR = BASE_URL +'/getThemeColor';//获取主题颜色
static const String GET_THEMECOLOR = BASE_URL + '/getThemeColor'; //获取主题颜色
static const String GET_WIDGET_TREE = BASE_URL + 'getCateList';//获取widget列表树
static const String GET_WIDGET_TREE = BASE_URL + 'getCateList'; //获取widget列表树
static const String SEARCH_WIDGET = BASE_URL+'searchWidget';//搜索组件
static const String SEARCH_WIDGET = BASE_URL + 'searchWidget'; //搜索组件
}

View File

@ -12,6 +12,7 @@ import 'package:html/parser.dart' show parse;
import './search_result.dart';
var dio = new Dio();
//class Api2 {
// /// 关键字提示(起点)
// Future<List<String>> suggestion(String query) async {
@ -42,9 +43,11 @@ class Api {
// http.Response response = await http.get(
// "https://www.qidian.com/ajax/Search/AutoComplete?siteid=1&query=$query");
/// var response = await dio.get("https://www.qidian.com/ajax/Search/AutoComplete?siteid=1&query=$query", data: {});
var response = await dio.get("https://www.so.com/s?ie=utf-8&q=$query flutter");
var response =
await dio.get("https://www.so.com/s?ie=utf-8&q=$query flutter");
var document = parse(response.data);
var app = document.querySelectorAll('.res-title a');
///print('1=====>${query}');
///print('2=====>${response.data}');
////print('3=====>${app}');
@ -59,7 +62,7 @@ class Api {
);
});
return Future.delayed(Duration(seconds:2), () {
return Future.delayed(Duration(seconds: 2), () {
return res;
});
//return suggestion;

View File

@ -16,8 +16,8 @@ class SuggestionBloc extends Bloc<SuggestionEvent, SuggestionState> {
@override
SuggestionState get initialState => SuggestionUninitialized();
@override
Stream<SuggestionState> mapEventToState(SuggestionEvent event)async* {
//Stream<SuggestionState> mapEventToState(SuggestionState currentState, SuggestionEvent event,) async* {
Stream<SuggestionState> mapEventToState(SuggestionEvent event) async* {
//Stream<SuggestionState> mapEventToState(SuggestionState currentState, SuggestionEvent event,) async* {
if (event is SuggestionFetch) {
//print('event==>${event}');
try {

View File

@ -8,6 +8,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import './industry_bloc.dart';
/// import './industry_event.dart';
import './industry_state.dart';
@ -15,7 +16,7 @@ final SuggestionBloc suggestion = SuggestionBloc();
class IndustryPage extends StatefulWidget {
final Function itemTitle;
IndustryPage({Key key,this.itemTitle}) : super(key: key);
IndustryPage({Key key, this.itemTitle}) : super(key: key);
@override
_IndustryState createState() => _IndustryState();
@ -40,15 +41,13 @@ class _IndustryState extends State<IndustryPage> {
return Center(
child: Text('没有适合的结果,更换查询条件试试'),
);
}else {
} else {
if (widget.itemTitle is Function) {
return widget.itemTitle(state);
}
}
}
return Center(
child: Text('没有适合的结果,更换查询条件试试')
);
return Center(child: Text('没有适合的结果,更换查询条件试试'));
}
@override
@ -59,7 +58,7 @@ class _IndustryState extends State<IndustryPage> {
Expanded(
child: BlocBuilder(
bloc: suggestion,
builder: (BuildContext context, SuggestionState state){
builder: (BuildContext context, SuggestionState state) {
/// print('BlocBuilder----${state}');
return renderItem(state);
},

View File

@ -21,8 +21,6 @@ class _CateCardState extends State<CateCard> {
_firstChildList = widget.category.children;
}
@override
Widget build(BuildContext context) {
double screenWidth = MediaQuery.of(context).size.width;
@ -100,14 +98,11 @@ class _CateCardState extends State<CateCard> {
padding: const EdgeInsets.only(bottom: 10.0, top: 5.0),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/paimaiLogo.png'),
alignment: Alignment.bottomRight
),
image: AssetImage('assets/images/paimaiLogo.png'),
alignment: Alignment.bottomRight),
),
child: WidgetItemContainer(
commonItems: this._firstChildList,
columnCount: 3
),
commonItems: this._firstChildList, columnCount: 3),
);
}
}

View File

@ -3,18 +3,16 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../routers/application.dart';
/// import '../model/cat.dart';
import '../model/widget.dart';
import '../widgets/index.dart';
import '../components/widget_item_container.dart';
class CategoryHome extends StatefulWidget {
CategoryHome(this.token);
final String token;
@override
_CategoryHome createState() => new _CategoryHome();
}
@ -26,7 +24,6 @@ class _CategoryHome extends State<CategoryHome> {
List<Object> widgetPoints = [];
List<CommonItem> catHistory = new List();
// 所有的可用demos;
List widgetDemosList = new WidgetDemoList().getDemos();
@ -39,17 +36,13 @@ class _CategoryHome extends State<CategoryHome> {
CommonItem targetGroup = Application.widgetTree.find(widget.token) ?? [];
print("targetGroup::: $targetGroup");
catHistory.add(
targetGroup
);
catHistory.add(targetGroup);
this.setState(() {
items = targetGroup.children;
});
searchCatOrWidget();
}
Future<bool> back() {
// if (catHistory.length == 1) {
// return Future<bool>.value(true);
@ -66,10 +59,9 @@ class _CategoryHome extends State<CategoryHome> {
void searchCatOrWidget() async {
/// CommonItem widgetTree = Application.widgetTree;
// 假设进入这个界面的parent一定存在
// 假设进入这个界面的parent一定存在
CommonItem targetGroup = catHistory.last;
this.setState(() {
title = targetGroup.name;
});
@ -79,14 +71,9 @@ class _CategoryHome extends State<CategoryHome> {
go(cat);
}
Widget _buildContent() {
WidgetItemContainer wiContaienr = WidgetItemContainer(
columnCount: 3,
commonItems: items
);
WidgetItemContainer wiContaienr =
WidgetItemContainer(columnCount: 3, commonItems: items);
return Container(
padding: const EdgeInsets.only(bottom: 10.0, top: 5.0),
@ -102,14 +89,11 @@ class _CategoryHome extends State<CategoryHome> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("$title"),
),
body: WillPopScope(
onWillPop: () {
return back();
},
@ -124,4 +108,3 @@ class _CategoryHome extends State<CategoryHome> {
);
}
}

View File

@ -22,7 +22,6 @@ class DisclaimerMsg extends StatefulWidget {
DisclaimerMsgState createState() => DisclaimerMsgState();
}
class DisclaimerMsgState extends State<DisclaimerMsg> {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<bool> _unKnow;
@ -39,8 +38,8 @@ class DisclaimerMsgState extends State<DisclaimerMsg> {
setState(() {
_unKnow =
prefs.setBool("disclaimer::Boolean", unKnow).then((bool success) {
return unKnow;
});
return unKnow;
});
});
}
}
@ -63,15 +62,13 @@ class DisclaimerMsgState extends State<DisclaimerMsg> {
context: context,
barrierDismissible: false, // user must tap button!
builder: (BuildContext context) {
return DisclaimerMsgDialog(_valBool, _readed, (b){
return DisclaimerMsgDialog(_valBool, _readed, (b) {
refs(b);
});
},
);
}
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
@ -85,7 +82,7 @@ class DisclaimerMsgState extends State<DisclaimerMsg> {
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius:
BorderRadius.horizontal(right: Radius.circular(10)),
BorderRadius.horizontal(right: Radius.circular(10)),
color: Colors.black45,
),
child: Text(
@ -102,14 +99,11 @@ class DisclaimerMsgState extends State<DisclaimerMsg> {
}
}
class DisclaimerMsgDialog extends StatefulWidget {
final bool valBool;
final bool readed;
final ValueChanged<bool> onValueChanged;
DisclaimerMsgDialog(this.valBool, this.readed, this.onValueChanged);
@override
@ -117,18 +111,14 @@ class DisclaimerMsgDialog extends StatefulWidget {
}
class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
bool readBool;
@override
void initState() {
super.initState();
readBool = widget.valBool;
}
Row _create() {
//已读
if (widget.readed) {
@ -140,9 +130,7 @@ class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
child: Text('已阅读知晓',
style: TextStyle(fontSize: 16, color: Colors.white)),
//可点击
color: Theme
.of(context)
.primaryColor,
color: Theme.of(context).primaryColor,
onPressed: () {
Navigator.of(context).pop();
},
@ -155,7 +143,7 @@ class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
}
/// 选中状态更新,并返回数据
checkChanged(){
checkChanged() {
if (mounted) {
setState(() {
readBool = !readBool;
@ -168,16 +156,14 @@ class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
//crossAxisAlignment:CrossAxisAlignment.start,
children: <Widget>[
GestureDetector(
onTap: (){
onTap: () {
checkChanged();
},
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Checkbox(
activeColor: Theme
.of(context)
.primaryColor,
activeColor: Theme.of(context).primaryColor,
tristate: false,
value: readBool,
onChanged: (bool bol) {
@ -192,13 +178,8 @@ class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
style: TextStyle(fontSize: 16, color: Colors.white)),
//可点击
color: readBool
? Theme
.of(context)
.primaryColor
: Theme
.of(context)
.primaryColor
.withAlpha(800),
? Theme.of(context).primaryColor
: Theme.of(context).primaryColor.withAlpha(800),
onPressed: () {
widget.onValueChanged(readBool);
Navigator.of(context).pop();
@ -220,7 +201,7 @@ class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
height: 35,
child: Text('免责声明',
style:
TextStyle(fontSize: 18, fontWeight: FontWeight.w700)),
TextStyle(fontSize: 18, fontWeight: FontWeight.w700)),
decoration: BoxDecoration(
//color: Colors.blue,
image: DecorationImage(
@ -247,4 +228,5 @@ class _DisclaimerMsgDialogState extends State<DisclaimerMsgDialog> {
)
],
);
}}
}
}

View File

@ -85,12 +85,8 @@ abstract class MarkdownBuilderDelegate {
/// * [Markdown], which is a widget that parses and displays Markdown.
class MarkdownBuilder implements md.NodeVisitor {
/// Creates an object that builds a [Widget] tree from parsed Markdown.
MarkdownBuilder({
this.delegate,
this.styleSheet,
this.imageDirectory,
this.demoParser
});
MarkdownBuilder(
{this.delegate, this.styleSheet, this.imageDirectory, this.demoParser});
/// A delegate that controls how link and `pre` elements behave.
final MarkdownBuilderDelegate delegate;
@ -99,6 +95,7 @@ class MarkdownBuilder implements md.NodeVisitor {
final MarkdownStyleSheet styleSheet;
final DemoBuilder demoParser;
/// The base directory holding images referenced by Img tags with local file paths.
final Directory imageDirectory;
@ -107,7 +104,6 @@ class MarkdownBuilder implements md.NodeVisitor {
final List<_InlineElement> _inlines = <_InlineElement>[];
final List<GestureRecognizer> _linkHandlers = <GestureRecognizer>[];
/// Returns widgets that display the given Markdown nodes.
///
/// The returned widgets are typically used as children in a [ListView].
@ -136,12 +132,12 @@ class MarkdownBuilder implements md.NodeVisitor {
_addParentInlineIfNeeded(_blocks.last.tag);
final TextSpan span = _blocks.last.tag == 'pre'
? delegate.formatText(styleSheet, text.text)
: new TextSpan(
style: _inlines.last.style,
text: text.text,
recognizer: _linkHandlers.isNotEmpty ? _linkHandlers.last : null,
);
? delegate.formatText(styleSheet, text.text)
: new TextSpan(
style: _inlines.last.style,
text: text.text,
recognizer: _linkHandlers.isNotEmpty ? _linkHandlers.last : null,
);
_inlines.last.children.add(new RichText(
textScaleFactor: styleSheet.textScaleFactor,
@ -155,8 +151,7 @@ class MarkdownBuilder implements md.NodeVisitor {
final String tag = element.tag;
if (_isBlockTag(tag)) {
_addAnonymousBlockIfNeeded(styleSheet.styles[tag]);
if (_isListTag(tag))
_listIndents.add(tag);
if (_isListTag(tag)) _listIndents.add(tag);
_blocks.add(new _BlockElement(tag));
} else {
_addParentInlineIfNeeded(_blocks.last.tag);
@ -232,7 +227,6 @@ class MarkdownBuilder implements md.NodeVisitor {
}
_addBlockChild(child);
} else {
final _InlineElement current = _inlines.removeLast();
final _InlineElement parent = _inlines.last;
@ -245,12 +239,12 @@ class MarkdownBuilder implements md.NodeVisitor {
current.children.add(_buildGoDemos(element.attributes));
}
if (current.children.isNotEmpty) {
parent.children.addAll(current.children);
}
}
}
Widget _buildGoDemos(Map<String, dynamic> attrs) {
Widget targetGoDemos;
@ -263,8 +257,7 @@ class MarkdownBuilder implements md.NodeVisitor {
Widget _buildImage(String src) {
final List<String> parts = src.split('#');
if (parts.isEmpty)
return const SizedBox();
if (parts.isEmpty) return const SizedBox();
final String path = parts.first;
double width;
@ -300,10 +293,12 @@ class MarkdownBuilder implements md.NodeVisitor {
}
}
Widget _handleDataSchemeUri(Uri uri, final double width, final double height) {
Widget _handleDataSchemeUri(
Uri uri, final double width, final double height) {
final String mimeType = uri.data.mimeType;
if (mimeType.startsWith('image/')) {
return new Image.memory(uri.data.contentAsBytes(), width: width, height: height);
return new Image.memory(uri.data.contentAsBytes(),
width: width, height: height);
} else if (mimeType.startsWith('text/')) {
return new Text(uri.data.contentAsString());
}
@ -312,12 +307,14 @@ class MarkdownBuilder implements md.NodeVisitor {
Widget _buildBullet(String listTag) {
if (listTag == 'ul')
return new Text('', textAlign: TextAlign.center, style: styleSheet.styles['li']);
return new Text('',
textAlign: TextAlign.center, style: styleSheet.styles['li']);
final int index = _blocks.last.nextListIndex;
return new Padding(
padding: const EdgeInsets.only(right: 5.0),
child: new Text('${index + 1}.', textAlign: TextAlign.right, style: styleSheet.styles['li']),
child: new Text('${index + 1}.',
textAlign: TextAlign.right, style: styleSheet.styles['li']),
);
}
@ -356,7 +353,9 @@ class MarkdownBuilder implements md.NodeVisitor {
List<Widget> _mergeInlineChildren(_InlineElement inline) {
List<Widget> mergedTexts = <Widget>[];
for (Widget child in inline.children) {
if (mergedTexts.isNotEmpty && mergedTexts.last is RichText && child is RichText) {
if (mergedTexts.isNotEmpty &&
mergedTexts.last is RichText &&
child is RichText) {
RichText previous = mergedTexts.removeLast();
List<TextSpan> children = previous.text.children != null
? new List.from(previous.text.children)

View File

@ -7,45 +7,45 @@ import 'package:flutter/material.dart';
/// Defines which [TextStyle] objects to use for which Markdown elements.
class MarkdownStyleSheet {
/// Creates an explicit mapping of [TextStyle] objects to Markdown elements.
MarkdownStyleSheet({
this.a,
this.p,
this.code,
this.h1,
this.h2,
this.h3,
this.h4,
this.h5,
this.h6,
this.em,
this.strong,
this.blockquote,
this.img,
this.blockSpacing,
this.listIndent,
this.blockquotePadding,
this.blockquoteDecoration,
this.codeblockPadding,
this.codeblockDecoration,
this.horizontalRuleDecoration,
this.textScaleFactor = 1.0
}) : _styles = <String, TextStyle>{
'a': a,
'p': p,
'li': p,
'code': code,
'pre': p,
'h1': h1,
'h2': h2,
'h3': h3,
'h4': h4,
'h5': h5,
'h6': h6,
'em': em,
'strong': strong,
'blockquote': blockquote,
'img': img,
};
MarkdownStyleSheet(
{this.a,
this.p,
this.code,
this.h1,
this.h2,
this.h3,
this.h4,
this.h5,
this.h6,
this.em,
this.strong,
this.blockquote,
this.img,
this.blockSpacing,
this.listIndent,
this.blockquotePadding,
this.blockquoteDecoration,
this.codeblockPadding,
this.codeblockDecoration,
this.horizontalRuleDecoration,
this.textScaleFactor = 1.0})
: _styles = <String, TextStyle>{
'a': a,
'p': p,
'li': p,
'code': code,
'pre': p,
'h1': h1,
'h2': h2,
'h3': h3,
'h4': h4,
'h5': h5,
'h6': h6,
'em': em,
'strong': strong,
'blockquote': blockquote,
'img': img,
};
/// Creates a [MarkdownStyleSheet] from the [TextStyle]s in the provided [ThemeData].
factory MarkdownStyleSheet.fromTheme(ThemeData theme) {
@ -54,10 +54,9 @@ class MarkdownStyleSheet {
a: const TextStyle(color: Colors.blue),
p: theme.textTheme.body1,
code: new TextStyle(
color: Colors.grey.shade700,
fontFamily: "monospace",
fontSize: theme.textTheme.body1.fontSize * 0.85
),
color: Colors.grey.shade700,
fontFamily: "monospace",
fontSize: theme.textTheme.body1.fontSize * 0.85),
h1: theme.textTheme.headline,
h2: theme.textTheme.title,
h3: theme.textTheme.subhead,
@ -72,18 +71,15 @@ class MarkdownStyleSheet {
listIndent: 32.0,
blockquotePadding: 8.0,
blockquoteDecoration: new BoxDecoration(
color: Colors.blue.shade100,
borderRadius: new BorderRadius.circular(2.0)
),
color: Colors.blue.shade100,
borderRadius: new BorderRadius.circular(2.0)),
codeblockPadding: 8.0,
codeblockDecoration: new BoxDecoration(
color: Colors.grey.shade100,
borderRadius: new BorderRadius.circular(2.0)
),
color: Colors.grey.shade100,
borderRadius: new BorderRadius.circular(2.0)),
horizontalRuleDecoration: new BoxDecoration(
border: new Border(
top: new BorderSide(width: 5.0, color: Colors.grey.shade300)
),
top: new BorderSide(width: 5.0, color: Colors.grey.shade300)),
),
);
}
@ -97,10 +93,9 @@ class MarkdownStyleSheet {
a: const TextStyle(color: Colors.blue),
p: theme.textTheme.body1,
code: new TextStyle(
color: Colors.grey.shade700,
fontFamily: "monospace",
fontSize: theme.textTheme.body1.fontSize * 0.85
),
color: Colors.grey.shade700,
fontFamily: "monospace",
fontSize: theme.textTheme.body1.fontSize * 0.85),
h1: theme.textTheme.display3,
h2: theme.textTheme.display2,
h3: theme.textTheme.display1,
@ -115,18 +110,15 @@ class MarkdownStyleSheet {
listIndent: 32.0,
blockquotePadding: 8.0,
blockquoteDecoration: new BoxDecoration(
color: Colors.blue.shade100,
borderRadius: new BorderRadius.circular(2.0)
),
color: Colors.blue.shade100,
borderRadius: new BorderRadius.circular(2.0)),
codeblockPadding: 8.0,
codeblockDecoration: new BoxDecoration(
color: Colors.grey.shade100,
borderRadius: new BorderRadius.circular(2.0)
),
color: Colors.grey.shade100,
borderRadius: new BorderRadius.circular(2.0)),
horizontalRuleDecoration: new BoxDecoration(
border: new Border(
top: new BorderSide(width: 5.0, color: Colors.grey.shade300)
),
top: new BorderSide(width: 5.0, color: Colors.grey.shade300)),
),
);
}
@ -176,8 +168,9 @@ class MarkdownStyleSheet {
blockquoteDecoration: blockquoteDecoration ?? this.blockquoteDecoration,
codeblockPadding: codeblockPadding ?? this.codeblockPadding,
codeblockDecoration: codeblockDecoration ?? this.codeblockDecoration,
horizontalRuleDecoration: horizontalRuleDecoration ?? this.horizontalRuleDecoration,
textScaleFactor : textScaleFactor ?? this.textScaleFactor,
horizontalRuleDecoration:
horizontalRuleDecoration ?? this.horizontalRuleDecoration,
textScaleFactor: textScaleFactor ?? this.textScaleFactor,
);
}
@ -250,32 +243,30 @@ class MarkdownStyleSheet {
@override
bool operator ==(dynamic other) {
if (identical(this, other))
return true;
if (other.runtimeType != MarkdownStyleSheet)
return false;
if (identical(this, other)) return true;
if (other.runtimeType != MarkdownStyleSheet) return false;
final MarkdownStyleSheet typedOther = other;
return typedOther.a == a
&& typedOther.p == p
&& typedOther.code == code
&& typedOther.h1 == h1
&& typedOther.h2 == h2
&& typedOther.h3 == h3
&& typedOther.h4 == h4
&& typedOther.h5 == h5
&& typedOther.h6 == h6
&& typedOther.em == em
&& typedOther.strong == strong
&& typedOther.blockquote == blockquote
&& typedOther.img == img
&& typedOther.blockSpacing == blockSpacing
&& typedOther.listIndent == listIndent
&& typedOther.blockquotePadding == blockquotePadding
&& typedOther.blockquoteDecoration == blockquoteDecoration
&& typedOther.codeblockPadding == codeblockPadding
&& typedOther.codeblockDecoration == codeblockDecoration
&& typedOther.horizontalRuleDecoration == horizontalRuleDecoration
&& typedOther.textScaleFactor == textScaleFactor;
return typedOther.a == a &&
typedOther.p == p &&
typedOther.code == code &&
typedOther.h1 == h1 &&
typedOther.h2 == h2 &&
typedOther.h3 == h3 &&
typedOther.h4 == h4 &&
typedOther.h5 == h5 &&
typedOther.h6 == h6 &&
typedOther.em == em &&
typedOther.strong == strong &&
typedOther.blockquote == blockquote &&
typedOther.img == img &&
typedOther.blockSpacing == blockSpacing &&
typedOther.listIndent == listIndent &&
typedOther.blockquotePadding == blockquotePadding &&
typedOther.blockquoteDecoration == blockquoteDecoration &&
typedOther.codeblockPadding == codeblockPadding &&
typedOther.codeblockDecoration == codeblockDecoration &&
typedOther.horizontalRuleDecoration == horizontalRuleDecoration &&
typedOther.textScaleFactor == textScaleFactor;
}
@override

View File

@ -11,6 +11,7 @@ import 'package:meta/meta.dart';
import 'builder.dart';
import 'style_sheet.dart';
//
typedef Widget ItemDemoBuilder(Map<String, dynamic> attrs);
@ -22,7 +23,8 @@ typedef void MarkdownTapLinkCallback(String href);
/// Creates a format [TextSpan] given a string.
///
/// Used by [MarkdownWidget] to highlight the contents of `pre` elements.
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
abstract class SyntaxHighlighter {
// ignore: one_member_abstracts
/// Returns the formated [TextSpan] for the given string.
TextSpan format(String source);
}
@ -49,8 +51,8 @@ abstract class MarkdownWidget extends StatefulWidget {
this.onTapLink,
this.imageDirectory,
this.demoBuilder,
}) : assert(data != null),
super(key: key);
}) : assert(data != null),
super(key: key);
/// The Markdown to display.
final String data;
@ -72,6 +74,7 @@ abstract class MarkdownWidget extends StatefulWidget {
final Directory imageDirectory;
final ItemDemoBuilder demoBuilder;
/// Subclasses should override this function to display the given children,
/// which are the parsed representation of [data].
@protected
@ -91,7 +94,8 @@ class DemosSyntax extends md.InlineSyntax {
}
}
class _MarkdownWidgetState extends State<MarkdownWidget> implements MarkdownBuilderDelegate {
class _MarkdownWidgetState extends State<MarkdownWidget>
implements MarkdownBuilderDelegate {
List<Widget> _children;
final List<GestureRecognizer> _recognizers = <GestureRecognizer>[];
@ -104,9 +108,8 @@ class _MarkdownWidgetState extends State<MarkdownWidget> implements MarkdownBuil
@override
void didUpdateWidget(MarkdownWidget oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.data != oldWidget.data
|| widget.styleSheet != oldWidget.styleSheet)
_parseMarkdown();
if (widget.data != oldWidget.data ||
widget.styleSheet != oldWidget.styleSheet) _parseMarkdown();
}
@override
@ -116,44 +119,43 @@ class _MarkdownWidgetState extends State<MarkdownWidget> implements MarkdownBuil
}
void _parseMarkdown() {
final MarkdownStyleSheet styleSheet = widget.styleSheet ?? new MarkdownStyleSheet.fromTheme(Theme.of(context));
final MarkdownStyleSheet styleSheet = widget.styleSheet ??
new MarkdownStyleSheet.fromTheme(Theme.of(context));
_disposeRecognizers();
// TODO: This can be optimized by doing the split and removing \r at the same time
final List<String> lines = widget.data.replaceAll('\r\n', '\n').split('\n');
final md.ExtensionSet extens = new md.ExtensionSet([
md.FencedCodeBlockSyntax()
md.FencedCodeBlockSyntax()
], [
new DemosSyntax(),
new md.InlineHtmlSyntax(),
]);
final md.Document document = new md.Document(encodeHtml: false, extensionSet: extens);
final md.Document document =
new md.Document(encodeHtml: false, extensionSet: extens);
final MarkdownBuilder builder = new MarkdownBuilder(
delegate: this,
styleSheet: styleSheet,
imageDirectory: widget.imageDirectory,
demoParser: widget.demoBuilder
);
delegate: this,
styleSheet: styleSheet,
imageDirectory: widget.imageDirectory,
demoParser: widget.demoBuilder);
_children = builder.build(document.parseLines(lines));
}
void _disposeRecognizers() {
if (_recognizers.isEmpty)
return;
final List<GestureRecognizer> localRecognizers = new List<GestureRecognizer>.from(_recognizers);
if (_recognizers.isEmpty) return;
final List<GestureRecognizer> localRecognizers =
new List<GestureRecognizer>.from(_recognizers);
_recognizers.clear();
for (GestureRecognizer recognizer in localRecognizers)
recognizer.dispose();
for (GestureRecognizer recognizer in localRecognizers) recognizer.dispose();
}
@override
GestureRecognizer createLink(String href) {
final TapGestureRecognizer recognizer = new TapGestureRecognizer()
..onTap = () {
if (widget.onTapLink != null)
widget.onTapLink(href);
};
if (widget.onTapLink != null) widget.onTapLink(href);
};
_recognizers.add(recognizer);
return recognizer;
}
@ -189,19 +191,17 @@ class MarkdownBody extends MarkdownWidget {
Directory imageDirectory,
ItemDemoBuilder demoBuilder,
}) : super(
key: key,
data: data,
styleSheet: styleSheet,
syntaxHighlighter: syntaxHighlighter,
onTapLink: onTapLink,
imageDirectory: imageDirectory,
demoBuilder: demoBuilder
);
key: key,
data: data,
styleSheet: styleSheet,
syntaxHighlighter: syntaxHighlighter,
onTapLink: onTapLink,
imageDirectory: imageDirectory,
demoBuilder: demoBuilder);
@override
Widget build(BuildContext context, List<Widget> children) {
if (children.length == 1)
return children.single;
if (children.length == 1) return children.single;
return new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
@ -229,13 +229,13 @@ class Markdown extends MarkdownWidget {
Directory imageDirectory,
this.padding: const EdgeInsets.all(16.0),
}) : super(
key: key,
data: data,
styleSheet: styleSheet,
syntaxHighlighter: syntaxHighlighter,
onTapLink: onTapLink,
imageDirectory: imageDirectory,
);
key: key,
data: data,
styleSheet: styleSheet,
syntaxHighlighter: syntaxHighlighter,
onTapLink: onTapLink,
imageDirectory: imageDirectory,
);
/// The amount of space by which to inset the children.
final EdgeInsets padding;

View File

@ -24,7 +24,8 @@ class _FullScreenCodeDialogState extends State<FullScreenCodeDialog> {
void didChangeDependencies() {
print('widget.filePath=======${widget.filePath}');
if (widget.filePath != null) {
getExampleCode(context,'${widget.filePath}', DefaultAssetBundle.of(context))
getExampleCode(
context, '${widget.filePath}', DefaultAssetBundle.of(context))
.then<void>((String code) {
if (mounted) {
setState(() {
@ -48,6 +49,7 @@ class _FullScreenCodeDialogState extends State<FullScreenCodeDialog> {
});
}
}
@override
Widget build(BuildContext context) {
final SyntaxHighlighterStyle style =
@ -60,16 +62,17 @@ class _FullScreenCodeDialogState extends State<FullScreenCodeDialog> {
body = const Center(child: CircularProgressIndicator());
} else {
Widget _codeWidget;
try{
try {
DartSyntaxHighlighter(style).format(_exampleCode);
_codeWidget = RichText(
text: TextSpan(
style: const TextStyle(fontFamily: 'monospace', fontSize: 10.0),
children: <TextSpan>[
DartSyntaxHighlighter(style).format(_exampleCode)
],),
style: const TextStyle(fontFamily: 'monospace', fontSize: 10.0),
children: <TextSpan>[
DartSyntaxHighlighter(style).format(_exampleCode)
],
),
);
}catch (err){
} catch (err) {
_codeWidget = Text(_exampleCode);
}
body = SingleChildScrollView(

View File

@ -8,8 +8,7 @@ class HomeBanner extends StatefulWidget {
final List<StoryModel> bannerStories;
final OnTapBannerItem onTap;
HomeBanner(this.bannerStories, this.onTap, {Key key})
:super(key: key);
HomeBanner(this.bannerStories, this.onTap, {Key key}) : super(key: key);
@override
State<StatefulWidget> createState() {
@ -27,11 +26,11 @@ class _BannerState extends State<HomeBanner> {
void initState() {
super.initState();
controller = PageController(initialPage: realIndex);
timer = Timer.periodic(Duration(seconds: 5), (timer) { // 自动滚动
timer = Timer.periodic(Duration(seconds: 5), (timer) {
// 自动滚动
/// print(realIndex);
controller.animateToPage(realIndex + 1,
duration: Duration(milliseconds: 300),
curve: Curves.linear);
duration: Duration(milliseconds: 300), curve: Curves.linear);
});
}
@ -50,7 +49,10 @@ class _BannerState extends State<HomeBanner> {
margin: EdgeInsets.only(top: 10.0, right: 5.0),
padding: EdgeInsets.symmetric(horizontal: 6.0, vertical: 2.0),
child: Text("${++index}/$itemCount",
style: TextStyle( color: Colors.white70, fontSize: 12.0, fontWeight:FontWeight.bold )),
style: TextStyle(
color: Colors.white70,
fontSize: 12.0,
fontWeight: FontWeight.bold)),
);
}
@ -58,43 +60,45 @@ class _BannerState extends State<HomeBanner> {
Widget build(BuildContext context) {
return Container(
height: 226.0,
child: Stack(
alignment: Alignment.bottomCenter,
children: <Widget>[
PageView(
controller: controller,
onPageChanged: _onPageChanged,
children: _buildItems(),),
_buildIndicator(), // 下面的小点
Positioned(//方法二
top: 0.0,
right: 0.0,
child: _numberIndicator(context,virtualIndex,widget.bannerStories.length),
)
]),
child: Stack(alignment: Alignment.bottomCenter, children: <Widget>[
PageView(
controller: controller,
onPageChanged: _onPageChanged,
children: _buildItems(),
),
_buildIndicator(), // 下面的小点
Positioned(
//方法二
top: 0.0,
right: 0.0,
child: _numberIndicator(
context, virtualIndex, widget.bannerStories.length),
)
]),
);
}
List<Widget> _buildItems() { // 排列轮播数组
List<Widget> _buildItems() {
// 排列轮播数组
List<Widget> items = [];
if (widget.bannerStories.length > 0) {
// 头部添加一个尾部Item模拟循环
items.add(
_buildItem(widget.bannerStories[widget.bannerStories.length - 1]));
// 正常添加Item
items.addAll(
widget.bannerStories.map((story) => _buildItem(story)).toList(
growable: false));
items.addAll(widget.bannerStories
.map((story) => _buildItem(story))
.toList(growable: false));
// 尾部
items.add(
_buildItem(widget.bannerStories[0]));
items.add(_buildItem(widget.bannerStories[0]));
}
return items;
}
Widget _buildItem(StoryModel story) {
return GestureDetector(
onTap: () { // 按下
onTap: () {
// 按下
if (widget.onTap != null) {
widget.onTap(story);
}
@ -102,14 +106,17 @@ class _BannerState extends State<HomeBanner> {
child: Stack(
fit: StackFit.expand,
children: <Widget>[
Image.network(story.image, fit: BoxFit.cover),
Image.network(story.image, fit: BoxFit.cover),
_buildItemTitle(story.title), // 内容文字,大意
],),);
],
),
);
}
Widget _buildItemTitle(String title) {
return Container(
decoration: BoxDecoration( /// 背景的渐变色
decoration: BoxDecoration(
/// 背景的渐变色
gradient: LinearGradient(
begin: Alignment.bottomCenter,
end: const Alignment(0.0, -0.8),
@ -120,7 +127,10 @@ class _BannerState extends State<HomeBanner> {
child: Container(
margin: EdgeInsets.symmetric(vertical: 22.0, horizontal: 16.0),
child: Text(
title, style: TextStyle(color: Colors.white, fontSize: 18.0),),),
title,
style: TextStyle(color: Colors.white, fontSize: 18.0),
),
),
);
}
@ -136,8 +146,7 @@ class _BannerState extends State<HomeBanner> {
color: i == virtualIndex ? Colors.white : Colors.grey)));
}
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: indicators);
mainAxisAlignment: MainAxisAlignment.center, children: indicators);
}
_onPageChanged(int index) {

View File

@ -14,7 +14,8 @@ class ListRefresh extends StatefulWidget {
final requestApi;
final headerView;
const ListRefresh([this.requestApi, this.renderItem, this.headerView]) : super();
const ListRefresh([this.requestApi, this.renderItem, this.headerView])
: super();
@override
State<StatefulWidget> createState() => _ListRefreshState();
@ -91,6 +92,7 @@ class _ListRefreshState extends State<ListRefresh> {
});
}
}
// 下拉加载的事件清空之前list内容取前X个
// 其实就是列表重置
Future<Null> _handleRefresh() async {
@ -158,9 +160,9 @@ class _ListRefreshState extends State<ListRefresh> {
itemCount: items.length + 1,
itemBuilder: (context, index) {
if (index == 0 && index != items.length) {
if(widget.headerView is Function){
if (widget.headerView is Function) {
return widget.headerView();
}else {
} else {
return Container(height: 0);
}
}

View File

@ -8,7 +8,6 @@ import '../routers/application.dart';
import '../routers/routers.dart';
import 'dart:core';
class ListViewItem extends StatelessWidget {
final String itemUrl;
final String itemTitle;
@ -17,7 +16,6 @@ class ListViewItem extends StatelessWidget {
const ListViewItem({Key key, this.itemUrl, this.itemTitle, this.data})
: super(key: key);
@override
Widget build(BuildContext context) {
return Card(
@ -27,7 +25,8 @@ class ListViewItem extends StatelessWidget {
child: ListTile(
onTap: () {
// _launchURL(itemUrl, context);
Application.router.navigateTo(context, '${Routes.webViewPage}?title=${Uri.encodeComponent(itemTitle)}&url=${Uri.encodeComponent(itemUrl)}');
Application.router.navigateTo(context,
'${Routes.webViewPage}?title=${Uri.encodeComponent(itemTitle)}&url=${Uri.encodeComponent(itemUrl)}');
},
title: Padding(
child: Text(

View File

@ -19,11 +19,11 @@ class NetLoadingDialog extends StatefulWidget {
NetLoadingDialog(
{Key key,
this.loadingText = "loading...",
this.outsideDismiss = true,
this.dismissCallback,
this.loading,
this.requestCallBack})
this.loadingText = "loading...",
this.outsideDismiss = true,
this.dismissCallback,
this.loading,
this.requestCallBack})
: super(key: key);
@override

View File

@ -6,21 +6,18 @@ import 'package:flutter_go/utils/high_light_code.dart';
/// 使用方法
/// MarkdownBody(markdown)
final hightlighter = new HighLight();
class HighLight extends md.SyntaxHighlighter {
@override
TextSpan format(String source) {
final SyntaxHighlighterStyle style = SyntaxHighlighterStyle.lightThemeStyle();
final SyntaxHighlighterStyle style =
SyntaxHighlighterStyle.lightThemeStyle();
return TextSpan(
style: const TextStyle(fontSize: 10.0),
children: <TextSpan>[
DartSyntaxHighlighter(style).format(source)
]
);
children: <TextSpan>[DartSyntaxHighlighter(style).format(source)]);
}
}
class MarkdownBody extends StatelessWidget {
final String data;
MarkdownBody(this.data);

View File

@ -20,10 +20,39 @@ class Pagination extends StatelessWidget {
];
final List<dynamic> arr = [
{'image': 'https://img.alicdn.com/tfs/TB1W4hMAwHqK1RjSZJnXXbNLpXa-519-260.jpg', 'type': 0, 'id': 9695909, 'url': 'https://www.zhihu.com/question/294145797/answer/551162834', 'title': '为什么阿里巴巴、腾讯和 Google 之类的企业都在使用 Flutter 开发 App'},
{'image': 'https://img.alicdn.com/tfs/TB1XmFIApzqK1RjSZSgXXcpAVXa-720-338.jpg', 'type': 0, 'id': 9695859, 'url': 'https://zhuanlan.zhihu.com/p/51696594', 'title': 'Flutter 1.0 正式发布: Google 的便携 UI 工具包'},
{'image': 'https://img.alicdn.com/tfs/TB1mClCABLoK1RjSZFuXXXn0XXa-600-362.jpg', 'type': 0, 'id': 96956491409, 'url':'https://zhuanlan.zhihu.com/p/53497167','title': 'Flutter 示范应用现已开源 — 万物起源(The History of Everything)'},
{'image': 'https://img.alicdn.com/tfs/TB1fXxIAAvoK1RjSZFNXXcxMVXa-600-362.jpg', 'type': 0, 'id': 9695816, 'url': 'https://mp.weixin.qq.com/s?__biz=MzAwODY4OTk2Mg==&mid=2652048101&idx=1&sn=20296088e4bd8ca33c5c9991167d9f7d&chksm=808caaa0b7fb23b65c0e5806209f8d86da6732f3a00a70353f3606018339518b0a8656f14dc5&mpsshare=1&scene=2&srcid=0106SZapVysZdIS6Oc5AhNH6&from=timeline&ascene=2&devicetype=android-27&version=27000038&nettype=WIFI&abtest_cookie=BQABAAgACgALABMAFAAFAJ2GHgAjlx4AV5keAJuZHgCcmR4AAAA%3D&lang=zh_CN&pass_ticket=4K1%2FUpsxP4suPj2iubR17wbAP7r9LW9iYrPAC2dppTqv7j7JO5FWMXtcKeBRxueV&wx_header=1', 'title': 'Flutter 与 Material Design 双剑合璧,助您构建精美应用'}
{
'image':
'https://img.alicdn.com/tfs/TB1W4hMAwHqK1RjSZJnXXbNLpXa-519-260.jpg',
'type': 0,
'id': 9695909,
'url': 'https://www.zhihu.com/question/294145797/answer/551162834',
'title': '为什么阿里巴巴、腾讯和 Google 之类的企业都在使用 Flutter 开发 App'
},
{
'image':
'https://img.alicdn.com/tfs/TB1XmFIApzqK1RjSZSgXXcpAVXa-720-338.jpg',
'type': 0,
'id': 9695859,
'url': 'https://zhuanlan.zhihu.com/p/51696594',
'title': 'Flutter 1.0 正式发布: Google 的便携 UI 工具包'
},
{
'image':
'https://img.alicdn.com/tfs/TB1mClCABLoK1RjSZFuXXXn0XXa-600-362.jpg',
'type': 0,
'id': 96956491409,
'url': 'https://zhuanlan.zhihu.com/p/53497167',
'title': 'Flutter 示范应用现已开源 — 万物起源(The History of Everything)'
},
{
'image':
'https://img.alicdn.com/tfs/TB1fXxIAAvoK1RjSZFNXXcxMVXa-600-362.jpg',
'type': 0,
'id': 9695816,
'url':
'https://mp.weixin.qq.com/s?__biz=MzAwODY4OTk2Mg==&mid=2652048101&idx=1&sn=20296088e4bd8ca33c5c9991167d9f7d&chksm=808caaa0b7fb23b65c0e5806209f8d86da6732f3a00a70353f3606018339518b0a8656f14dc5&mpsshare=1&scene=2&srcid=0106SZapVysZdIS6Oc5AhNH6&from=timeline&ascene=2&devicetype=android-27&version=27000038&nettype=WIFI&abtest_cookie=BQABAAgACgALABMAFAAFAJ2GHgAjlx4AV5keAJuZHgCcmR4AAAA%3D&lang=zh_CN&pass_ticket=4K1%2FUpsxP4suPj2iubR17wbAP7r9LW9iYrPAC2dppTqv7j7JO5FWMXtcKeBRxueV&wx_header=1',
'title': 'Flutter 与 Material Design 双剑合璧,助您构建精美应用'
}
];
void _launchURL(String url) async {
@ -37,12 +66,12 @@ class Pagination extends StatelessWidget {
List<Widget> _pageSelector(BuildContext context) {
List<Widget> list = [];
List<StoryModel> bannerStories = [];
/// super.initState();
arr.forEach((item) {
bannerStories.add(StoryModel.fromJson(item));
});
if (arr.length > 0) {
list.add(HomeBanner(bannerStories, (story) {
_launchURL('${story.url}');
@ -53,12 +82,10 @@ class Pagination extends StatelessWidget {
@override
Widget build(BuildContext context) {
return
Column(
key:Key('__header__'),
return Column(
key: Key('__header__'),
//physics: AlwaysScrollableScrollPhysics(),
//padding: EdgeInsets.only(),
children: _pageSelector(context)
);
children: _pageSelector(context));
}
}

View File

@ -13,10 +13,11 @@ class SingleThemeColor extends StatelessWidget {
@override
Widget build(BuildContext context) {
return InkWell(
onTap: (){
if(ApplicationEvent.event != null){
onTap: () {
if (ApplicationEvent.event != null) {
print('fire ${this.themeColor}');
ApplicationEvent.event.fire(UserSettingThemeColorEvent(this.themeColor));
ApplicationEvent.event
.fire(UserSettingThemeColorEvent(this.themeColor));
Navigator.of(context).pop();
}
},

View File

@ -9,6 +9,7 @@ import 'package:flutter_go/utils/data_utils.dart';
import '../routers/application.dart';
import '../routers/routers.dart';
import '../components/markdown.dart';
/// import '../model/collection.dart';
import '../widgets/index.dart';
import '../event/event_bus.dart';
@ -35,6 +36,7 @@ class WidgetDemo extends StatefulWidget {
class _WidgetDemoState extends State<WidgetDemo> {
bool _hasCollected = false;
/// CollectionControlModel _collectionControl = new CollectionControlModel();
var _collectionIcons;
List widgetDemosList = new WidgetDemoList().getDemos();
@ -141,38 +143,36 @@ class _WidgetDemoState extends State<WidgetDemo> {
'${Routes.codeView}?filePath=${Uri.encodeComponent(widget.codeUrl)}');
}
}
List<PopupMenuEntry<String>> buildPopupMenu() {
List<PopupMenuEntry<String>> comps = [];
if (widget.docUrl != null) {
comps.add(
PopupMenuItem<String>(
value: 'doc',
child: ListTile(
leading: Icon(
Icons.library_books,
size: 22.0,
),
title: Text('查看文档'),
),
)
);
comps.add(PopupMenuItem<String>(
value: 'doc',
child: ListTile(
leading: Icon(
Icons.library_books,
size: 22.0,
),
title: Text('查看文档'),
),
));
}
if (widget.codeUrl != null) {
comps.add(
PopupMenuItem<String>(
value: 'code',
child: ListTile(
leading: Icon(
Icons.code,
size: 22.0,
),
title: Text('查看Demo'),
),
)
);
comps.add(PopupMenuItem<String>(
value: 'code',
child: ListTile(
leading: Icon(
Icons.code,
size: 22.0,
),
title: Text('查看Demo'),
),
));
}
return comps;
}
@override
Widget build(BuildContext context) {
if (_hasCollected) {
@ -185,7 +185,7 @@ class _WidgetDemoState extends State<WidgetDemo> {
new IconButton(
tooltip: 'goBack home',
onPressed: () {
Navigator.popUntil(context, ModalRoute.withName(Routes.root));
Navigator.popUntil(context, ModalRoute.withName(Routes.root));
},
icon: Icon(Icons.home),
),
@ -196,12 +196,10 @@ class _WidgetDemoState extends State<WidgetDemo> {
),
];
if (menus.length > 0) {
actions.add(
PopupMenuButton<String>(
onSelected: _selectValue,
itemBuilder: (BuildContext context) => menus,
)
);
actions.add(PopupMenuButton<String>(
onSelected: _selectValue,
itemBuilder: (BuildContext context) => menus,
));
}
return Scaffold(
key: _scaffoldKey,

View File

@ -13,23 +13,21 @@ class WidgetItemContainer extends StatelessWidget {
// 所有的可用demos;
final List widgetDemosList = new WidgetDemoList().getDemos();
WidgetItemContainer(
{Key key,
@required this.commonItems,
@required this.columnCount,
WidgetItemContainer({
Key key,
@required this.commonItems,
@required this.columnCount,
// @required this.isWidgetPoint
})
: super(key: key);
}) : super(key: key);
/// 跳转goup
void tapToGroup(CategoryComponent cate, BuildContext context) {
Application.router
.navigateTo(context, "/category/${cate.token}", transition: TransitionType.inFromRight);
Application.router.navigateTo(context, "/category/${cate.token}",
transition: TransitionType.inFromRight);
}
/// 跳转到老的widget界面
void tapToOldWidget(WidgetLeaf leaf, BuildContext context) {
String targetName = leaf.name;
String targetRouter = '/category/error/404';
widgetDemosList.forEach((item) {
@ -38,13 +36,15 @@ class WidgetItemContainer extends StatelessWidget {
targetRouter = targetRouter.toLowerCase();
}
});
Application.router.navigateTo(context, targetRouter, transition: TransitionType.inFromRight);
Application.router.navigateTo(context, targetRouter,
transition: TransitionType.inFromRight);
}
/// 跳转到新的标准页
void tapToStandardPage(WidgetLeaf leaf, BuildContext context) {
String targetRouter = '/standard-page/${leaf.pageId}';
Application.router.navigateTo(context, targetRouter, transition: TransitionType.inFromRight);
Application.router.navigateTo(context, targetRouter,
transition: TransitionType.inFromRight);
}
List<Widget> _buildColumns(context) {
@ -58,37 +58,37 @@ class WidgetItemContainer extends StatelessWidget {
if (addI < length) {
CommonItem item = commonItems[addI];
_listRows.add(
Expanded(
flex: 1,
child: WidgetItem(
title: item.name,
onTap: () {
String type = item.type;
title: item.name,
onTap: () {
String type = item.type;
if (type == "category") {
return tapToGroup(item as CategoryComponent, context);
}
if (type == "widget") {
WidgetLeaf leaf = item as WidgetLeaf;
if (leaf.display == "standard") {
return tapToStandardPage(leaf, context);
} else {
return tapToOldWidget(leaf, context);
if (type == "category") {
return tapToGroup(item as CategoryComponent, context);
}
}
if (type == "widget") {
WidgetLeaf leaf = item as WidgetLeaf;
Application.router
.navigateTo(context, "/category/error/404", transition: TransitionType.inFromRight);
},
index: addI,
totalCount: length,
rowLength: columnCount,
/// textSize: true ? 'middle' : 'small',
textSize: 'middle'
),
if (leaf.display == "standard") {
return tapToStandardPage(leaf, context);
} else {
return tapToOldWidget(leaf, context);
}
}
Application.router.navigateTo(
context, "/category/error/404",
transition: TransitionType.inFromRight);
},
index: addI,
totalCount: length,
rowLength: columnCount,
/// textSize: true ? 'middle' : 'small',
textSize: 'middle'),
),
);
} else {
@ -116,4 +116,3 @@ class WidgetItemContainer extends StatelessWidget {
);
}
}

View File

@ -1,5 +1,5 @@
import 'package:event_bus/event_bus.dart';
class ApplicationEvent{
class ApplicationEvent {
static EventBus event;
}

View File

@ -1,19 +1,19 @@
class CollectionEvent{
class CollectionEvent {
final String widgetName;
final String router;
final bool isRemove;
// token uid...
CollectionEvent(this.widgetName,this.router,this.isRemove);
CollectionEvent(this.widgetName, this.router, this.isRemove);
}
class UserGithubOAuthEvent{
class UserGithubOAuthEvent {
final String loginName;
final String token;
final bool isSuccess;
UserGithubOAuthEvent(this.loginName,this.token,this.isSuccess);
UserGithubOAuthEvent(this.loginName, this.token, this.isSuccess);
}
class UserSettingThemeColorEvent{
class UserSettingThemeColorEvent {
final int settingThemeColor;
UserSettingThemeColorEvent(this.settingThemeColor);
}

View File

@ -54,14 +54,17 @@ class _MyAppState extends State<MyApp> {
Future _reqsMainPageIsOpen() async {
const reqs = 'https://flutter-go.pub/api/isInfoOpen';
var response;
try{
try {
response = await NetUtils.get(reqs, {});
print('response-$response');
if(response['status'] == 200 && response['success'] ==true && response['data'] is Map && response['data']['isOpen'] == true) {
print('response-$response');
if (response['status'] == 200 &&
response['success'] == true &&
response['data'] is Map &&
response['data']['isOpen'] == true) {
Application.pageIsOpen = true;
print('是否需要展开【业界动态】${Application.pageIsOpen}');
}
}catch(e){
} catch (e) {
print('response-$e');
}
return response;
@ -210,11 +213,11 @@ void main() async {
new SearchHistoryList(sp);
await DataUtils.getWidgetTreeList().then((List json) {
List data = WidgetTree.insertDevPagesToList(json, StandardPages().getLocalList());
List data =
WidgetTree.insertDevPagesToList(json, StandardPages().getLocalList());
Application.widgetTree = WidgetTree.buildWidgetTree(data);
print("Application.widgetTree>>>> ${Application.widgetTree}");
});
db = Provider.db;
runApp(new MyApp());
}

View File

@ -1,10 +1,10 @@
import 'package:sqflite/sqflite.dart';
class BaseModel{
Database db;
final String table = '';
var query;
BaseModel(this.db){
query = db.query;
}
class BaseModel {
Database db;
final String table = '';
var query;
BaseModel(this.db) {
query = db.query;
}
}

View File

@ -18,8 +18,8 @@ class Collection implements CollectionInterface {
Collection({this.name, this.router});
factory Collection.fromJSON(Map json){
return Collection(name: json['name'],router: json['router']);
factory Collection.fromJSON(Map json) {
return Collection(name: json['name'], router: json['router']);
}
Object toMap() {
@ -48,7 +48,7 @@ class CollectionControlModel {
Future<List<Collection>> getAllCollection() async {
List list = await sql.getByCondition();
List<Collection> resultList = [];
list.forEach((item){
list.forEach((item) {
print('collection item =>> $item');
resultList.add(Collection.fromJSON(item));
});
@ -68,11 +68,12 @@ class CollectionControlModel {
}
// 删除
Future deleteByName(String name) async{
return await sql.delete(name,'name');
Future deleteByName(String name) async {
return await sql.delete(name, 'name');
}
// 通过path删除
Future deleteByPath(String path) async{
return await sql.delete(path,'router');
Future deleteByPath(String path) async {
return await sql.delete(path, 'router');
}
}

View File

@ -1,25 +1,20 @@
class ResponseData{
class ResponseData {
int status;
bool success;
String message;
ResponseData(this.status, this.success,this.message);
ResponseData(this.status, this.success, this.message);
ResponseData.fromJson(Map<String, dynamic> json)
: status = json['status'],
success = json['success'],
message=json['message'];
message = json['message'];
Map<String, dynamic> toJson() =>
{
'status': status,
'success': success,
'messsage': message
};
{'status': status, 'success': success, 'messsage': message};
@override
String toString() {
return 'status: $status ,success: $success,message: ${message.toString()}';
}
}

View File

@ -12,7 +12,6 @@ import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_go/utils/shared_preferences.dart';
class SearchHistory {
final String name;
final String targetRouter;

View File

@ -4,20 +4,21 @@ class StoryModel {
final int id;
final String url;
StoryModel(this.id, this.title, {this.image,this.url});
StoryModel(this.id, this.title, {this.image, this.url});
StoryModel.fromJson(Map<String, dynamic> json)
: this(json['id'], json['title'],
image: json['image'] != null ? json['image'] : (json['images'] != null ? json['images'][0] : null),
url: json['url'] != null ? json['url'] : (json['url'] != null ? json['url'][0] : null),
);
: this(
json['id'],
json['title'],
image: json['image'] != null
? json['image']
: (json['images'] != null ? json['images'][0] : null),
url: json['url'] != null
? json['url']
: (json['url'] != null ? json['url'][0] : null),
);
Map<String, dynamic> toJson() {
return {
'id': id,
'title': title,
'image': image,
'url':url
};
return {'id': id, 'title': title, 'image': image, 'url': url};
}
}

View File

@ -14,13 +14,13 @@ class UserInformation {
factory UserInformation.fromJson(Map<String, dynamic> json) {
print('fromJOSN $json ${json['id'].runtimeType}');
String name = json['name'];
int userId ;
if(json['name'] == null){
int userId;
if (json['name'] == null) {
name = json['url_name'];
}
if(json['id'].runtimeType == int){
if (json['id'].runtimeType == int) {
userId = json['id'];
}else{
} else {
userId = int.parse(json['id']);
}
return UserInformation(

View File

@ -18,8 +18,8 @@ class UserInfo implements UserInfoInterface {
UserInfo({this.username, this.password});
factory UserInfo.fromJSON(Map json){
return UserInfo(username: json['username'],password: json['password']);
factory UserInfo.fromJSON(Map json) {
return UserInfo(username: json['username'], password: json['password']);
}
Object toMap() {
@ -39,8 +39,8 @@ class UserInfoControlModel {
// 插入新的缓存
Future insert(UserInfo userInfo) {
var result =
sql.insert({'username': userInfo.username, 'password': userInfo.password});
var result = sql
.insert({'username': userInfo.username, 'password': userInfo.password});
return result;
}
@ -48,7 +48,7 @@ class UserInfoControlModel {
Future<List<UserInfo>> getAllInfo() async {
List list = await sql.getByCondition();
List<UserInfo> resultList = [];
list.forEach((item){
list.forEach((item) {
print(item);
resultList.add(UserInfo.fromJSON(item));
});
@ -56,9 +56,7 @@ class UserInfoControlModel {
}
// 清空表中数据
Future deleteAll() async{
Future deleteAll() async {
return await sql.deleteAll();
}
}

View File

@ -1,14 +1,10 @@
import 'dart:async';
import "package:flutter/material.dart";
import "package:flutter_go/routers/application.dart";
import 'package:flutter_go/utils/sql.dart';
enum treeNode {
CategoryComponent,
WidgetLeaf
}
enum treeNode { CategoryComponent, WidgetLeaf }
//typedef aaa
@ -135,6 +131,7 @@ class WidgetControlModel {
}
return new WidgetPoint.fromJSON(json.first);
}
Future<List<WidgetPoint>> search(String name) async {
List json = await sql.search(conditions: {'name': name});
@ -149,6 +146,7 @@ class WidgetControlModel {
return widgets;
}
}
// 抽象类
abstract class CommonItem<T> {
int id;
@ -179,19 +177,17 @@ class CategoryComponent extends CommonItem {
CommonItem parent;
String token;
List<CommonItem> children = [];
String type = 'category';
CategoryComponent({
@required this.id,
@required this.name,
@required this.parentId,
this.type = 'categoryw',
this.children,
this.parent
});
CategoryComponent(
{@required this.id,
@required this.name,
@required this.parentId,
this.type = 'categoryw',
this.children,
this.parent});
CategoryComponent.fromJson(Map json) {
if (json['id'] != null && json['id'].runtimeType == String) {
this.id = int.parse(json['id']);
@ -206,27 +202,25 @@ class CategoryComponent extends CommonItem {
if (item is CategoryComponent) {
CategoryComponent cate = item;
cate.parent = this;
this.children.add(
cate
);
this.children.add(cate);
}
if (item is WidgetLeaf) {
WidgetLeaf widget = item;
widget.parent = this;
this.children.add(
widget
);
this.children.add(widget);
}
}
@override
CommonItem getChild(String token) {
return children.firstWhere((CommonItem item) => item.token == token, orElse: () => null);
return children.firstWhere((CommonItem item) => item.token == token,
orElse: () => null);
}
@override
CommonItem find(String token, [CommonItem node]) {
CommonItem ret;
if (node !=null) {
if (node != null) {
if (node.token == token) {
return node;
} else {
@ -260,14 +254,13 @@ class WidgetLeaf extends CommonItem {
CommonItem parent;
String type = 'widget';
WidgetLeaf({
@required this.id,
@required this.name,
@required this.display,
this.author,
this.path,
this.pageId
});
WidgetLeaf(
{@required this.id,
@required this.name,
@required this.display,
this.author,
this.path,
this.pageId});
WidgetLeaf.fromJson(Map json) {
if (json['id'] != null && json['id'].runtimeType == String) {
@ -286,25 +279,27 @@ class WidgetLeaf extends CommonItem {
CommonItem getChild(String token) {
return null;
}
@override
addChildren(Object item) {
// TODO: implement addChildren
return null;
}
CommonItem find(String token, [CommonItem node]){
CommonItem find(String token, [CommonItem node]) {
return null;
}
}
class WidgetTree {
// 构建树型结构
static CategoryComponent buildWidgetTree(List json, [parent]){
static CategoryComponent buildWidgetTree(List json, [parent]) {
CategoryComponent current;
if (parent != null) {
current = parent;
} else {
current = CategoryComponent(id: 0, name: 'root', parentId: null, children: []);
current =
CategoryComponent(id: 0, name: 'root', parentId: null, children: []);
}
json.forEach((item) {
// 归属分类级别
@ -357,10 +352,13 @@ class WidgetTree {
});
return list;
}
static CategoryComponent getCommonItemById(List<int> path, CategoryComponent root) {
static CategoryComponent getCommonItemById(
List<int> path, CategoryComponent root) {
print("getCommonItemByPath $path");
print("root $root");
CommonItem childLeaf;
/// int first = path.first;
path = path.sublist(1);
print("path:::: $path");
@ -368,7 +366,6 @@ class WidgetTree {
// childLeaf = root.getChild(path.first);
}
return childLeaf;
}
}

View File

@ -8,8 +8,4 @@
import 'src/index.dart';
var demoWidgets = [
new Demo()
];
var demoWidgets = [new Demo()];

View File

@ -3,7 +3,6 @@ import 'dart:math';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
class Demo extends StatefulWidget {
@override
_State createState() => _State();
@ -27,42 +26,45 @@ class Pulltorefresh extends StatefulWidget {
}
class _PulltorefreshState extends State<Pulltorefresh> {
List<Widget> datas=ListData.getList();
RefreshController _controller=RefreshController(initialRefresh: false);
List<Widget> datas = ListData.getList();
RefreshController _controller = RefreshController(initialRefresh: false);
void _onRefresh() async{
void _onRefresh() async {
await Future.delayed(Duration(milliseconds: 1000));
_controller.refreshCompleted();
}
void _onLoading() async{
void _onLoading() async {
await Future.delayed(Duration(milliseconds: 1500));
ItemModel model=ItemModel(getRandomColor(), Icons.airplanemode_active, "军事新闻", "俄军大秀战略",
"酝酿已久的俄罗斯“中部-2019”战略演习于16日正式启动", 5000);
ItemModel model = ItemModel(getRandomColor(), Icons.airplanemode_active,
"军事新闻", "俄军大秀战略", "酝酿已久的俄罗斯“中部-2019”战略演习于16日正式启动", 5000);
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle, model.subTitle, model.des, model.readCount));
if(mounted)
setState(() {
});
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
this.datas.add(Item(getRandomColor(), model.icon, model.mainTitle,
model.subTitle, model.des, model.readCount));
if (mounted) setState(() {});
_controller.loadComplete();
}
@override
Widget build(BuildContext context) {
Widget _itemBuilder(BuildContext context, int position) {
return Card(child: this.datas[position]);
}
return Scaffold(
appBar: AppBar(
title: Text("Pulltorefresh"),
@ -78,30 +80,29 @@ class _PulltorefreshState extends State<Pulltorefresh> {
onRefresh: _onRefresh,
onLoading: _onLoading,
controller: _controller,
child: ListView.builder(itemBuilder: _itemBuilder,itemCount: this.datas.length),
child: ListView.builder(
itemBuilder: _itemBuilder, itemCount: this.datas.length),
),
);
}
Color getRandomColor(){
List<Color> colors=[Colors.deepOrange,Colors.amber,Colors.cyan,Colors.green,Colors.red,Colors.yellow];
int randomValue=Random().nextInt(colors.length);
if(randomValue==colors.length){
randomValue=colors.length-1;
Color getRandomColor() {
List<Color> colors = [
Colors.deepOrange,
Colors.amber,
Colors.cyan,
Colors.green,
Colors.red,
Colors.yellow
];
int randomValue = Random().nextInt(colors.length);
if (randomValue == colors.length) {
randomValue = colors.length - 1;
}
return colors[randomValue];
}
}
class Item extends StatelessWidget {
Color color;
IconData icon;
@ -129,34 +130,34 @@ class Item extends StatelessWidget {
SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Text(mainTitle,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 18.0))),
Expanded(child: Text(subTitle, style: TextStyle(fontSize: 14.0))),
Expanded(
child: Text(
des,
style: TextStyle(fontSize: 13.0),
overflow: TextOverflow.ellipsis,
)),
Expanded(
child: Text("阅读量:${readCount.toString()}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.redAccent))),
],
))
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: Text(mainTitle,
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 18.0))),
Expanded(child: Text(subTitle, style: TextStyle(fontSize: 14.0))),
Expanded(
child: Text(
des,
style: TextStyle(fontSize: 13.0),
overflow: TextOverflow.ellipsis,
)),
Expanded(
child: Text("阅读量:${readCount.toString()}",
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 14.0,
color: Colors.redAccent))),
],
))
],
),
);
}
}
class ItemModel{
class ItemModel {
Color _color;
IconData _icon;
String _mainTitle;
@ -202,40 +203,44 @@ class ItemModel{
set color(Color value) {
_color = value;
}
}
class ListData{
static List<Widget> getList(){
List<Widget> models=[];
ItemModel model1= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "俄军大秀战略",
"酝酿已久的俄罗斯“中部-2019”战略演习于16日正式启动", 2999);
ItemModel model2= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "俄“中部”演习",
"俄罗斯卫星网报道称,俄罗斯国防部长绍伊古表示,“中央-2019”战略演习是", 4588);
ItemModel model3= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "中国2.7万吨坞登舰",
"据印度新德里电视台16日报道印度海军发现7艘中国军舰在印度洋", 7777);
ItemModel model4= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "针对中国?",
"美国空军着力打造军用5G网络5G+VR飞行员无需上天就能操控战机美军濒海", 8888);
ItemModel model5= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "“凯旋”防空导弹系统",
"俄罗斯卫星通讯社报道俄罗斯北方舰队Russian Northern Fleet新闻处", 9999);
ItemModel model6= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "火箭军还有骑兵连",
"迅速对禁区“敌特分子”活动区域进行侦察定位,战斗小分队", 104754);
ItemModel model7= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "侦察兵跨越冰川",
"在海拔5000多米的雪域高原第77集团军某合成旅的侦察兵们正在进行野外驻训", 47545);
ItemModel model8= ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻", "香港被护商船",
"新京报快讯 据北海舰队官微消息:“感谢海军!”“祖国万岁!”,当地时", 124574);
class ListData {
static List<Widget> getList() {
List<Widget> models = [];
ItemModel model1 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"俄军大秀战略", "酝酿已久的俄罗斯“中部-2019”战略演习于16日正式启动", 2999);
ItemModel model2 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"“中部”演习", "罗斯卫星网报道称,俄罗斯国防部长绍伊古表示,“中央-2019”战略演习是", 4588);
ItemModel model3 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"中国2.7万吨坞登舰", "据印度新德里电视台16日报道印度海军发现7艘中国军舰在印度洋", 7777);
ItemModel model4 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"针对中国?", "美国空军着力打造军用5G网络5G+VR飞行员无需上天就能操控战机美军濒海", 8888);
ItemModel model5 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"“凯旋”防空导弹系统", "俄罗斯卫星通讯社报道俄罗斯北方舰队Russian Northern Fleet新闻处", 9999);
ItemModel model6 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"火箭军还有骑兵连", "迅速对禁区“敌特分子”活动区域进行侦察定位,战斗小分队", 104754);
ItemModel model7 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"侦察兵跨越冰川", "在海拔5000多米的雪域高原第77集团军某合成旅的侦察兵们正在进行野外驻训", 47545);
ItemModel model8 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
"香港被护商船", "新京报快讯 据北海舰队官微消息:“感谢海军!”“祖国万岁!”,当地时", 124574);
models.add(Item(model1.color, model1.icon, model1.mainTitle, model1.subTitle, model1.des, model1.readCount));
models.add(Item(model2.color, model2.icon, model2.mainTitle, model2.subTitle, model2.des, model2.readCount));
models.add(Item(model3.color, model3.icon, model3.mainTitle, model3.subTitle, model3.des, model3.readCount));
models.add(Item(model4.color, model4.icon, model4.mainTitle, model4.subTitle, model4.des, model4.readCount));
models.add(Item(model5.color, model5.icon, model5.mainTitle, model5.subTitle, model5.des, model5.readCount));
models.add(Item(model6.color, model6.icon, model6.mainTitle, model6.subTitle, model6.des, model6.readCount));
models.add(Item(model7.color, model7.icon, model7.mainTitle, model7.subTitle, model7.des, model7.readCount));
models.add(Item(model8.color, model8.icon, model8.mainTitle, model8.subTitle, model8.des, model8.readCount));
models.add(Item(model1.color, model1.icon, model1.mainTitle,
model1.subTitle, model1.des, model1.readCount));
models.add(Item(model2.color, model2.icon, model2.mainTitle,
model2.subTitle, model2.des, model2.readCount));
models.add(Item(model3.color, model3.icon, model3.mainTitle,
model3.subTitle, model3.des, model3.readCount));
models.add(Item(model4.color, model4.icon, model4.mainTitle,
model4.subTitle, model4.des, model4.readCount));
models.add(Item(model5.color, model5.icon, model5.mainTitle,
model5.subTitle, model5.des, model5.readCount));
models.add(Item(model6.color, model6.icon, model6.mainTitle,
model6.subTitle, model6.des, model6.readCount));
models.add(Item(model7.color, model7.icon, model7.mainTitle,
model7.subTitle, model7.des, model7.readCount));
models.add(Item(model8.color, model8.icon, model8.mainTitle,
model8.subTitle, model8.des, model8.readCount));
return models;
}
}

View File

@ -8,8 +8,4 @@
import 'src/index.dart';
var demoWidgets = [
new Demo()
];
var demoWidgets = [new Demo()];

View File

@ -8,8 +8,4 @@
import 'src/index.dart';
var demoWidgets = [
new Demo()
];
var demoWidgets = [new Demo()];

View File

@ -9,8 +9,6 @@ class _State extends State<Demo> {
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(onPressed: () {}, child: Text('我是md中引入的demo'))
);
child: RaisedButton(onPressed: () {}, child: Text('我是md中引入的demo')));
}
}

View File

@ -1,10 +1,20 @@
import 'PullToRefresh_chenfeihu_5553db80_52ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardDemo_PullToRefresh_5553db80_52ae_4241_9c8a_5c9e1f92b096;
import 'RangeSlider_RangeSlider_e5f958bc_52ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardDemo_RangeSlider_e5f958bc_52ae_4241_9c8a_5c9e1f92b096;
import 'demoName_yourName_1a29aa8e_32ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardDemo_demoName_1a29aa8e_32ae_4241_9c8a_5c9e1f92b096;
import 'local_ab_2c1d57d0_42ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardDemo_local_2c1d57d0_42ae_4241_9c8a_5c9e1f92b096;
import 'PullToRefresh_chenfeihu_5553db80_52ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardDemo_PullToRefresh_5553db80_52ae_4241_9c8a_5c9e1f92b096;
import 'RangeSlider_RangeSlider_e5f958bc_52ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardDemo_RangeSlider_e5f958bc_52ae_4241_9c8a_5c9e1f92b096;
import 'demoName_yourName_1a29aa8e_32ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardDemo_demoName_1a29aa8e_32ae_4241_9c8a_5c9e1f92b096;
import 'local_ab_2c1d57d0_42ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardDemo_local_2c1d57d0_42ae_4241_9c8a_5c9e1f92b096;
var demoObjects = {
'5553db80_52ae_4241_9c8a_5c9e1f92b096': StandardDemo_PullToRefresh_5553db80_52ae_4241_9c8a_5c9e1f92b096.demoWidgets,
'e5f958bc_52ae_4241_9c8a_5c9e1f92b096': StandardDemo_RangeSlider_e5f958bc_52ae_4241_9c8a_5c9e1f92b096.demoWidgets,
'1a29aa8e_32ae_4241_9c8a_5c9e1f92b096': StandardDemo_demoName_1a29aa8e_32ae_4241_9c8a_5c9e1f92b096.demoWidgets,
'2c1d57d0_42ae_4241_9c8a_5c9e1f92b096': StandardDemo_local_2c1d57d0_42ae_4241_9c8a_5c9e1f92b096.demoWidgets
'5553db80_52ae_4241_9c8a_5c9e1f92b096':
StandardDemo_PullToRefresh_5553db80_52ae_4241_9c8a_5c9e1f92b096
.demoWidgets,
'e5f958bc_52ae_4241_9c8a_5c9e1f92b096':
StandardDemo_RangeSlider_e5f958bc_52ae_4241_9c8a_5c9e1f92b096.demoWidgets,
'1a29aa8e_32ae_4241_9c8a_5c9e1f92b096':
StandardDemo_demoName_1a29aa8e_32ae_4241_9c8a_5c9e1f92b096.demoWidgets,
'2c1d57d0_42ae_4241_9c8a_5c9e1f92b096':
StandardDemo_local_2c1d57d0_42ae_4241_9c8a_5c9e1f92b096.demoWidgets
};

View File

@ -8,8 +8,4 @@
import 'src/index.dart';
var demoWidgets = [
new Demo()
];
var demoWidgets = [new Demo()];

View File

@ -13,4 +13,3 @@ class _State extends State<Demo> {
);
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,4 +1,3 @@
// Created with Android Studio.
// User: 三帆
// Date: 31/01/2019
@ -7,7 +6,6 @@
// target: xxx
//
//enum DateType {
// Int,
// Double,
@ -27,6 +25,7 @@ class SharedPreferencesKeys {
/// boolean
/// 用于欢迎页面. 只有第一次访问才会显示. 或者手动将这个值设为false
static String showWelcome = 'loginWelcone';
/// json
/// 用于存放搜索页的搜索数据.
/// [{
@ -35,4 +34,3 @@ class SharedPreferencesKeys {
/// }]
static String searchHistory = 'searchHistory';
}

View File

@ -1,165 +1,166 @@
import 'package:flutter/material.dart';
class WidgetName2Icon {
static Map<String,dynamic> icons = {
static Map<String, dynamic> icons = {
"Developer": Icons.developer_mode,
"Standard": Icons.pages ,
"Element":Icons.explicit,
"Components":Icons.extension,
"Theme":Icons.filter_b_and_w,
"Form":Icons.table_chart,
"Frame":Icons.aspect_ratio,
"Media":Icons.subscriptions,
"Input":Icons.input,
"TextField":Icons.text_fields,
"Checkbox":Icons.check_box,
"CheckboxListTile":Icons.playlist_add_check,
"Button":Icons.aspect_ratio,
"FlatButton":Icons.outlined_flag,
"RaisedButton":Icons.picture_in_picture_alt,
"IconButton":Icons.import_contacts,
"PopupMenuButton":Icons.power_input,
"FloatingActionButton":Icons.flash_off,
"RawMaterialButton":Icons.rowing,
"DropdownButton":Icons.drag_handle,
"OutlineButton":Icons.done_outline,
"Text":Icons.text_format,
"RichText":Icons.text_rotation_angleup,
"Radio":Icons.radio_button_checked,
"RadioListTile":Icons.list,
"Slider":Icons.slideshow,
"SliderTheme":Icons.theaters,
"SliderComponentShape":Icons.format_shapes,
"SliderThemeData":Icons.data_usage,
"Switch":Icons.switch_camera,
"SwitchListTile":Icons.switch_video,
"AnimatedSwitcher":Icons.airplanemode_active,
"Align":Icons.format_align_left,
"Stack":Icons.storage,
"IndexedStack":Icons.star,
"Layout":Icons.layers,
"Row":Icons.recent_actors,
"Column":Icons.cloud_off,
"Container":Icons.edit_location,
"Center":Icons.gesture,
"Box":Icons.hdr_strong,
"ConstrainedBox":Icons.account_box,
"OverflowBox":Icons.email,
"DecoratedBox":Icons.settings_overscan,
"FittedBox":Icons.data_usage,
"LimitedBox":Icons.format_align_justify,
"RenderBox":Icons.error,
"RotateBox":Icons.navigate_next,
"SizedOverflowBox":Icons.undo,
"TextBox":Icons.wallpaper,
"UnconstrainedBox":Icons.account_box,
"Axis":Icons.access_alarm,
"MainAxis":Icons.add_circle,
"CrossAxis":Icons.dehaze,
"FlipAxis":Icons.zoom_out,
"Expanded":Icons.all_out,
"Spacing":Icons.crop_free,
"Padding":Icons.crop,
"SliverPadding":Icons.euro_symbol,
"AnimatedPadding":Icons.zoom_out_map,
"Table":Icons.table_chart,
"Image":Icons.image,
"AssetImage":Icons.image_aspect_ratio,
"DecorationImage":Icons.picture_in_picture,
"DecorationImagePainter":Icons.image,
"ExactAssetImage":Icons.assessment,
"FadeInImage":Icons.flip,
"FileImage":Icons.filter,
"NetworkImage":Icons.network_wifi,
"RawImage":Icons.text_rotation_down,
"PaintImage":Icons.format_paint,
"PrecacheImage":Icons.perm_camera_mic,
"MemoryImage":Icons.memory,
"Icon":Icons.event_available,
"ImageIcon":Icons.image,
"IconTheme":Icons.table_chart,
"IconData":Icons.date_range,
"IconThemeData":Icons.insert_comment,
"Canvas":Icons.edit,
"PainterPath":Icons.gesture,
"CircleProgressBarPainter":Icons.av_timer,
"PainterSketch":Icons.touch_app,
"Material":Icons.android,
"MaterialApp":Icons.android,
"MaterialButton":Icons.speaker,
"MaterialGap":Icons.view_week,
"MaterialSlice":Icons.format_list_numbered_rtl ,
"MaterialColor":Icons.color_lens,
"Cupertino":Icons.phone_iphone,
"Scroll":Icons.swap_vertical_circle,
"Tab":Icons.tab,
"Menu":Icons.menu,
"PopupMenuDivider":Icons.remove,
"PopupMenuEntry":Icons.menu,
"CheckedPopupMenuItem":Icons.playlist_add_check,
"DropdownMenuItem":Icons.playlist_play,
"Grid":Icons.grid_on,
"Scaffold":Icons.local_convenience_store,
"Dialog":Icons.add_alert,
"Bar":Icons.border_horizontal,
"Card":Icons.credit_card,
"Panel":Icons.video_label,
"Navigation":Icons.navigation,
"List":Icons.list,
"ScrollView":Icons.move_to_inbox,
"Scrollable":Icons.swap_vertical_circle,
"ScrollbarPainter":Icons.format_paint,
"ScrollMetrics":Icons.camera,
"ScrollPhysics":Icons.control_point_duplicate,
"BoxScrollView":Icons.inbox,
"Chip":Icons.sim_card,
"ChipTheme":Icons.sd_card,
"CustomScrollView":Icons.autorenew,
"NestedScrollView":Icons.panorama_fish_eye,
"ChipThemeData":Icons.sim_card_alert,
"ChoiceChip":Icons.insert_drive_file,
"FilterChip":Icons.note_add,
"InputChip":Icons.restore_page,
"RawChip":Icons.save,
"LinearProgressIndicator":Icons.trending_flat ,
"CircularProgressIndicator":Icons.rotate_left ,
"ExpansionPanel":Icons.view_stream,
"ExpansionPanelList":Icons.view_headline,
"BottomNavigationBar":Icons.call_to_action,
"ListView":Icons.view_list ,
"ListBody":Icons.list ,
"AnimatedList":Icons.format_line_spacing ,
"SliverAppBar":Icons.content_paste,
"AppBar":Icons.card_membership,
"BottomAppBar":Icons.call_to_action,
"BottomNavigationBarItem":Icons.crop_original,
"FlexibleSpaceBar":Icons.aspect_ratio,
"ButtonBar":Icons.branding_watermark,
"SnackBar":Icons.sms_failed,
"Progress":Icons.sync,
"Pick":Icons.event_note,
"DayPicker":Icons.calendar_today,
"MonthPicker":Icons.date_range,
"YearPicker":Icons.event_busy,
"ShowdatePicker":Icons.event,
"MaterialPageRoute":Icons.album,
"MaterialAccentColor":Icons.brush,
"SnackBarAction":Icons.assessment,
"TabBar":Icons.burst_mode,
"AlertDialog":Icons.sms_failed,
"AboutDialog":Icons.sms,
"SimpleDialog":Icons.message,
"ScaffoldState":Icons.local_bar,
"GridTile":Icons.apps,
"MergeableMaterialItem":Icons.view_list,
"CupertinoApp":Icons.face,
"CupertinoButton":Icons.crop_7_5,
"CupertinoColors":Icons.color_lens,
"CupertinoIcons":Icons.insert_emoticon,
"CupertinoNavigationBar":Icons.payment,
"CupertinoPageRoute":Icons.router,
"CupertinoPageScaffold":Icons.pages,
"CupertinoPicker":Icons.add_alarm,
"CupertinoPopupSurface":Icons.center_focus_weak,
"Standard": Icons.pages,
"Element": Icons.explicit,
"Components": Icons.extension,
"Theme": Icons.filter_b_and_w,
"Form": Icons.table_chart,
"Frame": Icons.aspect_ratio,
"Media": Icons.subscriptions,
"Input": Icons.input,
"TextField": Icons.text_fields,
"Checkbox": Icons.check_box,
"CheckboxListTile": Icons.playlist_add_check,
"Button": Icons.aspect_ratio,
"FlatButton": Icons.outlined_flag,
"RaisedButton": Icons.picture_in_picture_alt,
"IconButton": Icons.import_contacts,
"PopupMenuButton": Icons.power_input,
"FloatingActionButton": Icons.flash_off,
"RawMaterialButton": Icons.rowing,
"DropdownButton": Icons.drag_handle,
"OutlineButton": Icons.done_outline,
"Text": Icons.text_format,
"RichText": Icons.text_rotation_angleup,
"Radio": Icons.radio_button_checked,
"RadioListTile": Icons.list,
"Slider": Icons.slideshow,
"SliderTheme": Icons.theaters,
"SliderComponentShape": Icons.format_shapes,
"SliderThemeData": Icons.data_usage,
"Switch": Icons.switch_camera,
"SwitchListTile": Icons.switch_video,
"AnimatedSwitcher": Icons.airplanemode_active,
"Align": Icons.format_align_left,
"Stack": Icons.storage,
"IndexedStack": Icons.star,
"Layout": Icons.layers,
"Row": Icons.recent_actors,
"Column": Icons.cloud_off,
"Container": Icons.edit_location,
"Center": Icons.gesture,
"Box": Icons.hdr_strong,
"ConstrainedBox": Icons.account_box,
"OverflowBox": Icons.email,
"DecoratedBox": Icons.settings_overscan,
"FittedBox": Icons.data_usage,
"LimitedBox": Icons.format_align_justify,
"RenderBox": Icons.error,
"RotateBox": Icons.navigate_next,
"SizedOverflowBox": Icons.undo,
"TextBox": Icons.wallpaper,
"UnconstrainedBox": Icons.account_box,
"Axis": Icons.access_alarm,
"MainAxis": Icons.add_circle,
"CrossAxis": Icons.dehaze,
"FlipAxis": Icons.zoom_out,
"Expanded": Icons.all_out,
"Spacing": Icons.crop_free,
"Padding": Icons.crop,
"SliverPadding": Icons.euro_symbol,
"AnimatedPadding": Icons.zoom_out_map,
"Table": Icons.table_chart,
"Image": Icons.image,
"AssetImage": Icons.image_aspect_ratio,
"DecorationImage": Icons.picture_in_picture,
"DecorationImagePainter": Icons.image,
"ExactAssetImage": Icons.assessment,
"FadeInImage": Icons.flip,
"FileImage": Icons.filter,
"NetworkImage": Icons.network_wifi,
"RawImage": Icons.text_rotation_down,
"PaintImage": Icons.format_paint,
"PrecacheImage": Icons.perm_camera_mic,
"MemoryImage": Icons.memory,
"Icon": Icons.event_available,
"ImageIcon": Icons.image,
"IconTheme": Icons.table_chart,
"IconData": Icons.date_range,
"IconThemeData": Icons.insert_comment,
"Canvas": Icons.edit,
"PainterPath": Icons.gesture,
"CircleProgressBarPainter": Icons.av_timer,
"PainterSketch": Icons.touch_app,
"Material": Icons.android,
"MaterialApp": Icons.android,
"MaterialButton": Icons.speaker,
"MaterialGap": Icons.view_week,
"MaterialSlice": Icons.format_list_numbered_rtl,
"MaterialColor": Icons.color_lens,
"Cupertino": Icons.phone_iphone,
"Scroll": Icons.swap_vertical_circle,
"Tab": Icons.tab,
"Menu": Icons.menu,
"PopupMenuDivider": Icons.remove,
"PopupMenuEntry": Icons.menu,
"CheckedPopupMenuItem": Icons.playlist_add_check,
"DropdownMenuItem": Icons.playlist_play,
"Grid": Icons.grid_on,
"Scaffold": Icons.local_convenience_store,
"Dialog": Icons.add_alert,
"Bar": Icons.border_horizontal,
"Card": Icons.credit_card,
"Panel": Icons.video_label,
"Navigation": Icons.navigation,
"List": Icons.list,
"ScrollView": Icons.move_to_inbox,
"Scrollable": Icons.swap_vertical_circle,
"ScrollbarPainter": Icons.format_paint,
"ScrollMetrics": Icons.camera,
"ScrollPhysics": Icons.control_point_duplicate,
"BoxScrollView": Icons.inbox,
"Chip": Icons.sim_card,
"ChipTheme": Icons.sd_card,
"CustomScrollView": Icons.autorenew,
"NestedScrollView": Icons.panorama_fish_eye,
"ChipThemeData": Icons.sim_card_alert,
"ChoiceChip": Icons.insert_drive_file,
"FilterChip": Icons.note_add,
"InputChip": Icons.restore_page,
"RawChip": Icons.save,
"LinearProgressIndicator": Icons.trending_flat,
"CircularProgressIndicator": Icons.rotate_left,
"ExpansionPanel": Icons.view_stream,
"ExpansionPanelList": Icons.view_headline,
"BottomNavigationBar": Icons.call_to_action,
"ListView": Icons.view_list,
"ListBody": Icons.list,
"AnimatedList": Icons.format_line_spacing,
"SliverAppBar": Icons.content_paste,
"AppBar": Icons.card_membership,
"BottomAppBar": Icons.call_to_action,
"BottomNavigationBarItem": Icons.crop_original,
"FlexibleSpaceBar": Icons.aspect_ratio,
"ButtonBar": Icons.branding_watermark,
"SnackBar": Icons.sms_failed,
"Progress": Icons.sync,
"Pick": Icons.event_note,
"DayPicker": Icons.calendar_today,
"MonthPicker": Icons.date_range,
"YearPicker": Icons.event_busy,
"ShowdatePicker": Icons.event,
"MaterialPageRoute": Icons.album,
"MaterialAccentColor": Icons.brush,
"SnackBarAction": Icons.assessment,
"TabBar": Icons.burst_mode,
"AlertDialog": Icons.sms_failed,
"AboutDialog": Icons.sms,
"SimpleDialog": Icons.message,
"ScaffoldState": Icons.local_bar,
"GridTile": Icons.apps,
"MergeableMaterialItem": Icons.view_list,
"CupertinoApp": Icons.face,
"CupertinoButton": Icons.crop_7_5,
"CupertinoColors": Icons.color_lens,
"CupertinoIcons": Icons.insert_emoticon,
"CupertinoNavigationBar": Icons.payment,
"CupertinoPageRoute": Icons.router,
"CupertinoPageScaffold": Icons.pages,
"CupertinoPicker": Icons.add_alarm,
"CupertinoPopupSurface": Icons.center_focus_weak,
"CupertinoScrollbar": Icons.fullscreen,
"CupertinoSlider": Icons.switch_camera,
"CupertinoSegmentedControl": Icons.business_center,

View File

@ -3,10 +3,12 @@ import 'package:fluro/fluro.dart';
import 'package:flutter_go/utils/shared_preferences.dart';
import '../model/widget.dart';
enum ENV {
PRODUCTION,
DEV,
}
class Application {
/// 通过Application设计环境变量
static ENV env = ENV.DEV;
@ -18,20 +20,20 @@ class Application {
static bool pageIsOpen = false;
static Map<String, String> github = {
'widgetsURL':'https://github.com/alibaba/flutter-go/blob/develop/lib/widgets/',
'widgetsURL':
'https://github.com/alibaba/flutter-go/blob/develop/lib/widgets/',
//'develop':'https://github.com/alibaba-paimai-frontend/flutter-common-widgets-app/tree/develop/lib/widgets/',
//'master':'https://github.com/alibaba-paimai-frontend/flutter-common-widgets-app/tree/master/lib/widgets/'
};
/// 所有获取配置的唯一入口
Map<String, String> get config {
if (Application.env == ENV.PRODUCTION) {
return {};
}
if (Application.env == ENV.DEV) {
return {};
}
if (Application.env == ENV.PRODUCTION) {
return {};
}
if (Application.env == ENV.DEV) {
return {};
}
return {};
}
}

View File

@ -21,18 +21,16 @@ var homeHandler = new Handler(
);
var collectionFullHandler = new Handler(
handlerFunc: (BuildContext context,Map<String,List<String>> params){
bool hasLogined = params['hasLogin']?.first == 'true';
return CollectionFullPage(hasLogined: hasLogined);
}
);
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
bool hasLogined = params['hasLogin']?.first == 'true';
return CollectionFullPage(hasLogined: hasLogined);
});
var collectionHandler = new Handler(
handlerFunc: (BuildContext context,Map<String,List<String>> params){
bool hasLogined = params['hasLogin']?.first == 'true';
return CollectionPage(hasLogined: hasLogined);
}
);
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
bool hasLogined = params['hasLogin']?.first == 'true';
return CollectionPage(hasLogined: hasLogined);
});
var categoryHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
@ -44,29 +42,28 @@ var categoryHandler = new Handler(
var widgetNotFoundHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
return new WidgetNotFound();
});
return new WidgetNotFound();
});
var loginPageHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
return LoginPage();
});
return LoginPage();
});
var fullScreenCodeDialog = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
String path = params['filePath']?.first;
return new FullScreenCodeDialog(
filePath: path,
);
});
String path = params['filePath']?.first;
return new FullScreenCodeDialog(
filePath: path,
);
});
var githubCodeDialog = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
String path = params['remotePath']?.first;
return new FullScreenCodeDialog(
remoteFilePath: path,
);
});
String path = params['remotePath']?.first;
return new FullScreenCodeDialog(
remoteFilePath: path,
);
});
var webViewPageHand = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
@ -75,16 +72,13 @@ var webViewPageHand = new Handler(
return new WebViewPage(url, title);
});
var standardPageHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
String id = params['id']?.first;
return StandardView(id: id);
}
);
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
String id = params['id']?.first;
return StandardView(id: id);
});
var issuesMessageHandler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
return IssuesMessagePage();
});
return IssuesMessagePage();
});

View File

@ -1,9 +1,9 @@
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_go/utils/analytics.dart' show analytics;
import '../widgets/index.dart';
import './router_handler.dart';
/// import '../standard_pages/index.dart';
class Routes {
static String root = "/";
@ -13,7 +13,7 @@ class Routes {
static String githubCodeView = '/github-code-view';
static String webViewPage = '/web-view-page';
static String loginPage = '/loginpage';
static String issuesMessage='/issuesMessage';
static String issuesMessage = '/issuesMessage';
static String collectionPage = '/collection-page';
static String collectionFullPage = '/collection-full-page';
static String standardPage = '/standard-page/:id';
@ -25,24 +25,24 @@ class Routes {
// }
// );
router.define(home, handler: homeHandler);
router.define(collectionPage,handler:collectionHandler);
router.define(collectionFullPage,handler:collectionFullHandler);
router.define(collectionPage, handler: collectionHandler);
router.define(collectionFullPage, handler: collectionFullHandler);
router.define('/category/:ids', handler: categoryHandler);
router.define('/category/error/404', handler: widgetNotFoundHandler);
router.define(loginPage, handler: loginPageHandler);
router.define(codeView,handler:fullScreenCodeDialog);
router.define(githubCodeView,handler:githubCodeDialog);
router.define(webViewPage,handler:webViewPageHand);
router.define(codeView, handler: fullScreenCodeDialog);
router.define(githubCodeView, handler: githubCodeDialog);
router.define(webViewPage, handler: webViewPageHand);
router.define(issuesMessage, handler: issuesMessageHandler);
router.define(standardPage,handler:standardPageHandler);
router.define(standardPage, handler: standardPageHandler);
widgetDemosList.forEach((demo) {
Handler handler = new Handler(
handlerFunc: (BuildContext context, Map<String, List<String>> params) {
print('组件路由params=$params widgetsItem=${demo.routerName}');
analytics.logEvent(
name: 'component', parameters: {'name': demo.routerName });
return demo.buildRouter(context);
});
Handler handler = new Handler(handlerFunc:
(BuildContext context, Map<String, List<String>> params) {
print('组件路由params=$params widgetsItem=${demo.routerName}');
analytics
.logEvent(name: 'component', parameters: {'name': demo.routerName});
return demo.buildRouter(context);
});
String path = demo.routerName;
router.define('${path.toLowerCase()}', handler: handler);
});

View File

@ -83,5 +83,4 @@ PullToRefresh 是一个刷新列表组件借助于pull_to_refresh库实现
""";
}

View File

@ -30,7 +30,4 @@ slider 用来选择连续性的或者非连续性的数据. 默认是在一段
### 实例展示
[demo:e5f958bc_52ae_4241_9c8a_5c9e1f92b096]""";
}

View File

@ -1,45 +1,77 @@
import 'PullToRefresh_chenfeihu_cd9b8b80_52ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardPage_PullToRefresh_cd9b8b80_52ae_4241_9c8a_5c9e1f92b096;
import 'local_hnaxu_5d7178d0_42ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardPage_local_5d7178d0_42ae_4241_9c8a_5c9e1f92b096;
import 'test_abc_84f38e00_42ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardPage_test_84f38e00_42ae_4241_9c8a_5c9e1f92b096;
import 'standard_sanfan_ee4feb8e_32ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardPage_standard_ee4feb8e_32ae_4241_9c8a_5c9e1f92b096;
import 'standard_for_slider_sanfan_8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardPage_standard_for_slider_8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096;
import 'RangeSlider_hanxu_cbffbf7c_52ae_4241_9c8a_5c9e1f92b096/index.dart'
as StandardPage_RangeSlider_cbffbf7c_52ae_4241_9c8a_5c9e1f92b096;
import 'PullToRefresh_chenfeihu_cd9b8b80_52ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardPage_PullToRefresh_cd9b8b80_52ae_4241_9c8a_5c9e1f92b096;
import 'local_hnaxu_5d7178d0_42ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardPage_local_5d7178d0_42ae_4241_9c8a_5c9e1f92b096;
import 'test_abc_84f38e00_42ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardPage_test_84f38e00_42ae_4241_9c8a_5c9e1f92b096;
import 'standard_sanfan_ee4feb8e_32ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardPage_standard_ee4feb8e_32ae_4241_9c8a_5c9e1f92b096;
import 'standard_for_slider_sanfan_8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardPage_standard_for_slider_8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096;
import 'RangeSlider_hanxu_cbffbf7c_52ae_4241_9c8a_5c9e1f92b096/index.dart' as StandardPage_RangeSlider_cbffbf7c_52ae_4241_9c8a_5c9e1f92b096;
class StandardPages {
Map<String, String> standardPages;
Map<String, String> getPages() {
return {
"0": "0" ,
"cd9b8b80_52ae_4241_9c8a_5c9e1f92b096" : StandardPage_PullToRefresh_cd9b8b80_52ae_4241_9c8a_5c9e1f92b096.getMd()
,
"5d7178d0_42ae_4241_9c8a_5c9e1f92b096" : StandardPage_local_5d7178d0_42ae_4241_9c8a_5c9e1f92b096.getMd()
,
"84f38e00_42ae_4241_9c8a_5c9e1f92b096" : StandardPage_test_84f38e00_42ae_4241_9c8a_5c9e1f92b096.getMd()
,
"ee4feb8e_32ae_4241_9c8a_5c9e1f92b096" : StandardPage_standard_ee4feb8e_32ae_4241_9c8a_5c9e1f92b096.getMd()
,
"8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096" : StandardPage_standard_for_slider_8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096.getMd()
,
"cbffbf7c_52ae_4241_9c8a_5c9e1f92b096" : StandardPage_RangeSlider_cbffbf7c_52ae_4241_9c8a_5c9e1f92b096.getMd()
"0": "0",
"cd9b8b80_52ae_4241_9c8a_5c9e1f92b096":
StandardPage_PullToRefresh_cd9b8b80_52ae_4241_9c8a_5c9e1f92b096
.getMd(),
"5d7178d0_42ae_4241_9c8a_5c9e1f92b096":
StandardPage_local_5d7178d0_42ae_4241_9c8a_5c9e1f92b096.getMd(),
"84f38e00_42ae_4241_9c8a_5c9e1f92b096":
StandardPage_test_84f38e00_42ae_4241_9c8a_5c9e1f92b096.getMd(),
"ee4feb8e_32ae_4241_9c8a_5c9e1f92b096":
StandardPage_standard_ee4feb8e_32ae_4241_9c8a_5c9e1f92b096.getMd(),
"8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096":
StandardPage_standard_for_slider_8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096
.getMd(),
"cbffbf7c_52ae_4241_9c8a_5c9e1f92b096":
StandardPage_RangeSlider_cbffbf7c_52ae_4241_9c8a_5c9e1f92b096.getMd()
};
}
List<Map<String, String>> getLocalList() {
return [
{},
{ "id": "cd9b8b80_52ae_4241_9c8a_5c9e1f92b096", "name": "PullToRefresh", "email": "763551832@qq.com", "author": "chenfeihu"}
,
{ "id": "5d7178d0_42ae_4241_9c8a_5c9e1f92b096", "name": "local", "email": "hanxu@qq.com", "author": "hnaxu"}
,
{ "id": "84f38e00_42ae_4241_9c8a_5c9e1f92b096", "name": "test", "email": "adsf.com", "author": "abc"}
,
{ "id": "ee4feb8e_32ae_4241_9c8a_5c9e1f92b096", "name": "standard", "email": "hanxu317@qq.com", "author": "sanfan"}
,
{ "id": "8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096", "name": "standard_for_slider", "email": "hanxu@qq.com", "author": "sanfan"}
,
{ "id": "cbffbf7c_52ae_4241_9c8a_5c9e1f92b096", "name": "RangeSlider", "email": "hanxu317@qq.com", "author": "hanxu"}
{
"id": "cd9b8b80_52ae_4241_9c8a_5c9e1f92b096",
"name": "PullToRefresh",
"email": "763551832@qq.com",
"author": "chenfeihu"
},
{
"id": "5d7178d0_42ae_4241_9c8a_5c9e1f92b096",
"name": "local",
"email": "hanxu@qq.com",
"author": "hnaxu"
},
{
"id": "84f38e00_42ae_4241_9c8a_5c9e1f92b096",
"name": "test",
"email": "adsf.com",
"author": "abc"
},
{
"id": "ee4feb8e_32ae_4241_9c8a_5c9e1f92b096",
"name": "standard",
"email": "hanxu317@qq.com",
"author": "sanfan"
},
{
"id": "8ab2b5c2_42ae_4241_9c8a_5c9e1f92b096",
"name": "standard_for_slider",
"email": "hanxu@qq.com",
"author": "sanfan"
},
{
"id": "cbffbf7c_52ae_4241_9c8a_5c9e1f92b096",
"name": "RangeSlider",
"email": "hanxu317@qq.com",
"author": "hanxu"
}
];
}
}

View File

@ -48,5 +48,4 @@ goCLi createDemo
```
[demo: 1a29aa8e_32ae_4241_9c8a_5c9e1f92b096]
```""";
}

View File

@ -55,7 +55,4 @@ goCLi createDemo
调用效果:
[demo:1a29aa8e_32ae_4241_9c8a_5c9e1f92b096]""";
}

View File

@ -50,7 +50,4 @@ goCLi createDemo
```
[demo: 1a29aa8e_32ae_4241_9c8a_5c9e1f92b096]
```""";
}

View File

@ -48,5 +48,4 @@ goCLi createDemo
```
[demo: 1a29aa8e_32ae_4241_9c8a_5c9e1f92b096]
```""";
}

View File

@ -5,6 +5,7 @@ import 'package:flutter_go/model/collection.dart';
import 'package:flutter_go/model/version.dart';
import 'package:flutter_go/model/widget.dart';
import 'package:package_info/package_info.dart';
/// import 'package:flutter_go/model/responseData.dart';
import './net_utils.dart';
@ -190,7 +191,9 @@ class DataUtils {
"name": json['name'],
"cnName": json['name'],
"routerName": routerName,
"catId": json['parentId'].runtimeType == String ? int.parse(json['parentId']) : json['parentId']
"catId": json['parentId'].runtimeType == String
? int.parse(json['parentId'])
: json['parentId']
};
list.add(WidgetPoint.fromJSON(tempMap));
}

View File

@ -11,7 +11,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_go/routers/application.dart';
Map<String, String> _exampleCode;
String _code;
@ -23,12 +22,14 @@ void _launchURL(String url) async {
}
}
Future<String> getExampleCode(context,String filePath, AssetBundle bundle) async {
if (_exampleCode == null) await _parseExampleCode(context,filePath, bundle);
Future<String> getExampleCode(
context, String filePath, AssetBundle bundle) async {
if (_exampleCode == null) await _parseExampleCode(context, filePath, bundle);
return _code;
}
Future<void> _parseExampleCode(context,String filePath, AssetBundle bundle) async {
Future<void> _parseExampleCode(
context, String filePath, AssetBundle bundle) async {
String code;
try {
code = await bundle.loadString('lib/widgets/$filePath');

View File

@ -9,16 +9,15 @@ import 'package:string_scanner/string_scanner.dart';
/// DartSyntaxHighlighter(style).format(source)
class SyntaxHighlighterStyle {
SyntaxHighlighterStyle({
this.baseStyle,
this.numberStyle,
this.commentStyle,
this.keywordStyle,
this.stringStyle,
this.punctuationStyle,
this.classStyle,
this.constantStyle
});
SyntaxHighlighterStyle(
{this.baseStyle,
this.numberStyle,
this.commentStyle,
this.keywordStyle,
this.stringStyle,
this.punctuationStyle,
this.classStyle,
this.constantStyle});
static SyntaxHighlighterStyle lightThemeStyle() {
return SyntaxHighlighterStyle(
@ -29,8 +28,7 @@ class SyntaxHighlighterStyle {
stringStyle: const TextStyle(color: Color(0xFF43A047)),
punctuationStyle: const TextStyle(color: Color(0xFF000000)),
classStyle: const TextStyle(color: Color(0xFF512DA8)),
constantStyle: const TextStyle(color: Color(0xFF795548))
);
constantStyle: const TextStyle(color: Color(0xFF795548)));
}
static SyntaxHighlighterStyle darkThemeStyle() {
@ -42,8 +40,7 @@ class SyntaxHighlighterStyle {
stringStyle: const TextStyle(color: Color(0xFF009688)),
punctuationStyle: const TextStyle(color: Color(0xFFFFFFFF)),
classStyle: const TextStyle(color: Color(0xFF009688)),
constantStyle: const TextStyle(color: Color(0xFF795548))
);
constantStyle: const TextStyle(color: Color(0xFF795548)));
}
final TextStyle baseStyle;
@ -56,7 +53,8 @@ class SyntaxHighlighterStyle {
final TextStyle constantStyle;
}
abstract class Highlighter { // ignore: one_member_abstracts
abstract class Highlighter {
// ignore: one_member_abstracts
TextSpan format(String src);
}
@ -69,17 +67,66 @@ class DartSyntaxHighlighter extends Highlighter {
SyntaxHighlighterStyle _style;
static const List<String> _keywords = <String>[
'abstract', 'as', 'assert', 'async', 'await', 'break', 'case', 'catch',
'class', 'const', 'continue', 'default', 'deferred', 'do', 'dynamic', 'else',
'enum', 'export', 'external', 'extends', 'factory', 'false', 'final',
'finally', 'for', 'get', 'if', 'implements', 'import', 'in', 'is', 'library',
'new', 'null', 'operator', 'part', 'rethrow', 'return', 'set', 'static',
'super', 'switch', 'sync', 'this', 'throw', 'true', 'try', 'typedef', 'var',
'void', 'while', 'with', 'yield'
'abstract',
'as',
'assert',
'async',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'default',
'deferred',
'do',
'dynamic',
'else',
'enum',
'export',
'external',
'extends',
'factory',
'false',
'final',
'finally',
'for',
'get',
'if',
'implements',
'import',
'in',
'is',
'library',
'new',
'null',
'operator',
'part',
'rethrow',
'return',
'set',
'static',
'super',
'switch',
'sync',
'this',
'throw',
'true',
'try',
'typedef',
'var',
'void',
'while',
'with',
'yield'
];
static const List<String> _builtInTypes = <String>[
'int', 'double', 'num', 'bool'
'int',
'double',
'num',
'bool'
];
String _src;
@ -99,15 +146,18 @@ class DartSyntaxHighlighter extends Highlighter {
for (_HighlightSpan span in _spans) {
if (currentPosition != span.start)
formattedText.add(TextSpan(text: _src.substring(currentPosition, span.start)));
formattedText
.add(TextSpan(text: _src.substring(currentPosition, span.start)));
formattedText.add(TextSpan(style: span.textStyle(_style), text: span.textForSpan(_src)));
formattedText.add(TextSpan(
style: span.textStyle(_style), text: span.textForSpan(_src)));
currentPosition = span.end;
}
if (currentPosition != _src.length)
formattedText.add(TextSpan(text: _src.substring(currentPosition, _src.length)));
formattedText
.add(TextSpan(text: _src.substring(currentPosition, _src.length)));
return TextSpan(style: _style.baseStyle, children: formattedText);
} else {
@ -125,11 +175,8 @@ class DartSyntaxHighlighter extends Highlighter {
// Block comments
if (_scanner.scan(RegExp(r'/\*(.|\n)*\*/'))) {
_spans.add(_HighlightSpan(
_HighlightType.comment,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.comment,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
@ -146,115 +193,81 @@ class DartSyntaxHighlighter extends Highlighter {
endComment = _src.length;
}
_spans.add(_HighlightSpan(
_HighlightType.comment,
startComment,
endComment
));
_spans.add(
_HighlightSpan(_HighlightType.comment, startComment, endComment));
if (eof)
break;
if (eof) break;
continue;
}
// Raw r"String"
if (_scanner.scan(RegExp(r'r".*"'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Raw r'String'
if (_scanner.scan(RegExp(r"r'.*'"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Multiline """String"""
if (_scanner.scan(RegExp(r'"""(?:[^"\\]|\\(.|\n))*"""'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Multiline '''String'''
if (_scanner.scan(RegExp(r"'''(?:[^'\\]|\\(.|\n))*'''"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// "String"
if (_scanner.scan(RegExp(r'"(?:[^"\\]|\\.)*"'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// 'String'
if (_scanner.scan(RegExp(r"'(?:[^'\\]|\\.)*'"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Double
if (_scanner.scan(RegExp(r'\d+\.\d+'))) {
_spans.add(_HighlightSpan(
_HighlightType.number,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.number,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Integer
if (_scanner.scan(RegExp(r'\d+'))) {
_spans.add(_HighlightSpan(
_HighlightType.number,
_scanner.lastMatch.start,
_scanner.lastMatch.end)
);
_spans.add(_HighlightSpan(_HighlightType.number,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Punctuation
if (_scanner.scan(RegExp(r'[\[\]{}().!=<>&\|\?\+\-\*/%\^~;:,]'))) {
_spans.add(_HighlightSpan(
_HighlightType.punctuation,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.punctuation,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Meta data
if (_scanner.scan(RegExp(r'@\w+'))) {
_spans.add(_HighlightSpan(
_HighlightType.keyword,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.keyword,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
@ -263,8 +276,7 @@ class DartSyntaxHighlighter extends Highlighter {
_HighlightType type;
String word = _scanner.lastMatch[0];
if (word.startsWith('_'))
word = word.substring(1);
if (word.startsWith('_')) word = word.substring(1);
if (_keywords.contains(word))
type = _HighlightType.keyword;
@ -272,15 +284,14 @@ class DartSyntaxHighlighter extends Highlighter {
type = _HighlightType.keyword;
else if (_firstLetterIsUpperCase(word))
type = _HighlightType.klass;
else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1)))
else if (word.length >= 2 &&
word.startsWith('k') &&
_firstLetterIsUpperCase(word.substring(1)))
type = _HighlightType.constant;
if (type != null) {
_spans.add(_HighlightSpan(
type,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
type, _scanner.lastMatch.start, _scanner.lastMatch.end));
}
}
@ -298,12 +309,10 @@ class DartSyntaxHighlighter extends Highlighter {
void _simplify() {
for (int i = _spans.length - 2; i >= 0; i -= 1) {
if (_spans[i].type == _spans[i + 1].type && _spans[i].end == _spans[i + 1].start) {
_spans[i] = _HighlightSpan(
_spans[i].type,
_spans[i].start,
_spans[i + 1].end
);
if (_spans[i].type == _spans[i + 1].type &&
_spans[i].end == _spans[i + 1].start) {
_spans[i] =
_HighlightSpan(_spans[i].type, _spans[i].start, _spans[i + 1].end);
_spans.removeAt(i + 1);
}
}

View File

@ -32,9 +32,10 @@ class Provider {
if (db == null) {
return Future.value([]);
}
List tables = await db.rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
List tables = await db
.rawQuery('SELECT name FROM sqlite_master WHERE type = "table"');
List<String> targetList = [];
tables.forEach((item) {
tables.forEach((item) {
targetList.add(item['name']);
});
return targetList;
@ -46,13 +47,12 @@ class Provider {
List<String> tables = await getTables();
for(int i = 0; i < expectTables.length; i++) {
for (int i = 0; i < expectTables.length; i++) {
if (!tables.contains(expectTables[i])) {
return false;
}
}
return true;
return true;
}
//初始化数据库
@ -89,5 +89,4 @@ class Provider {
print("Opening existing database");
}
}
}

View File

@ -1,4 +1,3 @@
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
@ -14,14 +13,13 @@ class SpUtil {
static SharedPreferences _spf;
SpUtil._();
Future _init() async {
_spf = await SharedPreferences.getInstance();
}
static Future<SpUtil> getInstance() async {
static Future<SpUtil> getInstance() async {
if (_instance == null) {
_instance = new SpUtil._();
}
@ -37,6 +35,7 @@ class SpUtil {
}
return false;
}
// 判断是否存在数据
bool hasKey(String key) {
Set keys = getKeys();
@ -107,8 +106,6 @@ class SpUtil {
return _spf.get(key);
}
Future<bool> remove(String key) {
if (_beforeCheck()) return null;
return _spf.remove(key);

View File

@ -1,14 +1,12 @@
import 'package:sqflite/sqflite.dart';
import './provider.dart';
class BaseModel{
class BaseModel {
Database db;
final String table = '';
var query;
BaseModel(this.db){
BaseModel(this.db) {
query = db.query;
}
}
@ -20,18 +18,21 @@ class Sql extends BaseModel {
super(Provider.db);
// sdf
Future<List> get() async{
Future<List> get() async {
return await this.query(tableName);
}
String getTableName () {
String getTableName() {
return tableName;
}
Future<int> delete(String value,String key) async{
return await this.db.delete(tableName,where:'$key = ?',whereArgs:[value]);
Future<int> delete(String value, String key) async {
return await this
.db
.delete(tableName, where: '$key = ?', whereArgs: [value]);
}
Future<int> deleteAll() async{
Future<int> deleteAll() async {
return await this.db.delete(tableName);
}
@ -44,7 +45,7 @@ class Sql extends BaseModel {
int index = 0;
conditions.forEach((key, value) {
if (value == null) {
return ;
return;
}
if (value.runtimeType == String) {
stringConditions = '$stringConditions $key = "$value"';
@ -53,7 +54,7 @@ class Sql extends BaseModel {
stringConditions = '$stringConditions $key = $value';
}
if (index >= 0 && index < conditions.length -1) {
if (index >= 0 && index < conditions.length - 1) {
stringConditions = '$stringConditions and';
}
index++;
@ -61,18 +62,21 @@ class Sql extends BaseModel {
// print("this is string condition for sql > $stringConditions");
return await this.query(tableName, where: stringConditions);
}
Future<Map<String, dynamic>> insert(Map<String, dynamic> json) async {
var id = await this.db.insert(tableName, json);
json['id'] = id;
return json;
}
///
/// 搜索
/// @param Object condition
/// @mods [And, Or] default is Or
/// search({'name': "hanxu', 'id': 1};
///
Future<List> search({Map<String, dynamic> conditions, String mods = 'Or'}) async {
Future<List> search(
{Map<String, dynamic> conditions, String mods = 'Or'}) async {
if (conditions == null || conditions.isEmpty) {
return this.get();
}
@ -80,7 +84,7 @@ class Sql extends BaseModel {
int index = 0;
conditions.forEach((key, value) {
if (value == null) {
return ;
return;
}
if (value.runtimeType == String) {
@ -90,7 +94,7 @@ class Sql extends BaseModel {
stringConditions = '$stringConditions $key = "%$value%"';
}
if (index >= 0 && index < conditions.length -1) {
if (index >= 0 && index < conditions.length - 1) {
stringConditions = '$stringConditions $mods';
}
index++;

View File

@ -1,14 +1,14 @@
import 'package:flutter/material.dart';
//颜色配置
class AppColor{
class AppColor {
static const int white = 0xFFFFFFFF;
static const int mainTextColor = 0xFF121917;
static const int subTextColor = 0xff959595;
}
//文本设置
class AppText{
class AppText {
static const middleSize = 16.0;
static const middleText = TextStyle(
@ -21,9 +21,9 @@ class AppText{
fontSize: middleSize,
);
}
class WidgetDemoColor {
static const int fontColor = 0xFF607173;
static const int iconColor = 0xFF607173;
static const int borderColor = 0xFFEFEFEF;
}

View File

@ -7,41 +7,38 @@ import 'package:flutter/material.dart';
import 'package:string_scanner/string_scanner.dart';
class SyntaxHighlighterStyle {
SyntaxHighlighterStyle({
this.baseStyle,
this.numberStyle,
this.commentStyle,
this.keywordStyle,
this.stringStyle,
this.punctuationStyle,
this.classStyle,
this.constantStyle
});
SyntaxHighlighterStyle(
{this.baseStyle,
this.numberStyle,
this.commentStyle,
this.keywordStyle,
this.stringStyle,
this.punctuationStyle,
this.classStyle,
this.constantStyle});
static SyntaxHighlighterStyle lightThemeStyle() {
return SyntaxHighlighterStyle(
baseStyle: const TextStyle(color: Color(0xFF000000)),
numberStyle: const TextStyle(color: Color(0xFF1565C0)),
commentStyle: const TextStyle(color: Color(0xFF9E9E9E)),
keywordStyle: const TextStyle(color: Color(0xFF9C27B0)),
stringStyle: const TextStyle(color: Color(0xFF43A047)),
punctuationStyle: const TextStyle(color: Color(0xFF000000)),
classStyle: const TextStyle(color: Color(0xFF512DA8)),
constantStyle: const TextStyle(color: Color(0xFF795548))
);
baseStyle: const TextStyle(color: Color(0xFF000000)),
numberStyle: const TextStyle(color: Color(0xFF1565C0)),
commentStyle: const TextStyle(color: Color(0xFF9E9E9E)),
keywordStyle: const TextStyle(color: Color(0xFF9C27B0)),
stringStyle: const TextStyle(color: Color(0xFF43A047)),
punctuationStyle: const TextStyle(color: Color(0xFF000000)),
classStyle: const TextStyle(color: Color(0xFF512DA8)),
constantStyle: const TextStyle(color: Color(0xFF795548)));
}
static SyntaxHighlighterStyle darkThemeStyle() {
return SyntaxHighlighterStyle(
baseStyle: const TextStyle(color: Color(0xFFFFFFFF)),
numberStyle: const TextStyle(color: Color(0xFF1565C0)),
commentStyle: const TextStyle(color: Color(0xFF9E9E9E)),
keywordStyle: const TextStyle(color: Color(0xFF80CBC4)),
stringStyle: const TextStyle(color: Color(0xFF009688)),
punctuationStyle: const TextStyle(color: Color(0xFFFFFFFF)),
classStyle: const TextStyle(color: Color(0xFF009688)),
constantStyle: const TextStyle(color: Color(0xFF795548))
);
baseStyle: const TextStyle(color: Color(0xFFFFFFFF)),
numberStyle: const TextStyle(color: Color(0xFF1565C0)),
commentStyle: const TextStyle(color: Color(0xFF9E9E9E)),
keywordStyle: const TextStyle(color: Color(0xFF80CBC4)),
stringStyle: const TextStyle(color: Color(0xFF009688)),
punctuationStyle: const TextStyle(color: Color(0xFFFFFFFF)),
classStyle: const TextStyle(color: Color(0xFF009688)),
constantStyle: const TextStyle(color: Color(0xFF795548)));
}
final TextStyle baseStyle;
@ -54,7 +51,8 @@ class SyntaxHighlighterStyle {
final TextStyle constantStyle;
}
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
abstract class SyntaxHighlighter {
// ignore: one_member_abstracts
TextSpan format(String src);
}
@ -67,17 +65,66 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
SyntaxHighlighterStyle _style;
static const List<String> _keywords = <String>[
'abstract', 'as', 'assert', 'async', 'await', 'break', 'case', 'catch',
'class', 'const', 'continue', 'default', 'deferred', 'do', 'dynamic', 'else',
'enum', 'export', 'external', 'extends', 'factory', 'false', 'final',
'finally', 'for', 'get', 'if', 'implements', 'import', 'in', 'is', 'library',
'new', 'null', 'operator', 'part', 'rethrow', 'return', 'set', 'static',
'super', 'switch', 'sync', 'this', 'throw', 'true', 'try', 'typedef', 'var',
'void', 'while', 'with', 'yield'
'abstract',
'as',
'assert',
'async',
'await',
'break',
'case',
'catch',
'class',
'const',
'continue',
'default',
'deferred',
'do',
'dynamic',
'else',
'enum',
'export',
'external',
'extends',
'factory',
'false',
'final',
'finally',
'for',
'get',
'if',
'implements',
'import',
'in',
'is',
'library',
'new',
'null',
'operator',
'part',
'rethrow',
'return',
'set',
'static',
'super',
'switch',
'sync',
'this',
'throw',
'true',
'try',
'typedef',
'var',
'void',
'while',
'with',
'yield'
];
static const List<String> _builtInTypes = <String>[
'int', 'double', 'num', 'bool'
'int',
'double',
'num',
'bool'
];
String _src;
@ -97,15 +144,18 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
for (_HighlightSpan span in _spans) {
if (currentPosition != span.start)
formattedText.add(TextSpan(text: _src.substring(currentPosition, span.start)));
formattedText
.add(TextSpan(text: _src.substring(currentPosition, span.start)));
formattedText.add(TextSpan(style: span.textStyle(_style), text: span.textForSpan(_src)));
formattedText.add(TextSpan(
style: span.textStyle(_style), text: span.textForSpan(_src)));
currentPosition = span.end;
}
if (currentPosition != _src.length)
formattedText.add(TextSpan(text: _src.substring(currentPosition, _src.length)));
formattedText
.add(TextSpan(text: _src.substring(currentPosition, _src.length)));
return TextSpan(style: _style.baseStyle, children: formattedText);
} else {
@ -123,11 +173,8 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
// Block comments
if (_scanner.scan(RegExp(r'/\*(.|\n)*\*/'))) {
_spans.add(_HighlightSpan(
_HighlightType.comment,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.comment,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
@ -144,115 +191,81 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
endComment = _src.length;
}
_spans.add(_HighlightSpan(
_HighlightType.comment,
startComment,
endComment
));
_spans.add(
_HighlightSpan(_HighlightType.comment, startComment, endComment));
if (eof)
break;
if (eof) break;
continue;
}
// Raw r"String"
if (_scanner.scan(RegExp(r'r".*"'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Raw r'String'
if (_scanner.scan(RegExp(r"r'.*'"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Multiline """String"""
if (_scanner.scan(RegExp(r'"""(?:[^"\\]|\\(.|\n))*"""'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Multiline '''String'''
if (_scanner.scan(RegExp(r"'''(?:[^'\\]|\\(.|\n))*'''"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// "String"
if (_scanner.scan(RegExp(r'"(?:[^"\\]|\\.)*"'))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// 'String'
if (_scanner.scan(RegExp(r"'(?:[^'\\]|\\.)*'"))) {
_spans.add(_HighlightSpan(
_HighlightType.string,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.string,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Double
if (_scanner.scan(RegExp(r'\d+\.\d+'))) {
_spans.add(_HighlightSpan(
_HighlightType.number,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.number,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Integer
if (_scanner.scan(RegExp(r'\d+'))) {
_spans.add(_HighlightSpan(
_HighlightType.number,
_scanner.lastMatch.start,
_scanner.lastMatch.end)
);
_spans.add(_HighlightSpan(_HighlightType.number,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Punctuation
if (_scanner.scan(RegExp(r'[\[\]{}().!=<>&\|\?\+\-\*/%\^~;:,]'))) {
_spans.add(_HighlightSpan(
_HighlightType.punctuation,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.punctuation,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
// Meta data
if (_scanner.scan(RegExp(r'@\w+'))) {
_spans.add(_HighlightSpan(
_HighlightType.keyword,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
_spans.add(_HighlightSpan(_HighlightType.keyword,
_scanner.lastMatch.start, _scanner.lastMatch.end));
continue;
}
@ -261,8 +274,7 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
_HighlightType type;
String word = _scanner.lastMatch[0];
if (word.startsWith('_'))
word = word.substring(1);
if (word.startsWith('_')) word = word.substring(1);
if (_keywords.contains(word))
type = _HighlightType.keyword;
@ -270,15 +282,14 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
type = _HighlightType.keyword;
else if (_firstLetterIsUpperCase(word))
type = _HighlightType.klass;
else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1)))
else if (word.length >= 2 &&
word.startsWith('k') &&
_firstLetterIsUpperCase(word.substring(1)))
type = _HighlightType.constant;
if (type != null) {
_spans.add(_HighlightSpan(
type,
_scanner.lastMatch.start,
_scanner.lastMatch.end
));
type, _scanner.lastMatch.start, _scanner.lastMatch.end));
}
}
@ -296,12 +307,10 @@ class DartSyntaxHighlighter extends SyntaxHighlighter {
void _simplify() {
for (int i = _spans.length - 2; i >= 0; i -= 1) {
if (_spans[i].type == _spans[i + 1].type && _spans[i].end == _spans[i + 1].start) {
_spans[i] = _HighlightSpan(
_spans[i].type,
_spans[i].start,
_spans[i + 1].end
);
if (_spans[i].type == _spans[i + 1].type &&
_spans[i].end == _spans[i + 1].start) {
_spans[i] =
_HighlightSpan(_spans[i].type, _spans[i].start, _spans[i + 1].end);
_spans.removeAt(i + 1);
}
}

View File

@ -58,7 +58,6 @@ class _CollectionFullPageState extends State<CollectionFullPage> {
}
Widget _renderList(context, index) {
if (index == 0) {
return Container(
height: 40.0,
@ -115,8 +114,7 @@ class _CollectionFullPageState extends State<CollectionFullPage> {
trailing:
Icon(Icons.keyboard_arrow_right, color: Colors.grey, size: 30.0),
onTap: () {
Application.router.navigateTo(
context, targetRouter.toLowerCase(),
Application.router.navigateTo(context, targetRouter.toLowerCase(),
transition: TransitionType.inFromRight);
},
),

View File

@ -11,6 +11,7 @@ import 'package:flutter_go/routers/application.dart';
import 'package:flutter_go/routers/routers.dart';
import 'package:flutter_go/event/event_bus.dart';
import 'package:flutter_go/event/event_model.dart';
/// import 'package:flutter_go/utils/data_utils.dart';
class CollectionPage extends StatefulWidget {
@ -26,6 +27,7 @@ class _CollectionPageState extends State<CollectionPage> {
final eventBus = new EventBus();
ApplicationEvent.event = eventBus;
}
/// CollectionControlModel _collectionControl = new CollectionControlModel();
List<Collection> _collectionList = [];
ScrollController _scrollController = new ScrollController();

View File

@ -209,7 +209,6 @@ class _DrawerPageState extends State<DrawerPage> {
} else {
//No description provided.
Application.router.navigateTo(context, '${Routes.loginPage}');
}
},
),

View File

@ -17,7 +17,8 @@ class FirstPage extends StatefulWidget {
FirstPageState createState() => new FirstPageState();
}
class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin{
class FirstPageState extends State<FirstPage>
with AutomaticKeepAliveClientMixin {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<bool> _unKnow;
GlobalKey<DisclaimerMsgState> key;
@ -25,7 +26,6 @@ class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin
@override
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
@ -39,8 +39,10 @@ class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin
/// 判断是否需要弹出免责声明,已经勾选过不在显示,就不会主动弹
_unKnow.then((bool value) {
new Future.delayed(const Duration(seconds: 1),(){
if (!value && key.currentState is DisclaimerMsgState && key.currentState.showAlertDialog is Function) {
new Future.delayed(const Duration(seconds: 1), () {
if (!value &&
key.currentState is DisclaimerMsgState &&
key.currentState.showAlertDialog is Function) {
key.currentState.showAlertDialog(context);
}
});
@ -48,26 +50,24 @@ class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin
}
}
Future<Map> getIndexListData([Map<String, dynamic> params]) async {
/// const juejin_flutter = 'https://timeline-merger-ms.juejin.im/v1/get_tag_entry?src=web&tagId=5a96291f6fb9a0535b535438';
const juejin_flutter = 'https://fluttergo.pub:9527/juejin.im/v1/get_tag_entry?src=web&tagId=5a96291f6fb9a0535b535438';
const juejin_flutter =
'https://fluttergo.pub:9527/juejin.im/v1/get_tag_entry?src=web&tagId=5a96291f6fb9a0535b535438';
var pageIndex = (params is Map) ? params['pageIndex'] : 0;
final _param = {'page':pageIndex,'pageSize':20,'sort':'rankIndex'};
final _param = {'page': pageIndex, 'pageSize': 20, 'sort': 'rankIndex'};
var responseList = [];
var pageTotal = 0;
var pageTotal = 0;
try{
try {
var response = await NetUtils.get(juejin_flutter, _param);
responseList = response['d']['entrylist'];
pageTotal = response['d']['total'];
if (!(pageTotal is int) || pageTotal <= 0) {
pageTotal = 0;
}
}catch(e){
}
} catch (e) {}
pageIndex += 1;
List resultList = new List();
for (int i = 0; i < responseList.length; i++) {
@ -78,44 +78,50 @@ class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin
// No specified type, handles all
}
}
Map<String, dynamic> result = {"list":resultList, 'total':pageTotal, 'pageIndex':pageIndex};
Map<String, dynamic> result = {
"list": resultList,
'total': pageTotal,
'pageIndex': pageIndex
};
return result;
}
/// 每个item的样式
Widget makeCard(index,item){
Widget makeCard(index, item) {
var myTitle = '${item.title}';
var myUsername = '${'👲'}: ${item.username} ';
var codeUrl = '${item.detailUrl}';
return new ListViewItem(itemUrl:codeUrl,itemTitle: myTitle,data: myUsername,);
return new ListViewItem(
itemUrl: codeUrl,
itemTitle: myTitle,
data: myUsername,
);
}
headerView(){
return
Column(
children: <Widget>[
Stack(
headerView() {
return Column(
children: <Widget>[
Stack(
//alignment: const FractionalOffset(0.9, 0.1),//方法一
children: <Widget>[
Pagination(),
Positioned(//方法二
top: 10.0,
left: 0.0,
child: DisclaimerMsg(key:key,pWidget:this)
),
]),
SizedBox(height: 1, child:Container(color: Theme.of(context).primaryColor)),
SizedBox(height: 10),
],
);
children: <Widget>[
Pagination(),
Positioned(
//方法二
top: 10.0,
left: 0.0,
child: DisclaimerMsg(key: key, pWidget: this)),
]),
SizedBox(
height: 1, child: Container(color: Theme.of(context).primaryColor)),
SizedBox(height: 10),
],
);
}
@override
Widget build(BuildContext context) {
super.build(context);
return new Column(
children: <Widget>[
return new Column(children: <Widget>[
// new Stack(
// //alignment: const FractionalOffset(0.9, 0.1),//方法一
// children: <Widget>[
@ -127,14 +133,9 @@ class FirstPageState extends State<FirstPage> with AutomaticKeepAliveClientMixin
// ),
// ]),
// SizedBox(height: 2, child:Container(color: Theme.of(context).primaryColor)),
new Expanded(
//child: new List(),
child: listComp.ListRefresh(getIndexListData,makeCard,headerView)
)
]
);
new Expanded(
//child: new List(),
child: listComp.ListRefresh(getIndexListData, makeCard, headerView))
]);
}
}

View File

@ -20,18 +20,18 @@ class FirstPageItem {
FirstPageItem(
{this.hot,
this.tag,
this.username,
this.collectionCount,
this.createdTime,
this.commentCount,
this.title,
this.detailUrl,
this.isCollection});
this.tag,
this.username,
this.collectionCount,
this.createdTime,
this.commentCount,
this.title,
this.detailUrl,
this.isCollection});
factory FirstPageItem.fromJson(Map<String, dynamic> json) {
String _tag = '';
if(json['tags'].length>0){
if (json['tags'].length > 0) {
_tag = '${json['tags'][0]['title']}/';
}
return FirstPageItem(
@ -43,7 +43,7 @@ class FirstPageItem {
createdTime: Util.getTimeDuration(json['createdAt']),
title: json['title'],
detailUrl: json['originalUrl'],
isCollection: json['type'] ,
isCollection: json['type'],
);
}
}

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_go/views/first_page/drawer_page.dart';
import './first_page.dart';
/// import './sub_page.dart';
import './main_app_bar.dart';
import './search_page.dart';
@ -16,13 +17,14 @@ class _Page {
final String labelId;
final int labelIndex;
_Page(this.labelId,this.labelIndex);
_Page(this.labelId, this.labelIndex);
}
final List<_Page> _allPages = <_Page>[
_Page('热门资讯', 1),
_Page('FG-官网', 2),
_Page('FG-web版', 3),
///_Page('项目4'),
];
@ -36,11 +38,13 @@ class MainPage extends StatelessWidget {
_tabController = DefaultTabController(
length: _allPages.length,
child: Scaffold(
appBar: MyAppBar(
appBar: MyAppBar(
leading: Container(
child: ClipOval(
child: ClipOval(
child: Image.network(
userInfo.id == 0?'https://hbimg.huabanimg.com/9bfa0fad3b1284d652d370fa0a8155e1222c62c0bf9d-YjG0Vt_fw658':userInfo.avatarPic,
userInfo.id == 0
? 'https://hbimg.huabanimg.com/9bfa0fad3b1284d652d370fa0a8155e1222c62c0bf9d-YjG0Vt_fw658'
: userInfo.avatarPic,
scale: 15.0,
),
)),
@ -48,16 +52,14 @@ class MainPage extends StatelessWidget {
title: TabLayout(),
actions: <Widget>[
IconButton(
icon: Icon(Icons.search),
icon: Icon(Icons.search),
onPressed: () {
pushPage(context, SearchPage(), pageName: "SearchPage");
})
],
),
drawer: Drawer(
child: DrawerPage(
userInfo: userInfo
),
child: DrawerPage(userInfo: userInfo),
),
body: TabBarViewLayout(),
));
@ -74,26 +76,26 @@ class TabLayout extends StatelessWidget {
@override
Widget build(BuildContext context) {
_tabBar = TabBar(
isScrollable: true,
//labelPadding: EdgeInsets.all(12.0),
labelPadding: EdgeInsets.only(top: 12.0, left: 12.0, right: 12.0),
indicatorSize: TabBarIndicatorSize.label,
tabs: _allPages.map((_Page page) => Tab(text: page.labelId)).toList(),
onTap: (index) {
if (index == 1) {
DefaultTabController.of(context).animateTo(0);
Application.router.navigateTo(context, '${Routes.webViewPage}?title=${Uri.encodeComponent('Flutter Go 官方网站')}&url=${Uri.encodeComponent('https://flutter-go.pub')}');
} else if (index == 2) {
isScrollable: true,
//labelPadding: EdgeInsets.all(12.0),
labelPadding: EdgeInsets.only(top: 12.0, left: 12.0, right: 12.0),
indicatorSize: TabBarIndicatorSize.label,
tabs: _allPages.map((_Page page) => Tab(text: page.labelId)).toList(),
onTap: (index) {
if (index == 1) {
DefaultTabController.of(context).animateTo(0);
Application.router.navigateTo(context,
'${Routes.webViewPage}?title=${Uri.encodeComponent('Flutter Go 官方网站')}&url=${Uri.encodeComponent('https://flutter-go.pub')}');
} else if (index == 2) {
// new Future.delayed(const Duration(seconds: 1),(){
// showAlertDialog(Application.globalContext);
// });
DefaultTabController.of(context).animateTo(0);
Application.router.navigateTo(context, '${Routes.webViewPage}?title=${Uri.encodeComponent('Flutter Go web版(H5)')}&url=${Uri.encodeComponent('https://flutter-go.pub/flutter_go_web')}');
}
}
);
DefaultTabController.of(context).animateTo(0);
Application.router.navigateTo(context,
'${Routes.webViewPage}?title=${Uri.encodeComponent('Flutter Go web版(H5)')}&url=${Uri.encodeComponent('https://flutter-go.pub/flutter_go_web')}');
}
});
return _tabBar;
}
}
@ -116,7 +118,7 @@ class TabBarViewLayout extends StatelessWidget {
print("TabBarViewLayout build.......");
return TabBarView(
children: _allPages.map((_Page page) {
return buildTabView(context, page);
}).toList());
return buildTabView(context, page);
}).toList());
}
}

View File

@ -8,7 +8,7 @@ import 'package:flutter_go/blocs/industry_event.dart';
import 'package:flutter_go/routers/application.dart';
import 'package:flutter_go/routers/routers.dart';
final _industryPage = Industry.IndustryPage(itemTitle: (state){
final _industryPage = Industry.IndustryPage(itemTitle: (state) {
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return ListTile(
@ -27,7 +27,8 @@ final _industryPage = Industry.IndustryPage(itemTitle: (state){
print(state.res[index].source);
final itemTitle = state.res[index].title;
final itemUrl = state.res[index].source;
Application.router.navigateTo(context, '${Routes.webViewPage}?title=${Uri.encodeComponent(itemTitle)}&url=${Uri.encodeComponent(itemUrl)}');
Application.router.navigateTo(context,
'${Routes.webViewPage}?title=${Uri.encodeComponent(itemTitle)}&url=${Uri.encodeComponent(itemUrl)}');
},
);
},
@ -44,9 +45,8 @@ class SearchPage extends StatelessWidget {
/// print('suggestion::${Industry.suggestion}');
return Scaffold(
appBar: PreferredSize(
preferredSize: Size(double.infinity, 52), // is the height
child: AppBar(title: searchBarPage)
),
preferredSize: Size(double.infinity, 52), // is the height
child: AppBar(title: searchBarPage)),
//body: ProgressView(),
body: _industryPage,
floatingActionButton: FloatingActionButton(
@ -54,7 +54,9 @@ class SearchPage extends StatelessWidget {
onPressed: () {
//print('searchBarPage=====>${controller.text}');
//print('searchBarPage=====>${that.getResultsDebounced}');
if(that is _SearchBarPageState && that.getResultsDebounced is Function && controller.text is String ) {
if (that is _SearchBarPageState &&
that.getResultsDebounced is Function &&
controller.text is String) {
that.getResultsDebounced(controller.text);
}
},
@ -67,11 +69,11 @@ class SearchPage extends StatelessWidget {
class ProgressView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: SizedBox(
return Center(
child: SizedBox(
width: 24.0,
height: 24.0,
child: CircularProgressIndicator(
child: CircularProgressIndicator(
strokeWidth: 2.0,
),
),
@ -79,15 +81,15 @@ class ProgressView extends StatelessWidget {
}
}
class SearchBarPage extends StatefulWidget{
class SearchBarPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => _SearchBarPageState();
State<StatefulWidget> createState() => _SearchBarPageState();
}
final TextEditingController controller = TextEditingController();
var that;
var loading;
class _SearchBarPageState extends State<SearchBarPage> {
@override
void initState() {
@ -99,9 +101,10 @@ class _SearchBarPageState extends State<SearchBarPage> {
Timer _resultsTimer;
String oldKey;
/// 防抖函数
Future getResultsDebounced(String text) async {
if(oldKey == text){
if (oldKey == text) {
print('请求内容重复');
return;
}
@ -114,15 +117,14 @@ class _SearchBarPageState extends State<SearchBarPage> {
}
_resultsTimer = new Timer(new Duration(milliseconds: 400), () async {
loading = true;
if(mounted){
if (mounted) {
suggestion.dispatch(SuggestionFetch(query: text));
}
oldKey = text;
});
}
void onSearchTextChanged(String text){
void onSearchTextChanged(String text) {
print('onSearchTextChanged:$text');
//suggestion.dispatch(SuggestionFetch(query: text));
getResultsDebounced(text);
@ -136,56 +138,58 @@ class _SearchBarPageState extends State<SearchBarPage> {
super.dispose();
}
Widget build(BuildContext context) {
return Container(
color: Theme.of(context).primaryColor,
//color: Colors.amber,
child: Padding(
//padding: EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top,),
padding: EdgeInsets.all(0.0),
child: Container(
//height: 162.0,
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Card(
child: Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(width: 5.0,),
Icon(Icons.search, color: Colors.grey,size: 18.0,),
Expanded(
child: Container(
alignment: Alignment.center,
child: TextField(
controller: controller,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 0.0),
hintText: '全网搜索 Flutter 相关知识库',
hintStyle:TextStyle(fontSize: 12.0),
border: InputBorder.none
),
onChanged: onSearchTextChanged,
),
),
),
IconButton(
icon: Icon(Icons.cancel),
color: Colors.grey,
iconSize: 18.0,
onPressed: () {
controller.clear();
// onSearchTextChanged('');
},
),
],
color: Theme.of(context).primaryColor,
//color: Colors.amber,
child: Padding(
//padding: EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top,),
padding: EdgeInsets.all(0.0),
child: Container(
//height: 162.0,
child: Padding(
padding: const EdgeInsets.all(6.0),
child: Card(
child: Container(
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 5.0,
),
Icon(
Icons.search,
color: Colors.grey,
size: 18.0,
),
Expanded(
child: Container(
alignment: Alignment.center,
child: TextField(
controller: controller,
decoration: InputDecoration(
contentPadding: EdgeInsets.only(top: 0.0),
hintText: '全网搜索 Flutter 相关知识库',
hintStyle: TextStyle(fontSize: 12.0),
border: InputBorder.none),
onChanged: onSearchTextChanged,
),
),
)
)
),
),
),
IconButton(
icon: Icon(Icons.cancel),
color: Colors.grey,
iconSize: 18.0,
onPressed: () {
controller.clear();
// onSearchTextChanged('');
},
),
],
),
))),
),
);
),
);
}
}

View File

@ -17,7 +17,7 @@ class SubPage extends StatefulWidget {
SubPageState createState() => SubPageState();
}
class SubPageState extends State<SubPage> with AutomaticKeepAliveClientMixin{
class SubPageState extends State<SubPage> with AutomaticKeepAliveClientMixin {
Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
Future<bool> _unKnow;
GlobalKey<DisclaimerMsgState> key;
@ -25,47 +25,46 @@ class SubPageState extends State<SubPage> with AutomaticKeepAliveClientMixin{
@override
bool get wantKeepAlive => true;
@override
@override
void initState() {
super.initState();
if (key == null) {
key = GlobalKey<DisclaimerMsgState>();
// key = const Key('__RIKEY1__');
key = GlobalKey<DisclaimerMsgState>();
// key = const Key('__RIKEY1__');
//获取sharePre
_unKnow = _prefs.then((SharedPreferences prefs) {
return (prefs.getBool('disclaimer::Boolean') ?? false);
});
_unKnow = _prefs.then((SharedPreferences prefs) {
return (prefs.getBool('disclaimer::Boolean') ?? false);
});
/// 判断是否需要弹出免责声明,已经勾选过不在显示,就不会主动弹
_unKnow.then((bool value) {
new Future.delayed(const Duration(seconds: 1),(){
if (!value && key.currentState is DisclaimerMsgState && key.currentState.showAlertDialog is Function) {
key.currentState.showAlertDialog(context);
}
});
new Future.delayed(const Duration(seconds: 1), () {
if (!value &&
key.currentState is DisclaimerMsgState &&
key.currentState.showAlertDialog is Function) {
key.currentState.showAlertDialog(context);
}
});
});
}
}
Future<Map> getIndexListData([Map<String, dynamic> params]) async {
const juejin_flutter = 'https://timeline-merger-ms.juejin.im/v1/get_tag_entry?src=web&tagId=5a96291f6fb9a0535b535438';
const juejin_flutter =
'https://timeline-merger-ms.juejin.im/v1/get_tag_entry?src=web&tagId=5a96291f6fb9a0535b535438';
var pageIndex = (params is Map) ? params['pageIndex'] : 0;
final _param = {'page':pageIndex,'pageSize':20,'sort':'rankIndex'};
final _param = {'page': pageIndex, 'pageSize': 20, 'sort': 'rankIndex'};
var responseList = [];
var pageTotal = 0;
var pageTotal = 0;
try{
try {
var response = await NetUtils.get(juejin_flutter, _param);
responseList = response['d']['entrylist'];
pageTotal = response['d']['total'];
if (!(pageTotal is int) || pageTotal <= 0) {
pageTotal = 0;
}
}catch(e){
}
} catch (e) {}
pageIndex += 1;
List resultList = new List();
for (int i = 0; i < responseList.length; i++) {
@ -76,50 +75,50 @@ class SubPageState extends State<SubPage> with AutomaticKeepAliveClientMixin{
// No specified type, handles all
}
}
Map<String, dynamic> result = {"list":resultList, 'total':pageTotal, 'pageIndex':pageIndex};
Map<String, dynamic> result = {
"list": resultList,
'total': pageTotal,
'pageIndex': pageIndex
};
return result;
}
Widget makeCard(index,item){
Widget makeCard(index, item) {
var myTitle = '${item.title}';
var myUsername = '${'👲'}: ${item.username} ';
var codeUrl = '${item.detailUrl}';
return new ListViewItem(itemUrl:codeUrl,itemTitle: myTitle,data: myUsername,);
return new ListViewItem(
itemUrl: codeUrl,
itemTitle: myTitle,
data: myUsername,
);
}
headerView(){
return
Column(
children: <Widget>[
headerView() {
return Column(
children: <Widget>[
Stack(
//alignment: const FractionalOffset(0.9, 0.1),//方法一
children: <Widget>[
Pagination(),
Positioned(//方法二
top: 10.0,
left: 0.0,
child: DisclaimerMsg(key:key,pWidget:this)
),
]),
SizedBox(height: 1, child:Container(color: Theme.of(context).primaryColor)),
//alignment: const FractionalOffset(0.9, 0.1),//方法一
children: <Widget>[
Pagination(),
Positioned(
//方法二
top: 10.0,
left: 0.0,
child: DisclaimerMsg(key: key, pWidget: this)),
]),
SizedBox(
height: 1, child: Container(color: Theme.of(context).primaryColor)),
SizedBox(height: 10),
],
);
],
);
}
@override
Widget build(BuildContext context) {
super.build(context);
return new Column(
children: <Widget>[
new Expanded(
child: listComp.ListRefresh(getIndexListData,makeCard)
)
]
);
return new Column(children: <Widget>[
new Expanded(child: listComp.ListRefresh(getIndexListData, makeCard))
]);
}
}

View File

@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:ui';
@ -7,13 +6,11 @@ import 'package:flutter/material.dart';
import 'package:flutter_go/views/fourth_page/pager_indicator.dart';
class PageDragger extends StatefulWidget {
final canDragLeftToRight;
final canDragRightToLeft;
final StreamController<SlideUpdate> slideUpdateStream;
PageDragger({
this.canDragLeftToRight,
this.canDragRightToLeft,
@ -25,14 +22,13 @@ class PageDragger extends StatefulWidget {
}
class _PageDraggerState extends State<PageDragger> {
static const FULL_TRANSTITION_PX = 300.0;
Offset dragStart;
SlideDirection slideDirection;
double slidePercent = 0.0;
onDragStart(DragStartDetails details){
onDragStart(DragStartDetails details) {
dragStart = details.globalPosition;
}
@ -49,28 +45,22 @@ class _PageDraggerState extends State<PageDragger> {
slideDirection = SlideDirection.none;
}
if (slideDirection != SlideDirection.none){
slidePercent = (dx / FULL_TRANSTITION_PX).abs().clamp(0.0, 1.0);
if (slideDirection != SlideDirection.none) {
slidePercent = (dx / FULL_TRANSTITION_PX).abs().clamp(0.0, 1.0);
} else {
slidePercent = 0.0;
}
widget.slideUpdateStream.add(
new SlideUpdate(
UpdateType.dragging,
slideDirection,
slidePercent
));
new SlideUpdate(UpdateType.dragging, slideDirection, slidePercent));
}
}
onDragEnd(DragEndDetails details){
widget.slideUpdateStream.add(
new SlideUpdate(
onDragEnd(DragEndDetails details) {
widget.slideUpdateStream.add(new SlideUpdate(
UpdateType.doneDragging,
SlideDirection.none,
0.0,
)
);
));
dragStart = null;
}
@ -78,15 +68,14 @@ class _PageDraggerState extends State<PageDragger> {
@override
Widget build(BuildContext context) {
return GestureDetector(
onHorizontalDragStart: onDragStart ,
onHorizontalDragUpdate: onDragUpdate ,
onHorizontalDragEnd: onDragEnd ,
onHorizontalDragStart: onDragStart,
onHorizontalDragUpdate: onDragUpdate,
onHorizontalDragEnd: onDragEnd,
);
}
}
class AnimatedPageDragger{
class AnimatedPageDragger {
static const PERCENT_PER_MILLISECOND = 0.005;
final slideDirection;
@ -95,85 +84,67 @@ class AnimatedPageDragger{
AnimationController completionAnimationController;
AnimatedPageDragger({
this.slideDirection,
this.transitionGoal,
slidePercent,
StreamController<SlideUpdate> slideUpdateStream,
TickerProvider vsync,
this.slideDirection,
this.transitionGoal,
slidePercent,
StreamController<SlideUpdate> slideUpdateStream,
TickerProvider vsync,
}) {
final startSlidePercent = slidePercent;
var endSlidePercent;
var duration;
if ( transitionGoal == TransitionGoal.open){
if (transitionGoal == TransitionGoal.open) {
endSlidePercent = 1.0;
final slideRemaining = 1.0 - slidePercent;
duration = new Duration(
milliseconds: (slideRemaining / PERCENT_PER_MILLISECOND).round()
);
milliseconds: (slideRemaining / PERCENT_PER_MILLISECOND).round());
} else {
endSlidePercent = 0.0;
duration = new Duration(
milliseconds: (slidePercent / PERCENT_PER_MILLISECOND).round()
);
milliseconds: (slidePercent / PERCENT_PER_MILLISECOND).round());
}
completionAnimationController = new AnimationController(
duration: duration,
vsync: vsync
)
..addListener((){
slidePercent = lerpDouble(
startSlidePercent,
endSlidePercent,
completionAnimationController.value
);
slideUpdateStream.add(
new SlideUpdate(
UpdateType.animating,
slideDirection,
slidePercent,
)
);
})
..addStatusListener((AnimationStatus status){
if(status == AnimationStatus.completed){
slideUpdateStream.add(
new SlideUpdate(
UpdateType.doneAnimating,
slideDirection,
endSlidePercent,
)
);
}
});
completionAnimationController =
new AnimationController(duration: duration, vsync: vsync)
..addListener(() {
slidePercent = lerpDouble(startSlidePercent, endSlidePercent,
completionAnimationController.value);
slideUpdateStream.add(new SlideUpdate(
UpdateType.animating,
slideDirection,
slidePercent,
));
})
..addStatusListener((AnimationStatus status) {
if (status == AnimationStatus.completed) {
slideUpdateStream.add(new SlideUpdate(
UpdateType.doneAnimating,
slideDirection,
endSlidePercent,
));
}
});
}
run(){
run() {
completionAnimationController.forward(from: 0.0);
}
dispose(){
dispose() {
completionAnimationController.dispose();
}
}
enum TransitionGoal{
enum TransitionGoal {
open,
close,
}
enum UpdateType{
enum UpdateType {
dragging,
doneDragging,
animating,
@ -185,9 +156,5 @@ class SlideUpdate {
final direction;
final slidePercent;
SlideUpdate(
this.updateType,
this.direction,
this.slidePercent
);
SlideUpdate(this.updateType, this.direction, this.slidePercent);
}

View File

@ -3,14 +3,10 @@ import 'dart:math';
import 'package:flutter/material.dart';
class PageReveal extends StatelessWidget {
final double revealPercent;
final Widget child;
PageReveal({
this.revealPercent,
this.child
});
PageReveal({this.revealPercent, this.child});
@override
Widget build(BuildContext context) {
@ -21,18 +17,13 @@ class PageReveal extends StatelessWidget {
}
}
class CircleRevealClipper extends CustomClipper<Rect>{
class CircleRevealClipper extends CustomClipper<Rect> {
final double revealPercent;
CircleRevealClipper(
this.revealPercent
);
CircleRevealClipper(this.revealPercent);
@override
Rect getClip(Size size) {
final epicenter = new Offset(size.width / 2, size.height * 0.9);
double theta = atan(epicenter.dy / epicenter.dx);
@ -41,12 +32,12 @@ class CircleRevealClipper extends CustomClipper<Rect>{
final radius = distanceToCorner * revealPercent;
final diameter = 2 * radius;
return new Rect.fromLTWH(epicenter.dx - radius, epicenter.dy - radius, diameter, diameter);
return new Rect.fromLTWH(
epicenter.dx - radius, epicenter.dy - radius, diameter, diameter);
}
@override
bool shouldReclip(CustomClipper<Rect> oldClipper) {
return true;
}
}

View File

@ -5,7 +5,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_go/views/fourth_page/pages.dart';
class PagerIndicator extends StatelessWidget {
final PagerIndicatorViewModel viewModel;
PagerIndicator({
@ -14,47 +13,49 @@ class PagerIndicator extends StatelessWidget {
@override
Widget build(BuildContext context) {
List<PageBubble> bubbles = [];
for(var i = 0; i < viewModel.pages.length; ++i ){
for (var i = 0; i < viewModel.pages.length; ++i) {
final page = viewModel.pages[i];
var percentActive;
if(i == viewModel.activeIndex){
if (i == viewModel.activeIndex) {
percentActive = 1.0 - viewModel.slidePercent;
} else if (i == viewModel.activeIndex - 1 && viewModel.slideDirection == SlideDirection.leftToRight){
} else if (i == viewModel.activeIndex - 1 &&
viewModel.slideDirection == SlideDirection.leftToRight) {
percentActive = viewModel.slidePercent;
} else if (i == viewModel.activeIndex + 1 && viewModel.slideDirection == SlideDirection.rightToLeft){
} else if (i == viewModel.activeIndex + 1 &&
viewModel.slideDirection == SlideDirection.rightToLeft) {
percentActive = viewModel.slidePercent;
}else {
} else {
percentActive = 0.0;
}
bool isHollow = i > viewModel.activeIndex || (i == viewModel.activeIndex && viewModel.slideDirection == SlideDirection.leftToRight);
bool isHollow = i > viewModel.activeIndex ||
(i == viewModel.activeIndex &&
viewModel.slideDirection == SlideDirection.leftToRight);
bubbles.add(
new PageBubble(
new PageBubble(
viewModel: new PageBubbleViewModel(
page.iconAssetPath,
page.color,
isHollow,
percentActive,
page.iconAssetPath,
page.color,
isHollow,
percentActive,
),
),
);
}
final bubbleWidth = 55.0 ;
final baseTranslation = ((viewModel.pages.length * bubbleWidth) / 2) - (bubbleWidth / 2) ;
final bubbleWidth = 55.0;
final baseTranslation =
((viewModel.pages.length * bubbleWidth) / 2) - (bubbleWidth / 2);
var translation = baseTranslation - (viewModel.activeIndex * bubbleWidth);
if (viewModel.slideDirection == SlideDirection.leftToRight){
translation = bubbleWidth * viewModel.slidePercent + translation;
}else if (viewModel.slideDirection == SlideDirection.rightToLeft){
translation = bubbleWidth * viewModel.slidePercent - translation;
if (viewModel.slideDirection == SlideDirection.leftToRight) {
translation = bubbleWidth * viewModel.slidePercent + translation;
} else if (viewModel.slideDirection == SlideDirection.rightToLeft) {
translation = bubbleWidth * viewModel.slidePercent - translation;
}
return new Column(
@ -72,37 +73,26 @@ class PagerIndicator extends StatelessWidget {
}
}
enum SlideDirection{
enum SlideDirection {
leftToRight,
rightToLeft,
none,
}
class PagerIndicatorViewModel{
class PagerIndicatorViewModel {
final List<PageViewModel> pages;
final int activeIndex;
final SlideDirection slideDirection;
final double slidePercent;
PagerIndicatorViewModel(
this.pages,
this.activeIndex,
this.slideDirection,
this.slidePercent
);
this.pages, this.activeIndex, this.slideDirection, this.slidePercent);
}
class PageBubble extends StatelessWidget {
final PageBubbleViewModel viewModel;
PageBubble({
this.viewModel
});
PageBubble({this.viewModel});
@override
Widget build(BuildContext context) {
@ -111,16 +101,18 @@ class PageBubble extends StatelessWidget {
height: 65.0,
child: new Center(
child: new Container(
width: lerpDouble(20.0,45.0,viewModel.activePercent),
height: lerpDouble(20.0,45.0,viewModel.activePercent),
width: lerpDouble(20.0, 45.0, viewModel.activePercent),
height: lerpDouble(20.0, 45.0, viewModel.activePercent),
decoration: new BoxDecoration(
shape: BoxShape.circle,
color: viewModel.isHollow
? const Color(0x88FFFFFF).withAlpha(0x88 * viewModel.activePercent.round())
? const Color(0x88FFFFFF)
.withAlpha(0x88 * viewModel.activePercent.round())
: const Color(0x88FFFFFF),
border: new Border.all(
color: viewModel.isHollow
? const Color(0x88FFFFFF).withAlpha((0x88 * (1.0 - viewModel.activePercent)).round())
? const Color(0x88FFFFFF).withAlpha(
(0x88 * (1.0 - viewModel.activePercent)).round())
: Colors.transparent,
width: 3.0,
),
@ -138,20 +130,16 @@ class PageBubble extends StatelessWidget {
}
}
class PageBubbleViewModel {
final String iconAssetPath;
final Color color;
final bool isHollow;
final double activePercent;
PageBubbleViewModel (
this.iconAssetPath,
this.color,
this.isHollow,
this.activePercent,
);
PageBubbleViewModel(
this.iconAssetPath,
this.color,
this.isHollow,
this.activePercent,
);
}

View File

@ -58,7 +58,8 @@ class Page extends StatelessWidget {
elevation: 10.0,
color: Colors.black26,
// shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(left: Radius.circular(20.0))),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.horizontal(left: Radius.circular(20.0))),
//如果不手动设置icon和text颜色,则默认使用foregroundColor颜色
icon: Icon(iconName, color: Colors.white, size: 14.0),
label: Text(
@ -76,6 +77,7 @@ class Page extends StatelessWidget {
children: [
Container(
width: double.infinity,
/// height:MediaQuery.of(context).size.height-200.0,
color: viewModel.color,
padding: const EdgeInsets.fromLTRB(0, 0, 0, 0),
@ -86,15 +88,13 @@ class Page extends StatelessWidget {
layout(context),
],
),
)
),
)),
Positioned(
right: -5.0,
top: 2.0,
child: creatButton(context, 'GitHub', Icons.arrow_forward, 'goGithub')
),
]
);
child: creatButton(
context, 'GitHub', Icons.arrow_forward, 'goGithub')),
]);
}
Column layout(BuildContext context) {

View File

@ -6,27 +6,30 @@
/// target: app首页
import 'package:flutter/material.dart';
/// import 'package:flutter/rendering.dart';
import 'package:flutter_go/utils/data_utils.dart';
import 'package:flutter_go/utils/shared_preferences.dart';
/// import 'package:flutter_go/views/first_page/first_page.dart';
import 'package:flutter_go/views/first_page/main_page.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter_go/views/user_page/user_page.dart';
import 'package:flutter_go/views/widget_page/widget_page.dart';
import 'package:flutter_go/views/welcome_page/fourth_page.dart';
/// import 'package:flutter_go/views/collection_page/collection_page.dart';
import 'package:flutter_go/routers/application.dart';
/// import 'package:flutter_go/utils/provider.dart';
import 'package:flutter_go/model/widget.dart';
/// import 'package:flutter_go/widgets/index.dart';
import 'package:flutter_go/components/search_input.dart';
import 'package:flutter_go/model/search_history.dart';
import 'package:flutter_go/resources/widget_name_to_icon.dart';
import 'package:flutter_go/model/user_info.dart';
class AppPage extends StatefulWidget {
final UserInformation userInfo;
@ -62,10 +65,11 @@ class _MyHomePageState extends State<AppPage>
print('widget.userInfo ${widget.userInfo}');
initSearchHistory();
if(Application.pageIsOpen == true){// 是否展开业界动态
if (Application.pageIsOpen == true) {
// 是否展开业界动态
tabData.insert(0, {'text': '业界动态', 'icon': Icon(Icons.language)});
_list
//..add(FirstPage())
//..add(FirstPage())
..add(MainPage(userInfo: widget.userInfo));
}
appBarTitle = tabData[0]['text'];
@ -78,10 +82,10 @@ class _MyHomePageState extends State<AppPage>
),
));
}
_list
..add(WidgetPage())
..add(FourthPage())
..add(UserPage(userInfo: widget.userInfo));
_list
..add(WidgetPage())
..add(FourthPage())
..add(UserPage(userInfo: widget.userInfo));
}
@override
@ -99,8 +103,8 @@ class _MyHomePageState extends State<AppPage>
void onWidgetTap(WidgetPoint widgetPoint, BuildContext context) {
String targetName = widgetPoint.name;
String targetRouter = widgetPoint.routerName;
searchHistoryList.add(
SearchHistory(name: targetName, targetRouter: targetRouter));
searchHistoryList
.add(SearchHistory(name: targetName, targetRouter: targetRouter));
print("searchHistoryList1 ${searchHistoryList.toString()}");
Application.router.navigateTo(context, targetRouter.toLowerCase(),
transition: TransitionType.inFromRight);
@ -131,7 +135,7 @@ class _MyHomePageState extends State<AppPage>
renderAppBar(BuildContext context, Widget widget, int index) {
if (index == 1 && Application.pageIsOpen == true) {
return AppBar(title: buildSearchInput(context));
}else if(index == 0 && Application.pageIsOpen == false){
} else if (index == 0 && Application.pageIsOpen == false) {
return AppBar(title: buildSearchInput(context));
}
}

View File

@ -6,8 +6,6 @@ import 'package:flutter_go/utils/data_utils.dart';
import 'package:notus/convert.dart';
import 'package:fluttertoast/fluttertoast.dart';
class IssuesMessagePage extends StatefulWidget {
@override
_IssuesMessagePageState createState() => _IssuesMessagePageState();
@ -48,15 +46,17 @@ class _IssuesMessagePageState extends State<IssuesMessagePage> {
if (_title.trim().isEmpty) {
_show('标题不能为空');
} else {
String mk = (_delta==null)?'No description provided.':notusMarkdown.encode(_delta);
DataUtils.feedback({'title': _title, "body": mk},context).then((result) {
String mk = (_delta == null)
? 'No description provided.'
: notusMarkdown.encode(_delta);
DataUtils.feedback({'title': _title, "body": mk}, context).then((result) {
_show('提交成功');
Navigator.maybePop(context);
});
}
}
_show(String msgs){
_show(String msgs) {
Fluttertoast.showToast(
msg: msgs,
toastLength: Toast.LENGTH_SHORT,
@ -68,20 +68,19 @@ class _IssuesMessagePageState extends State<IssuesMessagePage> {
}
Widget buildLoading() {
return Opacity(
opacity: .5,
child: Container(
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
color: Colors.black,
),
child: SpinKitPouringHourglass(color: Colors.white),
return Opacity(
opacity: .5,
child: Container(
width: MediaQuery.of(context).size.width * 0.85,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
color: Colors.black,
),
);
child: SpinKitPouringHourglass(color: Colors.white),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(

View File

@ -256,15 +256,15 @@ class _LoginPageState extends State<LoginPage> {
MaterialPageRoute(builder: (context) => AppPage(userResult)),
(route) => route == null);
}
}else if(userResult.runtimeType == String){
} else if (userResult.runtimeType == String) {
Fluttertoast.showToast(
msg: userResult,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Theme.of(context).primaryColor,
textColor: Colors.white,
fontSize: 16.0);
msg: userResult,
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 1,
backgroundColor: Theme.of(context).primaryColor,
textColor: Colors.white,
fontSize: 16.0);
}
}).catchError((errorMsg) {
setState(() {
@ -388,7 +388,9 @@ class _LoginPageState extends State<LoginPage> {
decoration: TextDecoration.underline),
),
onPressed: () {
Application.router.navigateTo(context, Routes.home, clearStack: true);
Application.router.navigateTo(
context, Routes.home,
clearStack: true);
},
)
],

View File

@ -19,12 +19,12 @@ import 'package:flutter_go/routers/routers.dart';
import 'package:flutter_go/utils/net_utils.dart';
import 'package:flutter_go/components/loading.dart';
const githubHost = 'https://raw.githubusercontent.com/alibaba/flutter-go/master';
const githubHost =
'https://raw.githubusercontent.com/alibaba/flutter-go/master';
const githubUrl = '$githubHost/lib/standard_pages/';
const PagesUrl = '$githubHost/lib/standard_pages/.pages.json';
const DemosUrl = '$githubHost/lib/page_demo_package/.demo.json';
// ONLINE || LOCAL
ENV env = Application.env;
@ -54,9 +54,11 @@ class _StandardView extends State<StandardView> {
// }
/// 本地调用的获取文章属性的基本信息
Future<void> localGetPagesAttrsInfo() async {
String jsonString = await DefaultAssetBundle.of(context).loadString('lib/standard_pages/.pages.json');
String jsonString = await DefaultAssetBundle.of(context)
.loadString('lib/standard_pages/.pages.json');
List jsonList = json.decode(jsonString);
Map<String, dynamic> pageDetail = jsonList.firstWhere((item) => item['id'] == widget.id, orElse: null);
Map<String, dynamic> pageDetail =
jsonList.firstWhere((item) => item['id'] == widget.id, orElse: null);
if (pageDetail != null) {
setState(() {
@ -69,12 +71,12 @@ class _StandardView extends State<StandardView> {
/// 从本地获取基本文章信息
String localGetPagesMarkdown() {
String pageId = widget.id;
Map<String, String> pagesList = standardPage.getPages();
// print('pagesList[pageId]>>> ${pagesList[pageId]}');
return pagesList[pageId];
}
Future<String> getContentOnline() async {
this.setState(() {
isLoading = true;
@ -82,8 +84,6 @@ class _StandardView extends State<StandardView> {
List response = jsonDecode(await NetUtils.get(PagesUrl));
Map targetPage = response.firstWhere((page) => page['id'] == widget.id);
if (targetPage == null) {
setState(() {
@ -97,13 +97,18 @@ class _StandardView extends State<StandardView> {
email = targetPage['email'];
});
String pageName = targetPage['name'] + "_" +targetPage['author']+ "_" +targetPage['id'];
String pageName = targetPage['name'] +
"_" +
targetPage['author'] +
"_" +
targetPage['id'];
String pageContent = await NetUtils.get(githubUrl + pageName + "/index.md");
setState(() {
isLoading = false;
});
return Future(() => pageContent);
}
/// 获取当面界面的相关信息. 需要区分环境
/// 本地环境下, 从本地获取 standard_pages的目录中互殴
/// 线上环境. 从github的api中获取
@ -124,6 +129,7 @@ class _StandardView extends State<StandardView> {
}
return Future(() => conent);
}
void seeSourceCode(id) async {
List response;
try {
@ -132,16 +138,18 @@ class _StandardView extends State<StandardView> {
return alertDialog(msg: '请检查网络链接', title: '提示');
}
Map<String, dynamic> demoDetail = response.firstWhere((item) => item['id'] == id, orElse: null);
Map<String, dynamic> demoDetail =
response.firstWhere((item) => item['id'] == id, orElse: null);
if (demoDetail == null) {
return null;
}
String remoteSouceCode = '$githubHost/lib/page_demo_package/${demoDetail['name']}_${demoDetail['author']}_${demoDetail['id']}/src/index.dart';
Application.router.navigateTo(context,
'${Routes.githubCodeView}?remotePath=${Uri.encodeComponent(remoteSouceCode)}');
String remoteSouceCode =
'$githubHost/lib/page_demo_package/${demoDetail['name']}_${demoDetail['author']}_${demoDetail['id']}/src/index.dart';
Application.router.navigateTo(context,
'${Routes.githubCodeView}?remotePath=${Uri.encodeComponent(remoteSouceCode)}');
}
Widget buildFootInfo() {
if (!isLoading) {
return Container(
@ -159,8 +167,6 @@ class _StandardView extends State<StandardView> {
}
Widget buildMarkdown() {
if (markdownDesc == null) {
return null;
} else {
@ -172,7 +178,7 @@ class _StandardView extends State<StandardView> {
return MarkdownBody(
data: markdownDesc,
syntaxHighlighter:new mdCopy.HighLight(),
syntaxHighlighter: new mdCopy.HighLight(),
demoBuilder: (Map<String, dynamic> attrs) {
List<Widget> demo = demoObjects[attrs['id']];
if (demo == null) {
@ -193,28 +199,29 @@ class _StandardView extends State<StandardView> {
onTap: () {
seeSourceCode(attrs['id']);
},
child: Text("查看源码", style: TextStyle(color: Theme.of(context).primaryColor)),
child: Text("查看源码",
style: TextStyle(color: Theme.of(context).primaryColor)),
)
],
) ;
);
}
});
}
alertDialog({String msg, String title}) {
showDialog<Null>(
context: context,
barrierDismissible: true,
builder: (BuildContext context) {
return new AlertDialog(
title: new Text(title),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new Text(msg),
],
),
)
);
title: new Text(title),
content: new SingleChildScrollView(
child: new ListBody(
children: <Widget>[
new Text(msg),
],
),
));
},
);
}

View File

@ -20,12 +20,8 @@ class WelcomePage extends StatefulWidget {
}
class _WelcomePageState extends State<WelcomePage> {
@override
Widget build(BuildContext context) {
return new Container(
color: Colors.white,
child: FourthPage()
);
return new Container(color: Colors.white, child: FourthPage());
}
}

View File

@ -9,36 +9,27 @@ import 'package:flutter_go/components/cate_card.dart';
import 'package:flutter_go/routers/application.dart';
class WidgetPage extends StatefulWidget {
@override
SecondPageState createState() => new SecondPageState();
}
class SecondPageState extends State<WidgetPage> with AutomaticKeepAliveClientMixin{
class SecondPageState extends State<WidgetPage>
with AutomaticKeepAliveClientMixin {
SecondPageState() : super();
TextEditingController controller;
String active = 'test';
String data = '';
@override
bool get wantKeepAlive => true;
bool get wantKeepAlive => true;
@override
void initState() {
super.initState();
}
Widget buildGrid() {
// 存放最后的widget
List<Widget> tiles = [];
@ -58,5 +49,4 @@ class SecondPageState extends State<WidgetPage> with AutomaticKeepAliveClientMix
child: this.buildGrid(),
);
}
}

View File

@ -1,15 +1,12 @@
import 'package:flutter/material.dart';
class WidgetNotFound extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("widget not found"),
),
body: Container(
child: Text("widget not found")
)
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("widget not found"),
),
body: Container(child: Text("widget not found")));
}
}

View File

@ -18,15 +18,17 @@ class AppBarLessDefaultComplex extends StatefulWidget {
}
// AppBar 默认的实例,有状态
class _AppBarLessDefaultComplex extends State with SingleTickerProviderStateMixin {
class _AppBarLessDefaultComplex extends State
with SingleTickerProviderStateMixin {
ScrollController _scrollViewController;
TabController _tabController;
@override
void initState() {
super.initState();
_scrollViewController = ScrollController();
_tabController = TabController(vsync: this, length: 6);// 和下面的 TabBar.tabs 数量对应
_scrollViewController = ScrollController();
_tabController =
TabController(vsync: this, length: 6); // 和下面的 TabBar.tabs 数量对应
}
@override
@ -41,48 +43,49 @@ class _AppBarLessDefaultComplex extends State with SingleTickerProviderStateMixi
// 如果省略了 leading ,但 AppBar 在带有 Drawer 的 Scaffold 中,则会插入一个 button 以打开 Drawer。
// 否则,如果最近的 Navigator 具有任何先前的 router 则会插入BackButton。
// 这种行为可以通过设置来关闭automaticallyImplyLeading 为false。在这种情况下空的 leading widget 将导致 middle/title widget 拉伸开始。
return SizedBox(
return SizedBox(
height: 500,
child: AppBar( // 大量配置属性参考 SliverAppBar 示例
title: Text('title'),
leading: Icon(Icons.home),
child: AppBar(
// 大量配置属性参考 SliverAppBar 示例
title: Text('title'),
leading: Icon(Icons.home),
backgroundColor: Colors.amber[500],
centerTitle: true,
actions: <Widget>[
IconButton(
icon: Icon(Icons.add_alarm),
IconButton(
icon: Icon(Icons.add_alarm),
tooltip: 'Add Alarm',
onPressed: () {
// do nothing
}),
PopupMenuButton<String>(
PopupMenuButton<String>(
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: "price", child: Text('Sort by price')),
PopupMenuItem<String>(
value: "time", child: Text('Sort by time')),
],
PopupMenuItem<String>(
value: "price", child: Text('Sort by price')),
PopupMenuItem<String>(
value: "time", child: Text('Sort by time')),
],
onSelected: (String action) {
switch (action) {
case "price":
// do nothing
// do nothing
break;
case "time":
// do nothing
// do nothing
break;
}
})
],
bottom: TabBar(
bottom: TabBar(
isScrollable: true,
controller: _tabController,
tabs: <Widget>[
Tab(text: "Tabs 1"),
Tab(text: "Tabs 2"),
Tab(text: "Tabs 3"),
Tab(text: "Tabs 4"),
Tab(text: "Tabs 5"),
Tab(text: "Tabs 6"),
Tab(text: "Tabs 1"),
Tab(text: "Tabs 2"),
Tab(text: "Tabs 3"),
Tab(text: "Tabs 4"),
Tab(text: "Tabs 5"),
Tab(text: "Tabs 6"),
],
),
),
@ -90,40 +93,37 @@ class _AppBarLessDefaultComplex extends State with SingleTickerProviderStateMixi
}
}
// AppBar 默认的实例,无状态
class AppBarLessDefaultSimple extends StatelessWidget {
final widget;
final parent;
const AppBarLessDefaultSimple([this.widget, this.parent])
: super();
const AppBarLessDefaultSimple([this.widget, this.parent]) : super();
@override
Widget build(BuildContext context) {
return SizedBox(
height: 200,
child:AppBar(
title: Text('My Fancy Dress'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.playlist_play),
tooltip: 'Air it',
onPressed: ()=>{},
),
IconButton(
icon: Icon(Icons.playlist_add),
tooltip: 'Restitch it',
onPressed: ()=>{},
),
IconButton(
icon: Icon(Icons.playlist_add_check),
tooltip: 'Repair it',
onPressed: ()=>{},
),
],
)
);
return SizedBox(
height: 200,
child: AppBar(
title: Text('My Fancy Dress'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.playlist_play),
tooltip: 'Air it',
onPressed: () => {},
),
IconButton(
icon: Icon(Icons.playlist_add),
tooltip: 'Restitch it',
onPressed: () => {},
),
IconButton(
icon: Icon(Icons.playlist_add_check),
tooltip: 'Repair it',
onPressed: () => {},
),
],
));
}
}

View File

@ -10,23 +10,19 @@ import 'package:flutter/material.dart';
import './demo.dart' as AppBarDemo;
import 'package:flutter_go/components/widget_demo.dart';
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> AppBar “应用栏”
- 应用栏由工具栏组成,或者是工具栏和其他 widget 组合形成,例如 TabBar和FlexibleSpaceBar;
- 应用栏通常用于 Scaffold.appBar 属性,该属性将应用栏放置在屏幕顶部的固定高度小部件中;
- 对于可滚动的应用栏请参阅SliverAppBar它将AppBar嵌入 sliver 中以便在CustomScrollView中使用;
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> AppBar
- AppBar 在底部上方显示工具栏 widget前导 leading ,标题 title 和操作 actions;
""";
const String _Text2 =
"""### **进阶用法**
const String _Text2 = """### **进阶用法**
> AppBar
- 一个完整的 AppBar 的例子, 增加 PopupMenuButton,TabBar 的示例子;
- 所述底部通常用于一个的 TabBar;

View File

@ -12,31 +12,39 @@ class AppBarLessDefaultSimple extends StatelessWidget {
final widget;
final parent;
const AppBarLessDefaultSimple([this.widget, this.parent])
: super();
const AppBarLessDefaultSimple([this.widget, this.parent]) : super();
@override
Widget build(BuildContext context) {
return SizedBox(
height: 100,
child: Scaffold(
//appBar: AppBar(title: const Text('Bottom App Bar')),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add), onPressed: () {},),
return SizedBox(
height: 100,
child: Scaffold(
//appBar: AppBar(title: const Text('Bottom App Bar')),
floatingActionButtonLocation:
FloatingActionButtonLocation.centerDocked,
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {},
),
bottomNavigationBar: BottomAppBar(
shape: CircularNotchedRectangle(),
notchMargin: 10.0,// FloatingActionButton和BottomAppBar 之间的差距
color:Colors.pink,
notchMargin: 10.0, // FloatingActionButton和BottomAppBar 之间的差距
color: Colors.pink,
child: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(icon: Icon(Icons.menu), onPressed: () {},),
IconButton(icon: Icon(Icons.search), onPressed: () {},),
IconButton(
icon: Icon(Icons.menu),
onPressed: () {},
),
IconButton(
icon: Icon(Icons.search),
onPressed: () {},
),
],
),
),
)
);
}}
));
}
}

View File

@ -11,19 +11,15 @@ import 'package:flutter/material.dart';
import './demo.dart' as BottomAppBarDemo;
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> BottomAppBar “底部应用栏”
- 一个通常与 Scaffold.bottomNavigationBar 一起使用的容器可以在顶部有一个凹口为重叠的FloatingActionButton腾出空间;
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> 通常与 Scaffold 和 FloatingActionButton 一起使用;
""";
class Demo extends StatefulWidget {
static const String routeName = '/components//Bar/BottomAppBar';
@ -38,7 +34,8 @@ class _DemoState extends State<Demo> {
title: 'BottomAppBar',
codeUrl: 'components/Bar/BottomAppBar/demo.dart',
contentList: allDomes(context, this),
docUrl: 'https://docs.flutter.io/flutter/material/BottomAppBar-class.html',
docUrl:
'https://docs.flutter.io/flutter/material/BottomAppBar-class.html',
);
}
}
@ -56,6 +53,3 @@ List allDomes(BuildContext context, _DemoState that) {
SizedBox(height: 20.0), // 间距
];
}

View File

@ -20,8 +20,8 @@ class _ButtonBarFullDefault extends State {
@override
Widget build(BuildContext context) {
return ButtonBar(
// ... // 如果没有,就是不需要有状态的 StatefulWidget
);
// ... // 如果没有,就是不需要有状态的 StatefulWidget
);
}
}
@ -30,37 +30,61 @@ class ButtonBarLessDefault extends StatelessWidget {
final widget;
final parent;
const ButtonBarLessDefault([this.widget, this.parent])
: super();
const ButtonBarLessDefault([this.widget, this.parent]) : super();
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 0.0),
margin: EdgeInsets.symmetric(vertical: 0.0),
height: 100.0,
child: Scrollbar(child:ListView(
scrollDirection: Axis.horizontal, // 水平listView
children: <Widget>[
child: Scrollbar(
child: ListView(scrollDirection: Axis.horizontal, // 水平listView
children: <Widget>[
ButtonBar(
alignment: MainAxisAlignment.spaceAround, //布局方向默认MainAxisAlignment.end
alignment: MainAxisAlignment
.spaceAround, //布局方向默认MainAxisAlignment.end
mainAxisSize: MainAxisSize.max, //主轴大小默认MainAxisSize.max
children: <Widget>[ // Button集合
RaisedButton(child: Text('ButtonBar1'),color: Colors.red,onPressed: ()=>{},),
RaisedButton(child: Text('ButtonBar2'),color: Colors.red,onPressed: ()=>{},),
RaisedButton(child: Text('ButtonBar3'),color: Colors.red,onPressed: ()=>{},),
children: <Widget>[
// Button集合
RaisedButton(
child: Text('ButtonBar1'),
color: Colors.red,
onPressed: () => {},
),
RaisedButton(
child: Text('ButtonBar2'),
color: Colors.red,
onPressed: () => {},
),
RaisedButton(
child: Text('ButtonBar3'),
color: Colors.red,
onPressed: () => {},
),
],
),
ButtonBar(
alignment: MainAxisAlignment.end, //布局方向默认MainAxisAlignment.end
mainAxisSize: MainAxisSize.min, //主轴大小默认MainAxisSize.max
children: <Widget>[ // Button集合
RaisedButton(child: Text('ButtonBar1'),color: Colors.yellow,onPressed: ()=>{},),
RaisedButton(child: Text('ButtonBar2'),color: Colors.yellow,onPressed: ()=>{},),
RaisedButton(child: Text('ButtonBar3'),color: Colors.yellow,onPressed: ()=>{},),
children: <Widget>[
// Button集合
RaisedButton(
child: Text('ButtonBar1'),
color: Colors.yellow,
onPressed: () => {},
),
RaisedButton(
child: Text('ButtonBar2'),
color: Colors.yellow,
onPressed: () => {},
),
RaisedButton(
child: Text('ButtonBar3'),
color: Colors.yellow,
onPressed: () => {},
),
],
)
]
)
));
])));
}
}

View File

@ -11,22 +11,18 @@ import 'package:flutter/material.dart';
import './demo.dart' as ButtonBarDemo;
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> ButtonBar “末端对齐的按钮容器”
- 横排的Button布局
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> 根据当前 ButtonTheme 中的填充水平放置 button
- 子 button 在布置行与 MainAxisAlignment.end;
- 当 Directionality为TextDirection.ltr 时,按钮栏的子项右对齐,最后一个子项成为最右边的子项;
- 当 Directionality TextDirection.rtl 时,子项被左对齐,最后一个子项成为最左边的子项;
""";
class Demo extends StatefulWidget {
static const String routeName = '/components/Bar/ButtonBar';
@ -58,4 +54,3 @@ List allDomes(BuildContext context, _DemoState that) {
ButtonBarDemo.ButtonBarLessDefault()
];
}

View File

@ -11,21 +11,17 @@ import 'package:flutter/material.dart';
import './demo.dart' as FlexibleSpaceBarDemo;
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> FlexibleSpaceBar “扩展和折叠的应用栏”
- AppBar 的一部分,可以扩展和折叠;
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> 最常用于 SliverAppBar.flexibleSpace 字段
- 灵活的空格键随着应用滚动而扩展和收缩,以便 AppBar 从应用程序的顶部到达应用程序滚动内容的顶部;
- 要调整 AppBar 大小,必须将其包装在 FlexibleSpaceBar.createSettings 返回的 widget 中 ,以将大小调整信息传递给 FlexibleSpaceBar;
""";
class Demo extends StatefulWidget {
static const String routeName = '/components/Bar/FlexibleSpaceBar';
@ -40,7 +36,8 @@ class _DemoState extends State<Demo> {
title: 'FlexibleSpaceBar',
codeUrl: 'components/Bar/FlexibleSpaceBar/demo.dart',
contentList: allDomes(context, this),
docUrl: 'https://docs.flutter.io/flutter/material/FlexibleSpaceBar-class.html',
docUrl:
'https://docs.flutter.io/flutter/material/FlexibleSpaceBar-class.html',
);
}
}
@ -58,4 +55,3 @@ List allDomes(BuildContext context, _DemoState that) {
SizedBox(height: 20.0), // 间距
];
}

View File

@ -20,8 +20,8 @@ class _SliverAppBarFullDefault extends State {
@override
Widget build(BuildContext context) {
return SliverAppBar(
// ... // 如果没有,就是不需要有状态的 StatefulWidget
);
// ... // 如果没有,就是不需要有状态的 StatefulWidget
);
}
}
@ -36,9 +36,9 @@ class SliverAppBarLessDefault extends StatelessWidget {
@override
Widget build(BuildContext context) {
for (int i = 0; i < 20; i++) {
listData.add( ListItem("我是测试标题$i", Icons.cake));
listData.add(ListItem("我是测试标题$i", Icons.cake));
}
return SizedBox(
return SizedBox(
height: 500.0,
child: NestedScrollView(
headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
@ -56,15 +56,16 @@ class SliverAppBarLessDefault extends StatelessWidget {
//iconTheme, // 图标主题,App bar 上图标的颜色、透明度、和尺寸信息。默认值为 ThemeData.primaryIconTheme
//textTheme, //文字主题, App bar 上的文字样式。默认值为 ThemeData.primaryTextTheme
//centerTitle, //标题是否居中, 标题是否居中显示,默认值根据不同的操作系统,显示方式不一样
primary: true, //是否预留高度
forceElevated:false,
automaticallyImplyLeading:true,
primary: true, //是否预留高度
forceElevated: false,
automaticallyImplyLeading: true,
titleSpacing: NavigationToolbar.kMiddleSpacing,
snap:false, //与floating结合使用
expandedHeight: 200.0,//展开高度
floating: false,//是否随着滑动隐藏标题
pinned: true,//是否固定在顶部
flexibleSpace: FlexibleSpaceBar( //可以展开区域通常是一个FlexibleSpaceBar
snap: false, //与floating结合使用
expandedHeight: 200.0, //展开高度
floating: false, //是否随着滑动隐藏标题
pinned: true, //是否固定在顶部
flexibleSpace: FlexibleSpaceBar(
//可以展开区域通常是一个FlexibleSpaceBar
centerTitle: true,
title: Text("我是一个帅气的标题",
style: TextStyle(
@ -78,30 +79,30 @@ class SliverAppBarLessDefault extends StatelessWidget {
fit: BoxFit.fill,
)),
),
// SliverPersistentHeader(
// delegate: _SliverAppBarDelegate(
// TabBar(
// controller: TabController(length: 2, vsync: this),
// labelColor: Colors.black87,
// unselectedLabelColor: Colors.grey,
// tabs: [
// Tab(icon: Icon(Icons.security), text: "security"),
// Tab(icon: Icon(Icons.cake), text: "cake"),
// ],
// ),
// ))
// SliverPersistentHeader(
// delegate: _SliverAppBarDelegate(
// TabBar(
// controller: TabController(length: 2, vsync: this),
// labelColor: Colors.black87,
// unselectedLabelColor: Colors.grey,
// tabs: [
// Tab(icon: Icon(Icons.security), text: "security"),
// Tab(icon: Icon(Icons.cake), text: "cake"),
// ],
// ),
// ))
];
},
body: Center(
child: ListView.builder(
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return ListItemWidget(listData[index]);
},
itemCount: listData.length,
),
),
));
body: Center(
child: ListView.builder(
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) {
return ListItemWidget(listData[index]);
},
itemCount: listData.length,
),
),
));
}
}
@ -119,13 +120,12 @@ class ListItemWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return InkWell(
child: ListTile(
leading: Icon(listItem.iconData),
title: Text(listItem.title),
return InkWell(
child: ListTile(
leading: Icon(listItem.iconData),
title: Text(listItem.title),
),
onTap: () {},
);
}
}

View File

@ -11,15 +11,12 @@ import 'package:flutter/material.dart';
import './demo.dart' as SliverAppBarDemo;
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> SliverAppBar “应用栏”
- 它类似于Android中的toolbar;
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> 虽然基本相同,构造方法也是非常的简单,但是却不能直接使用它,由官方文档可以看到通常结合 ScrollView 来使用它;
- AppBar 和 SliverAppBar 都是继承StatefulWidget 类,都代表 Toobar;
- 二者的区别在于 AppBar 位置的固定的应用最上面的;而 SliverAppBar 是可以跟随内容滚动的;
@ -57,4 +54,3 @@ List allDomes(BuildContext context, _DemoState that) {
SliverAppBarDemo.SliverAppBarLessDefault()
];
}

View File

@ -12,48 +12,47 @@ class SnackBarLessDefault extends StatelessWidget {
final widget;
final parent;
const SnackBarLessDefault([this.widget, this.parent])
: super();
const SnackBarLessDefault([this.widget, this.parent]) : super();
@override
Widget build(BuildContext context) {
// 当BuildContext在Scaffold之前时调用Scaffold.of(context)会报错。这时可以通过Builder Widget来解决
return Center(
child: Column(
children: <Widget>[
GestureDetector(
onTap: () {
final snackBar = SnackBar(
content: Text('这是一个SnackBar, 右侧有SnackBarAction'),
backgroundColor:Colors.red,
action: SnackBarAction( // 提示信息上添加一个撤消的按钮
textColor:Colors.black,
label: '撤消',
onPressed: () {
// Some code to undo the change!
},
),
duration:Duration(minutes: 1),// 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('显示SnackBar'),
),
GestureDetector(
onTap: () {
final snackBar = SnackBar(
content: Text('右侧无SnackBarAction'),
backgroundColor:Colors.red,
duration:Duration(minutes: 1),// 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('显示无SnackBarAction的SnackBar'),
),
],
)
);
return Center(
child: Column(
children: <Widget>[
GestureDetector(
onTap: () {
final snackBar = SnackBar(
content: Text('这是一个SnackBar, 右侧有SnackBarAction'),
backgroundColor: Colors.red,
action: SnackBarAction(
// 提示信息上添加一个撤消的按钮
textColor: Colors.black,
label: '撤消',
onPressed: () {
// Some code to undo the change!
},
),
duration: Duration(minutes: 1), // 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('显示SnackBar'),
),
GestureDetector(
onTap: () {
final snackBar = SnackBar(
content: Text('右侧无SnackBarAction'),
backgroundColor: Colors.red,
duration: Duration(minutes: 1), // 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('显示无SnackBarAction的SnackBar'),
),
],
));
}
}

View File

@ -9,21 +9,17 @@ import 'package:flutter/material.dart';
import 'package:flutter_go/components/widget_demo.dart';
import './demo.dart' as SnackBarDemo;
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> SnackBar “屏幕底部消息”
- 带有可选操作的轻量级消息,短暂显示在屏幕底部
- SnackBar是用户操作后显示提示信息的一个控件类似Toast会自动隐藏;
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> Scaffold.of(context).showSnackBar(),传递描述消息的 SnackBar 实例;
- 要控制SnackBar保持可见的时间请指定持续时间。
""";
class Demo extends StatefulWidget {
static const String routeName = '/components//Bar/SnackBar';

View File

@ -13,44 +13,42 @@ class SnackBarActionDemo extends StatefulWidget {
class _Demo extends State<SnackBarActionDemo> {
Widget build(BuildContext context) {
return Center(
child: Column(
children: <Widget>[
new RaisedButton(
onPressed: () {
final snackBar = new SnackBar(
content: new Text('这是一个SnackBar, 右侧有SnackBarAction, 3秒后消失'),
backgroundColor:Color(0xffc91b3a),
action: SnackBarAction( // 提示信息上添加一个撤消的按钮
textColor:Colors.white,
label: '撤消',
onPressed: () {
// Some code to undo the change!
},
),
duration:Duration(seconds: 3),// 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('点我显示有action的SnackBar'),
),
new RaisedButton(
onPressed: () async {
final snackBar = new SnackBar(
content: new Text('右侧无SnackBarAction, 3秒后消失'),
backgroundColor:Color(0xffc91b3a),
duration:Duration(seconds: 3),// 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('点我显示无SnackBarAction的SnackBar'),
),
],
)
);
return Center(
child: Column(
children: <Widget>[
new RaisedButton(
onPressed: () {
final snackBar = new SnackBar(
content: new Text('这是一个SnackBar, 右侧有SnackBarAction, 3秒后消失'),
backgroundColor: Color(0xffc91b3a),
action: SnackBarAction(
// 提示信息上添加一个撤消的按钮
textColor: Colors.white,
label: '撤消',
onPressed: () {
// Some code to undo the change!
},
),
duration: Duration(seconds: 3), // 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('点我显示有action的SnackBar'),
),
new RaisedButton(
onPressed: () async {
final snackBar = new SnackBar(
content: new Text('右侧无SnackBarAction, 3秒后消失'),
backgroundColor: Color(0xffc91b3a),
duration: Duration(seconds: 3), // 持续时间
//animation,
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text('点我显示无SnackBarAction的SnackBar'),
),
],
));
}
}

View File

@ -22,7 +22,6 @@ const String _Text0 = """
""";
class Demo extends StatefulWidget {
static const String routeName = '/components/Bar/SnackBarAction';
@ -40,7 +39,8 @@ class _DemoState extends State<Demo> {
_Text0,
SnackBarDemo.SnackBarActionDemo(),
],
docUrl: 'https://docs.flutter.io/flutter/material/SnackBarAction-class.html',
docUrl:
'https://docs.flutter.io/flutter/material/SnackBarAction-class.html',
);
}
}

View File

@ -22,8 +22,9 @@ class _TabBarDemo extends State with SingleTickerProviderStateMixin {
@override
void initState() {
super.initState();
_scrollViewController = ScrollController();
_tabController = TabController(vsync: this, length: 6);// 和下面的 TabBar.tabs 数量对应
_scrollViewController = ScrollController();
_tabController =
TabController(vsync: this, length: 6); // 和下面的 TabBar.tabs 数量对应
}
@override
@ -38,36 +39,35 @@ class _TabBarDemo extends State with SingleTickerProviderStateMixin {
// 如果省略了 leading ,但 AppBar 在带有 Drawer 的 Scaffold 中,则会插入一个 button 以打开 Drawer。
// 否则,如果最近的 Navigator 具有任何先前的 router 则会插入BackButton。
// 这种行为可以通过设置来关闭automaticallyImplyLeading 为false。在这种情况下空的 leading widget 将导致 middle/title widget 拉伸开始。
return SizedBox(
height: 500,
child: Scaffold(
appBar: AppBar( // 大量配置属性参考 SliverAppBar 示例
title: Text('TabBar'),
leading: Icon(Icons.home),
backgroundColor: Colors.amber[1000],
bottom: TabBar(
isScrollable: true,
controller: _tabController,
tabs: <Widget>[
Tab(text: "Tabs 1"),
Tab(text: "Tabs 2"),
Tab(text: "Tabs 3"),
Tab(text: "Tabs 4"),
Tab(text: "Tabs 5"),
Tab(text: "Tabs 6"),
],
return SizedBox(
height: 500,
child: Scaffold(
appBar: AppBar(
// 大量配置属性参考 SliverAppBar 示例
title: Text('TabBar'),
leading: Icon(Icons.home),
backgroundColor: Colors.amber[1000],
bottom: TabBar(
isScrollable: true,
controller: _tabController,
tabs: <Widget>[
Tab(text: "Tabs 1"),
Tab(text: "Tabs 2"),
Tab(text: "Tabs 3"),
Tab(text: "Tabs 4"),
Tab(text: "Tabs 5"),
Tab(text: "Tabs 6"),
],
),
),
),
body: TabBarView(controller: _tabController, children: <Widget>[
Text('TabsView 1'),
Text('TabsView 2'),
Text('TabsView 3'),
Text('TabsView 4'),
Text('TabsView 5'),
Text('TabsView 6'),
]),
)
);
body: TabBarView(controller: _tabController, children: <Widget>[
Text('TabsView 1'),
Text('TabsView 2'),
Text('TabsView 3'),
Text('TabsView 4'),
Text('TabsView 5'),
Text('TabsView 6'),
]),
));
}
}

View File

@ -43,7 +43,6 @@ const String _Text0 = """
- controller TabController对象
""";
class Demo extends StatefulWidget {
static const String routeName = '/components/Bar/TabBar';
@ -57,11 +56,9 @@ class _DemoState extends State<Demo> {
return WidgetDemo(
title: 'TabBar',
codeUrl: 'components/Bar/TabBar/demo.dart',
contentList: [
_Text0,
TabBarDemo()
],
docUrl: 'https://docs.flutter.io/flutter/material/SnackBarAction-class.html',
contentList: [_Text0, TabBarDemo()],
docUrl:
'https://docs.flutter.io/flutter/material/SnackBarAction-class.html',
);
}
}

View File

@ -17,8 +17,6 @@ import 'SnackBar/index.dart' as SnackBar;
import 'SnackBarAction/index.dart' as SnackBarAction;
import 'TabBar/index.dart' as TabBar;
List<WidgetPoint> widgetPoints = [
WidgetPoint(
name: 'AppBar',

View File

@ -7,7 +7,6 @@
import 'package:flutter/material.dart';
/// Checkbox 默认Card的实例
class CardFullDefault extends StatefulWidget {
const CardFullDefault() : super();
@ -16,14 +15,13 @@ class CardFullDefault extends StatefulWidget {
State<StatefulWidget> createState() => _CardFullDefault();
}
/// Card 默认的实例,有状态
class _CardFullDefault extends State {
@override
Widget build(BuildContext context) {
return Card(
// ... // 如果没有,就是不需要有状态的 StatefulWidget
);
// ... // 如果没有,就是不需要有状态的 StatefulWidget
);
}
}
@ -32,41 +30,48 @@ class CardLessDefault extends StatelessWidget {
final widget;
final parent;
const CardLessDefault([this.widget, this.parent])
: super();
const CardLessDefault([this.widget, this.parent]) : super();
@override
Widget build(BuildContext context) {
return Card(
clipBehavior:Clip.antiAlias,// 根据设置裁剪内容
color:Colors.green, // 卡片背景颜色
elevation:20.0, // 卡片的z坐标,控制卡片下面的阴影大小
margin:EdgeInsets.all(20.0),
clipBehavior: Clip.antiAlias, // 根据设置裁剪内容
color: Colors.green, // 卡片背景颜色
elevation: 20.0, // 卡片的z坐标,控制卡片下面的阴影大小
margin: EdgeInsets.all(20.0),
// margin: EdgeInsetsDirectional.only(bottom: 30.0, top: 30.0, start: 30.0),// 边距
semanticContainer:true, // 表示单个语义容器还是false表示单个语义节点的集合接受单个child但该child可以是RowColumn或其他包含子级列表的widget
semanticContainer:
true, // 表示单个语义容器还是false表示单个语义节点的集合接受单个child但该child可以是RowColumn或其他包含子级列表的widget
// shape: Border.all(
// color: Colors.indigo, width: 1.0, style: BorderStyle.solid), // 卡片材质的形状,以及边框
shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)), // 圆角
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0)), // 圆角
//borderRadius: BorderRadius.all(Radius.circular(8.0)),
child: Column( //card里面的子控件
child: Column(
//card里面的子控件
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: Icon(Icons.access_time),
title: Text('The Enchanted Nightingale',style: TextStyle(color: Colors.white, fontSize: 40.0)),
subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.',style: TextStyle(color: Colors.yellow, fontSize: 16.0)),
contentPadding: EdgeInsets.all(20.0),// item 内容内边距
title: Text('The Enchanted Nightingale',
style: TextStyle(color: Colors.white, fontSize: 40.0)),
subtitle: Text('Music by Julie Gable. Lyrics by Sidney Stein.',
style: TextStyle(color: Colors.yellow, fontSize: 16.0)),
contentPadding: EdgeInsets.all(20.0), // item 内容内边距
),
ButtonTheme.bar( // make buttons use the appropriate styles for cards
ButtonTheme.bar(
// make buttons use the appropriate styles for cards
child: ButtonBar(
children: <Widget>[
FlatButton(
child: const Text('BUY TICKETS',style: TextStyle(color: Colors.black, fontSize: 14.0)),
onPressed: () { },
child: const Text('BUY TICKETS',
style: TextStyle(color: Colors.black, fontSize: 14.0)),
onPressed: () {},
),
FlatButton(
child: const Text('LISTEN',style: TextStyle(color: Colors.black, fontSize: 14.0)),
onPressed: () { },
child: const Text('LISTEN',
style: TextStyle(color: Colors.black, fontSize: 14.0)),
onPressed: () {},
),
],
),

View File

@ -10,19 +10,15 @@ import 'package:flutter/material.dart';
import 'package:flutter_go/components/widget_demo.dart';
import './demo.dart' as CardDemo;
const String _Text0 =
"""### **简介**
const String _Text0 = """### **简介**
> Card “卡片”
- 卡片用于表示一些相关信息,例如相册,地理位置,用餐,联系方式等
""";
const String _Text1 =
"""### **基本用法**
const String _Text1 = """### **基本用法**
> 此示例显示了创建卡片窗口组件,其中显示了相册信息和两个操作
""";
class Demo extends StatefulWidget {
static const String routeName = '/components/Card/Card';
@ -42,7 +38,6 @@ class _DemoState extends State<Demo> {
}
}
/// 所有的 Card widget
/// context: 运行上下文
/// that: 指向有状态的 StatefulWidget
@ -55,4 +50,3 @@ List allDomes(BuildContext context, _DemoState that) {
CardDemo.CardLessDefault()
];
}

View File

@ -31,11 +31,10 @@ class _DemoState extends State<Demo> {
contentList: [
content0,
content1,
ChipDemo(),
ChipDemo(),
],
codeUrl: 'components/Chip/Chip/demo.dart',
docUrl:
'https://docs.flutter.io/flutter/material/Chip-class.html',
docUrl: 'https://docs.flutter.io/flutter/material/Chip-class.html',
title: 'Chip');
}
}

View File

@ -15,9 +15,11 @@ class _ChipThemeDemoState extends State<ChipThemeDemo> {
@override
Widget build(BuildContext context) {
return ChipTheme(
data: ChipTheme.of(context).copyWith(backgroundColor:Colors.red.shade800 ),
data:
ChipTheme.of(context).copyWith(backgroundColor: Colors.red.shade800),
child: ChoiceChip(
padding: EdgeInsets.only(left: 100.0,right: 100.0,top: 10.0,bottom: 10.0),
padding:
EdgeInsets.only(left: 100.0, right: 100.0, top: 10.0, bottom: 10.0),
label: Text('down'),
labelStyle: TextStyle(color: Colors.white),
onSelected: (bool value) {
@ -31,29 +33,28 @@ class _ChipThemeDemoState extends State<ChipThemeDemo> {
}
}
// Widget build(BuildContext context) {
// Widget build(BuildContext context) {
// return Container(
// child: ChipTheme(
// data: ChipThemeData(
// backgroundColor: Colors.red.shade500,
// //描述颜色对比度(暗,亮,设置固定值)
// brightness : Brightness.dark,
// deleteIconColor: Colors.red.shade200,
// //背景颜色,表示它被禁用
// disabledColor: Colors.grey.shade50,
// labelPadding: EdgeInsets.all(10.0),
// labelStyle: TextStyle(fontSize: 15.0,fontStyle: FontStyle.italic),
// padding: EdgeInsets.all(2.0),
// //用于另一种chip widget 标签样式
// secondaryLabelStyle: TextStyle(fontSize: 20.0,fontStyle: FontStyle.normal),
// selectedColor: Colors.yellow,
// //表示已经选中度颜色
// secondarySelectedColor: Colors.black
// // shape:
// ),
// ),
// );
// return Container(
// child: ChipTheme(
// data: ChipThemeData(
// backgroundColor: Colors.red.shade500,
// //描述颜色对比度(暗,亮,设置固定值)
// brightness : Brightness.dark,
// deleteIconColor: Colors.red.shade200,
// //背景颜色,表示它被禁用
// disabledColor: Colors.grey.shade50,
// labelPadding: EdgeInsets.all(10.0),
// labelStyle: TextStyle(fontSize: 15.0,fontStyle: FontStyle.italic),
// padding: EdgeInsets.all(2.0),
// //用于另一种chip widget 标签样式
// secondaryLabelStyle: TextStyle(fontSize: 20.0,fontStyle: FontStyle.normal),
// selectedColor: Colors.yellow,
// //表示已经选中度颜色
// secondarySelectedColor: Colors.black
// // shape:
// ),
// ),
// );
// }
// }

View File

@ -32,11 +32,10 @@ class _DemoState extends State<Demo> {
contentList: [
content0,
content1,
ChipThemeDemo(),
ChipThemeDemo(),
],
codeUrl: 'components/Chip/ChipTheme/demo.dart',
docUrl:
'https://docs.flutter.io/flutter/material/ChipTheme-class.html',
docUrl: 'https://docs.flutter.io/flutter/material/ChipTheme-class.html',
title: 'ChipTheme');
}
}

Some files were not shown because too many files have changed in this diff Show More