Flutter detect crypto wallet provider

31 views Asked by At

I use flutter_web3: ^2.1.9 package for connect to crypto wallet .
this is sample code :

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'wallet_connector.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData.dark(useMaterial3: false),
      home: const MainPage(),
    );
  }
}

class MainPage extends StatefulWidget {
  const MainPage({super.key});

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  final WalletConnector _walletConnector = Get.put(WalletConnector());

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Column(
        children: [
          Text(_walletConnector.status.value,
              style: TextStyle(color: Colors.black, fontSize: 18)),
          SizedBox(height: 8),
          Text(_walletConnector.address.value,
              style: TextStyle(color: Colors.black, fontSize: 18)),
          SizedBox(height: 8),
          ElevatedButton(
            onPressed: _walletConnector.isConnected.isTrue ? null : () => _walletConnector.connect(),
            child: Text('Connect'),
          ),
        ],
      ),
    );
  }
}


// WalletConnector Class
import 'package:flutter/material.dart';
import 'package:flutter_web3/ethereum.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';

class WalletConnector {
  var address = ''.obs;
  var status = 'Disconnect'.obs;
  var isConnected = false.obs;

  Future<void> connect() async {
    try {
      if (Ethereum.isSupported && isConnected.isFalse) {
        var accounts = await ethereum!.requestAccount();
        if (accounts.isNotEmpty) {
          address.value = accounts.first;
          isConnected.value = ethereum!.isConnected();
          status.value = 'Connected';
        } else {
          status.value = 'Empty account';
        }
      } else {
        status.value = 'Wallet not supported or already connected';
      }
    } on EthereumUserRejected {
      status.value = 'Cancelled by user';
    }
  }

  Future<void> disconnect() async {
    address.value = '';
    status.value = 'Disconnect';
    isConnected.value = false;
  }
}

Two question :
1) this simple code does work on metamask , TrustWallet or any other wallets supported ethereum network. (I test it on chrome web browser)
my first question is , I want to understand client connected with which wallet , how to detect wallet provider ?

2) If client installed more than one wallet on browser , how to force client for connect with special wallet ? (for example only connect with TrustWallet)

0

There are 0 answers