我正在尝试学习颤动,现在我正在处理按钮单击。
我下面有一个非常简单的程序,其中整数sum =5。如果用户在文本字段中返回5并单击“提交”按钮,我的目标是在“提交”按钮下方返回一个绿色正方形。如果用户打印其他任何内容,则正方形将为红色。
与我的代码相比,我实际上不知道从哪里开始,因此非常感谢能使我朝正确方向发展的任何帮助。谢谢。
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"),
),
],
),
),
),
);
}
}
答案 0 :(得分:1)
类似以下内容。单击按钮时应调用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,
),
],
),
),
),
);
}
}