genvars.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package dartgen
  2. import (
  3. "io/ioutil"
  4. "os"
  5. )
  6. const varTemplate = `import 'dart:convert';
  7. import 'package:shared_preferences/shared_preferences.dart';
  8. import '../data/tokens.dart';
  9. /// 保存tokens到本地
  10. ///
  11. /// 传入null则删除本地tokens
  12. /// 返回:true:设置成功 false:设置失败
  13. Future<bool> setTokens(Tokens tokens) async {
  14. var sp = await SharedPreferences.getInstance();
  15. if (tokens == null) {
  16. sp.remove('tokens');
  17. return true;
  18. }
  19. return await sp.setString('tokens', jsonEncode(tokens.toJson()));
  20. }
  21. /// 获取本地存储的tokens
  22. ///
  23. /// 如果没有,则返回null
  24. Future<Tokens> getTokens() async {
  25. try {
  26. var sp = await SharedPreferences.getInstance();
  27. var str = sp.getString('tokens');
  28. if (str.isEmpty) {
  29. return null;
  30. }
  31. return Tokens.fromJson(jsonDecode(str));
  32. } catch (e) {
  33. print(e);
  34. return null;
  35. }
  36. }
  37. `
  38. func genVars(dir string) error {
  39. err := os.MkdirAll(dir, 0755)
  40. if err != nil {
  41. return err
  42. }
  43. if !fileExists(dir + "vars.dart") {
  44. err = ioutil.WriteFile(dir+"vars.dart", []byte(`const serverHost='demo-crm.xiaoheiban.cn';`), 0644)
  45. if err != nil {
  46. return err
  47. }
  48. }
  49. if !fileExists(dir + "kv.dart") {
  50. err = ioutil.WriteFile(dir+"kv.dart", []byte(varTemplate), 0644)
  51. if err != nil {
  52. return err
  53. }
  54. }
  55. return nil
  56. }