Skip to content

Instantly share code, notes, and snippets.

@cliftonlabrum
Last active October 12, 2022 17:50
Show Gist options
  • Save cliftonlabrum/7241b9102b3d76dea4f6fd3e895724d0 to your computer and use it in GitHub Desktop.
Save cliftonlabrum/7241b9102b3d76dea4f6fd3e895724d0 to your computer and use it in GitHub Desktop.
Riverpod Example
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import "dart:math";
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends ConsumerWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
//:::
final person = ref.watch(providerPerson);
final notifier = ref.read(providerPerson.notifier);
//:::
return MaterialApp(
title: 'Riverpod Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Riverpod'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: () {
notifier.addStar();
},
child: const Text('Add Star'),
),
Text(
'⭐️ ${person.stars}',
),
const Divider(),
TextButton(
onPressed: () {
notifier.addPet();
},
child: const Text('Add Pet'),
),
for (var pet in person.pets) Text(pet)
],
),
),
),
);
}
}
class Person {
final int stars;
final List<String> pets;
Person({
this.stars = 0,
this.pets = const [],
});
Person copyWith({int? stars, List<String>? pets}) {
return Person(
stars: stars ?? this.stars,
pets: pets ?? this.pets,
);
}
}
final providerPerson = StateNotifierProvider<PersonState, Person>((ref) {
return PersonState();
});
class PersonState extends StateNotifier<Person> {
PersonState() : super(Person());
addStar() {
state = state.copyWith(stars: state.stars + 1);
}
addPet() {
var list = ['cat', 'dog', 'hamster', 'fish', 'bird'];
//Get random list element
final random = Random();
var pet = list[random.nextInt(list.length)];
state = state.copyWith(pets: [...state.pets, pet]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment