Commit 68242b32 authored by 窦文's avatar 窦文

路由调试+多模块

parents 72950e01 c53ccd34
...@@ -2,6 +2,6 @@ ...@@ -2,6 +2,6 @@
<Workspace <Workspace
version = "1.0"> version = "1.0">
<FileRef <FileRef
location = "group:Runner.xcodeproj"> location = "self:">
</FileRef> </FileRef>
</Workspace> </Workspace>
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:netrain_flutter_app/laishanqi/netrain/Images.dart';
import 'second1.dart'; import 'secondpage.dart';
void main() { void main() {
runApp(MyApp()); runApp(MyApp());
...@@ -18,7 +19,7 @@ class MyApp extends StatelessWidget { ...@@ -18,7 +19,7 @@ class MyApp extends StatelessWidget {
return WillPopScope( return WillPopScope(
child: MaterialApp( child: MaterialApp(
title: 'Flutter Demo', title: 'Flutter Demo',
initialRoute: "/key1", // initialRoute: "/",
theme: ThemeData( theme: ThemeData(
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity, visualDensity: VisualDensity.adaptivePlatformDensity,
...@@ -29,7 +30,10 @@ class MyApp extends StatelessWidget { ...@@ -29,7 +30,10 @@ class MyApp extends StatelessWidget {
), ),
body: RouterNavigator(title: 'Flutter Demo Home Page'), body: RouterNavigator(title: 'Flutter Demo Home Page'),
), ),
// routes: <String, WidgetBuilder>{"/key2": (context) => second()}, routes: <String, WidgetBuilder>{
"key1": (context) => MyApp(),
"key2": (context) => Second()
},
), ),
onWillPop: () async { onWillPop: () async {
Fluttertoast.showToast(msg: "退出"); Fluttertoast.showToast(msg: "退出");
...@@ -55,10 +59,11 @@ class _RouterNavigatorState extends State<RouterNavigator> { ...@@ -55,10 +59,11 @@ class _RouterNavigatorState extends State<RouterNavigator> {
child: Column( child: Column(
children: [ children: [
_item("跳转", () async { _item("跳转", () async {
var result = await Navigator.push( var result = await Navigator.pushNamed(context, "key2",
context, MaterialPageRoute(builder: (context) => Second(text:""))); arguments: "this is value");
print("返回值:$result"); print("返回值:$result");
}) }),
Image.asset(Images.bg_my_01)
], ],
), ),
); );
......
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart'; import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart'; import 'package:http/http.dart';
import 'package:netrain_flutter_app/douwen/dwMain.dart';
class Second extends StatelessWidget { class Second extends StatelessWidget {
Second({
Key key,
@required this.text
}):super(key: key);
final String text;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return WillPopScope( return WillPopScope(
child: MaterialApp( child: Scaffold(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text("哦吼2"), title: Text("哦吼2"),
), ),
body: RouterNavigator(title: 'Flutter Demo Home Page'), body: RouterNavigator(title: 'Flutter Demo Home Page'),
), ),
),
onWillPop: () async { onWillPop: () async {
Fluttertoast.showToast(msg: "哦吼2"); Fluttertoast.showToast(msg: "哦吼2");
var args = ModalRoute.of(context).settings.arguments;
return true; return true;
}); });
} }
...@@ -50,7 +39,7 @@ class _RouterNavigatorState extends State<RouterNavigator> { ...@@ -50,7 +39,7 @@ class _RouterNavigatorState extends State<RouterNavigator> {
child: Column( child: Column(
children: [ children: [
_item("跳转", () { _item("跳转", () {
Navigator.popUntil(context, ModalRoute.withName("/key1")); Navigator.popUntil(context,ModalRoute.withName("/"));
}) })
], ],
), ),
......
...@@ -8,12 +8,12 @@ class HttpUtil { ...@@ -8,12 +8,12 @@ class HttpUtil {
static HashMap<String,String> headers; static HashMap<String,String> headers;
static String scheme = "http"; static String scheme = "http";
static String host = "api-docker.naiterui.com"; static String host = "api-docker.naiterui.com/";
static String global_config = "ad/doctorInfo/globalConfig"; static String global_config = "ad/doctorInfo/globalConfig";
static Future<http.Response> get(String path,{Map<String, dynamic> queryParameters}) async { static Future<http.Response> get(String path,{Map<String, dynamic> queryParameters}) async {
var response = await http.get("http://$host/$path"); var response = await http.get(Uri(host: "http://$host/$path"));
// _get(path, host: HttpUtil.host, queryParameters: queryParameters); // _get(path, host: HttpUtil.host, queryParameters: queryParameters);
return response; return response;
} }
......
...@@ -8,6 +8,8 @@ import 'laishanqi/netrain/user/loginPage.dart'; ...@@ -8,6 +8,8 @@ import 'laishanqi/netrain/user/loginPage.dart';
import 'laishanqi/netrain/user/RegisterPage.dart'; import 'laishanqi/netrain/user/RegisterPage.dart';
import 'laishanqi/photo.dart'; import 'laishanqi/photo.dart';
import 'zhangfeng/LoginPage.dart';
void main() { void main() {
runApp(MyApp()); runApp(MyApp());
// runApp(Login()); // runApp(Login());
...@@ -77,6 +79,7 @@ class _RouterNavigatorState extends State<RouterNavigator> { ...@@ -77,6 +79,7 @@ class _RouterNavigatorState extends State<RouterNavigator> {
_item("layout页面", LayoutPage(), 'layout'), _item("layout页面", LayoutPage(), 'layout'),
_item("拍照页面", PhotoApp(), 'photo'), _item("拍照页面", PhotoApp(), 'photo'),
_item("登陆", LoginPage(), 'login'), _item("登陆", LoginPage(), 'login'),
_item("登录网络请求", LoginRequestPage(), 'loginRequest'),
], ],
), ),
); );
......
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'Network/Api.dart';
class LoginRequestPage extends StatefulWidget {
final String title = "登录页";
@override
_LoginState createState() => _LoginState();
}
class _LoginState extends State<LoginRequestPage> {
// This widget is the root of your application.
void _loginAction() {
Map<String,String> map = new Map<String,String>();
map['workNumber'] = 'NTR000007';
map['password'] = '123456';
map['model'] = 'iPhone 12';
map['grant_type'] = 'worknumber_password';
map['client_id'] = 'app';
map['client_secret'] = '123456';
map['platform'] = '0';
Api.request(map);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
FloatingActionButton(
onPressed: _loginAction,
child:Icon(Icons.add),
),
],
),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
\ No newline at end of file
import 'HttpManager.dart';
import 'UrlPath.dart';
/// 所有接口类
class Api {
///示例请求
static request(Map<String, dynamic> param) {
return HttpManager.getInstance().get(UrlPath.baseUrl + 'auth/oauth/token', params: param);
}
}
///错误编码
class Code {
///网络错误
static const NETWORK_ERROR = -1;
///网络超时
static const NETWORK_TIMEOUT = -2;
///网络返回数据格式化一次
static const NETWORK_JSON_EXCEPTION = -3;
static const SUCCESS = 200;
static errorHandleFunction(code, message, noTip) {
if (noTip) {
return message;
}
return message;
}
}
import 'dart:collection';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:convert/convert.dart';
///参数加密工具
class DataHelper {
static encryptParams(Map<String, dynamic> map) {
var buffer = StringBuffer();
map.forEach((key, value) {
buffer.write(key);
buffer.write(value);
});
buffer.write("SERECT");
var sign = string2MD5(buffer.toString());
print("sign--->" + sign);
return sign;
}
static string2MD5(String data) {
var content = new Utf8Encoder().convert(data);
var digest = md5.convert(content);
return hex.encode(digest.bytes);
}
}
import 'package:dio/dio.dart';
///日志拦截器
class DioLogInterceptor extends Interceptor {
///请求前
@override
void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
String requestStr = "\n==================== REQUEST ====================\n"
"- URL:\n${options.baseUrl + options.path}\n"
"- METHOD: ${options.method}\n";
requestStr += "- HEADER:\n${options.headers.mapToStructureString()}\n";
final data = options.data;
if (data != null) {
if (data is Map)
requestStr += "- BODY:\n${data.mapToStructureString()}\n";
else if (data is FormData) {
final formDataMap = Map()
..addEntries(data.fields)
..addEntries(data.files);
requestStr += "- BODY:\n${formDataMap.mapToStructureString()}\n";
} else
requestStr += "- BODY:\n${data.toString()}\n";
}
print(requestStr);
handler.next(options);
}
///出错前
@override
void onError(DioError err, ErrorInterceptorHandler handler) {
String errorStr = "\n==================== RESPONSE ====================\n"
"- URL:\n${err.requestOptions.baseUrl + err.requestOptions.path}\n"
"- METHOD: ${err.requestOptions.method}\n";
errorStr +=
"- HEADER:\n${err.response.headers.map.mapToStructureString()}\n";
if (err.response != null && err.response.data != null) {
print('╔ ${err.type.toString()}');
errorStr += "- ERROR:\n${_parseResponse(err.response)}\n";
} else {
errorStr += "- ERRORTYPE: ${err.type}\n";
errorStr += "- MSG: ${err.message}\n";
}
print(errorStr);
handler.next(err);
}
///响应前
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
String responseStr =
"\n==================== RESPONSE ====================\n"
"- URL:\n${response.requestOptions.uri}\n";
responseStr += "- HEADER:\n{";
response.headers.forEach(
(key, list) => responseStr += "\n " + "\"$key\" : \"$list\",");
responseStr += "\n}\n";
responseStr += "- STATUS: ${response.statusCode}\n";
if (response.data != null) {
responseStr += "- BODY:\n ${_parseResponse(response)}";
}
printWrapped(responseStr);
handler.next(response);
}
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}
String _parseResponse(Response response) {
String responseStr = "";
var data = response.data;
if (data is Map)
responseStr += data.mapToStructureString();
else if (data is List)
responseStr += data.listToStructureString();
else
responseStr += response.data.toString();
return responseStr;
}
}
///Map拓展,MAp转字符串输出
extension Map2StringEx on Map {
String mapToStructureString({int indentation = 2}) {
String result = "";
String indentationStr = " " * indentation;
if (true) {
result += "{";
this.forEach((key, value) {
if (value is Map) {
var temp = value.mapToStructureString(indentation: indentation + 2);
result += "\n$indentationStr" + "\"$key\" : $temp,";
} else if (value is List) {
result += "\n$indentationStr" +
"\"$key\" : ${value.listToStructureString(indentation: indentation + 2)},";
} else {
result += "\n$indentationStr" + "\"$key\" : \"$value\",";
}
});
result = result.substring(0, result.length - 1);
result += indentation == 2 ? "\n}" : "\n${" " * (indentation - 1)}}";
}
return result;
}
}
///List拓展,List转字符串输出
extension List2StringEx on List {
String listToStructureString({int indentation = 2}) {
String result = "";
String indentationStr = " " * indentation;
if (true) {
result += "$indentationStr[";
this.forEach((value) {
if (value is Map) {
var temp = value.mapToStructureString(indentation: indentation + 2);
result += "\n$indentationStr" + "\"$temp\",";
} else if (value is List) {
result += value.listToStructureString(indentation: indentation + 2);
} else {
result += "\n$indentationStr" + "\"$value\",";
}
});
result = result.substring(0, result.length - 1);
result += "\n$indentationStr]";
}
return result;
}
}
import 'package:dio/dio.dart';
import 'Code.dart';
import 'DioLogInterceptor.dart';
import 'Loading.dart';
import 'ResponseInterceptor.dart';
import 'ResultData.dart';
import 'UrlPath.dart';
import 'DataHelper.dart';
class HttpManager {
static HttpManager _instance = HttpManager._internal();
Dio _dio;
static const CODE_SUCCESS = 200;
static const CODE_TIME_OUT = -1;
static const CONNECT_TIMEOUT = 15000;
factory HttpManager() => _instance;
///通用全局单例,第一次使用时初始化
HttpManager._internal({String baseUrl}) {
if (null == _dio) {
_dio = new Dio(new BaseOptions(
baseUrl: UrlPath.baseUrl, connectTimeout: CONNECT_TIMEOUT));
_dio.interceptors.add(new DioLogInterceptor());
_dio.interceptors.add(new ResponseInterceptors());
}
}
static HttpManager getInstance({String baseUrl}) {
if (baseUrl == null) {
return _instance._normal();
} else {
return _instance._baseUrl(baseUrl);
}
}
//用于指定特定域名
HttpManager _baseUrl(String baseUrl) {
if (_dio != null) {
_dio.options.baseUrl = baseUrl;
}
return this;
}
//一般请求,默认域名
HttpManager _normal() {
if (_dio != null) {
if (_dio.options.baseUrl != UrlPath.baseUrl) {
_dio.options.baseUrl = UrlPath.baseUrl;
}
}
return this;
}
///通用的GET请求
get(api, {params, withLoading = true}) async {
if (withLoading) {
Loading.show();
}
Response response;
// params["platform"] = "android";
// params["system"] = "1.0.0";
// params["channel"] = "App";
// params["time"] = new DateTime.now().millisecondsSinceEpoch.toString();
// params["sign"] = DataHelper.encryptParams(params);
try {
response = await _dio.get(api, queryParameters: params);
if (withLoading) {
Loading.dismiss();
}
} on DioError catch (e) {
if (withLoading) {
Loading.dismiss();
}
return resultError(e);
}
if (response.data is DioError) {
return resultError(response.data['code']);
}
return response.data;
}
///通用的POST请求
post(api, {params, withLoading = true}) async {
if (withLoading) {
Loading.show();
}
Response response;
// params["platform"] = "android";
// params["system"] = "1.0.0";
// params["channel"] = "App";
// params["time"] = new DateTime.now().millisecondsSinceEpoch.toString();
// params["sign"] = DataHelper.encryptParams(params);
try {
response = await _dio.post(api, data: params);
if (withLoading) {
Loading.dismiss();
}
} on DioError catch (e) {
if (withLoading) {
Loading.dismiss();
}
return resultError(e);
}
if (response.data is DioError) {
return resultError(response.data['code']);
}
return response.data;
}
}
ResultData resultError(DioError e) {
Response errorResponse;
if (e.response != null) {
errorResponse = e.response;
} else {
errorResponse = new Response(statusCode: 666);
}
if (e.type == DioErrorType.connectTimeout ||
e.type == DioErrorType.receiveTimeout) {
errorResponse.statusCode = Code.NETWORK_TIMEOUT;
}
return new ResultData(
null, false,-1,errorResponse.statusMessage);
}
import 'package:flutter_easyloading/flutter_easyloading.dart';
class Loading {
static show() {
EasyLoading.show();
}
static dismiss() {
EasyLoading.dismiss();
}
}
import 'package:dio/dio.dart';
import 'ResultData.dart';
/// 数据初步处理
class ResponseInterceptors extends InterceptorsWrapper {
@override
void onResponse(Response response, ResponseInterceptorHandler handler) {
RequestOptions option = response.requestOptions;
try {
if (option.contentType != null && option.contentType.contains("text")) {
response.data = ResultData(response.data, true, 0,'');
handler.next(response);
}
///一般只需要处理200的情况,300、400、500保留错误信息,外层为http协议定义的响应码
if (response.statusCode == 200 || response.statusCode == 201) {
///内层需要根据公司实际返回结构解析,一般会有code,data,msg字段
int code = response.data["code"];
String msg = response.data["msg"];
if (code == 0) {
response.data = ResultData(response.data, true, code ,msg);
handler.next(response);
} else {
response.data = ResultData(response.data, false, code, msg);
handler.next(response);
}
}
} catch (e) {
print("ResponseError====" + e.toString() + "****" + option.path);
response.data = ResultData(response.data, false, -1, '网络有误');
handler.next(response);
}
response.data = ResultData(response.data, false, -1,'网络有误');
handler.next(response);
}
}
class ResultData {
var data;
bool isSuccess;
int code;
var msg;
ResultData(this.data, this.isSuccess, this.code, this.msg);
}
class UrlPath {
static String baseUrl = "https://api.health100.naiterui.com/";
}
...@@ -25,14 +25,22 @@ dependencies: ...@@ -25,14 +25,22 @@ dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
test_package:
path: ../test_package
# The following adds the Cupertino Icons font to your application. # The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons. # Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.3 cupertino_icons: ^0.1.3
image_picker: ^0.6.7+11 image_picker: ^0.8.1+3
fluttertoast: ^3.1.3 fluttertoast: ^3.1.3
http: 0.12.2 http: 0.13.3
mqtt_client: ^9.3.2 mqtt_client: ^9.3.2
flutter_easyrefresh: ^2.2.1 #下拉刷新
json_annotation: ^4.0.1 #json解析
flutter_easyloading: ^3.0.0 #简单的加载loading
dio: ^4.0.0 #网络库
convert: ^3.0.1 #转码器
dev_dependencies: dev_dependencies:
......
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
build/
# Android related
**/android/**/gradle-wrapper.jar
**/android/.gradle
**/android/captures/
**/android/gradlew
**/android/gradlew.bat
**/android/local.properties
**/android/**/GeneratedPluginRegistrant.java
# iOS/XCode related
**/ios/**/*.mode1v3
**/ios/**/*.mode2v3
**/ios/**/*.moved-aside
**/ios/**/*.pbxuser
**/ios/**/*.perspectivev3
**/ios/**/*sync/
**/ios/**/.sconsign.dblite
**/ios/**/.tags*
**/ios/**/.vagrant/
**/ios/**/DerivedData/
**/ios/**/Icon?
**/ios/**/Pods/
**/ios/**/.symlinks/
**/ios/**/profile
**/ios/**/xcuserdata
**/ios/.generated/
**/ios/Flutter/App.framework
**/ios/Flutter/Flutter.framework
**/ios/Flutter/Flutter.podspec
**/ios/Flutter/Generated.xcconfig
**/ios/Flutter/ephemeral
**/ios/Flutter/app.flx
**/ios/Flutter/app.zip
**/ios/Flutter/flutter_assets/
**/ios/Flutter/flutter_export_environment.sh
**/ios/ServiceDefinitions.json
**/ios/Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!**/ios/**/default.mode1v3
!**/ios/**/default.mode2v3
!**/ios/**/default.pbxuser
!**/ios/**/default.perspectivev3
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: f4abaa0735eba4dfd8f33f73363911d63931fe03
channel: stable
project_type: package
## 0.0.1
* TODO: Describe initial release.
TODO: Add your license here.
# test_package
A new Flutter package.
## Getting Started
This project is a starting point for a Dart
[package](https://flutter.dev/developing-packages/),
a library module containing code that can be shared easily across
multiple Flutter or Dart projects.
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
library test_package;
/// A Calculator.
class Calculator {
/// Returns [value] plus 1.
int addOne(int value) => value + 1;
}
name: test_package
description: A new Flutter package.
version: 0.0.1
homepage:
environment:
sdk: ">=2.12.0 <3.0.0"
flutter: ">=1.17.0"
dependencies:
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# To add assets to your package, add an assets section, like this:
# assets:
# - assets/imagas/
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# To add custom fonts to your package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
import 'package:flutter_test/flutter_test.dart';
import 'package:test_package/test_package.dart';
void main() {
test('adds one to input values', () {
final calculator = Calculator();
expect(calculator.addOne(2), 3);
expect(calculator.addOne(-7), -6);
expect(calculator.addOne(0), 1);
});
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment