Skip to content

Instantly share code, notes, and snippets.

@abdullah
Last active January 29, 2020 08:21
Show Gist options
  • Save abdullah/29e496350452bb8c2db06a9753386840 to your computer and use it in GitHub Desktop.
Save abdullah/29e496350452bb8c2db06a9753386840 to your computer and use it in GitHub Desktop.
Simple provider example
import 'package:flutter/material.dart';
import 'package:flutter_bloc/blocs/featured_post_bloc.dart';
import 'package:provider/provider.dart';
import 'package:flutter_bloc/widgets/refresh.dart';
class FeaturedPostPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final FeaturedPostBloc featuredPostBloc =
Provider.of<FeaturedPostBloc>(context);
if (featuredPostBloc.posts.length == 0) {
featuredPostBloc.fetchPosts(); // It works but throws errors.
}
return Container(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
featuredPostBloc.isLoading
? CircularProgressIndicator()
: Text(
featuredPostBloc.posts.length.toString(),
style: TextStyle(fontSize: 62.0),
),
RefreshButton(),
],
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter_bloc/models/post.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
Future<List<Post>> _fetchPosts() async {
final response = await http.get('https://api.kodilan.com/posts?get=25');
if (response.statusCode == 200) {
var body = json.decode(response.body);
List<Object> list = body["data"];
return list.map((item) => Post.fromJson(item)).toList();
} else {
throw Exception('Failed to load post');
}
}
class FeaturedPostBloc extends ChangeNotifier {
List<Post> _posts = [];
bool _isLoading = false;
bool _hasError = false;
bool get hasError => _hasError;
bool get isLoading => _isLoading;
List<Post> get posts => _posts;
set isLoading(bool isLoading) {
_isLoading = isLoading;
notifyListeners();
}
set hasError(bool hasError) {
_hasError = hasError;
notifyListeners();
}
set posts(List<Post> posts) {
_posts = posts;
notifyListeners();
}
fetchPosts() async {
isLoading = true;
hasError = false;
try {
posts = await _fetchPosts();
} catch (e) {
print(e);
hasError = true;
} finally {
isLoading = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment