Lists of color and names i want to build an app that will change color and text on tap. I want to change the container color and the text which are displayed on a list and randomize both of them. How can i do that?Here i want to change randomize both of them and get on tap
CodePudding user response:
this will give you random color
Color(0xFF000000 Random().nextInt(0xFFFFFF))
CodePudding user response:
you can get random item from the list by using below code,
var randomName = names.elementAt(Random().nextInt(names.length)
use randomName and update in setState()
CodePudding user response:
You can change the name and color by tapping on the screen
import 'package:flutter/material.dart';
import "dart:math";
void main() => runApp(MyApp());
/// This Widget is the main application widget.
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: _title,
home: HomeScreen(),
);
}
}
List<String> names = [
'John',
'Maria',
'Mike',
'ABC',
'ABCDEF',
'XYZ',
'ZXY',
];
List<Color> colors = [
Colors.amber,
Colors.grey,
Colors.white,
Colors.yellow,
Colors.green,
];
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
String? randomName;
Color? randomColor;
@override
Widget build(BuildContext context) {
final random = new Random();
randomName = names[random.nextInt(names.length)];
randomColor = colors[random.nextInt(colors.length)];
return Scaffold(
body: GestureDetector(
onTap: () {
setState(() {
randomName = names[random.nextInt(names.length)];
randomColor = colors[random.nextInt(colors.length)];
});
},
child: Container(
color: randomColor,
child: Center(
child: Text(randomName!),
)
),
)
);
}
}