Basic Interactivity
You’ve been using Stateless Widgets up until now, which is fine unless you’re creating static layouts. However, in order to create dynamic layouts and add interactivity to your app, you must use Stateful Widgets.
Projects
1. The Famous Counter App
Create a new Flutter project. It by default comes with a stateful widget. Explore how the +
button is working incrementing the counter and how the state rebuilds to display the increased counter. Important to note that the setState()
method is called to rebuild the UI. Also note setState()
can only be used in a stateful widget.
2. Dice App
Create a dice App that displays a random dice number (between 1-6) when the Roll
button is clicked. The number should be displayed in the center of the screen in large font size. The Roll
button should be displayed at the bottom of the screen. Use dart’s Random class to generate a random number.
2. Quiz App
Create a new Flutter project, clear main.dart
and paste the following code. Complete the following code to build the UI as shown below. Then add the functionality to change the background color of the button when clicked as described below.
Starter Code
void main() => runApp(QuizApp());
class QuizApp extends StatelessWidget {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.grey.shade900,
body: SafeArea(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 10.0),
child: Quiz(),
),
),
),
);
}
}
class Quiz extends StatefulWidget {
_QuizState createState() => _QuizState();
}
class _QuizState extends State<Quiz> {
int questionNumber = 0;
List<Icon> scoreKeeper;
Widget build(BuildContext context) {
Map<String, dynamic> question = {
'question': 'Flutter stable version was launched in November 2018',
'options': ['Yes', 'No'],
'answer': 'No',
};
return Scaffold(); // complete the UI
}
}
When one of the buttons is clicked, change the background color of the clicked button to green if the answer was correct and red otherwise.