Browse Source

完成wel

liuyuqi-dellpc 2 years ago
parent
commit
123e935e73

+ 1 - 1
android/app/build.gradle

@@ -35,7 +35,7 @@ android {
     defaultConfig {
         // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
         applicationId "me.yoqi.flutter.flutter_tracker"
-        minSdkVersion 16
+        minSdkVersion 19
         targetSdkVersion 30
         versionCode flutterVersionCode.toInteger()
         versionName flutterVersionName

BIN
assets/images/home.jpg


+ 11 - 7
lib/dio/api.dart

@@ -1,9 +1,13 @@
-class Api {
+import 'package:flutter_tracker/model/user_model.dart';
+
+abstract class Api {
   static const String _host = "http://flutter.yoqi.me/API/flutter_tracker";
-  static String login = _host + "/login";
-  static String logout = _host + "/logout";
-  static String register = _host + "/register";
-  static String getUserInfo = _host + "/getUserInfo";
-  static String uploadImg = _host + "/uploadImg";
-  static String uploadTrack = _host + "/uploadTrack";
+  static String loginUrl = _host + "/login";
+  static String logoutUrl = _host + "/logout";
+  static String registerUrl = _host + "/register";
+  static String getUserInfoUrl = _host + "/getUserInfo";
+  static String uploadImgUrl = _host + "/uploadImg";
+  static String uploadTrackUrl = _host + "/uploadTrack";
+
+  Future<UserModel> login(String username, String password);
 }

+ 9 - 0
lib/dio/local_api.dart

@@ -0,0 +1,9 @@
+import 'package:flutter_tracker/dio/api.dart';
+import 'package:flutter_tracker/model/user_model.dart';
+
+class LocalApi extends Api {
+  @override
+  Future<UserModel> login(String username, String password) {
+    return null;
+  }
+}

+ 4 - 4
lib/dio/login_dao.dart

@@ -7,26 +7,26 @@ class LoginDao {
 
   static Future<UserModel> login(String username, String password) async {
     params.addAll({"username": username, "password": password});
-    Response response = await Dio().post(Api.login, queryParameters: params);
+    Response response = await Dio().post(Api.loginUrl, queryParameters: params);
     return UserModel.fromJson(response.data);
   }
 
   static Future<bool> logout(String token) async {
     params.addAll({"token": token});
-    Response response = await Dio().get(Api.logout);
+    Response response = await Dio().get(Api.logoutUrl);
     return true;
   }
 
   static Future<UserModel> register(String username, String password) async {
     params.addAll({"username": username, "password": password});
-    Response response = await Dio().post(Api.register, queryParameters: params);
+    Response response = await Dio().post(Api.registerUrl, queryParameters: params);
     return UserModel.fromJson(response.data);
   }
 
   static Future<UserModel> getUserInfo(String token) async {
     params.addAll({"token": token});
     Response response =
-        await Dio().get(Api.getUserInfo, queryParameters: params);
+        await Dio().get(Api.getUserInfoUrl, queryParameters: params);
     return UserModel.fromJson(response.data);
   }
 }

+ 9 - 0
lib/dio/remote_api.dart

@@ -0,0 +1,9 @@
+import 'package:flutter_tracker/model/user_model.dart';
+
+import 'api.dart';
+
+class RemoteApi extends Api {
+  Future<UserModel> login(String username, String password) {
+    return null;
+  }
+}

+ 2 - 2
lib/dio/track_dao.dart

@@ -9,7 +9,7 @@ class TrackDao {
       String token, String filePath, String fileName) async {
     params.addAll({"token": token, "filePath": filePath, "fileName": fileName});
 
-    await Dio().post(Api.uploadImg, queryParameters: params).then((response) {
+    await Dio().post(Api.uploadImgUrl, queryParameters: params).then((response) {
       return SubmitModel.fromJson(response.data);
     });
     return null;
@@ -24,7 +24,7 @@ class TrackDao {
       "health": health
     });
 
-    await Dio().post(Api.uploadTrack, queryParameters: params).then((response) {
+    await Dio().post(Api.uploadTrackUrl, queryParameters: params).then((response) {
       return SubmitModel.fromJson(response.data);
     });
     return null;

+ 4 - 3
lib/index_page.dart

@@ -13,7 +13,9 @@ class IndexPage extends StatefulWidget {
 class _IndexPageState extends State<IndexPage> {
   int navIndex = 0;
   List<Widget> pages = [
-    const HomePage(),
+    HomePage(url: "https://xw.qq.com/act/qgfeiyan"),
+    //http://m.look.360.cn/subject/400?sign=360_6aa05217&stab=0
+    // https://www.ipe.org.cn/MapGZBD/XQMap.html
     const TrackPage(),
     const MinePage(),
   ];
@@ -35,8 +37,7 @@ class _IndexPageState extends State<IndexPage> {
         currentIndex: navIndex,
         items: const [
           BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
-          BottomNavigationBarItem(
-              icon: Icon(Icons.art_track), label: "追踪"),
+          BottomNavigationBarItem(icon: Icon(Icons.art_track), label: "追踪"),
           BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
         ],
         onTap: (index) {

+ 20 - 4
lib/main.dart

@@ -1,13 +1,28 @@
 import 'package:flutter/material.dart';
 import 'package:flutter_screenutil/flutter_screenutil.dart';
+import 'package:flutter_tracker/pages/login_page.dart';
 import 'package:flutter_tracker/pages/welcome_page.dart';
+import 'package:shared_preferences/shared_preferences.dart';
 
-void main() {
-  runApp(const MyApp());
+import 'index_page.dart';
+import 'model/config.dart';
+
+void main() async {
+  WidgetsFlutterBinding.ensureInitialized();
+  Config.initConfig();
+  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
+  bool isLogin = sharedPreferences.getBool("isLogin");
+  isLogin ??= false;
+
+  runApp(MyApp(
+    isLogin: isLogin,
+  ));
 }
 
 class MyApp extends StatelessWidget {
-  const MyApp({Key key}) : super(key: key);
+  bool isLogin = false;
+
+  MyApp({Key key, this.isLogin}) : super(key: key);
 
   // This widget is the root of your application.
   @override
@@ -20,7 +35,8 @@ class MyApp extends StatelessWidget {
           primarySwatch: Colors.blue,
         ),
         debugShowCheckedModeBanner: false,
-        home: const WelComePage(),
+        // home: isLogin ? HomePage(url: "https://baidu.com") : LoginPage(),
+        home: isLogin ? IndexPage() : WelComePage(),
       ),
     );
   }

+ 19 - 1
lib/model/config.dart

@@ -1,6 +1,24 @@
 import 'package:flutter/material.dart';
+import 'package:flutter_tracker/dio/api.dart';
+import 'package:flutter_tracker/dio/remote_api.dart';
+import 'package:shared_preferences/shared_preferences.dart';
 
-class Config {}
+class Config {
+  static SharedPreferences pref;
+  static bool isLogin = false;
+
+  // 通过这个来控制全局环境变量
+  static Api apiClient;
+
+  static initConfig() async {
+    if (pref == null) {
+      pref = await SharedPreferences.getInstance();
+    }
+    if (apiClient == null) {
+      apiClient = RemoteApi();
+    }
+  }
+}
 
 class ThemeColor {
   static const Color appBg = Color(0xfff5f6f7);

+ 43 - 2
lib/pages/home_page.dart

@@ -1,15 +1,56 @@
 import 'package:flutter/material.dart';
+import 'package:webview_flutter/webview_flutter.dart';
 
 class HomePage extends StatefulWidget {
-  const HomePage({Key key}) : super(key: key);
+  String url;
+
+  HomePage({Key key, this.url}) : super(key: key);
 
   @override
   _HomePageState createState() => _HomePageState();
 }
 
 class _HomePageState extends State<HomePage> {
+  bool _isLoading = true;
+
   @override
   Widget build(BuildContext context) {
-    return const Center(child: Text('Home'));
+    return Stack(
+      children: <Widget>[
+        WebView(
+          initialUrl: widget.url,
+          onWebViewCreated: (WebViewController web) {
+            web.canGoBack().then((res) {
+//                print(res); // 是否能返回上一级
+            });
+            web.currentUrl().then((url) {
+//                print(url); // 返回当前url
+            });
+            web.canGoForward().then((res) {
+//                print(res); //是否能前进
+            });
+          },
+          onPageFinished: (String value) {
+            // 返回当前url
+//              print(value);
+            setState(() {
+              _isLoading = false;
+            });
+          },
+        ),
+        _loading()
+      ],
+    );
+  }
+
+  _loading() {
+    return _isLoading == true
+        ? Container(
+            decoration: BoxDecoration(color: Colors.white),
+            child: Center(
+              child: CircularProgressIndicator(),
+            ),
+          )
+        : Text('');
   }
 }

+ 10 - 4
lib/pages/login_page.dart

@@ -1,4 +1,7 @@
 import 'package:flutter/material.dart';
+import 'package:flutter_tracker/dio/login_dao.dart';
+import 'package:flutter_tracker/model/config.dart';
+import 'package:flutter_tracker/model/user_model.dart';
 import 'package:shared_preferences/shared_preferences.dart';
 
 class LoginPage extends StatefulWidget {
@@ -87,10 +90,13 @@ class _LoginPageState extends State<LoginPage> {
   void login() async {
     if (_formKey.currentState.validate()) {
       _formKey.currentState.save();
-      SharedPreferences prefs = await SharedPreferences.getInstance();
-      prefs.setString('username', _username);
-      prefs.setString('password', _password);
-      Navigator.of(context).pushReplacementNamed('/home');
+      UserModel userModel = await LoginDao.login(_username, _password);
+      if (userModel.username == "") {
+        Config.pref.setString('username', _username);
+        Config.pref.setString('password', _password);
+        Config.pref.setBool('isLogin', true);
+        Navigator.of(context).pushReplacementNamed('/home');
+      } else {}
     }
   }
 }

+ 15 - 2
lib/pages/mine_page.dart

@@ -10,8 +10,21 @@ class MinePage extends StatefulWidget {
 class _MinePageState extends State<MinePage> {
   @override
   Widget build(BuildContext context) {
-   return Container(
-      child: Center(child: Text('Mine')),
+    return Scaffold(
+      body: Column(
+        // mainAxisAlignment: MainAxisAlignment.center,
+        // crossAxisAlignment: CrossAxisAlignment.center,
+        // verticalDirection: VerticalDirection.down,
+        children: [
+          Image.asset(
+            "assets/images/home.jpg",
+            height: 50,
+            width: 50,
+          ),
+          Text("网小儿"),
+          Text("2021-11-25 10:10:10"),
+        ],
+      ),
     );
   }
 }

+ 121 - 1
lib/pages/register_page.dart

@@ -1,4 +1,8 @@
 import 'package:flutter/material.dart';
+import 'package:flutter_tracker/dio/login_dao.dart';
+import 'package:flutter_tracker/model/user_model.dart';
+import 'package:flutter_tracker/routes/routes.dart';
+import 'package:shared_preferences/shared_preferences.dart';
 
 class RegisterPage extends StatefulWidget {
   const RegisterPage({Key key}) : super(key: key);
@@ -8,8 +12,124 @@ class RegisterPage extends StatefulWidget {
 }
 
 class _RegisterPageState extends State<RegisterPage> {
+  //用户名密码控制器
+  final TextEditingController _controllerUsn = TextEditingController();
+  final TextEditingController _controllerPwd = TextEditingController();
+  final TextEditingController _controllerRepwd = TextEditingController();
+  final GlobalKey _formKey = GlobalKey<FormState>();
+
+  String _userName = "";
+  String _pwd = "";
+
   @override
   Widget build(BuildContext context) {
-    return Container();
+
+    return Scaffold(
+      appBar: AppBar(
+        title: Text("注册账号"),
+      ),
+      body: Padding(
+        padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
+        child: Form(
+          autovalidateMode: AutovalidateMode.always, key: _formKey, //开启自动校验
+          child: ListView(
+            children: [
+              TextFormField(
+                autofocus: true,
+                controller: _controllerUsn,
+                decoration: const InputDecoration(
+                    labelText: "用户名",
+                    hintText: "用户名或邮箱",
+                    icon: Icon(Icons.person)),
+                // 校验用户名
+                validator: (v) {
+                  return v.trim().length > 0 ? null : "用户名不能为空";
+                },
+                onChanged: (inputStr) {
+                  _userName = inputStr;
+                },
+              ),
+              TextFormField(
+                  controller: _controllerPwd,
+                  decoration: const InputDecoration(
+                      labelText: "密码",
+                      hintText: "您的登录密码",
+                      icon: Icon(Icons.lock)),
+                  obscureText: true,
+                  //校验密码
+                  validator: (v) {
+                    return v.trim().length > 5 ? null : "密码不能少于6位";
+                  }),
+              TextFormField(
+                controller: _controllerRepwd,
+                decoration: const InputDecoration(
+                    labelText: "确认密码",
+                    hintText: "确认登录密码",
+                    icon: Icon(Icons.lock)),
+                obscureText: true,
+                //校验密码
+                validator: (v) {
+                  return v.trim().length > 5 ? null : "密码不能少于6位";
+                },
+                onChanged: (inputStr) {
+                  _pwd = inputStr;
+                },
+              ),
+              // 登录按钮
+              Padding(
+                padding: const EdgeInsets.only(top: 28.0),
+                child: Row(
+                  children: <Widget>[
+                    Expanded(
+                      child: RaisedButton(
+                        padding: EdgeInsets.all(15.0),
+                        child: Text("注册"),
+                        color: Theme.of(context).primaryColor,
+                        textColor: Colors.white,
+                        onPressed: () {
+                          register(_userName, _pwd);
+                        },
+                      ),
+                    ),
+                  ],
+                ),
+              )
+            ],
+          ),
+        ),
+      ),
+    );
   }
+
+  //注册
+  void register(String userName, String password) async {
+    // UserModel loginEntity = await LoginDao.register(userName, password);
+    //注册成功挑战到登录界面
+    // if (loginEntity.userModel != null) {
+    //   DialogUtil.buildToast(loginEntity.msgModel.msg);
+    //   Navigator.of(context).pushNamed(Routes.loginPage);
+    // } else {
+    //   DialogUtil.buildToast(loginEntity.msgModel.msg);
+    // }
+  }
+
+  // // //保存用户信息
+  // void saveUserInfo(UserModel userModel) async {
+  //   SharedPreferences prefs = await SharedPreferences.getInstance();
+  //   prefs.setString("token", userModel.token);
+  //   AppConfig.isUser = false;
+  //   AppConfig.token = userModel.token;
+  //   loadUserInfo(userModel.token);
+  // }
+  //
+  // void loadUserInfo(String token) async {
+  //   UserEntity entity = await UserDao.fetch(token);
+  //   if (entity?.userInfoModel != null) {
+  //     DialogUtil.buildToast("登录成功~");
+  //     Navigator.pop(context);
+  //     // eventBus.fire(UserLoggedInEvent("sucuss"));
+  //   } else {
+  //     DialogUtil.buildToast(entity.msgModel.msg);
+  //   }
+  // }
 }

+ 86 - 84
lib/pages/welcome_page.dart

@@ -14,100 +14,102 @@ class WelComePage extends StatefulWidget {
 class _WelComePageState extends State<WelComePage> {
   @override
   Widget build(BuildContext context) {
-    return Stack(
-      children: [
-        Container(
-          child: Image.asset(
-            "assets/images/home.jpg",
-            fit: BoxFit.cover,
-            width: double.infinity,
-            height: double.infinity,
+    return Scaffold(
+      body: Stack(
+        children: [
+          Container(
+            child: Image.asset(
+              "assets/images/home.jpg",
+              fit: BoxFit.cover,
+              width: double.infinity,
+              height: double.infinity,
+            ),
           ),
-        ),
-        Positioned(
-          bottom: 80,
-          child: Container(
-            width: MediaQuery.of(context).size.width,
-            alignment: Alignment.center,
-            child: Row(
-              mainAxisAlignment: MainAxisAlignment.center,
-              children: [
-                Container(
-                  width: 150,
-                  child: InkWell(
-                    onTap: () {
-                      // 登录
-                      Navigator.of(context).push(
-                          MaterialPageRoute(builder: (context) => LoginPage()));
-                    },
-                    child: Container(
-                      width: double.infinity,
-                      height: AppUtil.height(100),
-                      padding: EdgeInsets.only(
-                          right: AppUtil.width(20), left: AppUtil.width(20)),
-                      decoration: BoxDecoration(
-                          gradient: LinearGradient(colors: [
-                            ThemeColor.loignColor,
-                            ThemeColor.loignColor
-                          ]),
-                          borderRadius: BorderRadius.circular(10),
-                          boxShadow: [
-                            BoxShadow(
-                              offset: Offset(1.0, 5.0),
-                              color: ThemeColor.loignColor,
-                              blurRadius: 5.0,
-                            )
-                          ]),
-                      child: Center(
-                        child: Text(
-                          "登录",
-                          style: TextStyle(fontSize: 20, color: Colors.white),
+          Positioned(
+            bottom: 100,
+            child: Container(
+              width: MediaQuery.of(context).size.width,
+              alignment: Alignment.center,
+              child: Row(
+                mainAxisAlignment: MainAxisAlignment.center,
+                children: [
+                  Container(
+                    width: 150,
+                    child: InkWell(
+                      onTap: () {
+                        // 登录
+                        Navigator.of(context).push(MaterialPageRoute(
+                            builder: (context) => LoginPage()));
+                      },
+                      child: Container(
+                        width: double.infinity,
+                        height: AppUtil.height(100),
+                        padding: EdgeInsets.only(
+                            right: AppUtil.width(20), left: AppUtil.width(20)),
+                        decoration: BoxDecoration(
+                            gradient: const LinearGradient(colors: [
+                              ThemeColor.loignColor,
+                              ThemeColor.loignColor
+                            ]),
+                            borderRadius: BorderRadius.circular(10),
+                            boxShadow: const [
+                              BoxShadow(
+                                offset: Offset(1.0, 5.0),
+                                color: ThemeColor.loignColor,
+                                blurRadius: 5.0,
+                              )
+                            ]),
+                        child: const Center(
+                          child: Text(
+                            "登录",
+                            style: TextStyle(fontSize: 20, color: Colors.white),
+                          ),
                         ),
                       ),
                     ),
                   ),
-                ),
-                Container(
-                  width: 150,
-                  child: InkWell(
-                    onTap: () {
-                      //注册
-                      Navigator.of(context).push(MaterialPageRoute(
-                          builder: (context) => RegisterPage()));
-                    },
-                    child: Container(
-                      margin: EdgeInsets.only(left: 20.0),
-                      width: double.infinity,
-                      height: AppUtil.height(100),
-                      padding: EdgeInsets.only(
-                          right: AppUtil.width(20), left: AppUtil.width(20)),
-                      decoration: BoxDecoration(
-                          gradient: LinearGradient(colors: [
-                            ThemeColor.loignColor,
-                            ThemeColor.loignColor
-                          ]),
-                          borderRadius: BorderRadius.circular(10),
-                          boxShadow: [
-                            BoxShadow(
-                              offset: Offset(1.0, 5.0),
-                              color: ThemeColor.loignColor,
-                              blurRadius: 5.0,
-                            )
-                          ]),
-                      child: Center(
-                        child: Text(
-                          "注册",
-                          style: TextStyle(fontSize: 20, color: Colors.white),
+                  Container(
+                    width: 200,
+                    child: InkWell(
+                      onTap: () {
+                        //注册
+                        Navigator.of(context).push(MaterialPageRoute(
+                            builder: (context) => RegisterPage()));
+                      },
+                      child: Container(
+                        margin: EdgeInsets.only(left: 20.0),
+                        width: double.infinity,
+                        height: AppUtil.height(100),
+                        padding: EdgeInsets.only(
+                            right: AppUtil.width(20), left: AppUtil.width(20)),
+                        decoration: BoxDecoration(
+                            gradient: const LinearGradient(colors: [
+                              ThemeColor.loignColor,
+                              ThemeColor.loignColor
+                            ]),
+                            borderRadius: BorderRadius.circular(10),
+                            boxShadow: const [
+                              BoxShadow(
+                                offset: Offset(1.0, 5.0),
+                                color: ThemeColor.loignColor,
+                                blurRadius: 5.0,
+                              )
+                            ]),
+                        child: const Center(
+                          child: Text(
+                            "新用户注册",
+                            style: TextStyle(fontSize: 20, color: Colors.white),
+                          ),
                         ),
                       ),
                     ),
                   ),
-                ),
-              ],
+                ],
+              ),
             ),
-          ),
-        )
-      ],
+          )
+        ],
+      ),
     );
   }
 }

+ 48 - 16
lib/routes/routes.dart

@@ -11,21 +11,53 @@ import 'package:flutter_tracker/pages/track_page.dart';
 import 'package:flutter_tracker/pages/welcome_page.dart';
 
 class Routes {
-  Map routes = {
-    "/home": (context) => HomePage(),
-    "/track": (context) => TrackPage(),
-    "/mine": (context) => MinePage(),
-    "/about": (context) => AboutPage(),
-    "/help": (context) => HelpPage(),
-    "/login": (context) => LoginPage(),
-    "/register": (context) => RegisterPage(),
-    "/submit": (context) => SubmitPage(),
-    "/welcome": (context) => WelComePage(),
-  };
+  static const String homePage = "/home";
+  static const String trackPage = '/track';
+  static const String minePage = '/mine';
+  static const String aboutPage = '/about_me';
+  static const String helpPage = '/help';
+  static const String loginPage = '/login';
+  static const String registerPage = '/register';
+  static const String submitPage = '/submit';
+  static const String welPage = '/welcome';
 
-  Route Function(RouteSettings settings) onGenerateRoute =
-      (RouteSettings settings) {
-    final String name = settings.name;
-    return MaterialPageRoute(builder: (_) => Scaffold());
-  };
+  static Route<dynamic> generateRoute(RouteSettings settings) {
+    switch (settings.name) {
+      case homePage:
+        return MaterialPageRoute(builder: (_) => HomePage());
+        break;
+      case trackPage:
+        return MaterialPageRoute(builder: (_) => TrackPage());
+        break;
+      case minePage:
+        return MaterialPageRoute(builder: (_) => MinePage());
+        break;
+      case aboutPage:
+        return MaterialPageRoute(builder: (_) => AboutPage());
+        break;
+      case helpPage:
+        return MaterialPageRoute(builder: (_) => HelpPage());
+        break;
+      case loginPage:
+        return MaterialPageRoute(builder: (_) => LoginPage());
+        break;
+      case registerPage:
+        return MaterialPageRoute(builder: (_) => RegisterPage());
+        break;
+      case submitPage:
+        return MaterialPageRoute(builder: (_) => SubmitPage());
+        break;
+      case welPage:
+        return MaterialPageRoute(builder: (_) => WelComePage());
+        break;
+      default:
+        return MaterialPageRoute(
+            builder: (_) => Scaffold(
+                  appBar: AppBar(title: Text("Route Error")),
+                  body: Center(
+                    child: Text('No route defined for ${settings.name}'),
+                  ),
+                ));
+    }
+  }
 }

+ 7 - 0
pubspec.lock

@@ -315,6 +315,13 @@ packages:
       url: "https://pub.flutter-io.cn"
     source: hosted
     version: "2.1.0"
+  webview_flutter:
+    dependency: "direct main"
+    description:
+      name: webview_flutter
+      url: "https://pub.flutter-io.cn"
+    source: hosted
+    version: "0.3.24"
   win32:
     dependency: transitive
     description:

+ 2 - 0
pubspec.yaml

@@ -14,6 +14,8 @@ dependencies:
   fluttertoast: ^8.0.8
   flutter_screenutil: ^5.0.0+2
   #  image_packer: ^0.6.3+4
+  #  flutter_blue: ^
+  webview_flutter: ^0.3.24
 
 dev_dependencies:
   flutter_test:

+ 1 - 1
test/widget_test.dart

@@ -13,7 +13,7 @@ import 'package:flutter_tracker/main.dart';
 void main() {
   testWidgets('Counter increments smoke test', (WidgetTester tester) async {
     // Build our app and trigger a frame.
-    await tester.pumpWidget(const MyApp());
+    await tester.pumpWidget(MyApp());
 
     // Verify that our counter starts at 0.
     expect(find.text('0'), findsOneWidget);