Home > Mobile >  Random parameter for FutureBuilder
Random parameter for FutureBuilder

Time:08-24

Here I have a StatefulWidget in which I want to get a random pet each time from a random url. Also, I have a condition for the random pet, if the condition is true, the pet will be shown, otherwise the random url and random pet should be selected again. I attached my code below, and the problem is the url only changes when the condition is false, but I want it to be randomly selected each time.

Putting the API.get_pets(init_random_url); in the future parameter of the FutureBuilder will solve the random selection but if the condition is false the URL and the pet would change two or three times, after searching about it and reading FutureBuilder documentation I put it in the initState and requestAgain and build, but I recognized the selectedURL in the build function does not work and the widget is stucked in the same URL until the condition gets false value.

import 'dart:developer';

import 'package:double_back_to_close/toast.dart';
import 'package:flutter/material.dart';
import 'package:pet_store/widgets/guess_game_random_card.dart';
import 'webservice/API.dart';
import 'main.dart';
import 'dart:math';
import 'utils/utils.dart';

Random random = new Random();

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

  @override
  State<Guess_Game> createState() => _Guess_GameState();
}

class _Guess_GameState extends State<Guess_Game> {

  void initState() {
    super.initState();
    init_random_url = randomly_select_URL();
    GuessGameFuture = API.get_pets(init_random_url);
  }

  void requestAgain() {
    setState(() {
      init_random_url = randomly_select_URL();
      GuessGameFuture = API.get_pets(init_random_url);
    });
  }

  @override
  Widget build(BuildContext context) {
    init_random_url = randomly_select_URL();
    return Scaffold(
      body: Center(
        child: 
              FutureBuilder<List<dynamic>>(
                future: GuessGameFuture,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {

                    List<dynamic>? pet_data = snapshot.data;
                      var number_of_parameters = snapshot.data!.length;
                      var random_pet = random.nextInt(number_of_parameters);
                      var category = pet_data![random_pet].category.toString();
                      var photoURL = pet_data![random_pet].photoUrls;
                      // Here is the condition that ensure pet category is in the list and has an image
                      if (checkCategoryInList(category, items) &&
                          photoURL.length != 0) {
                        return Random_Card(
                            pet_data: pet_data,
                            random_pet: random_pet,
                            dropdownvalue: dropdownvalue);
                      } else {
                        if (photoURL.length == 0) {
                          print(" NO PHOTO SUBMITTED FOR THIS PET");
                        } else {
                          print(category   "NOT IN CATEGORY");
                        }
                        WidgetsBinding.instance.addPostFrameCallback((_) {
                          requestAgain();
                        });
                      }
                    
                  } else if (snapshot.hasError) {
                    return Text("${snapshot.error}");
                  }
                  return const CircularProgressIndicator();
                },
              )
            else
              const Text(
                "Please select your guess",
                style: TextStyle(fontSize: 17, color: Colors.indigo),
              ),
        ),
      ),
    
  }
}

CodePudding user response:

Add this line to build

GuessGameFuture = API.get_pets(randomly_select_URL());

and Change requestAgain function to this:

  void requestAgain() {
    setState(() {
      GuessGameFuture = API.get_pets(randomly_select_URL());
    });
  }

Also you can use FutureProvider and riverpod library. Hope it helps

  • Related