search
テクノロジー

Vol.173 FlutLab記録 - Metamask連携はできるのか?

gryption's icon'
  • gryption
  • 2022/08/28 10:06

今回は、FlutLab開発日記的なものを書いていきたいと思います。FlatLabはこの前に記事化して紹介しましたが、いわゆる「mBaaS」的なものととらえて大丈夫かと負います。Zennというメディアがエンジニアとして利用するにあたり先進的だと考えているため、一部その情報をここで共有します。

Content image

Media間の情報共有は重要だと考えており、前述した通りここのALISで発言したものはほかのブログプラットフォームでも一部配信しています。

一応は下記の記事などを参照しましたが、現在でもFlatLabでメタマスクを実装するに至っていません。

上記のflutter_web3_sampleが開発しているものですが、これらのサンプルコードはgithub上からとってきました。

こちらkboyという方が編集してくれたもので、何もわからなかった身としてはありがたくもありました。私としてはあまりFlutterには詳しい方ではないので、このようなサンプルはありがたいです。しかし、動きませんでした。

Content image

チャットもしてみましたがわかりませんでした。

main.dart

// ignore_for_file: nullable_type_in_catch_clause

import 'package:flutter/material.dart';
import 'package:flutter_web3/flutter_web3.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: MyHomePage(),
    );
  }
}


class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);


  @override
  State<MyHomePage> createState() => _MyHomePageState();
}


const kboyAddress = '0x68035DC06E6282AD280c136139D65d00d7B99ec0';


class _MyHomePageState extends State<MyHomePage> {
  String account = '';
  double balanceString = 0;


  get ethereum => null;


  get provider => null;


  void _fetchBalance() async {
    print(ethereum);
    // `Ethereum.isSupported` is the same as `ethereum != null`
    if (ethereum != null) {
      try {
        // Prompt user to connect to the provider, i.e. confirm the connection modal
        final accounts = await ethereum!.requestAccount();
        final firstAccount = accounts.first;


        final BigInt balance = await provider!.getBalance(kboyAddress);
        final ethBalance =
            balance.toDouble() * 1 / 1000000000000000000; // WEI to ETH


        setState(() {
          account = firstAccount;
          balanceString = ethBalance;
        });
      } on EthereumUserRejected {
        print('User rejected the modal');
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutt'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Address: $account',
            ),
            Text(
              '$balanceString ETH',
              style: Theme.of(context).textTheme.headline4,
            ),
            TextButton(
                onPressed: () async {
                  // Send 1000000000 wei to `0xcorge`
                  final tx = await provider!.getSigner().sendTransaction(
                        TransactionRequest(
                          to: kboyAddress,
                          value: BigInt.from(1000000000000),
                        ),
                      );
                  final receipt = await tx.wait();
                  print(receipt);
                },
                child: const Text('send')),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _fetchBalance,
        child: const Icon(Icons.account_balance_wallet),
      ),
    );
  }

  TransactionRequest({required String to, required BigInt value}) {}
}

上記がmain.dartで、

Content image

index.htmlが、

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.


    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.


    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base


    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->
  <base href="$FLUTTER_BASE_HREF">


  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">


  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="flutter_web3_sample">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">


  <!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>


  <title>flutter_web3_sample</title>
  <link rel="manifest" href="manifest.json">
</head>
<body>
  <!-- This script installs service_worker.js to provide PWA functionality to
       application. For more information, see:
       https://developers.google.com/web/fundamentals/primers/service-workers -->
  <script>
    var serviceWorkerVersion = null;
    var scriptLoaded = false;
    function loadMainDartJs() {
      if (scriptLoaded) {
        return;
      }
      scriptLoaded = true;
      var scriptTag = document.createElement('script');
      scriptTag.src = 'main.dart.js';
      scriptTag.type = 'application/javascript';
      document.body.append(scriptTag);
    }


    if ('serviceWorker' in navigator) {
      // Service workers are supported. Use them.
      window.addEventListener('load', function () {
        // Wait for registration to finish before dropping the <script> tag.
        // Otherwise, the browser will load the script multiple times,
        // potentially different versions.
        var serviceWorkerUrl = 'flutter_service_worker.js?v=' + serviceWorkerVersion;
        navigator.serviceWorker.register(serviceWorkerUrl)
          .then((reg) => {
            function waitForActivation(serviceWorker) {
              serviceWorker.addEventListener('statechange', () => {
                if (serviceWorker.state == 'activated') {
                  console.log('Installed new service worker.');
                  loadMainDartJs();
                }
              });
            }
            if (!reg.active && (reg.installing || reg.waiting)) {
              // No active web worker and we have installed or are installing
              // one for the first time. Simply wait for it to activate.
              waitForActivation(reg.installing || reg.waiting);
            } else if (!reg.active.scriptURL.endsWith(serviceWorkerVersion)) {
              // When the app updates the serviceWorkerVersion changes, so we
              // need to ask the service worker to update.
              console.log('New service worker available.');
              reg.update();
              waitForActivation(reg.installing);
            } else {
              // Existing service worker is still good.
              console.log('Loading app from service worker.');
              loadMainDartJs();
            }
          });


        // If service worker doesn't succeed in a reasonable amount of time,
        // fallback to plaint <script> tag.
        setTimeout(() => {
          if (!scriptLoaded) {
            console.warn(
              'Failed to load app from service worker. Falling back to plain <script> tag.',
            );
            loadMainDartJs();
          }
        }, 4000);
      });
    } else {
      // Service workers not supported. Just drop the <script> tag.
      loadMainDartJs();
    }
  </script>


  <!--Ethers-->
  <script src="https://cdn.ethers.io/lib/ethers-5.4.umd.min.js" type="application/javascript"></script>
  <!--Wallet Connect-->
  <script src="https://cdn.jsdelivr.net/npm/@walletconnect/web3-provider@1.6.5/dist/umd/index.min.js" type="application/javascript"></script>
</body>
</html>

となります。ALISにはコード化する場合Flutterという選択がなかったので、追加してほしい所存です。

で、今のところMetamask連携はできていないので、なぜGithubでできたのかをいろいろ試したいと思っています。もしかしたら、AndroidStudioでやるかもしれません。
 

Supporter profile icon
Article tip 1人がサポートしています
獲得ALIS: Article like 3.89 ALIS Article tip 4.10 ALIS
Article registration Article registration
gryption's icon'
  • gryption
  • @biyori
金融系・テック関連のニッチな最新情報をわかりやすくアウトプット&解説ブログ本編:https://note.com/gensnotes/

投稿者の人気記事
コメントする
コメントする
こちらもおすすめ!
Eye catch
他カテゴリ

機械学習を体験してみよう!(難易度低)

nonstop-iida 2020/03/04
Like token Tip token
124.82 ALIS
Eye catch
クリプト

17万円のPCでTwitterやってるのはもったいないのでETHマイニングを始めた話

nnppnpp(んぺー) 2021/09/08
Like token Tip token
46.60 ALIS
Eye catch
クリプト

Bitcoin史 〜0.00076ドルから6万ドルへの歩み〜

大田コウキ 2021/04/06
Like token Tip token
947.13 ALIS
Eye catch
ゲーム

ドラクエで学ぶオーバフロー

keiju togashi 2020/03/12
Like token Tip token
30.10 ALIS
Eye catch
テクノロジー

なぜ、素人エンジニアの私が60日間でブロックチェーンゲームを制作できたのか、について語ってみた

ゆうき 2020/08/12
Like token Tip token
270.93 ALIS
Eye catch
クリプト

ジョークコインとして出発したDogecoin(ドージコイン)の誕生から現在まで。注目される非証券性🐶

昆布森ちゃん 2021/01/19
Like token Tip token
38.31 ALIS
Eye catch
クリプト

NFT解体新書・デジタルデータをNFTで販売するときのすべて【実証実験・共有レポート】

otakucoin 2021/03/29
Like token Tip token
121.79 ALIS
Eye catch
テクノロジー

彼女でも分かるように解説:ディープフェイク

Jimmy 2020/03/17
Like token Tip token
32.10 ALIS
Eye catch
テクノロジー

オープンソースプロジェクトに参加して自己肯定感を高める

おはぐろ氏 2020/02/15
Like token Tip token
85.05 ALIS
Eye catch
他カテゴリ

ALISのシステム概観

ALISブロックチェーンブログ 2018/07/03
Like token Tip token
5.00 ALIS
Eye catch
クリプト

約2年間ブロックチェ-ンゲームをして

kaya 2021/10/06
Like token Tip token
61.20 ALIS
Eye catch
テクノロジー

iOS15 配信開始!!

IMAKARA 2021/09/23
Like token Tip token
7.20 ALIS