我创建了一个示例应用来测试Dart Route API。我有以下代码:
urls.dart
library urls;
import 'package:route/url_pattern.dart';
final homeUrl = new UrlPattern(r'/');
final otherScreenUrl = new UrlPattern(r'/other_screen/');
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="sample_container_id">
<p id="sample_text_id"></p>
</div>
<script type="application/dart" src="main.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
main.dart
import 'dart:html';
import 'package:route/client.dart';
import 'urls.dart';
void main() {
var router = new Router()
..addHandler(homeUrl, _showHome)
..addHandler(otherScreenUrl, _showOtherScreen)
..listen();
querySelector("#sample_text_id")
..text = "Click me!"
..onClick.listen(_gotoOtherScreen);
}
_gotoOtherScreen(MouseEvent event) {
// I am trying to navigate to the "other screen" by using history.pushState here
window.history.pushState({'url' : otherScreenUrl}, "other screen", otherScreenUrl);
}
_showHome(String path) {
querySelector("#other_element")
..remove();
}
_showOtherScreen(String path) {
querySelector("#sample_container_id")
..append(new SpanElement()
..innerHtml = "now in other screen"
..id = "other_element");
}
运行应用程序然后单击<p>
标记时出现以下错误:
突发异常:非法参数:找不到处理程序 /test/web/main.html
异常:非法参数:找不到处理程序 /test/web/main.html Router._getUrl(package:route / client.dart:53:7) Router.handle(package:route / client.dart:71:22)
Router.listen。 (包:路线/ client.dart:102:15)突破异常:类型'UrlPattern'不是类型的子类型 'url'的'String'。
异常:类型'UrlPattern'不是'String'类型的子类型 'URL'。 _gotoOtherScreen
(http://127.0.0.1:3030/test/web/main.dart:18:27)
如何使用Route API?我做错了什么?
答案 0 :(得分:2)
以下是解决上述问题的更新代码:
<强> urls.dart
强>
library urls;
import 'package:route/url_pattern.dart';
final homeUrl = new UrlPattern(r'(.*)/');
final homeUrlWithFile = new UrlPattern(r'(.*)/main.html');
final otherScreenUrl = new UrlPattern(r'(.*)/other_screen');
<强> main.html
强>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="sample_container_id">
<a href="/other_screen">click me!!</a>
</div>
<script type="application/dart" src="main.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
<强> main.dart
强>
import 'dart:html';
import 'package:route/client.dart';
import 'urls.dart';
void main() {
var router = new Router()
..addHandler(homeUrl, _showHome)
..addHandler(homeUrlWithFile, _showHome)
..addHandler(otherScreenUrl, _showOtherScreen)
..listen();
}
_showHome(String path) {
var e = querySelector("#other_element");
if (e != null) e.remove();
}
_showOtherScreen(String path) {
querySelector("#sample_container_id")
..append(new SpanElement()
..innerHtml = "now in other screen"
..id = "other_element");
}