igrasso

igrasso

Hello everyone, I’m a totally new to phoenix, LiveView and in general frontend/backend development. But I think that starting with Phoenix LiveView is already a good step :slight_smile:.

Just to make things a bit more spicy, I need to take a self contained flutter web app and display it with LiveView. I’m following the guideline flutter_embedding. After reading enough about JS and how to work with LiveView I decided to create a hook. I moved all the generate flutter web files in the js/vendor/flutter_web folder. The hook is mounting correctly but I have no idea how to proceed. I’m not able to display anything in my flutter_targer div.
I’m sure that I’m missing something trivial but my inexperience with the web world is not helping me. Can somebody please point me in the correct direction?

import "../vendor/flutter_web/flutter.js"

let Hooks = {}

Hooks.Video = {
    mounted(){
        console.log("Hook Mounted!", this.el);

        window.addEventListener("phx:page-loading-start", function (ev) {
            // Embed flutter into div#flutter_target
            let target = document.querySelector("#flutter_target");
            _flutter.loader.loadEntrypoint({
              onEntrypointLoaded: async function (engineInitializer) {
                let appRunner = await engineInitializer.initializeEngine({
                  hostElement: target,
                });
                await appRunner.runApp();
              },
            });
          });
    }
}

Showing Posts 1 to 7

KristerV

KristerV

did you figure out how to run this hook? as in you need some HTML to make this code run: JavaScript interoperability — Phoenix LiveView v1.2.5

igrasso

igrasso OP

I’m using some html in the defmodule. This is how I defined it.

def render(assigns) do
    ~H"""
    <div class="mx-auto max-w-sm">
      <.header class="text-center">
        Text Example
      </.header>
      <div id="flutter_target" style="height: 200px; width: 200px" phx-hook="Video"></div>
    </div>
    """
end

def mount(_params, _session, socket) do
    {:ok, socket}
end

During the loading of the page, if I put a breakpoint, it seems that the line

let target = document.querySelector("#flutter_target");

is never reached.

ndrean

ndrean

I imagine you exported your hook and imported it in “app.js” and passed it to the Liveview socket.

igrasso

igrasso OP

This is the code that I wrote in app.js:

import "../vendor/flutter_web/flutter.js"

let Hooks = {}

Hooks.Video = {
    mounted(){
        console.log("Hook Mounted!", this.el);

        window.addEventListener("phx:page-loading-start", function (ev) {
            // Embed flutter into div#flutter_target
            let target = document.querySelector("#flutter_target");
            _flutter.loader.loadEntrypoint({
              onEntrypointLoaded: async function (engineInitializer) {
                let appRunner = await engineInitializer.initializeEngine({
                  hostElement: target,
                });
                await appRunner.runApp();
              },
            });
          });
    }
}

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
    params: {_csrf_token: csrfToken},
    hooks: Hooks
})

And in the console, I receive the message:
“Hook Mounted!”

<div id="flutter_target" phx-hook="Video"></div>
Zurga

Zurga

Instead of the document.querySelector you can use this.el. And then I would add phx-update="ignore" to the element with the Hook on it in the template. Or, if you want to receive updates, implement an update() function in the Hook.

ndrean

ndrean

Did you try without the “phx:page-loading-start” listener?

In case you want dynamic import, check this

igrasso

igrasso OP

@ndrean thank you for the reading, for sure the dynamic import could be useful in the future.

If I drop the listener I get an error on the _flutter.loader… telling me “Uncaught ReferenceError: _flutter is not defined”

Now I don’t know if this is expected because something is not loaded, or there is an issue with my import flutter.js. The path is correct and at the end of the flutter.js file I can read _flutter.loader = new FlutterLoader();

— All posts loaded —

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
psy-q
I’m trying to set up Emacs with elixir-ls via lsp-mode and credo via Flycheck. This should mostly be preconfigured as Flycheck picks up c...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews