我在 Flutter 中有一个用于移动和 Web 应用程序的代码。唯一的区别是使用另一种方法返回导航(因为 flutter web 中存在一些问题)。
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') 构建移动应用程序。即使我有平台条件。
有什么好的方法可以做到这一点?
我会使用条件导入。 将仅用于网络的内容放在一侧,将非网络内容放在另一侧。