feat(migrate): 将之前写好的部件迁移了过来

This commit is contained in:
李东云
2022-02-21 14:51:53 +08:00
parent d16e94876b
commit 2c81720df3
15 changed files with 907 additions and 82 deletions

25
lib/app.dart Normal file
View File

@@ -0,0 +1,25 @@
import 'package:flutter/material.dart';
import 'layout/LayoutScaffold.dart';
///
/// 应用页
///
class App extends StatefulWidget {
const App({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() => _AppState();
}
class _AppState extends State<App> {
@override
Widget build(BuildContext context) {
// TODO: implement build
return LayoutScaffold(
appBar: AppBar(
title: const Text('应用'),
),
body: null,
);
}
}

View File

@@ -0,0 +1,103 @@
import 'package:flutter/material.dart';
import 'global.dart';
import 'package:bistro/mine/login.dart';
typedef ACFCallback = Future Function(Map userInfo);
///
/// 登录状态检查
///
class AccessControlFilter extends StatefulWidget {
/// 头部
final AppBar? appBar;
/// 标题
final String? title;
/// 内容组件
final Widget child;
/// 未登录的显示
final Widget? didNotLoginWidget;
const AccessControlFilter({
required Key key,
this.appBar,
this.title,
required this.child,
this.didNotLoginWidget,
}) : super(key: key);
@override
_AccessControlFilterState createState() => _AccessControlFilterState();
}
class _AccessControlFilterState extends State<AccessControlFilter> {
/// 登录状态
bool _isLogin = false;
@override
void initState() {
super.initState();
_updateUserState();
}
@override
void didUpdateWidget(AccessControlFilter oldWidget) {
super.didUpdateWidget(oldWidget);
_updateUserState();
}
/// 更新用户信息
void _updateUserState({data}) {
// final Map userInfo = data != null ? data : UserInfo().userInfo;
// final bool isLogin = userInfo != null && userInfo.length != 0;
// setState(() {
// _isLogin = isLogin;
// });
}
/// 未登录的显示
Widget? _didNotLoginWidget() {
// 如果传入的未登录情况下显示的组件,则采用传入的
if (widget.didNotLoginWidget != null) return widget.didNotLoginWidget;
// 缺省的未登录情况下的显示
return Center(
child: RaisedButton(
color: Colors.blueAccent,
textTheme: ButtonTextTheme.primary,
child: const Text('请先登录'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) {
return Login(
successCallback: (Map data) {
_updateUserState(data: data);
printWhenDebug('登录成功');
},
key: widget.key ?? const Key('acf'),
);
},
),
);
},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: widget.appBar ??
AppBar(
centerTitle: true,
title: Text(widget.title ?? ""),
),
body: _isLogin ? widget.child : _didNotLoginWidget(),
);
}
}

112
lib/common/global.dart Normal file
View File

@@ -0,0 +1,112 @@
import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
// 提供五套可选主题色
const _themes = <MaterialColor>[
Colors.blue,
Colors.cyan,
Colors.teal,
Colors.green,
Colors.red,
];
///
/// 当调试模式打开时打印
///
void printWhenDebug(Object object) {
if (Global.debug) {
if (kDebugMode) {
print(object);
}
}
}
///
/// 当前环境
///
enum Env {
dev,
pro,
}
class Global {
static SharedPreferences? _prefs;
static Dio? dio;
static Map profile = {};
static bool debug = false;
///
/// 当前环境
///
static const Env env = Env.dev;
///
/// 根域名
///
static const Map baseUrlList = {
Env.dev: 'http://safe.doylee.cn',
// Env.dev: 'http://192.168.31.189/campus_safety',
Env.pro: 'http://10.111.2.158',
};
///
/// 接口根路由
///
static String baseUrl = baseUrlList[env];
// 网络缓存对象
static DioCacheManager netCache = DioCacheManager(
CacheConfig(
baseUrl: baseUrl,
),
);
// 可选的主题列表
static List<MaterialColor> get themes => _themes;
// 是否为release版
static bool get isRelease => bool.fromEnvironment("dart.vm.product");
//初始化全局信息会在APP启动时执行
static Future init() async {
dio = Dio();
// 添加拦截器
dio?.interceptors.add(netCache.interceptor);
// 初始化用户信息
_prefs = await SharedPreferences.getInstance();
var _profile = _prefs?.getString("user_info");
if (_profile != null) {
try {
if (kDebugMode) {
print('开始读取用户信息...');
}
profile = jsonDecode(_profile);
if (kDebugMode) {
print('用户信息读取成功');
}
} catch (e) {
if (kDebugMode) {
print(e);
}
}
}
}
// 持久化Profile信息
static Future<bool>? saveProfile({required Map userInfo}) {
profile = userInfo;
final userJson = jsonEncode(userInfo);
return _prefs?.setString("user_info", userJson);
}
/// 读取持久化Profile信息
static Future<Map> getProfile() {
return jsonDecode(_prefs?.getString("user_info") ?? '{}');
}
}

View File

@@ -0,0 +1,34 @@
import 'package:flutter/material.dart';
class LayoutScaffold extends StatelessWidget {
final AppBar appBar;
final Widget? body;
const LayoutScaffold({
Key? key,
required this.appBar,
this.body,
}) : super(key: key);
@override
Widget build(BuildContext context) {
Text title = appBar.title as Text;
return Scaffold(
appBar: PreferredSize(
child: AppBar(
title: Text(
title.data ?? '',
style: const TextStyle(
fontSize: 30,
),
),
centerTitle: true,
bottom: appBar.bottom,
),
preferredSize: appBar.preferredSize,
),
body: body,
);
}
}

111
lib/life.dart Normal file
View File

@@ -0,0 +1,111 @@
import 'package:flutter/material.dart';
import 'package:bistro/layout/LayoutScaffold.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
class Life extends StatelessWidget {
const Life({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return LayoutScaffold(
appBar: AppBar(
title: const Text('讨论'),
bottom: PreferredSize(
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
IconButton(
icon: Icon(
Icons.add,
color: Theme.of(context).primaryColor,
),
onPressed: () {},
)
],
),
preferredSize: const Size.fromHeight(50),
),
),
body: MasonryGridView.count(
crossAxisCount: 2,
itemBuilder: cardBuilder,
padding: const EdgeInsets.only(top: 23),
mainAxisSpacing: 12.0,
crossAxisSpacing: 3.0,
),
);
}
Widget cardBuilder(BuildContext context, int index) {
return Card(
elevation: 4,
color: Theme.of(context).backgroundColor,
child: Column(
children: <Widget>[
InkWell(
child: Image.asset(
[
'res/assets/images/logo.jpg',
'res/assets/images/dololo.jpg',
'res/assets/images/Spider-Man.jpg',
'res/assets/images/ch4o5.png',
'res/assets/images/fire.jpg',
'res/assets/images/tiefutu.jpg',
'res/assets/images/big-dog.jpg',
][index % 7],
),
onTap: () {},
),
ListTile(
title: const Text(
'苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉苏月桉',
maxLines: 2,
style: TextStyle(
fontSize: 13,
),
overflow: TextOverflow.visible,
),
isThreeLine: true,
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
InkWell(
child: Column(
children: <Widget>[
Row(
children: <Widget>[
Icon(
Icons.person_outline,
color: Theme.of(context).primaryColor,
),
Text(
'苏月桉苏月桉苏月桉苏月苏月苏月苏月'.substring(0, 11),
overflow: TextOverflow.clip,
style: const TextStyle(
fontSize: 11,
),
),
],
),
],
),
onTap: () {},
),
InkWell(
child: Icon(
[
Icons.favorite_border,
Icons.favorite,
][index % 2],
color: Theme.of(context).primaryColor,
),
onTap: () {},
),
],
),
)
],
),
);
}
}

View File

@@ -1,115 +1,179 @@
import 'package:flutter/material.dart';
// import 'package:flutter_localizations/flutter_localizations.dart';
import 'app.dart';
import 'life.dart';
import 'news.dart';
import 'mine.dart';
import 'router/router.dart';
void main() {
runApp(const MyApp());
}
//import 'common/access_control_filter.dart';
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
void main() => runApp(const Bistro());
class Bistro extends StatelessWidget {
const Bistro({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
title: '小酒馆',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
fontFamily: "SongTiHeavy",
primaryColor: const Color(0xFFff857a),
primaryColorDark: Colors.black54,
backgroundColor: const Color(0xFFFFF7F8),
bottomAppBarColor: const Color(0xFFFFF7F8),
appBarTheme: const AppBarTheme(color: Colors.white), colorScheme: ColorScheme.fromSwatch(primarySwatch: Colors.amber).copyWith(secondary: Colors.deepOrangeAccent)),
home: const BistroFrame(title: 'Flutter Demo Home Page', ),
// 国际化
// localizationsDelegates: [
// GlobalMaterialLocalizations.delegate,
// GlobalWidgetsLocalizations.delegate,
// ],
// supportedLocales: const [
// Locale('zh', 'CN'),
// ],
// locale: const Locale('zh'),
// 路由
routes: router,
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
class BistroFrame extends StatefulWidget {
const BistroFrame({Key? key,required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
_BistroFrameState createState() => _BistroFrameState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
class _BistroFrameState extends State<BistroFrame> {
late Widget _body;
int _index = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
void initData() {
//页面初始化时要干的事
_body = IndexedStack(
children: <Widget>[
const App(),
Life(),
const App(),
News(),
Mine(),
],
index: _index,
);
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
initData();
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also a layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
body: _body,
bottomNavigationBar: BottomAppBar(
shape: const CircularNotchedRectangle(),
child: Row(
children: <Widget>[
const Text(
'You have pushed the button this many times:',
bottomAppBarItem(
index: 0,
icon: Icons.apps,
title: '应用',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
bottomAppBarItem(
index: 1,
icon: Icons.forum,
title: '讨论',
),
bottomAppBarItem(
index: 2,
isShow: false,
),
bottomAppBarItem(
index: 3,
icon: Icons.business,
title: '资讯',
),
bottomAppBarItem(
index: 4,
icon: Icons.perm_identity,
title: '我的',
),
],
mainAxisAlignment: MainAxisAlignment.spaceAround,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
backgroundColor: Theme.of(context).backgroundColor,
onPressed: () => {},
child: Icon(
Icons.search,
color: Theme.of(context).primaryColor,
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
Widget bottomAppBarItem({
required int index, // 序列
IconData? icon, // 图标
String? title, // 标签
bool isShow = true, // 是否需要显示
}) {
//设置默认未选中的状态
double size = 13;
Color color = Colors.black87;
if (_index == index) {
//选中的话
size = 15;
color = Theme.of(context).primaryColor;
}
TextStyle style = TextStyle(
fontSize: size,
);
Widget child;
if (isShow) {
child = GestureDetector(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
width: 25.0,
height: 23.0,
child: Icon(
icon,
color: color,
size: size * 1.7,
),
),
Text(
title!,
style: style,
)
],
),
onTap: () {
if (_index != index) {
setState(() {
_index = index;
});
}
},
);
} else {
child = Container();
}
//构造返回的Widget
return SizedBox(
height: 49,
width: MediaQuery.of(context).size.width / 5,
child: child,
);
}
}

20
lib/mine.dart Normal file
View File

@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
import 'layout/LayoutScaffold.dart';
///
/// 【我的】页
///
class Mine extends StatelessWidget {
const Mine({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return LayoutScaffold(
appBar: AppBar(
title: const Text('我的'),
),
);
}
}

35
lib/mine/login.dart Normal file
View File

@@ -0,0 +1,35 @@
import 'package:flutter/material.dart';
///
/// 登录页
///
class Login extends StatefulWidget {
final Function successCallback;
const Login({
required Key key,
required this.successCallback,
}) : super(key: key);
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<Login> {
@override
Widget build(BuildContext context) {
// TODO: implement build
return Scaffold(
appBar: AppBar(
title: const Text(
'登录',
style: TextStyle(
fontSize: 30,
),
),
centerTitle: true,
),
body: const Text('登录'),
);;
}
}

15
lib/news.dart Normal file
View File

@@ -0,0 +1,15 @@
import 'package:flutter/material.dart';
import 'layout/LayoutScaffold.dart';
class News extends StatelessWidget {
@override
Widget build(BuildContext context) {
return LayoutScaffold(
appBar: AppBar(
title: const Text('资讯'),
),
body: null,
);
}
}

5
lib/router/router.dart Normal file
View File

@@ -0,0 +1,5 @@
import 'package:bistro/app.dart';
var router = {
'/app': (context) => App(), //应用页
};