Flutter wallet钱包的随机生成和sqflite数据库存储

前言:

    Flutter钱包具有管理密钥、地址、转账交易等功能,是一种互联网钱包或区块链钱包通过助记词可以拿到私钥,而私钥可以获取地址信息 ,私钥与地址一一对应,地址是用户的唯一标识,用户的所有钱都是存放在地址里面。提到钱包,首先都会考虑如何安全的存放用户的钱。在这里,我使用的是sqflite数据库来存储钱包地址,用户可以随机创建钱包,查询钱包和删除钱包。

效果图:

         

实现的步骤:

1.在pubspec.yaml添加sdk

dependencies:
  ...
  cupertino_icons: ^0.1.3
  bip39: ^1.0.3
  ed25519_hd_key: ^1.0.1
  web3dart: ^1.2.3
  hex: ^0.1.2
  sqflite: 1.3.1

2.随机生成钱包地址

//导包
import 'package:bip39/bip39.dart' as bip39;
import 'package:ed25519_hd_key/ed25519_hd_key.dart';
import "package:hex/hex.dart";
import 'package:web3dart/web3dart.dart';


//随机生成钱包地址的方法
Future _getWalletAddress(String password) async {
    //随机生成助记词
    String seed = bip39.mnemonicToSeedHex(password);
    KeyData master = ED25519_HD_KEY.getMasterKeyFromSeed(seed);
    //通过助记词生成私钥
    String privateKey = HEX.encode(master.key);

    //通过私钥拿到地址信息
    final private = EthPrivateKey.fromHex(privateKey);
    final address = await private.extractAddress();
}

3.Sqflite数据库存储钱包的信息

 3.1创建数据库

Database db;
String tableWallet = 'wallet';
String columnId = 'id';
String columnName = 'name';
String columnAddress = 'address';

//创建数据库的方法
openSqlite() async {
    // 路径
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'walletAddress.db');

    // 创建数据库
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
          CREATE TABLE $tableWallet (
            $columnId INTEGER PRIMARY KEY autoincrement, 
            $columnName String, 
            $columnAddress String)
          ''');
        });
  }

3.2增加钱包地址信息

//增
Future insert(String name, String address) async {
    String sql =
        "INSERT INTO $tableWallet($columnName,$columnAddress) VALUES('$name','$address')";
    await db.rawInsert(sql);
}

3.3删除钱包地址信息

//删
Future<int> delete(String name) async {
    return await db.rawDelete('DELETE FROM $tableWallet WHERE $columnName = ?', ['$name']);
}

3.4修改钱包地址信息

//改
Future<void> update(String name,int id) async {
    await db.rawUpdate('UPDATE $tableWallet SET $columnName = ? WHERE $columnId = ?', ['$name', '$id']);

}

3.5查询钱包地址信息

//查
Future<List<Map>> queryAll() async {
    String sqlQuery = 'SELECT * FROM $tableWallet';
    return await db.rawQuery(sqlQuery);
}

3.6关闭数据库

//关闭
Future close() async {
    await db.close();
}

4.封装Sqflite数据库的完整代码

import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:async';

class SqliteWallet {
  Database db;
  String tableWallet = 'wallet';
  String columnId = 'id';
  String columnName = 'name';
  String columnAddress = 'address';

  openSqlite() async {
    // 路径
    var databasesPath = await getDatabasesPath();
    String path = join(databasesPath, 'walletAddress.db');

    // 创建数据库
    db = await openDatabase(path, version: 1,
        onCreate: (Database db, int version) async {
          await db.execute('''
          CREATE TABLE $tableWallet (
            $columnId INTEGER PRIMARY KEY autoincrement, 
            $columnName String, 
            $columnAddress String)
          ''');
        });
  }

  // 增
  Future insert(String name, String address) async {
    String sql =
        "INSERT INTO $tableWallet($columnName,$columnAddress) VALUES('$name','$address')";
    await db.rawInsert(sql);
  }

  // 删
  Future<int> delete(String name) async {
    return await db.rawDelete('DELETE FROM $tableWallet WHERE $columnName = ?', ['$name']);
  }

  //改
  Future<void> update(String name,int id) async {
    await db.rawUpdate('UPDATE $tableWallet SET $columnName = ? WHERE $columnId = ?', ['$name', '$id']);

  }

  // 查
  Future<List<Map>> queryAll() async {
    String sqlQuery = 'SELECT * FROM $tableWallet';
    return await db.rawQuery(sqlQuery);
  }

  //清空
  Future<int> clear() async {
    return await db.delete('$tableWallet');
  }

  // 关闭数据库
  Future close() async {
    await db.close();
  }
}

5.在CreateWalletPage页面调用创建钱包的方法

class CreateWalletPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new CreateWalletPageState();
}

class CreateWalletPageState extends State<CreateWalletPage> {
   SqliteWallet _sqliteWallet = new SqliteWallet();
   
   @override
   Widget build(BuildContext context) {
       return new Scaffold(
          ...
       );
   }
   
   //创建钱包的方法
   Future createWallet() async {
       _getWalletAddress(_password.text);//获取钱包地址
       await _sqliteWallet.openSqlite();//打开数据库
       await _sqliteWallet.insert(_name.text, _address);//插入数据
       await _sqliteWallet.close();//关闭数据库
  }

}

6.在HomePage页面调用查询钱包的方法

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
   SqliteWallet _sqliteWallet = new SqliteWallet();
   var _walletList = [];

   @override
   Widget build(BuildContext context) {
       return Scaffold(
       ...
       );
   }

   //查询钱包的方法
   Future _getQueryWalletAddressData() async {
       await _sqliteWallet.openSqlite();
       var queryWalletAddressList = await _sqliteWallet.queryAll();
       await _sqliteWallet.close();
       setState(() {
          _walletList = queryWalletAddressList;
       });
   }

}

7.在WalletMangerPage页面调用删除钱包的方法

class WalletMangerPage extends StatefulWidget {
  Wallets wallets;
  WalletMangerPage({@required this.wallets});

  @override
  State<StatefulWidget> createState() => new WalletMangerPageState();
}

class WalletMangerPageState extends State<WalletMangerPage> {
  SqliteWallet _sqliteWallet = new SqliteWallet();

  @override
  Widget build(BuildContext context) {
     return Scaffold(
     ...
     );
  }

  //删除钱包的方法
  Future _deleteWallet() async {
    await _sqliteWallet.openSqlite();
    await _sqliteWallet.delete(widget.wallets.name);
    await _sqliteWallet.close();
    navigateToPage(context, "${Routes.home}");
  }

}

8.总结

在Flutter上已经实现钱包地址的随机生成和sqflite数据库存储的功能,欢迎大家围观。源码地址: https://github.com/wupeilinloveu/flutter_sqlite,如果有什么疑问的话,欢迎留言联系我!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章