Flutter: Fetch certain elements of a HTML page

前端 未结 1 1496
野性不改
野性不改 2021-02-04 15:16

I recently started developing an app for an animal shelter using dart & flutter, and ran into problem.

The idea is that there is a donation page, where the user can

相关标签:
1条回答
  • 2021-02-04 16:10

    Furthering Seth's comment, you should be able to use the html library for this.

    That should look something like this:

    import 'package:html/parser.dart' show parse;
    import 'package:html/dom.dart';
    
    var document = parse(response.body);
    var priceElement = document.getElementsByClassName("product_price_from");
    // priceElement may have weird formatting (I see  ) so you might need to do some parsing
    // here to solve that
    

    I'd also recommend learning about Regular Expressions (RegEx) as they could be used to solve this fairly simply as well and is useful for all sorts of programming problems. Here is a link to dart's regex documentation and a general RegEx tutorial.

    That being said, this code will be dependent on the URL changing, the website changing or being down, that particular product not being sold anymore, and will use the user's data, and many other factors that may or may not be under your control - so I'd be a bit leery about putting it in production code even if it's just for an app for a shelter. At least make sure it has a safe fallback (i.e. fallback to the current price of 11500 Ft).

    I'd give a good thought as to whether this is actually necessary, rather than simply updating it yourself once every year if/when the price changes. Or if you have a server backend for your app (or even access to the shelter's website - you could put a page at shelter.com/donationprices/joseraadultactive with just "11499" being returned), I'd recommend making this just a parameter the app can retrieve that you can update (and if you absolutely want it to be done automatically, have a task that runs on the server once a day to retrieve the newest price). Also, I don't know how shelters work where you are, but where I live they tend to buy food in bulk at larger quantities or when it's on sale so the price for one bag of food is somewhat irrelevant - at that point you may as well just have a donate button with a picture of a bag and an arbitrary price as you'll probably get just as many donations, and many more than if there is a problem with the app.

    0 讨论(0)
提交回复
热议问题