Search code examples
androidstringflutterrandominteger

Hi how can I do random operations with flutter?


Hi how do I want to show you random city name and time in my application? Different times and cities should appear each time the app is entered?Let me illustrate what I mean: The user entered the application and saw Amsterdam at 23:43 as the time. How can I do if I want the output from the application to appear in the opposite Hague 08:37 when it enters again? Please help


Solution

  • You can have list of cities and list of times or you can even generate time based on present time.

    Sample code:

    class MyApp extends StatelessWidget {
      final cities = ['Amsterdam', 'The Hague', 'Rotterdam', 'Utrecht', 'Groningen'];
    
      @override
      Widget build(BuildContext context) {
        final random = Random(); // You can use random to generate random cities
        final city = cities[random.nextInt(cities.length)];
        final time = DateTime.now().add(Duration(minutes: random.nextInt(60 * 24)));
    
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(title: Text('Random City')),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(city, style: TextStyle(fontSize: 32)),
                  SizedBox(height: 16),
                  Text('${time.hour.toString()}:${time.minute.toString()}'),
                ],
              ),
            ),
          ),
        );
      }
    }