// news_provider.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
final String baseUrl = '';
final newsProvider = FutureProvider<List<Berita>> ((ref) async {
// final response = await http.get(Uri.parse('$baseUrl/posts?_embed')); //ini asli
final response = await http.get(Uri.parse('$baseUrl/posts?per_page=20&_embed'));
if (response.statusCode == 200) {
List<dynamic> jsonResponse = json.decode(response.body);
return jsonResponse.map((post) => Berita.fromJson(post)).toList();
} else {
throw Exception('GAGAL MENGAMBIL BERITA TERBARU');
}
});
class Berita {
final int id;
final String title;
final String content;
final String excerpt;
final String featuredImageUrl;
final DateTime date;
final String link;
final List<dynamic> categories;
Berita({
required this.id,
required this.title,
required this.content,
required this.excerpt,
required this.featuredImageUrl,
required this.date,
required this.link,
required this.categories
});
factory Berita.fromJson(Map<String, dynamic> json) {
return Berita(
id: json['id'],
title: json['title']['rendered'],
content: json['content']['rendered'],
excerpt: json['excerpt']['rendered'],
featuredImageUrl: json['_embedded']['wp:featuredmedia'] != null
? json['_embedded']['wp:featuredmedia'][0]['source_url']
: '', // Replace with default image URL
date: DateTime.parse(json['date']),
link: json['link'],
categories: json['categories'],
);
}
}
//Here is the HomeScreen. So I want to display the fire data here, how do I do it. So I want to display api data here, how to do it. I am still learning to use Riverpod State and I am still confused to implement it in Stateful Widget
//Here is the HomeScreen. So I want to display the fire data here, how do I do it. So I want to display api data here, how to do it. I am still learning to use Riverpod State and I am still confused to implement it in Stateful Widget
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
late Future<List<Berita>> _postsFuture;
late Future<List<Category>> categories;
@override
void initState() {
super.initState();
_postsFuture = ApiService().getLatestPosts();
categories = ApiService().fetchCategories();
}
@override
Widget build(BuildContext context) {
return Scaffold(
// drawer: Drawer(),
appBar: AppBar(
title: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Aplikasi'),
Text(
'Berita',
style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
),
],
),
actions: [
IconButton(
icon: Icon(Icons.search, color: Colors.red),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SearchNews()),
);
},
),
],
centerTitle: true,
elevation: 0.0,
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Kategori',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
_buildCategory(),
Padding(
padding: const EdgeInsets.only(top: 50.0, bottom: 20, left: 8),
child: Text(
'Berita Utama',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.redAccent,
),
),
),
_buildCarousel(),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SearchNews()),
);
},
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(
top: 40.0,
bottom: 20,
left: 8,
right: 8,
),
child: Text(
'Berita Terbaru',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.orange,
),
),
),
Spacer(),
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => BeritaTerbaru()),
);
},
child: Padding(
padding: const EdgeInsets.only(
top: 40.0,
bottom: 20,
left: 8,
right: 8,
),
child: Text(
"Lihat",
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.bold,
color: Colors.black45,
),
),
),
),
],
),
),
_buildLatestNews(),
],
),
),
);
}
Widget _buildCategory() {
return SizedBox(
height: 35,
// width: MediaQuery.of(context).size.width,
child: FutureBuilder<List<Category>>(
future: categories,
builder: (context, snapshot) {
if (snapshot.hasData) {
return SizedBox(
height: 15,
width: MediaQuery.of(context).size.width,
child: ListView.builder(
shrinkWrap: true,
scrollDirection: Axis.horizontal,
itemCount: snapshot.data!.length,
itemBuilder: (context, index) {
return Stack(
children: [
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder:
(context) => ListNewsScreen(
categoryId: snapshot.data![index].id,
categoryName: snapshot.data![index].name,
),
),
);
},
child: Container(
margin: const EdgeInsets.only(left: 10, right: 10),
height: 250,
width: MediaQuery.of(context).size.width / 3.5,
decoration: BoxDecoration(
color: Colors.blue,
borderRadius: BorderRadius.circular(10),
),
child: Center(
child: Text(
snapshot.data![index].name,
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
),
),
),
],
);
},
),
);
} else if (snapshot.hasError) {
return Center(child: Text('${snapshot.error}'));
}
return Center(child: CircularProgressIndicator());
},
),
);
}
}