How can I fetch data from url by class name or id using Flutter?
609
here is package http package.
here is a complete method to get a response.
HttpClient client = new HttpClient()
..badCertificateCallback =
((X509Certificate cert, String host, int port) => true);
return client.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
request.headers.set('content-type', 'application/json-patch+json');
request.headers.set('accept', 'application/json');
var response = request.close().timeout(new Duration(seconds: 5));
return response;
}).then((HttpClientResponse response) {
var result = response.transform(utf8.decoder).join();
return result;
}).catchError((onError) {
var result = onError.transform(utf8.decoder).join();
return result;
});
Author by
Admin
Updated on December 27, 2022Comments
-
Admin over 1 year
As you see in the title of the question, I need to fetch data from URL by class name or id in Flutter. There is some data I haven't got its JSON data, and I need them to display on my app. I could fetch data using the code in the below, but I can't fetch any data by class name or id because I don't know what I need to use. Please help me
class _MyHomePageState extends State<MyHomePage> { String stringResponse; Future fetcData() async { http.Response response; response = await http.get("www.example.com"); //Consider that the URL has just a string such as "This is a string." if (response.statusCode == 200) { setState(() { stringResponse = response.body; }); } else { } } @override void initState() { // TODO: implement initState fetcData(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Http request"), ), body: Center( child: Text(stringResponse.toString()), ), ); } }
-
Tirth Patel about 3 yearsUse FutureBuilder or add
then
callback forfetcData
. -
Admin about 3 yearsSorry, I couldn't understand again how can I fetch by "class name" or "id". I guess your answer isn't about my question. In fact, my question is like that there are two paragraph in HTML, and I want to fetch the paragraph which has id's "p1".
-
Tirth Patel about 3 yearsUse some html parser library. pub.dev/packages/html
-
Balasubramani Sundaram about 3 yearsCould you please share the demo code of your response body.
-
Admin about 3 years@BalasubramaniSundaram Actually I haven't got any code in the body, I just considered there are string paragraphs. For example; <p id="p1">First string</p> <p id="p2">Second string</p> And I want to fetch first string by id.
-
Admin about 3 years@TirthPatel Thanks so much I'll check it out.
-
Admin about 3 yearsThank you again. I solved my problem thanks to you. @TirthPatel Resolution: parse(response.body).getElementById("p3").text; I implemented html library and I used this parse method and my problem was solved.
-
Tirth Patel about 3 yearsThat's Awesome! :D
-