Commit a680c565 authored by 林生雨's avatar 林生雨

Initial commit

parents
File added
.atom/
.dart_tool/
.idea
.vscode/
.packages
.pub/
android/
build/
ios/
packages
.flutter-plugins
# Since the current expectation is that clients are using Flutter head,
# and Dart SDK changes unlock dependencies, pubspec.lock isn't useful.
# Ignore it since it just creates noise. When there's a system in place
# for versioning this project relative to Flutter, remove this.
pubspec.lock
# 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: eaa9b47a4ac278a9439468911d2c361a472b114b
channel: master
# Application Customization
Because `example` is still in the process of being converted to
`flutter create` templates, support for customizing the application
is a work in progres. This page describes the current process for
making common modification to the native application on each platform.
It will be updated as `example` evolves. Keep in mind that as with
everything in this repository, forward-compatibility is not guaranteed;
the process for any customization may change in the future without
warning.
Please file issues for any basic application-level customizations that you would
like to be able to make that aren't listed here.
## macOS
- **Application Name**: Change `PRODUCT_NAME` in
`macos/Runner/Configs/AppInfo.xcconfig`.
- **Bundle Identifier**: Change `PRODUCT_BUNDLE_IDENTIFIER` in
`macos/Runner/Configs/AppInfo.xcconfig`.
- **Application Icon**: Replace `macos/Assets.xcassets/app_icon_*` with your
icon in the appropriate sizes.
## Windows
**Remember that Windows builds are currently debug-only, and should not be
distributed. These instructions are intended for experimentation and feedback
only.**
- **Application Name**: Change `TargetName` in
`windows\AppConfiguration.props`.
- You will likely want to change `kFlutterWindowTitle` in
`windows\window_configuration.cpp` to match. In the future this
will use the application name automatically by default.
- **Application Icon**: Replace `windows\resources\app_icon.ico` with your
icon.
- This will also change the Window icon.
## Linux
**Remember that Linux builds are currently debug-only, and should not be
distributed. These instructions are intended for experimentation and feedback
only.**
Linux has not yet had any customization support added. The fact that these steps
are non-trivial is a known issue.
- **Executable Name**: Change `BINARY_NAME` in `linux/Makefile`.
- You will likely want to change `window_properties.title` in
`linux/main.cc` to match. In the future this
will use the application name automatically by default.
- **Application Icon**: Prepare image data using the method of your choice
(e.g., by loading from a file in a set location; this may require the use
of a third-party library depending on the image format) and call `SetIcon`
on `flutter_controller.window()`. See the `SetIcon` comment in
`flutter_window.h` for the required format.
# Desktop Flutter Example
This is the standard Flutter template application, modified to run on desktop.
The `linux` and `windows` directories serve as early prototypes of
what will eventually become the `flutter create` templates for desktop, and will
be evolving over time to better reflect that goal. The `macos` directory has
now become a `flutter create` template, so is largely identical to what that
command creates.
## Building and Running
See [the main project README](../README.md).
To build without running, use `flutter build macos`/`windows`/`linux` rather than `flutter run`, as with
a standard Flutter project.
## Dart Differences from Flutter Template
The `main.dart` and `pubspec.yaml` have minor changes to support desktop:
* `debugDefaultTargetPlatformOverride` is set to avoid 'Unknown platform'
exceptions.
* The font is explicitly set to Roboto, and Roboto is bundled via
`pubspec.yaml`, to ensure that text displays on all platforms.
See the [Flutter Application Requirements section of the Flutter page on
desktop support](https://github.com/flutter/flutter/wiki/Desktop-shells#flutter-application-requirements)
for more information.
## Adapting for Another Project
Since `flutter create` is not yet supported for Windows and Linux, the easiest
way to try out desktop support with an existing Flutter application on those
platforms is to copy the platform directories from this example; see below for
details. For macOS, just run `flutter create --macos .` in your project.
Be sure to read the [Flutter page on desktop
support](https://github.com/flutter/flutter/wiki/Desktop-shells) before trying to
run an existing project on desktop, especially the [Flutter Application Requirements
section](https://github.com/flutter/flutter/wiki/Desktop-shells#flutter-application-requirements).
### Copying the Desktop Runners
The 'linux' and 'windows' directories are self-contained, and can be copied to
an existing Flutter project, enabling `flutter run` for those platforms.
**Be aware that neither the API surface of the Flutter desktop libraries nor the
interaction between the `flutter` tool and the platform directories is stable,
and no attempt will be made to provide supported migration paths as things
change.** You should expect that every time you update Flutter you may have
to delete your copies of the platform directories and re-copy them from an
updated version of flutter-desktop-embedding.
### Customizing the Runners
See [Application Customization](App-Customization.md) for premilinary
documenation on modifying basic application information like name and icon.
If you are building for macOS, you should also read about [managing macOS
security configurations](../macOS-Security.md).
flutter packages pub run build_runner clean
flutter packages pub run build_runner build --delete-conflicting-outputs
\ No newline at end of file
targets:
$default:
builders:
code_gen_demo|mark_builder:
enabled: true
builders:
user:
import: "package:example_flutter/Annotations/ServiceGenerator.dart"
builder_factories: ["userBuilder"]
build_extensions: {'.dart': ['.user.dart'] }
auto_apply: root_package
build_to: source
Router:
import: "package:example_flutter/Annotations/ServiceGenerator.dart"
builder_factories: ["routerBuilder"]
build_extensions: {'.dart': ['.rout.dart'] }
auto_apply: root_package
runs_before: ['routerCenter']
build_to: source
routerCenter:
import: "package:example_flutter/Annotations/ServiceGenerator.dart"
builder_factories: ["routerCenterBuilder"]
build_extensions: {'.dart': ['.mark.dart'] }
auto_apply: root_package
build_to: source
api_generator:
import: "package:example_flutter/Annotations/ServiceGenerator.dart"
builder_factories: ["apiBuilder"]
build_extensions: {".dart": [".serv.dart"]}
auto_apply: all_packages
build_to: source
applies_builders: ["source_gen|combining_builder"]
#
# json:
# import: "package:gmalpha_flutter/Annotations/ServiceGenerator.dart"
# builder_factories: ["jsonBuilder"]
# build_extensions: {".dart": [".json.dart"]}
# auto_apply: all_packages
# build_to: source
# applies_builders: ["source_gen|combining_builder"]
This diff is collapsed.
<svg width="135" height="158" viewBox="0 0 135 158" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="2" y="2" width="131" height="154" rx="65.5" stroke="#323232" stroke-width="4"/>
<path d="M43.7324 120.012C50.4299 124.752 58.6355 127.542 67.5 127.542C76.3646 127.542 84.5701 124.752 91.2677 120.012" stroke="#323232" stroke-width="4"/>
<path d="M40.8804 65.6747V85.6626" stroke="#323232" stroke-width="4"/>
<path d="M94.1198 65.6747V85.6626" stroke="#323232" stroke-width="4"/>
<path d="M70.3522 68.5301V98.9879C70.3522 102.142 67.7984 104.699 64.648 104.699C63.9813 104.699 63.3413 104.584 62.7466 104.374" stroke="#323232" stroke-width="4"/>
</svg>
<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="0.75" y="0.75" width="98.5" height="98.5" stroke="#E4E4E4" stroke-width="1.5"/>
<path d="M40 50H60" stroke="#E4E4E4" stroke-width="2"/>
<path d="M50 60L50 40" stroke="#E4E4E4" stroke-width="2"/>
</svg>
<svg width="14" height="7" viewBox="0 0 14 7" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1 1L7 6L13 1" stroke="#323232" stroke-width="1.5"/>
</svg>
<svg width="13" height="22" viewBox="0 0 13 22" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 1L2 11L12 21" stroke="#323232" stroke-width="1.5"/>
</svg>
This diff is collapsed.
/*
* @author lsy
* @date 2019-09-02
**/
import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:example_flutter/Annotations/anno/RouterCenter.dart';
import 'package:source_gen/source_gen.dart';
import '../RouterCenterRestore.dart';
class RouterCenterGenerator extends GeneratorForAnnotation<RouterCenter> {
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
StringBuffer buffer = new StringBuffer();
StringBuffer importBuffer = new StringBuffer();
StringBuffer annoBuffer = new StringBuffer();
StringBuffer funBuffer = new StringBuffer();
RouterCenterRestore().buildMap.forEach((f, s) {
if (s.four) {
buffer.write("map.putIfAbsent(\"${f}\", ()=>${s.second}());\n");
}
annoBuffer.write("//${s.second} is resign : ${s.four} \n");
importBuffer.write("${s.first}${s.second}.dart\";\n");
importBuffer.write("${s.first}${s.third}.dart\";\n");
funBuffer.write("""
${s.third} find${s.third}(){
if(map[\"${f}\"]==null){
return null;
}
return map[\"${f}\"] as ${s.third};
}
""");
});
var pathSegments = buildStep.inputId.pathSegments;
StringBuffer pathBuffer = new StringBuffer();
for (int i = 0; i < pathSegments.length; i++) {
if (pathSegments[i] != "lib" && i != pathSegments.length - 1) {
pathBuffer.write(pathSegments[i] + "/");
}
}
String sufPath = pathBuffer.toString();
return """
${annoBuffer.toString()}
${importBuffer.toString()}
import "${"package:${buildStep.inputId.package}/${sufPath}RouterCenterRestore.dart"}";
import "${"package:${buildStep.inputId.package}/${sufPath}RouterBaser.dart"}";
class RouterCenterImpl {
Map<String,RouterBaser> map;
factory RouterCenterImpl() => _sharedInstance();
static RouterCenterImpl _instance;
RouterCenterImpl._() {
if (map == null) {
map = new Map();
init();
} else {
throw Exception("too many RouterCenter instance!!! fix it ");
}
}
static RouterCenterImpl _sharedInstance(){
if (_instance == null) {
_instance = RouterCenterImpl._();
}
return _instance;
}
void init(){
${buffer.toString()}
}
RouterBaser getModel(String modelName){
return map[modelName];
}
${funBuffer.toString()}
}
""";
}
}
/*
* @author lsy
* @date 2019-09-02
**/
import 'dart:math';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:example_flutter/Annotations/anno/Router.dart';
import 'package:example_flutter/Annotations/base/RouterBuildItem.dart';
import 'package:source_gen/source_gen.dart';
import '../RouterCenterRestore.dart';
class RouterGenerator extends GeneratorForAnnotation<Router> {
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
var modelName = annotation.peek("modelName").stringValue;
var typeValue = annotation.peek("impl").typeValue;
var resignThisModel = annotation.peek("resignThisModel").boolValue;
var pathSegments = buildStep.inputId.pathSegments;
StringBuffer buffer = new StringBuffer();
String interfaceName;
for (int i = 0; i < pathSegments.length; i++) {
if (pathSegments[i] != "lib" && i != pathSegments.length - 1) {
buffer.write(pathSegments[i] + "/");
} else if (i == pathSegments.length - 1) {
// buffer.write("${typeValue.name}.dart");
interfaceName = pathSegments[i].replaceAll(".dart", "");
}
}
String first =
"import \"package:${buildStep.inputId.package}/${buffer.toString()}";
String second = typeValue.name;
String third = interfaceName;
bool four = resignThisModel;
RouterBuildItem item = new RouterBuildItem(first, second, third, four);
if (RouterCenterRestore().buildMap[modelName] != null) {
throw Exception("router error have same model name !!! change it name ");
}
RouterCenterRestore().buildMap.putIfAbsent(modelName, () => item);
// return """
//// import ${"package:${buildStep.inputId.package}/${buildStep.inputId.path.replaceFirst('lib/', '')}"}
// class APT {
// Map<String,RouterBaser> map={};
// }
// """;
return null;
}
}
/*
* @author lsy
* @date 2019-09-03
**/
import 'dart:convert';
import 'dart:core';
import 'dart:math';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:example_flutter/Annotations/anno/ServiceCenter.dart';
import 'package:source_gen/source_gen.dart';
import '../RouterCenterRestore.dart';
class ServiceGenerator extends GeneratorForAnnotation<ServiceCenter> {
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
print("element is $element");
if (element is! ClassElement) {
throw InvalidGenerationSourceError(
"Request class is not ok for ${element.displayName}");
}
StringBuffer improtBuffer = new StringBuffer();
StringBuffer methodBuffer = StringBuffer("");
StringBuffer outBuffer = StringBuffer();
StringBuffer mapBuffer = new StringBuffer();
List<String> differentList = [];
for (var methodElement in (element as ClassElement).methods) {
for (var annometadata in methodElement.metadata) {
final metadata = annometadata.computeConstantValue();
if (metadata.type.name == "Post" ||
metadata.type.name == "Get" ||
metadata.type.name == "Put") {
if (!differentList.contains(methodElement.returnType.name)) {
if (methodElement.returnType.name == "SimpleResponce") {
improtBuffer.write(
"import 'package:gmalpha_flutter/commonModel/net/Responce/SimpleResponce.dart';\n");
} else {
var pathSegments = buildStep.inputId.pathSegments;
StringBuffer path = new StringBuffer();
for (int i = 0; i < pathSegments.length; i++) {
if (i < pathSegments.length - 2 && pathSegments[i] != "lib") {
path.write("${pathSegments[i]}/");
}
}
improtBuffer.write(
"import 'package:${buildStep.inputId.package}/${path.toString()}entity/${methodElement.returnType.name}.dart\';\n");
}
differentList.add(methodElement.returnType.name);
}
String tempParams;
String sendType = metadata.type.name == "Post" ? "post" : "get";
if (metadata.type.name == "Put") {
sendType = "put";
}
mapBuffer.write("""
return Observable.fromFuture(DioUtil().${sendType}(\'${metadata.getField("sufUrl").toStringValue()}\'
""");
bool needMap = false;
for (int i = 0; i < methodElement.parameters.length; i++) {
var paramsMeta = methodElement.parameters[i];
for (int j = 0; j < paramsMeta.metadata.length; j++) {
var parameter = paramsMeta.metadata[j];
final queryAnno = parameter.computeConstantValue();
if (queryAnno.type.name == "Query") {
needMap = true;
if (tempParams == null) {
tempParams = "${paramsMeta}";
} else {
tempParams = "${tempParams},${paramsMeta}";
}
if (i == 0) {
mapBuffer.write(
",data:{\'${queryAnno.getField("params").toStringValue()}\':${paramsMeta.name}");
if (methodElement.parameters.length > 1) {
mapBuffer.write(",");
} else {
mapBuffer.write("}");
}
} else if (i == methodElement.parameters.length - 1) {
mapBuffer.write(
"\'${queryAnno.getField("params").toStringValue()}\':${paramsMeta.name}}");
} else {
mapBuffer.write(
"\'${queryAnno.getField("params").toStringValue()}\':${paramsMeta.name},");
}
}
}
}
//else{
// throw HttpException("RESPONCE error :\${value}");
// }
// Map map = json.decode(value.toString());
// return ${methodElement.returnType.name}.fromJson(map);
mapBuffer.write("))");
outBuffer.write("""
${methodElement.returnType.name} pase${methodElement.returnType.name}(String value){
return ${methodElement.returnType.name}.fromJson(json.decode(value));
}\n
""");
mapBuffer.write("""
.flatMap((value){
if(value!=null&&(value.statusCode>=200&&value.statusCode<300)){
return Observable.fromFuture(compute(pase${methodElement.returnType.name}, value.toString()));
}else {
return Observable.fromFuture(null);
}
});
""");
// mapBuffer.write("""
// .map((value){
// if(value!=null&&value.statusCode==200){
// Map map = json.decode(value.toString());
// return ${methodElement.returnType.name}.fromJson(map);
// }
// });
// """);
methodBuffer.write("""
Observable<${methodElement.returnType.name}> ${methodElement.name}(${tempParams == null ? "" : tempParams}){
${mapBuffer.toString()}
}
""");
mapBuffer.clear();
}
}
}
return """
import 'dart:convert';\n
import 'dart:io';\n
import 'package:rxdart/rxdart.dart';\n
import 'package:dio/dio.dart';\n
import 'package:flutter/foundation.dart';\n
${improtBuffer.toString()}
import 'package:example_flutter/commonModel/net/DioUtil.dart';\n
class ${element.displayName}Impl{
factory ${element.displayName}Impl() => _sharedInstance();
static ${element.displayName}Impl _instance;
${element.displayName}Impl._() {
}
static ${element.displayName}Impl _sharedInstance() {
if (_instance == null) {
_instance = ${element.displayName}Impl._();
}
return _instance;
}
${methodBuffer.toString()}
}
${outBuffer.toString()}
""";
}
}
/*
* @author lsy
* @date 2019-09-02
**/
import 'dart:math';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/src/builder/build_step.dart';
import 'package:example_flutter/Annotations/anno/UserCenter.dart';
import 'package:source_gen/source_gen.dart';
import '../RouterCenterRestore.dart';
Map<String, String> map = {};
class UserGenerator extends GeneratorForAnnotation<UserCenter> {
@override
generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) {
StringBuffer buffer = new StringBuffer();
for (var fieldData in (element as ClassElement).fields) {
for (var annometadata in fieldData.metadata) {
final metadata = annometadata.computeConstantValue();
// final metadatatype = annometadata.runtimeType;
// print("metadatatype is $metadatatype");
// print("metadataNAME is ${metadata.type.name}");
// print("element is $element");
if (element is! ClassElement) {
throw InvalidGenerationSourceError(
"Request class is not ok for ${element.displayName}");
}
if (metadata.type.name == "User") {
String key = metadata.getField("key").toStringValue();
var field = metadata.getField("type");
var type = field.type.name;
if (type == "String") {
buffer.write("""
String _${fieldData.name};
Observable<bool> save${fieldData.name}(String ${fieldData.name}){
return Observable.fromFuture(spUtil.saveStringKv("${key}",${fieldData.name}))
.map((value){
if(value){
this._${fieldData.name}=${fieldData.name};
}
return value;
});
}
Observable<String> get${fieldData.name}(){
if(_${fieldData.name}!=null){
return Observable.fromFuture(Future.value(_${fieldData.name}));
}
return Observable.fromFuture(spUtil.getStringKv("${key}")).map((value){
if(value==""){
return null;
}
return value;
});
}
""");
} else if (type == "int") {
buffer.write("""
int _${fieldData.name};
Observable<bool> save${fieldData.name}(int ${fieldData.name}){
return Observable.fromFuture(spUtil.saveIntKv("${key}",${fieldData.name}))
.map((value){
if(value){
this._${fieldData.name}=${fieldData.name};
}
return value;
});
}
Observable<int> get${fieldData.name}(){
if(_${fieldData.name}!=null){
return Observable.fromFuture(Future.value(_${fieldData.name}));
}
return Observable.fromFuture(spUtil.getIntKv("${key}"));
}
""");
} else if (type == "double") {
buffer.write("""
double _${fieldData.name};
Observable<bool> save${fieldData.name}(double ${fieldData.name}){
return Observable.fromFuture(spUtil.saveDoubleKv("${key}",${fieldData.name}))
.map((value){
if(value){
this._${fieldData.name}=${fieldData.name};
}
return value;
});
}
Observable<double> get${fieldData.name}(){
if(_${fieldData.name}!=null){
return Observable.fromFuture(Future.value(_${fieldData.name}));
}
return Observable.fromFuture(spUtil.getDoubleKv("${key}"));
}
""");
} else if (type == "bool") {
buffer.write("""
bool _${fieldData.name};
Observable<bool> save${fieldData.name}(bool ${fieldData.name}){
return Observable.fromFuture(spUtil.saveBoolKv("${key}",${fieldData.name}))
.map((value){
if(value){
this._${fieldData.name}=${fieldData.name};
}
return value;
});
}
Observable<bool> get${fieldData.name}(){
if(_${fieldData.name}!=null){
return Observable.fromFuture(Future.value(_${fieldData.name}));
}
return Observable.fromFuture(spUtil.getBoolKv("${key}"));
}
""");
}
}
}
}
return """
import 'package:rxdart/rxdart.dart';
import 'package:gmalpha_flutter/commonModel/sp/SpUtil.dart';
class ${element.displayName}Impl{
factory ${element.displayName}Impl() => _sharedInstance();
static ${element.displayName}Impl _instance;
${element.displayName}Impl._() {
}
static ${element.displayName}Impl _sharedInstance() {
if (_instance == null) {
_instance = ${element.displayName}Impl._();
}
return _instance;
}
SpUtil spUtil=SpUtil.getInstance();
${buffer.toString()}
}
""";
}
}
/*
* @author lsy
* @date 2019-09-02
**/
abstract class RouterBaser{
//TODO
}
/*
* @author lsy
* @date 2019-09-02
**/
import 'anno/RouterCenter.dart';
import 'base/RouterBuildItem.dart';
@RouterCenter()
class RouterCenterRestore {
Map<String, RouterBuildItem> buildMap;
factory RouterCenterRestore() => _sharedInstance();
static RouterCenterRestore _instance;
RouterCenterRestore._() {
print("INITTT ");
if (buildMap == null) {
buildMap = new Map();
} else {
throw Exception("too many RouterCenter instance!!! fix it ");
}
}
static RouterCenterRestore _sharedInstance() {
if (_instance == null) {
_instance = RouterCenterRestore._();
}
return _instance;
}
}
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// RouterCenterGenerator
// **************************************************************************
//HomeRouterImpl is resign : true
//UserRouterImpl is resign : true
import "package:example_flutter/HomeModel/HomeRouterImpl.dart";
import "package:example_flutter/HomeModel/HomeRouter.dart";
import "package:example_flutter/UserModel/UserRouterImpl.dart";
import "package:example_flutter/UserModel/UserRouter.dart";
import "package:example_flutter/Annotations/RouterCenterRestore.dart";
import "package:example_flutter/Annotations/RouterBaser.dart";
class RouterCenterImpl {
Map<String, RouterBaser> map;
factory RouterCenterImpl() => _sharedInstance();
static RouterCenterImpl _instance;
RouterCenterImpl._() {
if (map == null) {
map = new Map();
init();
} else {
throw Exception("too many RouterCenter instance!!! fix it ");
}
}
static RouterCenterImpl _sharedInstance() {
if (_instance == null) {
_instance = RouterCenterImpl._();
}
return _instance;
}
void init() {
map.putIfAbsent("HomeRouter", () => HomeRouterImpl());
map.putIfAbsent("UserRouter", () => UserRouterImpl());
}
RouterBaser getModel(String modelName) {
return map[modelName];
}
HomeRouter findHomeRouter() {
if (map["HomeRouter"] == null) {
return null;
}
return map["HomeRouter"] as HomeRouter;
}
UserRouter findUserRouter() {
if (map["UserRouter"] == null) {
return null;
}
return map["UserRouter"] as UserRouter;
}
}
import 'package:example_flutter/Annotations/Generator/ServiceGenerator.dart';
import 'package:example_flutter/Annotations/Generator/UserGenerator.dart';
import 'package:source_gen/source_gen.dart';
import 'package:build/src/builder/builder.dart';
import 'Generator/RouterCenterGenerator.dart';
import 'Generator/RouterGenerator.dart';
Builder routerBuilder(BuilderOptions options) =>
LibraryBuilder(RouterGenerator(), generatedExtension: ".rout.dart");
Builder routerCenterBuilder(BuilderOptions options) =>
LibraryBuilder(RouterCenterGenerator(), generatedExtension: ".mark.dart");
Builder userBuilder(BuilderOptions options)=>
LibraryBuilder(UserGenerator(),generatedExtension: ".user.dart");
Builder apiBuilder(BuilderOptions options)=>
LibraryBuilder(ServiceGenerator(),generatedExtension: ".serv.dart");
//Builder jsonBuilder(BuilderOptions options)=>
// LibraryBuilder(JsonSerializableGenerator(),generatedExtension: ".json.dart");
\ No newline at end of file
/*
* @author lsy
* @date 2019-09-04
**/
library Get;
class Get {
final String sufUrl;
const Get(this.sufUrl);
}
/*
* @author lsy
* @date 2019-09-04
**/
library Post;
class Post {
final String sufUrl;
const Post(this.sufUrl);
}
/*
* @author lsy
* @date 2019-11-15
**/
library Put;
class Put {
final String sufUrl;
const Put(this.sufUrl);
}
/*
* @author lsy
* @date 2019-09-04
**/
library Query;
class Query {
final String params;
const Query(this.params);
}
/*
* @author lsy
* @date 2019-09-02
**/
library Router;
class Router {
final String modelName;
final Type impl;
final bool resignThisModel;
const Router(this.modelName, this.impl, this.resignThisModel);
}
/*
* @author lsy
* @date 2019-09-02
**/
library RouterCenter;
class RouterCenter {
const RouterCenter();
}
/*
* @author lsy
* @date 2019-09-04
**/
library ServiceCenter;
class ServiceCenter{
const ServiceCenter();
}
\ No newline at end of file
/*
* @author lsy
* @date 2019-09-03
**/
library User;
class User {
final String key;
final Object type;
const User(this.key, this.type);
}
/*
* @author lsy
* @date 2019-09-03
**/
library UserCenter;
class UserCenter {
const UserCenter();
}
/*
* @author lsy
* @date 2019-09-02
**/
class RouterBuildItem<S, T, Z, W> {
S first;
T second;
Z third;
W four;
RouterBuildItem(this.first, this.second, this.third, this.four);
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/Annotations/RouterBaser.dart';
import 'package:example_flutter/Annotations/anno/Router.dart';
import 'package:example_flutter/HomeModel/HomeRouterImpl.dart';
import 'package:flutter/cupertino.dart';
@Router("HomeRouter", HomeRouterImpl, true)
abstract class HomeRouter extends RouterBaser {
Widget getHomePage();
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/HomeModel/HomeRouter.dart';
import 'package:example_flutter/HomeModel/page/home/HomePage.dart';
import 'package:flutter/src/widgets/framework.dart';
class HomeRouterImpl extends HomeRouter{
@override
Widget getHomePage() {
return HomePage();
}
}
\ No newline at end of file
/*
* @author lsy
* @date 2019-11-13
**/
import 'package:example_flutter/commonModel/GMBase.dart';
import 'package:example_flutter/commonModel/cache/CacheManager.dart';
import 'package:example_flutter/res/value/ALColors.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
getBaseTitle(BuildContext context) {
String userName =
CacheManager.getInstance().get(MEMORY_CACHE).get("userName");
return baseAppBar(
backgroundColor: ALColors.Color5276F4,
backClick: () {
Navigator.pop(context);
},
action: <Widget>[
Expanded(
child: Container(),
),
Container(
margin: EdgeInsets.only(right: ScreenUtil.instance.setWidth(10)),
alignment: Alignment.center,
child: baseText(userName, 30, ALColors.ColorF8F8F8),
),
Container(
width: kToolbarHeight,
height: kToolbarHeight,
margin: EdgeInsets.only(
left: ScreenUtil.instance.setWidth(5),
right: ScreenUtil.instance.setWidth(50),
top: 5,
bottom: 5),
child: SvgPicture.asset("image/Face.svg"),
),
]);
}
/*
* @author lsy
* @date 2019-11-22
**/
import 'dart:ui' as ui;
class PointItem {
List<ui.Offset> list = new List();
ui.Image image;
double x = -1;
double y = -1;
double scareSize = 1;
double tranX = 0;
double tranY = 0;
bool drawPath = false;
void reset() {
list.clear();
x = -1;
y = -1;
scareSize = 1;
tranY = 0;
tranX = 0;
drawPath = false;
}
PointItem();
setScareSize(double scareSize) {
if (scareSize < 1) {
scareSize = 1;
}
this.scareSize = scareSize;
}
double getScareSize() {
return scareSize;
}
setTranX(double tranX) {
if (tranX < 0) {
tranX = 0;
}
this.tranX = tranX;
}
double getTranX() {
return tranX;
}
setTranY(double tranY) {
if (tranY < 0) {
tranY = 0;
}
this.tranY = tranY;
}
double getTranY() {
return tranY;
}
List<ui.Offset> getPoints() {
return list;
}
addPoint(double x, double y) {
double realX = (x + getTranX()) / scareSize;
double realY = (y + getTranY()) / scareSize;
list.add(new ui.Offset(realX, realY));
}
removePoint() {
if (list.isNotEmpty) {
list.removeAt(list.length - 1);
drawPath = false;
}
}
setImage(ui.Image image) {
this.image = image;
}
ui.Image getImage() {
return image;
}
setX(double x) {
this.x = x;
}
setY(double y) {
this.y = y;
}
double getX() {
return x;
}
double getY() {
return y;
}
void close() {
if (list.isNotEmpty && list.length > 2) {
list.add(list[0]);
drawPath = true;
}
}
}
/*
* @author lsy
* @date 2019-11-22
**/
import 'dart:async';
import 'dart:ui';
import 'package:example_flutter/HomeModel/base/bean/PointItem.dart';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;
//
//class WorkViewController extends StatefulWidget {
// @override
// State<StatefulWidget> createState() => WorkViewState();
//}
//
//class WorkViewState extends State<WorkViewController> {
// ui.Image img;
//
// @override
// void initState() {
// super.initState();
// String testImg =
// "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1574413347096&di=44b91b322281ad449b4d93cf79df3d0c&imgtype=0&src=http%3A%2F%2Fpic27.nipic.com%2F20130324%2F9252150_152129329000_2.jpg";
// loadImage(testImg).then((value) {
// setState(() {
// img = value;
// });
// });
// }
//
// @override
// Widget build(BuildContext context) {
// return CustomPaint(painter: WorkView(img));
// }
//
// Future<ui.Image> loadImage(var path) async {
// ImageStream stream = NetworkImage(
// path,
// ).resolve(ImageConfiguration.empty);
// Completer<ui.Image> completer = Completer<ui.Image>();
// void listener(ImageInfo frame, bool synchronousCall) {
// final ui.Image image = frame.image as ui.Image;
// completer.complete(image);
// stream.removeListener(ImageStreamListener(listener));
// }
//
// stream.addListener(ImageStreamListener(listener));
// return completer.future;
// }
//}
class WorkView extends CustomPainter {
PointItem item;
WorkView(this.item) {}
Paint ImagePaint = new Paint()..isAntiAlias = true;
Paint linePaint = new Paint()
..isAntiAlias = true
..color = Colors.black
..strokeWidth = 1;
Paint pointPaint = new Paint()
..isAntiAlias = true
..color = Colors.red
..strokeWidth = 1;
Paint pathPaint = new Paint()
..isAntiAlias = true
..color = Colors.black38
..style = PaintingStyle.fill;
@override
void paint(Canvas canvas, Size size) {
if (item.tranX != 0 || item.tranY != 0) {
if (item.tranX / item.scareSize > size.width) {
item.tranX = size.width * item.scareSize;
}
if (item.tranY / item.scareSize > size.height) {
item.tranY = size.height * item.scareSize;
}
canvas.translate(-item.tranX, -item.tranY);
}
if (item.scareSize != 1) {
canvas.scale(item.scareSize, item.scareSize);
}
if (item.getImage() != null) {
double scareSize = item.getImage().width / size.width;
double showWidth = size.width;
double showheight = item.getImage().height / scareSize;
if (showheight > size.height) {
showheight = size.height;
}
double top = (size.height - showheight) / 2;
canvas.drawImageRect(
item.getImage(),
Rect.fromLTWH(0.0, 0.0, item.getImage().width.toDouble(),
item.getImage().height.toDouble()),
Rect.fromLTWH(0, top, showWidth, showheight),
ImagePaint);
}
double newX = (item.getX() + item.getTranX()) / item.scareSize;
double newY = (item.getY() + item.getTranY()) / item.scareSize;
if (item.getX() != null &&
item.getY() != null &&
item.getX() >= 0 &&
item.getY() >= 0) {
canvas.drawLine(Offset(newX, 0), Offset(newX, size.height), linePaint);
canvas.drawLine(Offset(0, newY), Offset(size.width, newY), linePaint);
TextPainter(
text: TextSpan(
text: "${newX.toInt()},${newY.toInt()}",
style: TextStyle(
fontSize: 15,
color: Colors.yellow,
fontWeight: FontWeight.w300)),
textDirection: TextDirection.ltr,
textAlign: TextAlign.center)
..layout(maxWidth: 150, minWidth: 30)
..paint(canvas, Offset(newX + 5, newY - 20));
}
if (item.getPoints().isNotEmpty) {
// if(item.getPoints().length==1){
// canvas.drawPoints(pointMode, points, paint)
// }else if(item.getPoints().length==2){
//
// } else{
// for(int i=0;i<item.getPoints().length;i++){
// if(i==item.getPoints().length-1){
//
// }else{
//
// }
// }
// }
canvas.drawPoints(PointMode.polygon, item.getPoints(), pointPaint);
}
print("OK?? ${item.drawPath}");
if (item.drawPath) {
if (item.getPoints().length < 2) {
return;
}
Path path = new Path();
path.moveTo(item.getPoints()[0].dx, item.getPoints()[0].dy);
for (int i = 0; i < item.getPoints().length; i++) {
path.lineTo(item.getPoints()[i].dx, item.getPoints()[i].dy);
}
path.close();
canvas.drawPath(path, pathPaint);
}
}
@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:example_flutter/HomeModel/page/picture/PicPage.dart';
import 'package:example_flutter/HomeModel/page/work/WorkPage.dart';
import 'package:example_flutter/HomeModel/service/HomeRepo.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/UploadResultBean.dart';
import 'package:example_flutter/commonModel/GMBase.dart';
import 'package:example_flutter/commonModel/picker/base/BasePickerComponent.dart';
import 'package:example_flutter/commonModel/toast/toast.dart';
import 'package:example_flutter/res/anim/Anim.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:file_chooser/file_chooser.dart';
class HomeModel extends BaseModel {
HomeRepo repo = HomeRepo.getInstance();
List<UploadResultBean> scanList = new List();
int allSize;
int nowSize;
List<String> uploadFile = new List();
@override
void dispose() {}
void scanImages(BuildContext context) async {
await showOpenPanel((result, files) {
if (result != FileChooserResult.ok || files.isEmpty) {
Toast.show(context, "没有选择文件 批量上传 可以按住shift 或者拖拽鼠标!");
return;
}
BaseCenterPicker()
..setPicker(BaseLoadingItem("上传中..."))
..show(context);
allSize = files.length ;
nowSize = 0;
scanList.clear();
uploadFile.clear();
uploadFile.addAll(files);
uploadImage(context, uploadFile[nowSize]);
}, allowsMultipleSelection: true);
}
void uploadImage(
BuildContext context,
String path,
) {
netUpload(path).then((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
nowSize++;
if (allSize == nowSize) {
Toast.show(context, "上传成功");
// repo.updateScanList(scanList);
success(context);
} else {
uploadImage(context,uploadFile[nowSize]);
}
} else {
Toast.show(context, "上传图片返回接口有空值 暂停上传");
print("上传图片返回接口有空值 暂停上传");
Navigator.pop(context);
}
}).catchError((erro) {
Toast.show(context, erro.toString());
print(erro.toString());
Navigator.pop(context);
});
}
void success(BuildContext buildContext) {
Navigator.pop(buildContext);
Navigator.push(buildContext, CustomRoute(PicPage()));
}
}
Future<Response> netUpload(String path) async {
return DioUtil.getInstance().uploadFile("image-upload/", path);
}
UploadResultBean uploadImg(String value) {
return UploadResultBean.fromJson(json.decode(value));
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/HomeModel/page/home/HomeModel.dart';
import 'package:example_flutter/HomeModel/page/picture/PicPage.dart';
import 'package:example_flutter/commonModel/base/BaseComponent.dart';
import 'package:example_flutter/commonModel/cache/CacheManager.dart';
import 'package:example_flutter/res/GMRes.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/flutter_svg.dart';
class HomePage extends StatefulWidget {
@override
State<StatefulWidget> createState() => HomeState();
}
class HomeState extends State<HomePage> {
HomeModel _model;
Size screenSize;
HomeState() {
_model = new HomeModel();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
screenSize = MediaQuery.of(context).size;
String userName =
CacheManager.getInstance().get(MEMORY_CACHE).get("userName");
return Scaffold(
// appBar: AppBar(
// leading: Text(""),
// backgroundColor: ALColors.Color5276F4,
// actions: <Widget>[
// Expanded(
// child: Container(),
// ),
// Container(
// margin: EdgeInsets.only(right: ScreenUtil.instance.setWidth(10)),
// alignment: Alignment.center,
// child: baseText(userName, 30, ALColors.ColorF8F8F8),
// ),
// Container(
// width: kToolbarHeight,
// height: kToolbarHeight,
// margin: EdgeInsets.only(
// left: ScreenUtil.instance.setWidth(5),
// right: ScreenUtil.instance.setWidth(50),
// top: 5,
// bottom: 5),
// child: SvgPicture.asset("image/Face.svg"),
// ),
// ]),
body: uploadItem(),
);
}
uploadItem() {
return Container(
decoration: BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(
'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1573655792197&di=f9469fa087a082aedfd22514c1549e1f&imgtype=0&src=http%3A%2F%2Fimg8.zol.com.cn%2Fbbs%2Fupload%2F19571%2F19570481.jpg'))),
padding: EdgeInsets.only(
top: ScreenUtil.instance.setWidth(50),
bottom: ScreenUtil.instance.setWidth(80),
left: ScreenUtil.instance.setWidth(80),
right: ScreenUtil.instance.setWidth(80)),
alignment: Alignment.center,
width: screenSize.width,
height: double.maxFinite,
child: InkWell(
onTap: () {
_model.scanImages(context);
},
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.all(
//圆角
Radius.circular(20.0),
),
border: Border.all(width: 1.0),
),
alignment: Alignment.center,
width: double.maxFinite,
height: double.maxFinite,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: 25,
width: 100,
color: Colors.blueAccent,
child: FlatButton(
onPressed: () {
Navigator.push(context, CustomRoute(PicPage()));
},
child: baseText("跳过", 15, Colors.white),
)),
Expanded(
child: Container(
),
),
SvgPicture.asset("image/add.svg"),
Container(
margin: EdgeInsets.only(top: 30),
child: baseText("点击上传照片", 20, ALColors.ColorE4E4E4),
),
Expanded(
child: Container(),
),
],
),
)));
}
}
/*
* @author lsy
* @date 2019-11-13
**/
import 'dart:io';
import 'package:example_flutter/HomeModel/page/work/WorkModel.dart';
import 'package:example_flutter/HomeModel/page/work/WorkPage.dart';
import 'package:example_flutter/HomeModel/service/HomeRepo.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/ImageResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/TotalImageBean.dart';
import 'package:example_flutter/commonModel/GMBase.dart';
import 'package:example_flutter/commonModel/picker/base/BasePickerComponent.dart';
import 'package:example_flutter/commonModel/toast/toast.dart';
import 'package:example_flutter/res/anim/Anim.dart';
import 'package:flutter/cupertino.dart';
class PicModel extends BaseModel {
HomeRepo _repo;
LiveData<List<PicList>> imageLive = new LiveData();
LiveData<int> countLive = new LiveData();
LiveData<TotalImageBean> totalLive = new LiveData();
PicModel() {
_repo = HomeRepo.getInstance();
countLive.notifyView(_repo.currentPage);
}
void getImages(BuildContext context, bool showPop) {
if (showPop) {
BaseCenterPicker()
..setPicker(BaseLoadingItem("加载中。。。"))
..show(context);
}
_repo.getImageResult(_repo.currentPage, 9).listen((data) {
_repo.updateCurrentPageList(data.picList);
imageLive.notifyView(data.picList);
if (showPop) {
Navigator.pop(context);
}
}).onError((error) {
Toast.show(context, error.toString());
print(error.toString());
if (showPop) {
Navigator.pop(context);
}
});
}
void getTotalImages(BuildContext context) {
_repo.getTotalImage().listen((value) {
totalLive.notifyView(value);
}).onError((error) {
Toast.show(context, error.toString());
print(error.toString());
});
}
@override
void dispose() {
imageLive.dispost();
countLive.dispost();
totalLive.dispost();
}
void onItemClick(BuildContext context, int index) {
Navigator.push(
context,
new CustomRoute(WorkPage(_repo.getCurrentPageList()[index].picurl,
_repo.getCurrentPageList()[index].id, index)))
.then((value) {
if (value == -1) {
getImages(context, false);
} else {
imageLive.notifyView(_repo.getCurrentPageList());
}
countLive.notifyView(_repo.currentPage);
});
}
void after(BuildContext context) {
BaseCenterPicker()
..setPicker(BaseLoadingItem("加载中。。。"))
..show(context);
_repo.getImageResult(_repo.currentPage + 1, 9).listen((data) {
if (data == null || data.picList == null || data.picList.isEmpty) {
Toast.show(context, "已经是最后一页了哦~");
} else {
_repo.currentPage = _repo.currentPage + 1;
_repo.updateCurrentPageList(data.picList);
imageLive.notifyView(data.picList);
}
countLive.notifyView(_repo.currentPage);
Navigator.pop(context);
}).onError((error) {
Toast.show(context, error.toString());
print(error.toString());
Navigator.pop(context);
});
}
void before(BuildContext context) {
if (_repo.currentPage == 1) {
Toast.show(context, "已经是第一页了哦");
return;
}
_repo.currentPage = _repo.currentPage - 1;
getImages(context, true);
countLive.notifyView(_repo.currentPage);
}
void onDeleteItem(BuildContext context, int index) {
//TODO
BaseCenterPicker()
..setPicker(SurePicker("确定删除这张照片吗?", () {
Navigator.pop(context);
}, () {
Navigator.pop(context);
//DELETE
_repo.deleteItem(_repo.getCurrentPageList()[index].id).listen((value) {
if (value != null && value.result == "DeleteSucceed") {
//OK
_repo.getImageResult(_repo.currentPage, 9).listen((data) {
if (data != null &&
data.picList != null &&
data.picList.isNotEmpty) {
_repo.updateCurrentPageList(data.picList);
imageLive.notifyView(data.picList);
} else {
if (_repo.currentPage == 1) {
Toast.show(context, "没有数据了");
} else {
_repo
.getImageResult(_repo.currentPage - 1, 9)
.listen((value) {
_repo.currentPage = _repo.currentPage - 1;
_repo.updateCurrentPageList(data.picList);
imageLive.notifyView(data.picList);
}).onError((error) {
Toast.show(context, error.toString());
print(error.toString());
});
}
}
}).onError((error) {
Toast.show(context, error.toString());
print(error.toString());
});
}
}).onError((error) {
Toast.show(context, error.toString());
print(error.toString());
});
}))
..show(context);
}
}
/*
* @author lsy
* @date 2019-11-13
**/
import 'package:example_flutter/HomeModel/base/BaseTitle.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/ImageResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/TotalImageBean.dart';
import 'package:example_flutter/commonModel/base/BaseComponent.dart';
import 'package:example_flutter/res/GMRes.dart';
import 'package:flutter/material.dart';
import 'PicModel.dart';
class PicPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => PicState();
}
class PicState extends State<PicPage> {
PicModel _model;
Size screenSize;
PicState() {
_model = PicModel();
}
@override
void initState() {
super.initState();
_model.getImages(context, false);
_model.getTotalImages(context);
}
@override
void dispose() {
_model.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
screenSize = MediaQuery.of(context).size;
return Scaffold(
appBar: getBaseTitle(context),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
sync(context),
Expanded(
child: imageList(context),
),
nextBefor(context)
],
),
);
}
imageList(BuildContext context) {
for (int i = 0; i < 9; i++) {}
return StreamBuilder<List<PicList>>(
stream: _model.imageLive.stream,
initialData: _model.imageLive.data,
builder: (con, data) {
if (data.data == null) {
return loadingItem();
}
List<Widget> gridList = new List();
for (int i = 0; i < data.data.length; i++) {
String showText;
Color color;
if (data.data[i].status == "0") {
showText = "未分配";
color = Colors.blueGrey;
} else if (data.data[i].status == "1") {
showText = "已分配未标记";
color = Colors.red;
} else if (data.data[i].status == "2") {
showText = "已分配已标记";
color = Colors.green;
}
gridList.add(gridItem(data.data[i].picurl, showText, i, color));
}
return Container(
width: double.maxFinite,
height: double.maxFinite,
alignment: Alignment.center,
child: Container(
width: screenSize.height - 80-58,
height: screenSize.height - 80-58,
child: GridView.count(
crossAxisCount: 3,
mainAxisSpacing: 2.0,
crossAxisSpacing: 2.0,
children: gridList,
)));
},
);
}
gridItem(String url, String showText, int index, Color color) {
return GestureDetector(
onTap: () {
_model.onItemClick(context, index);
},
onLongPress: () {
_model.onDeleteItem(context, index);
},
child: Container(
alignment: Alignment.bottomRight,
decoration: BoxDecoration(
image:
DecorationImage(fit: BoxFit.cover, image: NetworkImage(url))),
child: Container(
color: Colors.yellow,
alignment: Alignment.center,
width: 150,
height: 30,
child: baseText(showText, 15, color),
),
));
}
sync(BuildContext context) {
return Container(
width: double.maxFinite,
height: 30,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
width: 16,
),
baseText("刷新", 15, ALColors.Color323232),
GestureDetector(
onTap: () {
_model.getImages(context, true);
_model.getTotalImages(context);
},
child: Container(
padding: EdgeInsets.only(left: 20),
child: Icon(
Icons.sync,
color: Colors.black,
),
)),
Container(
margin: EdgeInsets.only(left: 50),
child: baseText("长按删除图片", 15, Colors.red),
),
Expanded(
child: StreamBuilder<TotalImageBean>(
stream: _model.totalLive.stream,
initialData: _model.totalLive.data,
builder: (con, data) {
if (data.data == null) {
return loadingItem();
}
return Container(
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20),
child: baseText(
"已标注图片的数量:${data.data.totalTag} 未标注图片的数量${data.data.total}",
15,
Colors.black),
);
},
))
],
),
);
}
nextBefor(BuildContext context) {
return Container(
width: double.maxFinite,
height: 50,
child: Row(
children: <Widget>[
FlatButton(
onPressed: () {
_model.before(context);
},
child: Container(
width: 100,
height: double.maxFinite,
alignment: Alignment.center,
child: baseText("上一页", 15, Colors.black),
),
),
Expanded(
child: StreamBuilder<int>(
stream: _model.countLive.stream,
initialData: _model.countLive.data,
builder: (con, data) {
if (data.data == null) {
return loadingItem();
}
return Container(
alignment: Alignment.center,
child: baseText("第${data.data}页", 15, Colors.black),
);
},
)),
FlatButton(
onPressed: () {
_model.after(context);
},
child: Container(
width: 100,
height: double.maxFinite,
alignment: Alignment.center,
child: baseText("下一页", 15, Colors.black),
),
)
],
),
);
}
}
This diff is collapsed.
This diff is collapsed.
/*
* @author lsy
* @date 2019-11-14
**/
const String TEST_IMAGES = """
{
"pic_list": [
{
"picurl": "https://anno-1258538551.cos.ap-chengdu.myqcloud.com/f540275d1e6d2fbad9273a8f17924e94.png",
"id": 11,
"status": "2"
},
{
"picurl": "https://anno-1258538551.cos.ap-chengdu.myqcloud.com/f540275d1e6d2fbad9273a8f17924e94",
"id": 12,
"status": "2"
}
]
}
""";
const String CACHE_JSON = """
{
"left_eye": {
"name": "左眼",
"leftEyeData": {
"seye": "单眼皮",
"eyes": "双眼皮",
"doubleIn": "内双"
}
},
"rigth_eye": {
"name": "右眼",
"rigthEyeData": {
"seye": "单眼皮",
"eyes": "双眼皮",
"doubleIn": "内双"
}
},
"eyebag": {
"name": "眼袋",
"eyebagData": {
"yes": "有",
"no": "无"
}
},
"eyestyle_left": {
"name": "左眼风格",
"eyestyleLeftData": {
"Almon_eyes": "杏眼",
"Peach": "桃花眼",
"Fine_cheng": "细凤眼",
"deer_eye": "小鹿眼",
"dog_eye": "小狗眼"
}
},
"eyestyle_right": {
"name": "右眼眼风格",
"eyestyleRightData": {
"Almon_eyes": "杏眼",
"Peach": "桃花眼",
"Fine_cheng": "细凤眼",
"deer_eye": "小鹿眼",
"dog_eye": "小狗眼"
}
},
"nose": {
"name": "鼻翼",
"noseData": {
"Narrow_nose": "窄鼻翼",
"Standard_nose": "标准鼻翼",
"widep_nose": "偏宽鼻翼",
"wide_nose": "宽鼻翼"
}
},
"mouth": {
"name": "嘴唇厚度",
"mouthData": {
"Standard": "标准唇",
"Thick": "厚唇",
"thin": "薄唇"
}
},
"lip": {
"name": "唇峰",
"lipData": {
"yes": "有",
"no": "无",
"not_obvious": "有唇峰,但不明显"
}
},
"wrink": {
"name": "法令纹",
"wrinkData": {
"yes": "有",
"no": "无"
}
},
"checkbone": {
"name": "颧骨",
"checkboneData": {
"high": "高颧骨",
"flat": "平颧骨"
}
},
"eyebow": {
"name": "眉毛挑度",
"eyebowData": {
"On": "上挑眉",
"Standard": "标准眉",
"one": "一字眉",
"sagging": "下垂眉"
}
},
"chin": {
"name": "下巴",
"chinData": {
"tip": "尖",
"party": "方",
"round": "圆",
"Ass": "屁股下巴"
}
},
"Eyebrowstyle": {
"name": "眉毛风格",
"eyebrowstyleData": {
"willow": "柳叶眉",
"wild": "野生眉"
}
},
"eyebrowthickness": {
"name": "眉毛粗细",
"eyebrowthicknessData": {
"cumei": "粗眉",
"biaozhunmei": "标准眉",
"xiemei": "细眉"
}
},
"Eyebrowsconcentration": {
"name": "眉毛浓度",
"eyebrowsconcentrationData": {
"piandan": "偏淡",
"feichandan": "非常淡",
"nongduzhenghao": "浓密正好"
}
},
"Eyebrowsconcentration_f": {
"name": "浓度分布",
"eyebrowsconcentration_fData": {
"fenbujunyun": "分布均匀",
"qianshuhoumi": "前疏后密",
"qianmuhoushu": "前密后疏",
"lianjunyun": "分布偏均匀"
}
},
"eyespacing": {
"name": "两眼间距",
"eyespacingData": {
"wide": "宽",
"narrow": "窄",
"appropriate": "适当"
}
},
"brow": {
"name": "两眉间距",
"browData": {
"wide": "宽",
"narrow": "窄",
"appropriate": "适当"
}
},
"lipscurved": {
"name": "嘴唇弧度",
"lipscurvedData": {
"smile": "微笑唇",
"moderate": "温和唇",
"attitude": "态度唇"
}
},
"Speciallip": {
"name": "嘴唇形态",
"speciallipData": {
"Cherry_lip": "樱桃唇",
"Supermodel_lip": "超模唇"
}
},
"face": {
"name": "脸型",
"faceData": {
"baby_face": "娃娃脸",
"guazilian": "瓜子脸",
"fanglian": "方脸",
"edanlian": "鹅蛋脸",
"changxinglian": "长型脸",
"lixinglian": "梨形脸",
"jingzhuan": "晶钻脸"
}
}
}
""";
const Map<String, String> EXPLAN = {
"eyelid_right": "右眼",
"eyelid_left": "左眼",
"nose": "鼻翼",
"eye_shape_right": "右眼风格",
"eye_shape_left": "左眼风格",
"wrink": "法令纹",
"lip_thickness": "嘴唇厚度",
"lip_peak": "唇峰",
"cheekbone": "颧骨",
"brow_shape": "眉毛挑度",
"brow_density": "浓度分布",
"pouch": "眼袋",
"chin_shape": "下巴",
"eye_distance": "两眼间距",
"lip_shape": "嘴唇形态",
"lip_radian": "嘴唇弧度",
"brows_style": "眉毛风格",
"brows_thickness": "眉毛粗细",
"Dense": "眉毛浓度",
"brows_spacing": "两眉间距",
"face": "脸型",
};
/*
* @author lsy
* @date 2019-11-07
**/
import 'dart:convert';
import 'package:example_flutter/HomeModel/page/work/temp.dart';
import 'package:example_flutter/HomeModel/service/remote/api/HomeApi.serv.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/AllTabBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/DeleteResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/ImageAiBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/ImageResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/PutImageDataBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/TotalImageBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/UploadResultBean.dart';
import 'package:example_flutter/commonModel/GMBase.dart';
import 'package:flutter/foundation.dart';
import 'package:rxdart/rxdart.dart';
ImageResultBean paseImageResult(String value) {
return ImageResultBean.fromJson(json.decode(value));
}
class HomeRepo {
static HomeRepo _repo;
HomeRepo._();
static HomeRepo getInstance() {
if (_repo == null) {
_repo = new HomeRepo._();
}
return _repo;
}
int currentPage = 1;
Observable<AllTabBean> getAllTab() {
return HomeApiImpl().getAllTab();
}
List<UploadResultBean> scanList = new List();
void updateScanList(List<UploadResultBean> newList) {
this.scanList = newList;
}
Observable<ImageResultBean> getImageResult(
int currentPage, int onePageCount) {
return HomeApiImpl().getImageList(currentPage, 9);
// return Observable.fromFuture(compute(paseImageResult, TEST_IMAGES));
}
Observable<UploadResultBean> upload() {
// DioUtil().downloadFile(urlPath, savePath)
}
List<PicList> currentList = new List();
void updateCurrentPageList(List<PicList> picList) {
if (picList != null && picList.isNotEmpty) {
currentList.clear();
currentList.addAll(picList);
}
}
List<PicList> getCurrentPageList() {
return currentList;
}
Observable<ImageAiBean> imageAi(int id) {
return Observable.fromFuture(DioUtil().get('images/${id}/'))
.flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(compute(paseImageAi, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<PutImageDataBean> saveImageResult(int id, String jsonResult) {
return Observable.fromFuture(DioUtil.getInstance()
.getDio()
.put('images/${id}/', data: jsonResult))
.flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(compute(parsePutImageBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<DeleteResultBean> deleteItem(int id) {
return Observable.fromFuture(
DioUtil.getInstance().getDio().delete("images/${id}/"))
.flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(compute(parseDeleteResult, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<TotalImageBean> getTotalImage() {
return HomeApiImpl().getTotalImages();
}
// Observable<>
}
ImageAiBean paseImageAi(String value) {
return ImageAiBean.fromJson(json.decode(value));
}
DeleteResultBean parseDeleteResult(String value) {
return DeleteResultBean.fromJson(json.decode(value));
}
PutImageDataBean parsePutImageBean(String value){
return PutImageDataBean.fromJson(json.decode(value));
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/Annotations/anno/Get.dart';
import 'package:example_flutter/Annotations/anno/Post.dart';
import 'package:example_flutter/Annotations/anno/Query.dart';
import 'package:example_flutter/Annotations/anno/ServiceCenter.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/AllTabBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/ImageResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/TotalImageBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/UploadResultBean.dart';
@ServiceCenter()
abstract class HomeApi{
@Get("anno-meta/")
AllTabBean getAllTab();
@Post("image-upload/")
UploadResultBean upload(Map upload);
@Get("imagelist/")
ImageResultBean getImageList(@Query("page")int page,@Query("pageSize")int pageSize);
@Get("countimage/")
TotalImageBean getTotalImages();
}
\ No newline at end of file
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// ServiceGenerator
// **************************************************************************
import 'dart:convert';
import 'dart:io';
import 'package:rxdart/rxdart.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/AllTabBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/UploadResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/ImageResultBean.dart';
import 'package:example_flutter/HomeModel/service/remote/entity/TotalImageBean.dart';
import 'package:example_flutter/commonModel/net/DioUtil.dart';
class HomeApiImpl {
factory HomeApiImpl() => _sharedInstance();
static HomeApiImpl _instance;
HomeApiImpl._() {}
static HomeApiImpl _sharedInstance() {
if (_instance == null) {
_instance = HomeApiImpl._();
}
return _instance;
}
Observable<AllTabBean> getAllTab() {
return Observable.fromFuture(DioUtil().get('anno-meta/')).flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(compute(paseAllTabBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<UploadResultBean> upload() {
return Observable.fromFuture(DioUtil().post('image-upload/'))
.flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(
compute(paseUploadResultBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<ImageResultBean> getImageList(int page, int pageSize) {
return Observable.fromFuture(DioUtil().get('imagelist/',
data: {'page': page, 'pageSize': pageSize})).flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(
compute(paseImageResultBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<TotalImageBean> getTotalImages() {
return Observable.fromFuture(DioUtil().get('countimage/')).flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(
compute(paseTotalImageBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
}
AllTabBean paseAllTabBean(String value) {
return AllTabBean.fromJson(json.decode(value));
}
UploadResultBean paseUploadResultBean(String value) {
return UploadResultBean.fromJson(json.decode(value));
}
ImageResultBean paseImageResultBean(String value) {
return ImageResultBean.fromJson(json.decode(value));
}
TotalImageBean paseTotalImageBean(String value) {
return TotalImageBean.fromJson(json.decode(value));
}
This diff is collapsed.
/*
* @author lsy
* @date 2019-11-18
**/
class DeleteResultBean {
String result;
DeleteResultBean({this.result});
DeleteResultBean.fromJson(Map<String, dynamic> json) {
result = json['result'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['result'] = this.result;
return data;
}
}
/*
* @author lsy
* @date 2019-11-15
**/
class ImageAiBean {
String url;
Anno anno;
ImageAiBean({this.url, this.anno});
ImageAiBean.fromJson(Map<String, dynamic> json) {
url = json['url'];
anno = json['anno'] != null ? new Anno.fromJson(json['anno']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
if (this.anno != null) {
data['anno'] = this.anno.toJson();
}
return data;
}
}
class Anno {
String browShape;
String browsStyle;
String browsSpacing;
String browsThickness;
String dense;
String browDensity;
String face;
String pouch;
String eyelidLeft;
String eyelidRight;
String eyeShapeLeft;
String eyeShapeRight;
String eyeDistance;
String cheekbone;
String chinShape;
String wrink;
String nose;
String lipThickness;
String lipRadian;
String lipShape;
String lipPeak;
Anno(
{this.browShape,
this.browsStyle,
this.browsSpacing,
this.browsThickness,
this.dense,
this.browDensity,
this.face,
this.pouch,
this.eyelidLeft,
this.eyelidRight,
this.eyeShapeLeft,
this.eyeShapeRight,
this.eyeDistance,
this.cheekbone,
this.chinShape,
this.wrink,
this.nose,
this.lipThickness,
this.lipRadian,
this.lipShape,
this.lipPeak});
Anno.fromJson(Map<String, dynamic> json) {
browShape = json['brow_shape'];
browsStyle = json['brows_style'];
browsSpacing = json['brows_spacing'];
browsThickness = json['brows_thickness'];
dense = json['Dense'];
browDensity = json['brow_density'];
face = json['face'];
pouch = json['pouch'];
eyelidLeft = json['eyelid_left'];
eyelidRight = json['eyelid_right'];
eyeShapeLeft = json['eye_shape_left'];
eyeShapeRight = json['eye_shape_right'];
eyeDistance = json['eye_distance'];
cheekbone = json['cheekbone'];
chinShape = json['chin_shape'];
wrink = json['wrink'];
nose = json['nose'];
lipThickness = json['lip_thickness'];
lipRadian = json['lip_radian'];
lipShape = json['lip_shape'];
lipPeak = json['lip_peak'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['brow_shape'] = this.browShape;
data['brows_style'] = this.browsStyle;
data['brows_spacing'] = this.browsSpacing;
data['brows_thickness'] = this.browsThickness;
data['Dense'] = this.dense;
data['brow_density'] = this.browDensity;
data['face'] = this.face;
data['pouch'] = this.pouch;
data['eyelid_left'] = this.eyelidLeft;
data['eyelid_right'] = this.eyelidRight;
data['eye_shape_left'] = this.eyeShapeLeft;
data['eye_shape_right'] = this.eyeShapeRight;
data['eye_distance'] = this.eyeDistance;
data['cheekbone'] = this.cheekbone;
data['chin_shape'] = this.chinShape;
data['wrink'] = this.wrink;
data['nose'] = this.nose;
data['lip_thickness'] = this.lipThickness;
data['lip_radian'] = this.lipRadian;
data['lip_shape'] = this.lipShape;
data['lip_peak'] = this.lipPeak;
return data;
}
}
/*
* @author lsy
* @date 2019-11-14
**/
class ImageResultBean {
List<PicList> picList;
ImageResultBean({this.picList});
ImageResultBean.fromJson(Map<String, dynamic> json) {
if (json['pic_list'] != null) {
picList = new List<PicList>();
json['pic_list'].forEach((v) {
picList.add(new PicList.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.picList != null) {
data['pic_list'] = this.picList.map((v) => v.toJson()).toList();
}
return data;
}
}
class PicList {
String picurl;
int id;
String status;
PicList({this.picurl, this.id, this.status});
PicList.fromJson(Map<String, dynamic> json) {
picurl = json['picurl'];
id = json['id'];
status = json['status'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['picurl'] = this.picurl;
data['id'] = this.id;
data['status'] = this.status;
return data;
}
}
/*
* @author lsy
* @date 2019-11-18
**/
class PutImageDataBean {
Result result;
PutImageDataBean({this.result});
PutImageDataBean.fromJson(Map<String, dynamic> json) {
result =
json['result'] != null ? new Result.fromJson(json['result']) : null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.result != null) {
data['result'] = this.result.toJson();
}
return data;
}
}
class Result {
String url;
FaceDetails faceDetails;
Result({this.url, this.faceDetails});
Result.fromJson(Map<String, dynamic> json) {
url = json['url'];
faceDetails = json['face_details'] != null
? new FaceDetails.fromJson(json['face_details'])
: null;
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
if (this.faceDetails != null) {
data['face_details'] = this.faceDetails.toJson();
}
return data;
}
}
class FaceDetails {
String eyelidRight;
String eyelidLeft;
String nose;
String wrink;
String lipThickness;
String lipPeak;
String pouch;
String cheekbone;
String browShape;
String browDensity;
String chinShape;
String lipShape;
String lipRadian;
String eyeShapeRight;
String eyeShapeLeft;
String eyebrowstyle;
String eyebrowthickness;
String eyebrowsconcentration;
String brow;
String eyeDistance;
String face;
FaceDetails(
{this.eyelidRight,
this.eyelidLeft,
this.nose,
this.wrink,
this.lipThickness,
this.lipPeak,
this.pouch,
this.cheekbone,
this.browShape,
this.browDensity,
this.chinShape,
this.lipShape,
this.lipRadian,
this.eyeShapeRight,
this.eyeShapeLeft,
this.eyebrowstyle,
this.eyebrowthickness,
this.eyebrowsconcentration,
this.brow,
this.eyeDistance,
this.face});
FaceDetails.fromJson(Map<String, dynamic> json) {
eyelidRight = json['eyelid_right'];
eyelidLeft = json['eyelid_left'];
nose = json['nose'];
wrink = json['wrink'];
lipThickness = json['lip_thickness'];
lipPeak = json['lip_peak'];
pouch = json['pouch'];
cheekbone = json['cheekbone'];
browShape = json['brow_shape'];
browDensity = json['brow_density'];
chinShape = json['chin_shape'];
lipShape = json['lip_shape'];
lipRadian = json['lip_radian'];
eyeShapeRight = json['eye_shape_right'];
eyeShapeLeft = json['eye_shape_left'];
eyebrowstyle = json['Eyebrowstyle'];
eyebrowthickness = json['eyebrowthickness'];
eyebrowsconcentration = json['Eyebrowsconcentration'];
brow = json['brow'];
eyeDistance = json['eye_distance'];
face = json['face'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['eyelid_right'] = this.eyelidRight;
data['eyelid_left'] = this.eyelidLeft;
data['nose'] = this.nose;
data['wrink'] = this.wrink;
data['lip_thickness'] = this.lipThickness;
data['lip_peak'] = this.lipPeak;
data['pouch'] = this.pouch;
data['cheekbone'] = this.cheekbone;
data['brow_shape'] = this.browShape;
data['brow_density'] = this.browDensity;
data['chin_shape'] = this.chinShape;
data['lip_shape'] = this.lipShape;
data['lip_radian'] = this.lipRadian;
data['eye_shape_right'] = this.eyeShapeRight;
data['eye_shape_left'] = this.eyeShapeLeft;
data['Eyebrowstyle'] = this.eyebrowstyle;
data['eyebrowthickness'] = this.eyebrowthickness;
data['Eyebrowsconcentration'] = this.eyebrowsconcentration;
data['brow'] = this.brow;
data['eye_distance'] = this.eyeDistance;
data['face'] = this.face;
return data;
}
}
/*
* @author lsy
* @date 2019-11-18
**/
class TotalImageBean {
int totalTag;
int total;
TotalImageBean({this.totalTag, this.total});
TotalImageBean.fromJson(Map<String, dynamic> json) {
totalTag = json['total_tag'];
total = json['total'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['total_tag'] = this.totalTag;
data['total'] = this.total;
return data;
}
}
/*
* @author lsy
* @date 2019-11-07
**/
class UploadResultBean {
String url;
int id;
UploadResultBean({this.url, this.id});
UploadResultBean.fromJson(Map<String, dynamic> json) {
url = json['url'];
id = json['id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['url'] = this.url;
data['id'] = this.id;
return data;
}
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/Annotations/RouterBaser.dart';
import 'package:example_flutter/Annotations/anno/Router.dart';
import 'package:example_flutter/UserModel/UserRouterImpl.dart';
import 'package:flutter/cupertino.dart';
@Router("UserRouter",UserRouterImpl,true)
abstract class UserRouter extends RouterBaser{
Widget getLoginPage();
}
\ No newline at end of file
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/UserModel/UserRouter.dart';
import 'package:example_flutter/UserModel/page/login/LoginPage.dart';
import 'package:flutter/src/widgets/framework.dart';
class UserRouterImpl implements UserRouter {
@override
Widget getLoginPage() {
return LoginPage();
}
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'dart:io';
import 'package:example_flutter/Annotations/RouterCenterRestore.mark.dart';
import 'package:example_flutter/UserModel/service/Resp.dart';
import 'package:example_flutter/commonModel/GMBase.dart';
import 'package:example_flutter/commonModel/cache/CacheManager.dart';
import 'package:example_flutter/commonModel/toast/toast.dart';
import 'package:example_flutter/res/anim/Anim.dart';
import 'package:flutter/cupertino.dart';
class LoginModel extends BaseModel {
resign(BuildContext context, String text, String text2) {
Resp.getInstance().resign(text, text2).listen((value) {
Navigator.pop(context);
if (value != null && value.username != null) {
login(context, text, text2);
} else {
Toast.show(context, "网络接口错误 ==> resign");
}
}).onError((error) {
Navigator.pop(context);
Toast.show(context, "该用户名已经被注册");
print(error.toString());
});
}
login(BuildContext context, String text, String text2) async {
Resp.getInstance().login(text, text2).listen((value) {
Navigator.pop(context);
if (value != null && value.token != null) {
CacheManager.getInstance().get(MEMORY_CACHE).save("token", value.token);
CacheManager.getInstance().get(MEMORY_CACHE).save("userName", text);
CacheManager.getInstance().get(MEMORY_CACHE).save("userWorld", text2);
Toast.show(context, "登入成功");
Navigator.push(context, CustomRoute(
RouterCenterImpl().findHomeRouter()?.getHomePage()
));
} else {
Toast.show(context, "接口请求错误 ==> login");
}
}).onError((error) {
Navigator.pop(context);
Toast.show(context, error.toString());
print(error.toString());
});
}
@override
void dispose() {}
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'dart:ui';
import 'package:example_flutter/UserModel/page/login/LoginModel.dart';
import 'package:example_flutter/commonModel/GMBase.dart';
import 'package:example_flutter/commonModel/base/BaseComponent.dart';
import 'package:example_flutter/commonModel/picker/base/BasePickerComponent.dart';
import 'package:example_flutter/commonModel/toast/toast.dart';
import 'package:example_flutter/res/GMRes.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
class LoginPage extends StatefulWidget {
@override
State<StatefulWidget> createState() => LoginState();
}
class LoginState extends State<LoginPage> {
LoginModel _model;
TextEditingController _nameCon;
TextEditingController _wordCon;
LoginState() {
_model = LoginModel();
}
@override
void initState() {
super.initState();
_nameCon = TextEditingController();
_wordCon = TextEditingController();
}
@override
void dispose() {
super.dispose();
_nameCon.dispose();
_wordCon.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints.expand(),
child: BackdropFilter(
filter: new ImageFilter.blur(sigmaX: 100, sigmaY: 100),
child: Image.network(
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1573655792197&di=f9469fa087a082aedfd22514c1549e1f&imgtype=0&src=http%3A%2F%2Fimg8.zol.com.cn%2Fbbs%2Fupload%2F19571%2F19570481.jpg",
fit: BoxFit.cover,
)),
),
main()
],
));
}
main() {
return Container(
width: double.maxFinite,
height: double.maxFinite,
alignment: Alignment.center,
child: Container(
width: 600,
height: 350,
color: Colors.black38,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expanded(
child: Container(),
),
baseText("更美AI标注平台", 30, ALColors.ColorF8F8F8),
Container(
margin: EdgeInsets.only(
top: ScreenUtil.instance.setHeight(20),
left: ScreenUtil.instance.setWidth(100),
right: ScreenUtil.instance.setWidth(100)),
child: TextField(
controller: _nameCon,
keyboardType: TextInputType.number,
cursorColor: Colors.white,
decoration: InputDecoration(
hoverColor: Colors.white,
fillColor: Colors.white,
focusColor: Colors.white,
contentPadding: EdgeInsets.all(10.0),
icon: Icon(
Icons.person,
size: ScreenUtil.instance.setSp(30),
),
labelText: '请输入你的用户名',
// helperText: '请输入你的用户名',
labelStyle: TextStyle(color: Colors.white),
helperStyle: TextStyle(color: Colors.white)),
autofocus: false,
),
),
Container(
margin: EdgeInsets.only(
top: ScreenUtil.instance.setHeight(20),
left: ScreenUtil.instance.setWidth(100),
right: ScreenUtil.instance.setWidth(100)),
child: TextField(
controller: _wordCon,
keyboardType: TextInputType.number,
cursorColor: Colors.white,
decoration: InputDecoration(
hoverColor: Colors.white,
fillColor: Colors.white,
focusColor: Colors.white,
contentPadding: EdgeInsets.all(10.0),
icon: Icon(
Icons.wb_cloudy,
size: ScreenUtil.instance.setSp(30),
),
labelText: '请输入你的密码',
// helperText: '请输入你的用户名',
labelStyle: TextStyle(color: Colors.white),
helperStyle: TextStyle(color: Colors.white)),
autofocus: false,
),
),
Container(
width: double.maxFinite,
height: ScreenUtil.instance.setHeight(130),
margin: EdgeInsets.only(
top: ScreenUtil.instance.setHeight(80),
left: ScreenUtil.instance.setWidth(100),
right: ScreenUtil.instance.setWidth(100)),
child: RaisedButton(
onPressed: () {
if (_nameCon.text.length == 0 ||
_wordCon.text.length == 0) {
Toast.show(context, "账号或者密码为空");
return;
}
BaseCenterPicker()
..setPicker(BaseLoadingItem("加载中..."))
..show(context);
_model.login(context, _nameCon.text, _wordCon.text);
},
color: Colors.deepOrange,
child: baseText("登入", ScreenUtil.instance.setSp(15),
ALColors.ColorFFFFFF),
)),
Container(
width: double.maxFinite,
height: ScreenUtil.instance.setHeight(130),
margin: EdgeInsets.only(
top: ScreenUtil.instance.setHeight(20),
left: ScreenUtil.instance.setWidth(100),
right: ScreenUtil.instance.setWidth(100)),
child: RaisedButton(
color: Colors.deepPurpleAccent,
onPressed: () {
BaseCenterPicker()
..setPicker(BaseLoadingItem("加载中..."))
..show(context);
_model.resign(context, _nameCon.text, _wordCon.text);
},
child: baseText("注册", ScreenUtil.instance.setSp(15),
ALColors.ColorFFFFFF),
)),
Expanded(
child: Container(),
),
],
),
));
}
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'dart:convert';
import 'dart:io';
import 'package:example_flutter/UserModel/service/remote/api/UserApi.serv.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserBean.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserToken.dart';
import 'package:rxdart/rxdart.dart';
class Resp {
static Resp _resp;
Resp._();
static Resp getInstance() {
if (_resp == null) {
_resp = Resp._();
}
return _resp;
}
Observable<UserToken> login(String userName, String userWord) {
return UserApiImpl().login(userName, userWord);
}
Observable<UserBean> resign(String userName, String userWord) {
return UserApiImpl().resign(userName, userWord);
}
}
/*
* @author lsy
* @date 2019-11-07
**/
import 'package:example_flutter/Annotations/anno/Get.dart';
import 'package:example_flutter/Annotations/anno/Post.dart';
import 'package:example_flutter/Annotations/anno/Query.dart';
import 'package:example_flutter/Annotations/anno/ServiceCenter.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserBean.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserInfoBean.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserToken.dart';
@ServiceCenter()
abstract class UserApi {
@Post("api-token-auth/")
UserToken login(
@Query("username") String userName, @Query("password") String password);
@Post("users/")
UserBean resign(
@Query("username") String userName, @Query("password") String password);
@Get("userinfo/")
UserInfoBean getUserInfo();
}
// GENERATED CODE - DO NOT MODIFY BY HAND
// **************************************************************************
// ServiceGenerator
// **************************************************************************
import 'dart:convert';
import 'dart:io';
import 'package:rxdart/rxdart.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserToken.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserBean.dart';
import 'package:example_flutter/UserModel/service/remote/entity/UserInfoBean.dart';
import 'package:example_flutter/commonModel/net/DioUtil.dart';
class UserApiImpl {
factory UserApiImpl() => _sharedInstance();
static UserApiImpl _instance;
UserApiImpl._() {}
static UserApiImpl _sharedInstance() {
if (_instance == null) {
_instance = UserApiImpl._();
}
return _instance;
}
Observable<UserToken> login(String userName, String password) {
return Observable.fromFuture(DioUtil().post('api-token-auth/',
data: {'username': userName, 'password': password})).flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(compute(paseUserToken, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<UserBean> resign(String userName, String password) {
return Observable.fromFuture(DioUtil().post('users/',
data: {'username': userName, 'password': password})).flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(compute(paseUserBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
Observable<UserInfoBean> getUserInfo() {
return Observable.fromFuture(DioUtil().get('userinfo/')).flatMap((value) {
if (value != null &&
(value.statusCode >= 200 && value.statusCode < 300)) {
return Observable.fromFuture(
compute(paseUserInfoBean, value.toString()));
} else {
return Observable.fromFuture(null);
}
});
}
}
UserToken paseUserToken(String value) {
return UserToken.fromJson(json.decode(value));
}
UserBean paseUserBean(String value) {
return UserBean.fromJson(json.decode(value));
}
UserInfoBean paseUserInfoBean(String value) {
return UserInfoBean.fromJson(json.decode(value));
}
/*
* @author lsy
* @date 2019-11-07
**/
class UserBean {
String username;
UserBean({this.username});
UserBean.fromJson(Map<String, dynamic> json) {
username = json['username'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['username'] = this.username;
return data;
}
}
/*
* @author lsy
* @date 2019-11-15
**/
class UserInfoBean {
int uid;
String username;
UserInfoBean({this.uid, this.username});
UserInfoBean.fromJson(Map<String, dynamic> json) {
uid = json['uid'];
username = json['username'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uid'] = this.uid;
data['username'] = this.username;
return data;
}
}
/*
* @author lsy
* @date 2019-11-07
**/
class UserToken {
String token;
UserToken({this.token});
UserToken.fromJson(Map<String, dynamic> json) {
token = json['token'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['token'] = this.token;
return data;
}
}
/*
* @author lsy
* @date 2019-10-15
**/
library GMBase;
export 'base/BaseComponent.dart';
export 'base/BaseUtil.dart';
export 'live/BaseModel.dart';
export 'live/LiveData.dart';
export 'net/Api.dart';
export 'net/DioUtil.dart';
export 'net/ALNetWork.dart';
export 'picker/loadingPicker.dart';
export 'picker/base/BaseCenterPicker.dart';
/*
* @author lsy
* @date 2019-10-13
**/
import 'package:example_flutter/res/value/ALColors.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
MethodChannel channel=new MethodChannel("plugins.flutter.io/path_provider");
Future getTempDir(){
return channel.invokeMethod("getTemporaryDirectory");
}
Future openCachce(){
return channel.invokeMethod("openCache");
}
AppBar baseAppBar(
{String title,
List<Widget> action,
bool centerTitle,
VoidCallback backClick,
Color backgroundColor}) {
return baseAppBarChangeTitle(
title: title == null
? Container()
: baseText(title, 16, ALColors.Color323232),
action: action,
centerTitle: centerTitle,
backClick: backClick,
backgroundColor: backgroundColor);
}
AppBar baseAppBarChangeTitle(
{Widget title,
List<Widget> action,
bool centerTitle,
VoidCallback backClick,
Color backgroundColor}) {
return AppBar(
backgroundColor:
backgroundColor == null ? ALColors.ColorFFFFFF : backgroundColor,
title: title,
centerTitle: centerTitle,
elevation: 0.0,
leading: GestureDetector(
onTap: backClick,
child: Hero(
tag: "left_arrow",
child: Container(
color: backgroundColor == null
? ALColors.ColorFFFFFF
: backgroundColor,
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 22),
width: 30,
height: double.maxFinite,
child: SvgPicture.asset(
"image/left_arrow.svg",
color: Color(0xff323232),
))),
),
actions: action == null ? List<Widget>() : action,
);
}
Text baseText(String text, double fontSize, Color color) {
return Text(
text,
textScaleFactor: 1.0,
softWrap: true,
style: TextStyle(fontSize: fontSize, color: color),
);
}
/**
* 基础的liveView分割线
*/
Widget baseDivide(double height, double padding, Color color) {
return Container(
height: height,
margin: EdgeInsets.only(
right: ScreenUtil.instance.setWidth(padding),
left: ScreenUtil.instance.setWidth(padding)),
child: Container(
color: color,
));
}
Widget loadingItem() {
//TODO
return Center(child: CircularProgressIndicator());
}
Widget netErrorItem() {}
//TODO
/*
* @author lsy
* @date 2019-10-14
**/
import 'dart:ui';
import 'package:flutter/material.dart';
void jumpToPage(Widget page, BuildContext context) {
Navigator.push(context, MaterialPageRoute(builder: ((context) {
return page;
})));
}
/*
* @author lsy
* @date 2019-11-14
**/
import 'package:flutter/material.dart';
class MySeparator extends StatelessWidget {
final double height;
final Color color;
const MySeparator({this.height = 1, this.color = Colors.black});
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
final boxWidth = constraints.constrainWidth();
final dashWidth = 10.0;
final dashHeight = height;
final dashCount = (boxWidth / (2 * dashWidth)).floor();
return Flex(
children: List.generate(dashCount, (_) {
return SizedBox(
width: dashWidth,
height: dashHeight,
child: DecoratedBox(
decoration: BoxDecoration(color: color),
),
);
}),
mainAxisAlignment: MainAxisAlignment.spaceBetween,
direction: Axis.horizontal,
);
},
);
}
}
abstract class BlocBase {
void dispose();
}
import 'package:flutter/widgets.dart';
import 'bloc_base.dart';
Type _typeOf<T>() => T;
class BlocProvider<T extends BlocBase> extends StatefulWidget {
BlocProvider({
Key key,
@required this.child,
@required this.blocs,
}) : super(key: key);
final Widget child;
final List<T> blocs;
@override
_BlocProviderState<T> createState() => _BlocProviderState<T>();
static List<T> of<T extends BlocBase>(BuildContext context) {
final type = _typeOf<_BlocProviderInherited<T>>();
_BlocProviderInherited<T> provider =
context.ancestorInheritedElementForWidgetOfExactType(type)?.widget;
return provider?.blocs;
}
}
class _BlocProviderState<T extends BlocBase> extends State<BlocProvider<T>> {
@override
void dispose() {
widget.blocs.map((bloc) {
bloc.dispose();
});
super.dispose();
}
@override
Widget build(BuildContext context) {
return _BlocProviderInherited<T>(
blocs: widget.blocs,
child: widget.child,
);
}
}
class _BlocProviderInherited<T> extends InheritedWidget {
_BlocProviderInherited({
Key key,
@required Widget child,
@required this.blocs,
}) : super(key: key, child: child);
final List<T> blocs;
@override
bool updateShouldNotify(_BlocProviderInherited oldWidget) => false;
}
/*
* @author lsy
* @date 2019-10-08
**/
import 'MemoryCache.dart';
const MEMORY_CACHE = "MEMORY_CACHE";
const SHARE_CACHE = "SHARE_CACHE";
class CacheManager {
MemoryCache memoryCache;
static CacheManager _instance = CacheManager._();
CacheManager._() {
memoryCache = new MemoryCache();
}
static CacheManager getInstance() {
return _instance;
}
ICache get(String whichCache) {
if (whichCache == MEMORY_CACHE) {
return memoryCache;
}
}
}
class ICache {
dynamic get(String key) {}
void save(String key, dynamic value) {}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
library flutter_drag_scale;
export './core/drag_scale_widget.dart';
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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