前言
这一次被要求实现屏幕上同时展示两个页面,并且两个页面的逻辑,功能互不影响,通俗一点讲就是在Flutter内部实现一个类似于分屏的功能,这可难不倒我。
方法
要在 Flutter 中实现一个屏幕的上半部分和下半部分展示不同的页面(我这里是左右两部分),并且两个页面的逻辑互不影响,可以使用 Row 和 Expanded 组件来划分屏幕的左右部分,并分别在这两个部分中使用 Navigator 进行页面导航。还可以依赖 Navigator 在任一页面中对另一个页面的路由进行控制。
效果如下:
代码
dart
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final GlobalKey<NavigatorState> topNavigatorKey = GlobalKey<NavigatorState>();
final GlobalKey<NavigatorState> bottomNavigatorKey =
GlobalKey<NavigatorState>();
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Row(
children: [
Expanded(
child: Navigator(
key: topNavigatorKey,
onGenerateRoute: (settings) {
return MaterialPageRoute(
settings: settings,
builder: (_) => TopPage(
bottomNavigatorKey: bottomNavigatorKey,
),
);
},
),
),
Expanded(
child: Navigator(
key: bottomNavigatorKey,
onGenerateRoute: (settings) {
return MaterialPageRoute(
settings: settings,
builder: (_) =>
BottomPage(), // Placeholder, BottomPage can be added here
);
},
),
),
],
),
),
);
}
}
class TopPage extends StatelessWidget {
final GlobalKey<NavigatorState> bottomNavigatorKey;
TopPage({required this.bottomNavigatorKey});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Top Page')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(children: [
Center(
child: ElevatedButton(
child: Text('Go to Top Details'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => TopDetailsPage()),
);
},
),
),
SizedBox(height: 20),
Center(
child: ElevatedButton(
child: Text('Show Bottom Page Details'),
onPressed: () {
// changeBottomPageState();
bottomNavigatorKey.currentState!.push(
MaterialPageRoute(builder: (_) => BottomDetailsPage()),
);
},
),
),
]),
),
);
}
}
class TopDetailsPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Top Details Page')),
body: Center(
child: ElevatedButton(
child: Text(
'Go to Bottom Page'), // Add a button to navigate to BottomPage
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => BottomPage()),
);
},
),
),
);
}
}
class BottomPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bottom Page')),
body: Center(
child: ElevatedButton(
child: Text('Go to Bottom Details'),
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (_) => BottomDetailsPage()),
);
},
),
),
);
}
}
class BottomDetailsPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Bottom Details Page')),
body: Center(
child: Text('This is the Bottom Details Page'),
),
);
}
}
总结
以上就是本期内容啦,如果你有其他的实现方法,欢迎留言一起讨论交流哦。