英文:
WebViewController shows error if I don't use cascade
问题
在使用级联操作符时,不会显示错误。
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({super.key});
final controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: WebViewWidget(
controller: controller,
),
);
}
}
但是,当我不使用级联操作符时,Flutter 会显示错误。
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({super.key});
final controller = WebViewController();
controller.setJavaScriptMode(JavaScriptMode.unrestricted);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: WebViewWidget(
controller: controller,
),
);
}
}
英文:
When I write a WebViewController with cascade, it does not show an error.
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({super.key});
final controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: WebViewWidget(
controller: controller,
),
);
}
}
But when I write code without cascade, flutter shows an error.
Does anyone know why?
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class HomeScreen extends StatelessWidget {
HomeScreen({super.key});
final controller = WebViewController();
controller.setJavaScriptMode(JavaScriptMode.unrestricted);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: WebViewWidget(
controller: controller,
),
);
}
}
答案1
得分: 0
你在那里不在一个函数内,所以不能只在那里执行代码行,只能声明变量。通过使用级联,它将其作为声明的一部分。如果你想不使用级联来写,你可以在构造函数中这样做,例如
class HomeScreen extends StatelessWidget {
HomeScreen({super.key}){
controller.setJavaScriptMode(JavaScriptMode.unrestricted);
}
final controller = WebViewController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: WebViewWidget(
controller: controller,
),
);
}
}
英文:
You are not inside a function there so you can't just execute lines of code there, only declarations of variables. By using the cascade it makes it part of the declaration. If you want to write it without cascade you could do it in the constructor for example, like
class HomeScreen extends StatelessWidget {
HomeScreen({super.key}){
controller.setJavaScriptMode(JavaScriptMode.unrestricted);
}
final controller = WebViewController();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: WebViewWidget(
controller: controller,
),
);
}
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论