我正在尝试学习 flutter,现在我正在研究按钮点击。
我在下面有一个非常简单的程序,其中整数和 = 5。如果用户在文本字段中返回 5 并单击提交按钮,我的目标是在提交按钮下方返回一个绿色方 block 。如果用户打印任何其他内容,正方形将为红色。
我实际上不知道从哪里开始,我的代码比我的代码更多,所以非常感谢任何帮助我走向正确方向的帮助。谢谢。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'buttonclicks',
theme: ThemeData(primarySwatch: Colors.deepOrange),
home: FirstClass(),
);
}
}
class FirstClass extends StatefulWidget {
@override
_FirstClassState createState() => _FirstClassState();
}
class _FirstClassState extends State<FirstClass> {
int sum = 5;
String enterAnswer;
void handleCorrect() {
setState(() {
Container(
height: 60.0,
width: 70.0,
decoration: BoxDecoration(color: Colors.green),
child: Text('CORRECT'),
);
});
}
void handleFalse() {
setState(() {
Container(
height: 60.0,
width: 70.0,
decoration: BoxDecoration(color: Colors.red),
child: Text('FALSE'),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BUTTON-CLICKS'),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
Container(
width: 50.0,
child: TextField(
textAlign: TextAlign.center,
autofocus: true,
keyboardType: TextInputType.number,
onChanged: (val) {
enterAnswer = val;
},
),
),
RaisedButton(
child: Text('SUBMIT'),
onPressed: () {
if (enterAnswer.isNotEmpty) {
if (enterAnswer == sum) {
handleCorrect(); //setState
} else {
handleFalse(); //setState
}
}
}),
Container(
//handleCorrect or handleFalse
child: Text("RETURN A GREEN OR A RED BOX"),
),
],
),
),
),
);
}
}
最佳答案
像下面这样的东西怎么样。您应该在单击按钮时调用 setState 并设置一些状态以确定要显示的颜色。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'buttonclicks',
theme: ThemeData(primarySwatch: Colors.deepOrange),
home: FirstClass(),
);
}
}
class FirstClass extends StatefulWidget {
@override
_FirstClassState createState() => _FirstClassState();
}
class _FirstClassState extends State<FirstClass> {
int sum = 5;
String enterAnswer;
Color containerColor;
void setColorForAnswer()
{
setState(() {
containerColor = enterAnswer != null && enterAnswer.isNotEmpty
? (int.parse(enterAnswer) == sum
? Colors.green
: Colors.red)
: Colors.transparent;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('BUTTON-CLICKS'),
),
body: Container(
child: Center(
child: Column(
children: <Widget>[
Container(
width: 50.0,
child: TextField(
textAlign: TextAlign.center,
autofocus: true,
keyboardType: TextInputType.number,
onChanged: (val) {
enterAnswer = val;
},
),
),
RaisedButton(
child: Text('SUBMIT'),
onPressed: () {
setColorForAnswer();
}),
Container(
width: 50,
height: 50,
color: containerColor,
),
],
),
),
),
);
}
}
关于button - 按下按钮后返回一个彩色框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54791581/