Public account: wechat search front end tool person; Take more dry goods

Original link: my blog garden article

First, opening remarks:

  1. At present asflutter github startNumber has been94.4 K.This potentially illustrates the trend of App development after this event.
  2. As a new show, it has a strong following but the community ecology is not perfect. There are also many functions that do not have plug-ins.
  3. I am honored to contribute to the Flutter community

Second, the steps

2.1. Create a plug-in package

Note: The Flutter plugin project uses Objective-C by default for iOS code and Java for Android code. Unless you manually change it (mine is)

flutter create --org com.example --template=plugin hello



// Change the native language

flutter create --template=plugin -i swift -a kotlin hello

/ / or

flutter create --template=plugin -i objc -a java hello

Copy the code

2.2. Partial structure

  1. The plug-in packageDart API
    • lib/hello.dart
  2. The plug-in packageAPItheAndroidimplementation
    • lib/hello.dart
  3. The plug-in packageAPItheiosimplementation
    • ios/Classes/HelloPlugin.m
  4. One that depends on the plug-inFlutterApplication, to explain how to use it
    • example/

2.3 implementationpackagepackage

Write business code (note: if you modify native code, you need to run flutter build apk so that your example can use the function you edited)

To edit Android code with Android Studio or Vscode, make sure the code has been built at least once before you write it (for example, CD to hello/example; Build APK in flutter)

  1. Exposed method: The directory is in the root directorylib/hello.dart
class Flutter3desPlugin {

  static const MethodChannel _channel =

      const MethodChannel('hello');



  static Future<String> get platformVersion async {

    final String version = await _channel.invokeMethod('getPlatformVersion');

    return version;

  }

// Encryption method

  static Future<String> encrypt(String key, String data) async{

    return await _channel.invokeMethod('encrypt' , <String,dynamic>{'data':data,'key':key});

  }



Copy the code
  1. The directory changed by Android isandroid/src/main/java/com/yourcompany/​hello/HelloPlugin.javaThe inside of theonMethodCallMethod, as shown below, where the comment section is needed
@Override

public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {

/ / theifGracefully change to switch and add the ENCRYPT condition, which will correspond to the name of the method you expose

  switch (call.method) {

    case "getPlatformVersion":

      result.success("Android " + android.os.Build.VERSION.RELEASE);

      break;

    case "encrypt": // Method mapping

        String body = call.argument("data");

        String keys = call.argument("key");

        String key = keys + keys.substring(0,16);

        byte [] text = encrypt(hexStr2Bytes(key),hexStr2Bytes(body));

        result.success(bytes2HexStr(text));

      break;

    default:

      result.notImplemented();

      break;

}

}

private static final String algorithm = "DESede";



// The implementation of the method

public static byte[] encrypt(byte[] key, byte[] body) {

  try {

      SecretKey deskey = new SecretKeySpec(key, algorithm);

      Cipher c1 = Cipher.getInstance(algorithm);

      c1.init(Cipher.ENCRYPT_MODE, deskey);

      return c1.doFinal(body);

  } catch (java.security.NoSuchAlgorithmException e1) {

      e1.printStackTrace();

  } catch (javax.crypto.NoSuchPaddingException e2) {

      e2.printStackTrace();

  } catch (java.lang.Exception e3) {

      e3.printStackTrace();

  }

  return null;



. (Other methods are omitted.)

Copy the code
  1. Ios changed the directory toios\Classes\hello.mIn thehandleMethodCallMethod, addencryptMethod mapping, andjavaPartially similar; The comments section needs to be added
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {

  FlutterMethodChannel* channel = [FlutterMethodChannel

      methodChannelWithName:@"flutter_3des_plugin"

            binaryMessenger:[registrar messenger]];

  Flutter3desPlugin* instance = [[Flutter3desPlugin alloc] init];

  [registrar addMethodCallDelegate:instance channel:channel];

}



- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {

  if ([@"getPlatformVersion" isEqualToString:call.method]) {

    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);

  } else if([@"encrypt"IsEqualToString: call method]) {/ / the method name mapping, pay attention to the method name and exposed out

    NSDictionary* argsMap=call.arguments;

    NSString * data=argsMap[@"data"];

    NSString * key=argsMap[@"key"];

    NSString *batteryLevel = [self encrypt:data key:key];

    if (batteryLevel) {

        result(batteryLevel);

    } else

    {

        result([FlutterError errorWithCode:@"UNAVAILABLE"

        message:@"Battery info unavailable"

        details:nil]);

    }

  } else {

    result(FlutterMethodNotImplemented);

  }

}

// The implementation of business code

- (NSString *)encrypt:(NSString *)data key:(NSString *)key {

    JKEncrypt * en = [[JKEncrypt alloc]init];

/ / encryption

    NSString * encryptStr = [en encrypt3DesData:data key:key];

    return encryptStr;

}

@end

Copy the code

2.4. Then run the test your code

Note: you don’t need to distinguish between android and ios, the framework will automatically distinguish, you just need to write native code, example\lib\main.dart

import 'package:flutter_3des_plugin/flutter_3des_plugin.dart';

@override

  void initState() {

    super.initState();

    encrypt();

  }

/ / 3 des encryption

 encrypt () {

    Flutter3desPlugin.encrypt(_key, _data).then((res) {

// TODO: res is encrypted data

      setState(() {

        _result = res; 

      });

    });

  } 

Copy the code

Publish package to pub.dev

  1. Before Posting, checkYaml, readme. md, and Changelog. md filesTo ensure the integrity and correctness of its content
  2. And in the root directorypubspec.yamlAt the top of the fileVersion, the author, the homepageAnd so on, execute the following command will be prompted; Success prompt: after executing the second command and authorizing Google login:Successfully uploaded package.
Flutter packages pub publish --dry-run --server=https://pub.dartlang.org;

Flutter packages pub publish; Or flutter packages pub publish;

Copy the code

Five, possible problems

If the fourth walk is ok, you don’t have to look down. Next comes the release pit (pit of my physical and mental exhaustion) now summarizes the method

5.1. Let’s look at the errors:

// Error 1, stuck, desperate..... See these report error I all.....

Waiting for your authorization...

Authorization received, processing...

It looks like accounts.google.com is having some trouble.

Pub will wait for a while before trying to connect again.

OS Error: Operation timed out, errno = 60, address = accounts.google.com, port = 53481

pub finished with exit code 69

Copy the code
// Error # 2, it is stuck

Package has 2 warnings. Upload anyway (y/n)? y

Uploading...

Copy the code

5.2. The solution; Regardless of what kind of error is reported, follow the steps below to execute the command

Step 1

  • Using the command line (git,cmdOpen your project root directory and run the following command
  • Objective: To remove the domestic mirror; Note: the following command is only valid on the current terminal port, you run it in another window will reset.
unset FLUTTER_STORAGE_BASE_URL

unset PUB_HOSTED_URL

Copy the code

2. Set the local proxy

// The default Windows port number is 1080. Unless you change, the MAC port number is 1081

setHttp_proxy = http://127.0.0.1:1080

setHttps_proxy = http://127.0.0.1:1080

// Replace the top with the bottom

exportHttp_proxy = http://127.0.0.1:1080

exportHttps_proxy = http://127.0.0.1:1080

Copy the code

3. Step 3 Set the terminal agent

  • In this case you need a foreign server…….. (Awkward, 1,001 years cheap);
  • Then download the small plane (Shadowocks.exe). Add your server, system agent mode to global mode **

Step 4

  • Test your terminal agent setup successfully
  • Enter from the command line of the previous installmentscurl -vv http://www.google.comAnd check whether you can access Google.

Step 5

  • pinggoogleAfter executing the send packet command, you should see the following, indicating success:
  • At this time topub.devSearch your plugin and you’ll find it.
Package has 2 warnings. Upload anyway (y/n)? y

Uploading...

Successfully uploaded package.

Copy the code