Я использую Webview_Flutter. Заголовок сайта перекрывает положение строки состояния, и я хотел бы добавить отступ, чтобы избежать этого.
Это процесс вставки заполнения, чтобы избежать строки состояния, если веб-просмотр открыт или если вверху есть позиция прокрутки.
body: Padding(
padding: (controller?.getScrollY() == null || controller?.getScrollY() == 0)
? EdgeInsets.only(top: height)
: EdgeInsets.only(top: 0),
child: Expanded(
child: Padding(
padding: const EdgeInsets.only(bottom: 0.0),
child: WebView(
javascriptMode: JavascriptMode.unrestricted,
initialUrl: Uri.parse(widget.link).toString(),
onWebResourceError: (error) {
// print(error.domain);
},
onWebViewCreated: (controller) {
this.controller = controller;
},
onProgress: (progress) {
setState(() {
this.progress = progress / 100;
progressPercent = progress;
});
},
),
Я пытался найти слушателя прокрутки webView, я не смог его найти, вы правы. Есть решение ^^, оно простое, мы могли бы обернуть WebView в ListView, тогда мы могли бы использовать scrollListener(1) илиnotificationListener(2) и не забудьте использовать setState для обновления значений заполнения
class _HomeScreenState extends State<HomeScreen> {
WebViewController? _webViewController;
ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return
Scaffold(
body:Scaffold(
backgroundColor: Colors.green,
appBar: AppBar(
title: const Text('Flutter WebView example'),
// This drop down menu demonstrates that Flutter widgets can be shown over the web view.
actions: <Widget>[
],
),
//NotificationListener(2)
body: NotificationListener<ScrollNotification>(
onNotification: (scrollNotification) {
if (scrollNotification is ScrollStartNotification) {
WidgetsBinding.instance.addPostFrameCallback((_) {
print("ScrollStartNotification / pixel => ${scrollNotification.metrics.pixels}");
});
} else if (scrollNotification is ScrollEndNotification) {
WidgetsBinding.instance.addPostFrameCallback((_) {
setState(() {
print("ScrollEndNotification / pixel =>${scrollNotification.metrics.pixels}");
});
});
}
return true;
},
child: ListView(
physics: ClampingScrollPhysics(),
controller: _scrollController,
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(maxHeight: 10000),
child: WebView(
initialUrl: 'https://flutter.dev',
javascriptMode: JavascriptMode.unrestricted,
onWebViewCreated: (WebViewController webViewController) {},
onProgress: (int progress) {
print('WebView is loading (progress : $progress%)');
},
javascriptChannels: <JavascriptChannel>{
},
onPageStarted: (String url) {},
onPageFinished: (String url) {},
gestureNavigationEnabled: true,
backgroundColor: const Color(0x00000000),
),
),
],
),
)));
}
@override
void initState() {
super.initState();
//scrollListener(1)
_scrollController.addListener(() {
print("scrollListener / pixel =>${_scrollController.position.pixels}");
});
}
}
Чтобы обнаружить событие прокрутки WebView, вы можете использовать плагин flutter_inappwebview (я автор) и реализовать событие InAppWebView.onScrollChanged
.
Однако, вероятно, вам не нужно добавлять верхний отступ для вашего WebView. Вы можете установить AppBar.toolbarHeight
на 0
, чтобы панель приложения имела достаточную высоту, чтобы закрыть строку состояния.
Вот полный пример кода в обоих случаях с использованием последней доступной версии 6 плагина (6.0.0-beta.16):
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
if (!kIsWeb &&
kDebugMode &&
defaultTargetPlatform == TargetPlatform.android) {
await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
}
runApp(const MaterialApp(home: MyApp()));
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final GlobalKey webViewKey = GlobalKey();
InAppWebViewController? webViewController;
int scrollY = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
toolbarHeight: 0,
),
body: Padding(
padding: EdgeInsets.only(top: scrollY <= 0 ? 25 : 0),
child: Column(
children: [
Expanded(
child: InAppWebView(
key: webViewKey,
initialUrlRequest:
URLRequest(url: WebUri("https://github.com/flutter")),
onWebViewCreated: (controller) {
webViewController = controller;
},
onScrollChanged: (controller, x, y) {
setState(() {
scrollY = y;
});
},
),
)
],
),
));
}
}