96 lines
2.8 KiB
Dart
96 lines
2.8 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:flutter/material.dart';
|
|
import 'classes/events.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
|
|
import 'variable/globals.dart' as globals;
|
|
|
|
// app starting point
|
|
void main() {
|
|
runApp(const MyApp());
|
|
}
|
|
|
|
class MyApp extends StatelessWidget {
|
|
const MyApp({super.key});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return MaterialApp(
|
|
home: const ListItemMenu(),
|
|
debugShowCheckedModeBanner: false,
|
|
);
|
|
}
|
|
}
|
|
|
|
// homepage class
|
|
class ListItemMenu extends StatefulWidget {
|
|
const ListItemMenu({super.key});
|
|
|
|
@override
|
|
State<ListItemMenu> createState() => _MyHomePageState();
|
|
}
|
|
|
|
// homepage state
|
|
class _MyHomePageState extends State<ListItemMenu> {
|
|
// variable to call and store future list of posts
|
|
Future<List<Events>> postsFuture = getPosts();
|
|
|
|
// function to fetch data from api and return future list of posts
|
|
static Future<List<Events>> getPosts() async {
|
|
SharedPreferences prefs = await SharedPreferences.getInstance();
|
|
var accessToken = prefs.getString("access_token") ?? "";
|
|
final List<Events> body = [];
|
|
if (accessToken.isNotEmpty) {
|
|
var url = Uri.parse("http://${globals.api}/events");
|
|
final response = await http.get(url, headers: {
|
|
"Content-Type": "application/json",
|
|
HttpHeaders.cookieHeader: "access_token=${accessToken}"
|
|
});
|
|
final List body = json.decode(utf8.decode(response.bodyBytes));
|
|
return body.map((e) => Events.fromJson(e)).toList();
|
|
}
|
|
return body;
|
|
}
|
|
|
|
// build function
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return Scaffold(
|
|
body: Center(
|
|
// FutureBuilder
|
|
child: FutureBuilder<List<Events>>(
|
|
future: postsFuture,
|
|
builder: (context, snapshot) {
|
|
if (snapshot.connectionState == ConnectionState.waiting) {
|
|
// until data is fetched, show loader
|
|
return const CircularProgressIndicator();
|
|
} else if (snapshot.hasData) {
|
|
// once data is fetched, display it on screen (call buildPosts())
|
|
final posts = snapshot.data!;
|
|
return buildPosts(posts);
|
|
} else {
|
|
// if no data, show simple Text
|
|
return const Text("No data available");
|
|
}
|
|
},
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
// function to display fetched data on screen
|
|
Widget buildPosts(List<Events> posts) {
|
|
// ListView Builder to show data in a list
|
|
return ListView.builder(
|
|
itemCount: posts.length,
|
|
itemBuilder: (context, index) {
|
|
final post = posts[index];
|
|
return ListTile(
|
|
title: Text('${post.name!}'), subtitle: Text('${post.place!}'));
|
|
},
|
|
);
|
|
}
|
|
}
|