The way your code is currently organized, you're querying for #test
before the the HTML fragment has been appended to the div
. If you do the stuff requiring #test
in the callback, things should work:
HttpRequest.getString(fileName).then((resp) {
div.appendHtml(resp);
Element elem = query("#test");
if (elem == null)
print("element is null");
});
If it's not clear to you what's going on, your HttpRequest is asynchronous. This is as it should be (you don't want to block while you wait on the network), but your code needs to account for this; you can't expect the fetched HTML to have been added to the page just because loadHTML()
has returned.