Home > Net >  How to make Image Random Generator in flutter?
How to make Image Random Generator in flutter?

Time:04-25

hey guys I'm new to Flutter & Dart and I'm trying to make an app that will show a different image every time the user opens it,, I marked this method randomNum but I know it will not work for long because I want the user to download their own images with the default images that I have,

my method is to make the images have the same name but with different numbers and make a RandomNumber generator :

Random random = new Random();
int randomNum = random.nextInt(3)   1;

class _qouteeState extends State<qoutee> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: SafeArea(
          child: Expanded(
            flex: 3,
            child: Container(
              color: Colors.grey[300],
              child: Center(
                child: Image.asset('images/q$randomNum.jpg'),
              ),
            ),
          ),
        ),
      ),

    );
  }
}

images : enter image description here

So how can I make Random image function without making the images have the same name

CodePudding user response:

you can save the path of your images in a list of String. then make a random object that depends on the length of this list. For example, if the random value was 1 then return the value of the index 1 in the list. here is a very simple example. List paths = [path_of_image1, image2 ...];

Random random = Random();
int randomNum = random.nextInt(paths.length);
String selectedImagePath = paths[randomNum];
//you can display your image by a specific widget.

If you ask about how to add an image by the user and take the path you can find a lot of resources and solutions.

  • Related