Skip to content

Instantly share code, notes, and snippets.

@av
Created August 14, 2019 13:09
Show Gist options
  • Save av/4383a7b78015304fecbae746041a13ab to your computer and use it in GitHub Desktop.
Save av/4383a7b78015304fecbae746041a13ab to your computer and use it in GitHub Desktop.
Singletone services and provider
import 'service.dart';
class HomeScreen extends StatelessWidget {
@override
build(BuildContext context) {
// When service will notify its listeners, we'll be automatically
// rebuilt
List<Model> items = Provider.of<Service>(context).items;
return Scaffold(
body: Column(
children: <Widget>[
...items.map((Model item) => Text(item.name)),
Button(
onPressed: () {
// Dispatch action to service, no need to
// use provider for this
Service.instance.fetchItems();
}
)
]
)
);
}
}
void main() => runApp(RootWidget());
class RootWidget extends StatefulWidget {
@override
_RootWidgetState createState() => _RootWidgetState();
}
class _RootWidgetState extends State<RootWidget> {
Service service;
Future init() async {
service = Service.instance;
return Future.wait(<Future>[
service.init(),
]);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Example app',
routes: {
'/': _buildRoot,
},
);
}
Widget _buildRoot(context) {
return FutureBuilder(
future: init(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return HomeScreen();
} else if (snapshot.hasError) {
return ErrorScreen();
}
return SplashScreen();
},
);
}
}
class Model {
String name;
Model({ this.name });
}
class Service with ChangeNotifier {
static final Service _instance = Service();
static Service get instance => _instance;
// Needs to be
// rendered in list
List<Model> items = [];
Future init() async {
// Do something asynchronous, for example read SharedPreferences
// or query sqflite db.
return Future.delayed(const Duration(milliseconds: 1000));
}
Future fetchItems() async {
List<Model> response = await api.get('/items');
items.addAll(response);
notifyListeners();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment