Skip to content

Instantly share code, notes, and snippets.

@jamiecollinson
Created September 16, 2022 15:07
Show Gist options
  • Save jamiecollinson/27a78ca05e168ffc483a587a98de3d0d to your computer and use it in GitHub Desktop.
Save jamiecollinson/27a78ca05e168ffc483a587a98de3d0d to your computer and use it in GitHub Desktop.
Stateless widget example

Stateless widget example

Created with <3 with dartpad.dev.

// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
// This is state, which can change,
// and each time it does anything that depends on it changes
bool _toggled = false;
void _switchToggle(bool value) {
setState(() {
_toggled = value;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Parent state: $_toggled"),
MyToggle(_toggled, _switchToggle),
],
),
),
);
}
}
class MyToggle extends StatelessWidget {
const MyToggle(this._toggled, this._switch);
// This is set by the constructor above - it's never set by MyToggle directly
// It's not state, a new MyToggle is created each time the parent re-renders
final bool _toggled;
final Function(bool) _switch;
@override
Widget build(BuildContext context) {
return Switch(
// This bool value toggles the switch.
value: _toggled,
activeColor: Colors.red,
onChanged: (bool value) {
// This is called when the user toggles the switch.
_switch(value);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment