gpt4 book ai didi

flutter - 如何在 flutter App 上叠加一个小部件?

转载 作者:IT王子 更新时间:2023-10-29 06:52:35 26 4
gpt4 key购买 nike

我想要一个位于整个应用程序之上的小部件。当我尝试使用 Overlay.of(context).insert 执行此操作时,覆盖层会在替换该路由后消失。有没有一种方法可以在我的应用程序顶部放置一个小部件,即使屏幕稍后弹出?

最佳答案

也许存在更优化的方式,但作为一个选项,这是一个包含两个页面的示例,本地导航器和覆盖。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
final _navigatorKey = GlobalKey<NavigatorState>();

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: WillPopScope(
onWillPop: () async => !await _navigatorKey.currentState.maybePop(),
child: LayoutBuilder(
builder: (context, constraints) {
WidgetsBinding.instance.addPostFrameCallback((_) => _insertOverlay(context));
return Navigator(
key: _navigatorKey,
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
case '/page2':
return MaterialPageRoute(builder: (_) => Page2());
default:
return MaterialPageRoute(builder: (_) => Page1(_navigatorKey));
}
},
);
},
),
),
);
}

void _insertOverlay(BuildContext context) {
return Overlay.of(context).insert(
OverlayEntry(builder: (context) {
final size = MediaQuery.of(context).size;
print(size.width);
return Positioned(
width: 56,
height: 56,
top: size.height - 72,
left: size.width - 72,
child: Material(
color: Colors.transparent,
child: GestureDetector(
onTap: () => print('ON TAP OVERLAY!'),
child: Container(
decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.redAccent),
),
),
),
);
}),
);
}
}

class Page1 extends StatelessWidget {
final GlobalKey<NavigatorState> navigatorKey;

Page1(this.navigatorKey);

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.green[200],
appBar: AppBar(title: Text('Page1')),
body: Container(
alignment: Alignment.center,
child: RaisedButton(
child: Text('go to Page2'),
onPressed: () => navigatorKey.currentState.pushNamed('/page2'),
),
),
);
}
}

class Page2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.yellow[200],
appBar: AppBar(title: Text('back to Page1')),
body: Container(
alignment: Alignment.center,
child: Text('Page 2'),
),
);
}
}

enter image description here

关于flutter - 如何在 flutter App 上叠加一个小部件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57069641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com