Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Last active November 29, 2023 23:59
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/850a8261c535cb64f80620ed372eff33 to your computer and use it in GitHub Desktop.
Save MelbourneDeveloper/850a8261c535cb64f80620ed372eff33 to your computer and use it in GitHub Desktop.
Rx Example - ChangeNotifier
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) => const MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
);
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class PersonData extends ChangeNotifier {
String _firstName = 'Jane';
String _surname = 'Doe';
String get firstName => _firstName;
String get surname => _surname;
String get fullName => '$_firstName $_surname';
set firstName(String newName) {
if (newName != _firstName) {
_firstName = newName;
// Triggers rebuild
notifyListeners();
}
}
set surname(String newSurname) {
if (newSurname != _surname) {
_surname = newSurname;
// Triggers rebuild
notifyListeners();
}
}
}
class _MyHomePageState extends State<MyHomePage> {
final PersonData personData = PersonData();
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('ChangeNotifier Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedBuilder(
animation: personData,
builder: (context, child) => Text(
personData.fullName,
style: Theme.of(context).textTheme.headlineMedium,
),
),
ElevatedButton(
onPressed: () => setState(() {
personData.firstName =
personData.firstName == 'Jane' ? 'John' : 'Jane';
}),
child: const Text('Change First Name'),
),
ElevatedButton(
onPressed: () => setState(() {
personData.surname =
personData.surname == 'Doe' ? 'Dop' : 'Doe';
}),
child: const Text('Change Surname'),
),
],
),
),
);
@override
void dispose() {
personData.dispose();
super.dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment