首页 > 解决方案 > 颤振背景颜色

问题描述

我需要在点击时更改背景颜色,并在屏幕中间添加一些文本,但我不知道放置这些文本的最佳方式是什么,我这样做了:`

main() => runApp(
  const Directionality(
    textDirection: TextDirection.ltr,
    child: MyApp(),
  ),
);

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

@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
Color color =
  Color((Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0);

@override
Widget build(BuildContext context) {
  return Container(
  color: color,
  child: GestureDetector(
    onTap: () {
      setState(
        () {
          color = Color((Random().nextDouble() * 0xFFFFFF).toInt())
              .withOpacity(1.0);
        },
      );
    },
    child: const Center(child: Text('tttt')),
  ),
);
}
}` 

并且它在没有这条线的情况下改变了 bg child: const Center(child: Text('tttt')),但它只是停止工作,所以我该怎么做才能正确地做到这一点?

标签: flutterdart

解决方案


发生这种情况是因为您使用手势检测器包装了文本,因此,当您单击文本时,它会更改背景颜色。

要解决这个问题,只需ContainerGestureDetector

@override
Widget build(BuildContext context) {
  return GestureDetector(
    onTap: () {
      setState(
        () {
          color = Color((Random().nextDouble() * 0xFFFFFF).toInt())
              .withOpacity(1.0);
        },
      );
    },
    child: Container(color:color,child:child),
  ),
);
}
}` 

推荐阅读