Last active
March 5, 2020 14:16
-
-
Save rvdsoft/872fda2047b694381777bcd267638f6b to your computer and use it in GitHub Desktop.
Passing parameters between screens + initialising the view model
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 'package:meta/meta.dart'; | |
import 'package:provider/provider.dart'; | |
abstract class ViewModel implements ChangeNotifier { | |
Future<void> initState(); | |
} | |
abstract class BaseViewModel with ChangeNotifier implements ViewModel { | |
bool _isDisposed = false; | |
bool _isInitialized = false; | |
void setState(VoidCallback fn) { | |
assert(fn != null); | |
assert(_isInitialized); | |
fn(); | |
if (!_isDisposed) { | |
notifyListeners(); | |
} | |
} | |
@override | |
void notifyListeners() { | |
assert(_isInitialized); | |
super.notifyListeners(); | |
} | |
@override | |
void dispose() { | |
_isDisposed = true; | |
super.dispose(); | |
} | |
@override | |
@mustCallSuper | |
Future<void> initState() async { | |
assert(!_isInitialized); | |
_isInitialized = true; | |
} | |
} | |
abstract class ExampleViewModel extends ViewModel { | |
@override | |
Future<void> initState({@required String param1, @required int param2}); | |
void onButtonClick(); | |
factory ExampleViewModel() => ExampleViewModelImpl(); | |
} | |
class ExampleViewModelImpl extends BaseViewModel implements ExampleViewModel { | |
String param1; | |
int param2; | |
@override | |
Future<void> initState( | |
{@required String param1, @required int param2}) async { | |
assert(param1 != null); | |
assert(param2 != null); | |
super.initState(); | |
this.param1 = param1; | |
this.param2 = param2; | |
await fetchData(); | |
} | |
Future<void> fetchData() { | |
return Future.delayed(const Duration(seconds: 1)); | |
} | |
@override | |
void onButtonClick() { | |
print("button clicked"); | |
} | |
} | |
class ExampleWidget extends StatelessWidget { | |
final String param1; | |
final int param2; | |
const ExampleWidget({Key key, this.param1, this.param2}) : super(key: key); | |
@override | |
Widget build(BuildContext context) { | |
return ChangeNotifierProvider( | |
create: (_) => | |
ExampleViewModel()..initState(param1: param1, param2: param2), | |
child: Builder(builder: (context) { | |
final vm = Provider.of<ExampleViewModel>(context); | |
return RaisedButton( | |
onPressed: vm.onButtonClick, | |
); | |
}), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment