1)splash_screen.dart
import 'package:flutter/material.dart';
import 'dart:async';
import 'listview_screen.dart'; // Import the ListView screen
class SplashScreen extends StatefulWidget {
@override
_SplashScreenState createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
Timer(Duration(seconds: 3), () {
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (context) => ListViewScreen()),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal,
body: Center(
child: Text(
"Welcome to My App",
style: TextStyle(color: Colors.white, fontSize: 24),
),
),
);
}
}
2) main.dart
import 'package:flutter/material.dart';
import 'package:listview_demo/splash_screen.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: SplashScreen(), // Set Splash Screen as the initial screen
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headlineMedium,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
3)listview_screen.dart
import 'package:flutter/material.dart';
import 'dart:convert'; // For decoding JSON
import 'package:http/http.dart' as http;
import 'package:listview_demo/list_item.dart';
import 'package:listview_demo/user_data.dart'; // For making HTTP requests
class ListViewScreen extends StatefulWidget {
@override
_ListViewScreenState createState() => _ListViewScreenState();
}
class _ListViewScreenState extends State<ListViewScreen> {
late List<UserData> data = [];
@override
void initState() {
super.initState();
fetchData();
}
// Fetch data from API
fetchData() async {
var response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
if (response.statusCode == 200) {
setState(() {
// data = json.decode(response.body);
if (response != null) {
try {
if (data.isNotEmpty) data.clear();
// Convert JSON response into a List<UserData>
List<dynamic> jsonData = json.decode(response.body);
// Map the JSON to UserData model
data = jsonData.map((jsonItem) => UserData.fromJson(jsonItem)).toList();
// Print to check the data
for (var user in data) {
print('${user.title}');
}
} catch (e) {
// Log.severe('Error: $e');
}
}
});
} else {
throw Exception('Failed to load data');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
centerTitle: true,
backgroundColor: Colors.teal,
leading: IconButton(onPressed: () {
Navigator.pop(context);
}, icon: Icon(Icons.arrow_back,color: Colors.white,)),
title: Text("ListView",style: TextStyle(color: Colors.white),),
),
body: data.isEmpty
? Center(child: CircularProgressIndicator())
: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: ListItem(
data: data[index],
// title: Text(data[index]['title']),
// subtitle: Text(data[index]['body']),
),
);
},
),
);
}
}
4)list_item.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:listview_demo/user_data.dart';
//Alt+Enter
class ListItem extends StatefulWidget{
UserData data;
ListItem({
super.key,
required this.data,
});
@override
State<ListItem> createState() => _ListItemState();
}
class _ListItemState extends State<ListItem> {
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(left: 4.0,right: 4),
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
),
child: Padding(
padding: const EdgeInsets.all(10.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.data.title,maxLines: 2, style: TextStyle(fontSize: 20,letterSpacing : 0.0 ,fontWeight: FontWeight.w600,color: Colors.black),),
Text(widget.data.body, maxLines: 4, style: TextStyle(fontSize: 16, letterSpacing: 0.0, color: Colors.black,),),
],
),
),
),
);
}
}
5)api_response.dart
import 'package:listview_demo/user_data.dart';
class ApiResponse {
final List<UserData> data;
ApiResponse({required this.data});
// Factory method to create ApiResponse from JSON
factory ApiResponse.fromJson(Map<String, dynamic> json) {
var list = json['data'] as List;
List<UserData> userList = list.map((i) => UserData.fromJson(i)).toList();
return ApiResponse(data: userList);
}
}
6)user_data.dart
import 'dart:convert';
List<UserData> userDataFromJson(String str) => List<UserData>.from(json.decode(str).map((x) => UserData.fromJson(x)));
String userDataToJson(List<UserData> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
class UserData {
int userId;
int id;
String title;
String body;
UserData({
required this.userId,
required this.id,
required this.title,
required this.body,
});
factory UserData.fromJson(Map<String, dynamic> json) => UserData(
userId: json["userId"],
id: json["id"],
title: json["title"],
body: json["body"],
);
Map<String, dynamic> toJson() => {
"userId": userId,
"id": id,
"title": title,
"body": body,
};
}
7) pubspac.yaml
name: listview_demo
description: "A new Flutter project."
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ^3.5.3
dependencies:
flutter:
sdk: flutter
http: ^1.3.0
cupertino_icons: ^1.0.8
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^4.0.0
flutter:
uses-material-design: true