Home > Back-end >  Change Link when button is clicked in flutter
Change Link when button is clicked in flutter

Time:08-24

I wanted to ask this certain question, I don't know if I'm being silly or not. [https://mobile.alphacoders.com/by-category/10?page=1&quickload=1] here you can see in the link "page=1", I want to create a button in my flutter app so that when I click on the button the page number increases with one digit so like page=1 1 I think I can use the '$' property in the URL and add a setState but the trickier thing is I'm trying to scrape a website's wallpaper so when the user clicks on the next page button he must be redirected to a new page with new wallpapers

class Top2 extends StatefulWidget {
const Top2({Key? key}) : super(key: key);

@override
State<Top2> createState() => _Top2State();
}

class _Top2State extends State<Top2> {
 late List<Map<String, dynamic>> top2Wall;
  bool top2Loaded = false;

 void top2Fetch() async {
  final top2Scraper = WebScraper('https://mobile.alphacoders.com');

  if (await top2Scraper.loadWebPage('/by-category/3?page=1')) {
    top2Wall = top2Scraper.getElement(
      'div.container-masonry > div.item > a > img.img-responsive',
      ['src', 'title']);

 // ignore: avoid_print
  print(top2Wall);
   setState(() {
    top2Loaded = true;
   });
}
  }

   @override
   void initState() {
  super.initState();
 top2Fetch();
 }

      @override
   Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;
    return Scaffold(
body: top2Loaded

    // ignore: sized_box_for_whitespace
    ? Container(
        height: screenSize.height,
        width: double.infinity,
        child: SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          child: Wrap(children: [
            for (int i = 1; i < top2Wall.length; i  )
              WallCard(src: top2Wall[i]['attributes']['src'])
          ]),
        ),
      )
    : const Center(
        child: CircularProgressIndicator(color: Colors.cyanAccent),
      ));
      }
   } 

please refer to this image for clear code sample

CodePudding user response:

Hello @Cheems Monarch

You can try like this :

First create a variable:

int page=1;

Then change your method like this:

 void top2Fetch(String page) async {
final top2Scraper = WebScraper('https://mobile.alphacoders.com');

if (await top2Scraper.loadWebPage('/by-category/3?page=$page')) {
  top2Wall = top2Scraper.getElement(
      'div.container-masonry > div.item > a > img.img-responsive',
      ['src', 'title']);

  // ignore: avoid_print
  print(top2Wall);
  setState(() {
    top2Loaded = true;
  });
}

}

And call this function on your button's onPressed:

 onPressed: () {
  top2Fetch(page.toString());            
   setState(() {
      page  ;
  });
 }
  • Related