Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Created January 9, 2023 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MelbourneDeveloper/83fcabba9c41221bc7e222f24ec7547d to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/83fcabba9c41221bc7e222f24ec7547d to your computer and use it in GitHub Desktop.
Immutable State and StatelessWidgets Without Library
import 'package:flutter/material.dart';
@immutable
class Counter {
const Counter(this.count);
final int count;
Counter copyWith({int? count}) => Counter(count ?? this.count);
}
class CounterNotifier extends ValueNotifier<Counter> {
CounterNotifier(super.value);
void increment() => value = value.copyWith(count: value.count + 1);
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
MyApp({super.key});
final CounterNotifier counter = CounterNotifier(const Counter(0));
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'Flutter Demo Home Page',
counter: counter,
),
);
}
class MyHomePage extends StatelessWidget {
const MyHomePage({
required this.title,
required this.counter,
super.key,
});
final String title;
final CounterNotifier counter;
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
AnimatedBuilder(
animation: counter,
builder: (context, widget) => Text(
'${counter.value.count}',
style: Theme.of(context).textTheme.headline4,
),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: counter.increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment