On and Off With a Switch
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 27 of 34.
A Switch is the on and off toggle you know from phone settings. It shows a bool, and tells you when someone flips it:
Switch(
value: _wifi,
onChanged: (bool value) {
setState(() {
_wifi = value;
});
},
)value: is where it is drawn: on for true, off for false. onChanged gets the new value when it is tapped.
The switch does not move by itself. A tap only calls onChanged; you store the new value with setState, the screen is built again, and the switch is drawn in its new place. Forget that, and the switch springs back every time you tap it.
Challenge
Easy- Make the switch work: store the new value in
_darkwithsetState. - Give the
ScaffoldabackgroundColorofColors.blackwhen dark mode is on, andColors.whitewhen it is off. The label already changes color.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _dark = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(title: const Text('Settings')),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'Dark mode',
style: TextStyle(fontSize: 20, color: _dark ? Colors.white : Colors.black),
),
const SizedBox(width: 12),
Switch(
value: _dark,
onChanged: (bool value) {},
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
Practice on your own: Online Flutter compiler