如何执行来自仅针对一个平台(WEB)指定的包的方法

问题描述 投票:0回答:1

我在 Flutter 中有一个用于移动和 Web 应用程序的代码。唯一的区别是使用另一种方法返回导航(因为 flutter web 中存在一些问题)。

  1. 对于网络:js.context.callMethod('back')
  2. 对于移动设备:Navigator.pop(context);
import 'package:flutter/material.dart';
import 'dart:js' as js;  ///this is only for web

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(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home:  HomePage(),
    );
  }
}

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

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text("Homepage"),
      ),
      body: Container(),


      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => SecondPage()),
          );
        },
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text("Second page"),
      ),
      body: Container(),


      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.pop(context);  ///   for mobile
          js.context.callMethod('back');   /// for web
        },
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

}

我无法使用 'dart:js' 并在代码中使用方法 js.context.callMethod('back') 构建移动应用程序。即使我有平台条件。

有什么好的方法可以做到这一点?

flutter
1个回答
0
投票

我会使用条件导入。 将仅用于网络的内容放在一侧,将非网络内容放在另一侧。

© www.soinside.com 2019 - 2024. All rights reserved.