flutter 抖动更改文本和颜色

tktrz96b  于 2022-11-30  发布在  Flutter
关注(0)|答案(3)|浏览(201)


颜色和名称的列表我想构建一个应用程序,它将改变颜色和文本点击。我想改变容器的颜色和文本显示在一个列表上,并随机化他们。我该怎么做?在这里我想改变随机化他们,并点击

syqv5f0l

syqv5f0l1#

这会给你随机颜色

Color(0xFF000000+Random().nextInt(0xFFFFFF))
6tdlim6h

6tdlim6h2#

你可以使用下面的代码从列表中获得随机项,

var randomName = names.elementAt(Random().nextInt(names.length)

在setState()中使用随机名称和更新

k3fezbri

k3fezbri3#

您可以通过点击屏幕上的

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!),
          )
        ),
      )
    );
  }
}

相关问题