Dsky
Dsky

Reputation: 1

How can I use uwp or winRT in flutter?

I am trying to use "NetworkUsage" of Windows.Networking.Connectivity to get the network usage that the user used today, but flutter recently ended support for UWP.

So I tried to use MIB_IFROW of win32 to get network usage and do "current value - previous value", but there are many problems.

And I followed this post and used #include <winrt/Windows.Networking.Connectivity.h> to create native code and run it, but I got the following error.

error

winodows/runner/flutter_window.cpp:

static uint64_t GetTodayNetworkUsage() {
    using namespace winrt;
    using namespace winrt::Windows::Networking::Connectivity;
    using namespace winrt::Windows::Foundation;

    try {
        auto connectionProfile = NetworkInformation::GetInternetConnectionProfile();
        if (!connectionProfile) {
            return 0;
        }

        auto now = clock::now();
        auto midnight = now - std::chrono::hours(24);

        NetworkUsageStates states{ TriStates::DoNotCare, TriStates::DoNotCare };

        auto usageData = connectionProfile.GetNetworkUsageAsync(midnight, now, DataUsageGranularity::PerDay, states).get();

        uint64_t totalData = 0;

        for (auto const& usage : usageData) {
            totalData += usage.BytesSent() + usage.BytesReceived();
        }

        return totalData;

    } catch (const hresult_error& ex) {
        std::wcerr << L"Error: " << ex.message().c_str() << std::endl;
        return 0;
    } catch (...) {
        std::cerr << "Unknown error occurred!" << std::endl;
        return 0;
    }
}


FlutterWindow::FlutterWindow(const flutter::DartProject& project)
    : project_(project) {}

FlutterWindow::~FlutterWindow() {}

bool FlutterWindow::OnCreate() {
  if (!Win32Window::OnCreate()) {
    return false;
  }

  winrt::init_apartment();

  RECT frame = GetClientArea();

  // The size here must match the window dimensions to avoid unnecessary surface
  // creation / destruction in the startup path.
  flutter_controller_ = std::make_unique<flutter::FlutterViewController>(
      frame.right - frame.left, frame.bottom - frame.top, project_);
  // Ensure that basic setup of the controller was successful.
  if (!flutter_controller_->engine() || !flutter_controller_->view()) {
    return false;
  }
  RegisterPlugins(flutter_controller_->engine());
  SetChildContent(flutter_controller_->view()->GetNativeWindow());

  auto channel = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(
      flutter_controller_->engine()->messenger(),
      "samples.flutter.dev/networkUsage",
      &flutter::StandardMethodCodec::GetInstance());

  channel->SetMethodCallHandler(
      [](const flutter::MethodCall<>& call, std::unique_ptr<flutter::MethodResult<>> result) {
          if (call.method_name() == "getNetworkUsage") {
              uint64_t dataUsage = GetTodayNetworkUsage();
              result->Success(flutter::EncodableValue(static_cast<int64_t>(dataUsage)));
          }
          else {
              result->NotImplemented();
          }
      });

  flutter_controller_->engine()->SetNextFrameCallback([&]() {
    this->Show();
  });

  // Flutter can complete the first frame before the "show window" callback is
  // registered. The following call ensures a frame is pending to ensure the
  // window is shown. It is a no-op if the first frame hasn't completed yet.
  flutter_controller_->ForceRedraw();

  return true;
}

void FlutterWindow::OnDestroy() {
  if (flutter_controller_) {
    flutter_controller_ = nullptr;
  }

  Win32Window::OnDestroy();
}

LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
                              WPARAM const wparam,
                              LPARAM const lparam) noexcept {
  // Give Flutter, including plugins, an opportunity to handle window messages.
  if (flutter_controller_) {
    std::optional<LRESULT> result =
        flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
                                                      lparam);
    if (result) {
      return *result;
    }
  }

  switch (message) {
    case WM_FONTCHANGE:
      flutter_controller_->engine()->ReloadSystemFonts();
      break;
  }

  return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}

I found a way to apply flutter winrt in "https://github.com/woodemi/quick_notify/discussions/8", but my project has multiple CMakeLists in windows and runner, and the code inside them was different. so I don't know where to apply it.

Is there a way to use winrt or uwp in flutter? Or is there no other alternative?

I'm new to flutter so I don't know much and Sorry for using Google Translator.

Upvotes: 0

Views: 51

Answers (0)

Related Questions