Kaynağa Gözat

1、网络工具修复

tags/0.0.1
PH2 4 yıl önce
ebeveyn
işleme
c6a253cb23
8 değiştirilmiş dosya ile 425 ekleme ve 77 silme
  1. +19
    -8
      example/android/app/src/main/java/cn/zhios/zhiying_comm_example/MainActivity.java
  2. +144
    -0
      example/lib/device_info_page.dart
  3. +57
    -0
      example/lib/log_util.dart
  4. +92
    -34
      example/lib/main.dart
  5. +77
    -0
      example/lib/package_info_page.dart
  6. +1
    -1
      lib/util/global_config.dart
  7. +1
    -1
      lib/util/log/let_log.dart
  8. +34
    -33
      lib/util/net_util.dart

+ 19
- 8
example/android/app/src/main/java/cn/zhios/zhiying_comm_example/MainActivity.java Dosyayı Görüntüle

@@ -1,5 +1,6 @@
package cn.zhios.zhiying_comm_example;

import cn.zhios.zhiying_comm.ZhiyingCommPlugin;
import cn.zhios.zhiying_comm.ZhiyingFlutterCommHandler;
import cn.zhios.zhiying_comm.ZhiyingFlutterCommNativable;
import cn.zhios.zhiying_comm.ZhiyingFlutterCommNative;
@@ -9,18 +10,20 @@ import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugins.GeneratedPluginRegistrant;

public class MainActivity extends FlutterActivity implements ZhiyingFlutterCommNativable {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
ZhiyingFlutterCommNative.getInstance().regist((ZhiyingFlutterCommNativable) this);
}
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
ZhiyingFlutterCommNative.getInstance().regist(this);
}

boolean localDebug = false;

boolean localDebug = false;

@Override
public void openPage(Map params) {
@@ -35,13 +38,21 @@ public class MainActivity extends FlutterActivity implements ZhiyingFlutterCommN
@Override
public Map getSetting() {
Map map = new HashMap();
map.put("domain", "http://120.76.175.204:8989");
map.put("domain", "http://192.168.0.113:5000"); //"http://120.76.175.204:8989");
map.put("master_id", "123456");
map.put("secret_key", "123456");
map.put("token", "123465");
return map;
}

@Override
public void invokeMethod(String method, Map<String, Object> params, ZhiyingFlutterCommHandler handler) {
return ;
return;
}

@Override
protected void onDestroy() {
super.onDestroy();
ZhiyingFlutterCommNative.getInstance().unregist();
}
}

+ 144
- 0
example/lib/device_info_page.dart Dosyayı Görüntüle

@@ -0,0 +1,144 @@
import 'dart:async';

import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:device_info/device_info.dart';


class DeviceInfoPage extends StatefulWidget {
@override
_DeviceInfoPageState createState() => _DeviceInfoPageState();
}

class _DeviceInfoPageState extends State<DeviceInfoPage> {
static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
Map<String, dynamic> _deviceData = <String, dynamic>{};

@override
void initState() {
super.initState();
initPlatformState();
}

Future<void> initPlatformState() async {
Map<String, dynamic> deviceData;

try {
if (Platform.isAndroid) {
deviceData = _readAndroidBuildData(await deviceInfoPlugin.androidInfo);
} else if (Platform.isIOS) {
deviceData = _readIosDeviceInfo(await deviceInfoPlugin.iosInfo);
}
} on PlatformException {
deviceData = <String, dynamic>{
'Error:': 'Failed to get platform version.'
};
}

if (!mounted) return;

setState(() {
_deviceData = deviceData;
});
}

Map<String, dynamic> _readAndroidBuildData(AndroidDeviceInfo build) {
// 分辨率
int width = window.physicalSize.width.floor();
int height = window.physicalSize.height.floor();

return <String, dynamic>{
'version.securityPatch': build.version.securityPatch,
'version.sdkInt': build.version.sdkInt,
'version.release': build.version.release,
'version.previewSdkInt': build.version.previewSdkInt,
'version.incremental': build.version.incremental,
'version.codename': build.version.codename,
'version.baseOS': build.version.baseOS,
'board': build.board,
'bootloader': build.bootloader,
'brand': build.brand,
'device': build.device,
'display': build.display,
'fingerprint': build.fingerprint,
'hardware': build.hardware,
'host': build.host,
'id': build.id,
'manufacturer': build.manufacturer,
'model': build.model,
'product': build.product,
'supported32BitAbis': build.supported32BitAbis,
'supported64BitAbis': build.supported64BitAbis,
'supportedAbis': build.supportedAbis,
'tags': build.tags,
'type': build.type,
'isPhysicalDevice': build.isPhysicalDevice,
'androidId': build.androidId,
'systemFeatures': build.systemFeatures,
'分辨率': '${width} * ${height}',
};
}

Map<String, dynamic> _readIosDeviceInfo(IosDeviceInfo data) {

// 分辨率
int width = window.physicalSize.width.floor();
int height = window.physicalSize.height.floor();

return <String, dynamic>{
'name': data.name,
'systemName': data.systemName,
'systemVersion': data.systemVersion,
'model': data.model,
'localizedModel': data.localizedModel,
'identifierForVendor': data.identifierForVendor,
'isPhysicalDevice': data.isPhysicalDevice,
'utsname.sysname:': data.utsname.sysname,
'utsname.nodename:': data.utsname.nodename,
'utsname.release:': data.utsname.release,
'utsname.version:': data.utsname.version,
'utsname.machine:': data.utsname.machine,
'分辨率': '${width} * ${height}',
};
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text(
Platform.isAndroid ? 'Android Device Info' : 'iOS Device Info'),
),
body: ListView(
children: _deviceData.keys.map((String property) {
return Row(
children: <Widget>[
Container(
padding: const EdgeInsets.all(10.0),
child: Text(
property,
style: const TextStyle(
fontWeight: FontWeight.bold,
),
),
),
Expanded(
child: Container(
padding: const EdgeInsets.fromLTRB(0.0, 10.0, 0.0, 10.0),
child: Text(
'${_deviceData[property]}',
maxLines: 10,
overflow: TextOverflow.ellipsis,
),
)),
],
);
}).toList(),
),
),
);
}
}

+ 57
- 0
example/lib/log_util.dart Dosyayı Görüntüle

@@ -0,0 +1,57 @@

import 'package:zhiying_comm/zhiying_comm.dart';

class LogUtil {
static void test() {
// log
Logger.log("this is log");

// debug
Logger.debug("this is debug", "this is debug message");

// warn
Logger.warn("this is warn", "this is a warning message");

// error
Logger.error("this is error", "this is a error message");

// test error
try {
final test = {};
test["test"]["test"] = 1;
} catch (a, e) {
Logger.error(a, e);
}

// time test
Logger.time("timeTest");
Logger.endTime("timeTest");

// log net work
Logger.net(
"api/user/getUser",
data: {"user": "yung", "pass": "xxxxxx"},
);
Logger.endNet(
"api/user/getUser",
data: {
"users": [
{"id": 1, "name": "yung", "avatar": "xxx"},
{"id": 2, "name": "yung2", "avatar": "xxx"}
]
},
);

// log net work
Logger.net("ws/chat/getList", data: {"chanel": 1}, type: "Socket");
Logger.endNet(
"ws/chat/getList",
data: {
"users": [
{"id": 1, "name": "yung", "avatar": "xxx"},
{"id": 2, "name": "yung2", "avatar": "xxx"}
]
},
);
}
}

+ 92
- 34
example/lib/main.dart Dosyayı Görüntüle

@@ -1,8 +1,8 @@
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_comm_example/device_info_page.dart';
import 'package:zhiying_comm_example/log_util.dart';
import 'package:zhiying_comm_example/package_info_page.dart';

void main() => runApp(MyApp());

@@ -21,37 +21,95 @@ class _MyAppState extends State<MyApp> {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('智莺-基础库'),
),
body: Wrap(
direction: Axis.horizontal,
spacing: 5,
children: <Widget>[
RaisedButton(
onPressed: () {
NetUtil.post('/siteapi/v1/ucenter/login/', params: {
'username': 'xiangguohui',
'password': 'fnuo123com'
});
},
child: Text('登录请求'),
),
RaisedButton(
onPressed: () {
NetUtil.request('/api/v1/rec/featured?page=1',
method: NetMethod.GET, params: {});
},
child: Text('页面请求'),
),
RaisedButton(
onPressed: () {
NetUtil.request('/api/v1/config.json', params: {});
},
child: Text('基础配置'),
)
],
)),
appBar: AppBar(
title: const Text('智莺-基础库'),
),
body: HomePage(),
),
);
}
}

class HomePage extends StatelessWidget {
netPost() async {
dynamic result = await NetUtil.post('/api/v1/rec/featured?page=1', params: null);
print("result === ${result?.toString()}");
}


@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return DeviceInfoPage();
}));
},
child: Text('设备信息'),
),
RaisedButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return PackageInfoPage();
}));
},
child: Text('应用信息'),
),
RaisedButton(
onPressed: () {
NetUtil.post('/siteapi/v1/ucenter/login/', params: {
'username': 'xiangguohui',
'password': 'fnuo123com'
});
},
child: Text('登录请求'),
),
RaisedButton(
onPressed: () {
NetUtil.request('/api/v1/rec/featured?page=1', params: null,
onError: (msg) {
print('onERROR = ${msg?.toString() ?? 'onError'}');
}, onSuccess: (json) {
print('onSuccess = ${json?.toString() ?? 'onSuccess'}');
}, onCache: (json) {
print('onCache = ${json?.toString() ?? 'onCache'}');
});
},
child: Text('网络异步请求(带缓存)'),
),
RaisedButton(
onPressed: () {
netPost();
},
child: Text('网络同步请求(无缓存)'),
),

RaisedButton(
onPressed: (){
LogUtil.test();
},
child: Text('显示日志'),
),
RaisedButton(
onPressed: (){
Navigator.push(context, MaterialPageRoute(
builder: (_){
return Logger();
}
));
},
child: Text('打开日志视图'),
),

],
),
),
);
}
}

+ 77
- 0
example/lib/package_info_page.dart Dosyayı Görüntüle

@@ -0,0 +1,77 @@
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// ignore_for_file: public_member_api_docs

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';

class PackageInfoPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'PackageInfo Demo',
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(title: 'PackageInfo example app'),
);
}
}

class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
PackageInfo _packageInfo = PackageInfo(
appName: 'Unknown',
packageName: 'Unknown',
version: 'Unknown',
buildNumber: 'Unknown',
);

@override
void initState() {
super.initState();
_initPackageInfo();
}

Future<void> _initPackageInfo() async {
final PackageInfo info = await PackageInfo.fromPlatform();
setState(() {
_packageInfo = info;
});
}

Widget _infoTile(String title, String subtitle) {
return ListTile(
title: Text(title),
subtitle: Text(subtitle ?? 'Not set'),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_infoTile('App name', _packageInfo.appName),
_infoTile('Package name', _packageInfo.packageName),
_infoTile('App version', _packageInfo.version),
_infoTile('Build number', _packageInfo.buildNumber),
],
),
);
}
}

+ 1
- 1
lib/util/global_config.dart Dosyayı Görüntüle

@@ -4,5 +4,5 @@ class GlobalConfig {
static final String HTTP_RESPONSE_KEY_MSG = 'msg';
static final String HTTP_RESPONSE_KEY_DATA = 'data';
/// 成功返回的CODE值
static final int RESPONSE_SUCCESS_CODE = 200;
static final int RESPONSE_SUCCESS_CODE = 1;
}

+ 1
- 1
lib/util/log/let_log.dart Dosyayı Görüntüle

@@ -132,7 +132,7 @@ class Logger extends StatelessWidget {

/// Recording network information
static void net(String api,
{String type = "请求接口", int status = 100, Object data}) {
{String type = "接口", int status = 100, Object data}) {
assert(api != null);
if (enabled) _Net.request(api, type, status, data);
}


+ 34
- 33
lib/util/net_util.dart Dosyayı Görüntüle

@@ -153,39 +153,41 @@ class NetUtil {
Response response;
try {
Dio dio = await NetUtil.getInstance().dio;
dio.request(path,
data: sign, options: Options(method: enumToString(method)));
response = await dio.request(path, data: sign, options: Options(method: enumToString(method)));
} on DioError catch (e) {
_formatError(e);
}

if (response == null) {
return null;
}
try{
var result = response.data is Map ? response.data : jsonDecode(response.data);
// TODO 解密?
if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}') {
if (onSuccess != null) {
onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
// 缓存返回的数据
_setCallBackCacheData(cacheKey, response.data is Map ? jsonEncode(response.data) : response.data);
}
return;
}

var result = jsonDecode(response.data);
//TODO 加密?
if (result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
result[GlobalConfig.HTTP_RESPONSE_KEY_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}') {
if (onSuccess != null) {
onSuccess(result[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
// 缓存返回的数据
_setCallBackCacheData(cacheKey, response.data);
Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]);
Fluttertoast.showToast(
msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
);
if (onError != null) {
onError(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG] ?? '未知错误');
}
}catch (e){
if (onError != null) {
onError(e?.toString() ?? '未知错误');
}
return;
}

Logger.error('error: ' + result[GlobalConfig.HTTP_RESPONSE_KEY_MSG]);
Fluttertoast.showToast(
msg: result[GlobalConfig.HTTP_RESPONSE_KEY_MSG],
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
);
if (onError != null) {
onError(result[GlobalConfig.HTTP_RESPONSE_KEY_MSG] ?? '未知错误');
}
return;
}

@@ -273,14 +275,13 @@ class NetUtil {
// 读取缓存
Map<String, dynamic> cacheMap =
await SharedPreferencesUtil.getNetCacheResult(cacheKey);

if (!EmptyUtil.isEmpty(cacheMap) &&
cacheMap.containsKey(GlobalConfig.RESPONSE_SUCCESS_CODE) &&
(cacheMap[GlobalConfig.RESPONSE_SUCCESS_CODE] ==
GlobalConfig.RESPONSE_SUCCESS_CODE ||
cacheMap[GlobalConfig.RESPONSE_SUCCESS_CODE] ==
'${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
cacheMap.containsKey(GlobalConfig.HTTP_RESPONSE_KEY_CODE) &&
(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == GlobalConfig.RESPONSE_SUCCESS_CODE ||
cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_CODE] == '${GlobalConfig.RESPONSE_SUCCESS_CODE}') &&
null != cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]) {
onCache(cacheMap['data']);
onCache(cacheMap[GlobalConfig.HTTP_RESPONSE_KEY_DATA]);
return;
}
return;
@@ -341,14 +342,14 @@ class NetUtil {
class _NetInterceptors extends InterceptorsWrapper {
@override
Future onRequest(RequestOptions options) {
Logger.net(options?.path, data: options.data.toString());
Logger.net(options?.uri?.toString(), data: options.data.toString());
// TODO 加密?
return super.onRequest(options);
}

@override
Future onResponse(Response response) {
Logger.endNet(response?.statusCode?.toString(),
Logger.endNet(response?.request?.uri?.toString(),
data: response?.data?.toString() ?? '');
// TODO 解密?
return super.onResponse(response);


Yükleniyor…
İptal
Kaydet