Last active
September 28, 2024 02:41
-
-
Save tomasbaran/c361be27eaf6df76c2d6429f2a83b9dd to your computer and use it in GitHub Desktop.
Simple ValueNotifier State Management Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:math'; | |
void main() { | |
runApp(const MainApp()); | |
} | |
class MainApp extends StatelessWidget { | |
const MainApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
// randomNumberVM is usually instantiated via Provider (Scopped for part of the tree) or ServiceLocator (singleton) | |
// For the sake of simplicity, I'll instantiate it here—not to focus on the providing part of the state management | |
final RandomNumberVM randomNumberVM = RandomNumberVM(); | |
return MaterialApp( | |
home: Scaffold( | |
body: Center( | |
child: ValueListenableBuilder<LoadingState>( | |
valueListenable: randomNumberVM.loadingState, | |
builder: (_, loadingState, __) { | |
switch (loadingState) { | |
case LoadingState.initial: | |
return const Text('Random Number: --'); | |
case LoadingState.loading: | |
return const CircularProgressIndicator(); | |
case LoadingState.loaded: | |
return Text('Random Number: ${randomNumberVM._randomNumber}'); | |
case LoadingState.error: | |
return const Text( | |
'Error!', | |
style: TextStyle(color: Colors.red), | |
); | |
} | |
}), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () => randomNumberVM.generateRandomNumber(), | |
child: const Icon(Icons.star), | |
), | |
), | |
); | |
} | |
} | |
enum LoadingState { initial, loading, loaded, error } | |
class RandomNumberVM { | |
final ValueNotifier<LoadingState> loadingState = ValueNotifier<LoadingState>(LoadingState.initial); | |
late int _randomNumber; | |
get randomNumber => _randomNumber; | |
Future<void> generateRandomNumber() async { | |
loadingState.value = LoadingState.loading; | |
await Future.delayed(const Duration(seconds: 1)); | |
_randomNumber = Random().nextInt(100); | |
if (_randomNumber % 2 == 0) { | |
loadingState.value = LoadingState.loaded; | |
} else { | |
loadingState.value = LoadingState.error; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment