Api Flutter
Api Flutter
Jacob Rodriguez
Code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:share/share.dart';
void main() {
runApp(MyApp());
}
class RandomUser {
final String gender;
final String name;
final String email;
final String address;
RandomUser({
required this.gender,
required this.name,
required this.email,
required this.address,
});
try {
final response = await http.get(Uri.parse('https://randomuser.me/api/'));
if (response.statusCode == 200) {
final jsonData = jsonDecode(response.body);
RandomUser user = RandomUser.fromJson(jsonData);
setState(() {
randomUser = user;
});
} else {
setState(() {
randomUser = null;
});
}
} catch (e) {
setState(() {
randomUser = null;
});
} finally {
setState(() {
isLoading = false;
});
}
}
void deleteUserInformation() {
setState(() {
randomUser = null;
});
}
void shareUserInformation() {
if (randomUser != null) {
String message = 'Name: ${randomUser!.name}\n'
'Gender: ${randomUser!.gender}\n'
'Email: ${randomUser!.email}\n'
'Address: ${randomUser!.address}\n';
Share.share(message);
}
}
try {
final response = await http
.get(Uri.parse('https://randomuser.me/api/?name=$searchName'));
if (response.statusCode == 200) {
final jsonData = jsonDecode(response.body);
RandomUser user = RandomUser.fromJson(jsonData);
setState(() {
randomUser = user;
});
} else {
setState(() {
randomUser = null;
});
}
} catch (e) {
setState(() {
randomUser = null;
});
} finally {
setState(() {
isLoading = false;
});
}
}
}
@override
void initState() {
super.initState();
fetchRandomUser();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
'User Information',
style: TextStyle(
fontSize: 27,
fontWeight: FontWeight.bold,
fontFamily: 'YourDesiredFont',
color: Colors.black,
),
),
centerTitle: true,
leading: IconButton(
icon: Icon(
Icons.menu,
color: Colors.black,
size: 32, // Adjust the size as per your requirement
),
onPressed: () {
// Implement the search functionality here
},
),
),
body: Center(
child: isLoading
? CircularProgressIndicator()
: randomUser != null
? UserInfoCard(
randomUser: randomUser!,
onDelete: deleteUserInformation,
)
: Text(searchName != null && searchName!.isNotEmpty
? 'No user found with the name "$searchName".'
: 'User Information Deleted Successfull.'),
),
backgroundColor: const Color.fromARGB(255, 232, 230, 230),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: 70,
height: 70,
child: ElevatedButton(
onPressed: () => searchUser(),
child: Icon(Icons.search, size: 32),
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
),
),
),
SizedBox(
width: 70,
height: 70,
child: ElevatedButton(
onPressed: randomUser != null ? deleteUserInformation : null,
child: Icon(Icons.delete, size: 32),
style: ElevatedButton.styleFrom(
shape: CircleBorder(),
),
),
),
SizedBox(
width: 70,
height: 70,
child: FloatingActionButton(
onPressed: () => fetchRandomUser(),
tooltip: 'New User',
child: Icon(Icons.navigate_next, size: 32),
),
),
],
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButtonAnimator: FloatingActionButtonAnimator.scaling,
);
}
}
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(25.0, 45.0, 25.0, 0),
child: Align(
alignment: Alignment.topCenter,
child: Card(
color: Color.fromARGB(255, 255, 239, 93),
elevation: 20.0,
child: Table(
border: TableBorder(
horizontalInside: BorderSide(
color: Colors.black,
width: 4.0,
),
),
children: [
buildTableRow('Name', '${randomUser.name}'),
buildTableRow('Gender', '${randomUser.gender}'),
buildTableRow('Email', '${randomUser.email}'),
buildTableRow('Address', '${randomUser.address}'),
],
),
),
),
);
}
Output:
Documentation: Random User Information App
Dependencies
The app uses the following external packages:
1. `flutter/material.dart`: The Flutter material library that provides the basic building blocks for
creating Flutter applications with a material design-based look and feel.
2. `http/http.dart`: An HTTP client for Dart that allows making HTTP requests to interact with
APIs and web services.
3. `dart:convert`: A built-in Dart package that provides encoding and decoding functionalities for
converting between Dart objects and JSON data.
4. `share`: A Flutter plugin that allows sharing content with other installed applications on the
device.
App Structure
1. `RandomUser` class: A model class representing a random user with properties for gender,
name, email, and address. It also includes a factory method to convert JSON data into a
`RandomUser` object.
2. `MyApp` class: The root of the application, a `StatelessWidget` that sets up the basic structure
of the app, including the `MaterialApp` widget, the app's title, theme, and the initial screen,
which is `RandomUserScreen`.
3. `RandomUserScreen` class: A `StatefulWidget` that represents the main screen of the app. It
includes state variables for managing the current random user, loading state, and the search
name. This class also handles fetching random users from the API, searching users by name,
deleting user information, and sharing user information.
1. When the app starts, it runs the `main()` function, which initializes the Flutter application by
running the `MyApp` widget.
2. The `MyApp` widget sets up the application's title and theme using `MaterialApp`. It also
defines `RandomUserScreen` as the initial screen of the app.
3. The `RandomUserScreen` widget is the main screen of the app and is responsible for
displaying user information.
4. When the `RandomUserScreen` widget is created (`_RandomUserScreenState`), the
`initState()` method is called. This method calls the `fetchRandomUser()` function to fetch a
random user from the API when the screen is first shown.
6. If the API call is successful (status code 200), the user information is updated in the
`randomUser` state variable, and the screen is rebuilt to display the user's information.
7. If there is an error while fetching the data, the `randomUser` state variable is set to `null`, and
the screen is rebuilt to show an appropriate message.
9. The `AppBar` displays the app's title and an icon button for future implementation of search
functionality.
10. The body of the `Scaffold` shows a `Center` widget, which contains the user information card
or a loading indicator based on the `randomUser` and `isLoading` states.
11. If a user is fetched successfully and the `randomUser` variable is not null, the app displays
the `UserInfoCard` widget with the user's details.
12. The `UserInfoCard` widget displays the user information in a `Card` with a `Table` inside it.
Each row of the table represents a user property (Name, Gender, Email, Address) along with its
corresponding value.
13. If the `randomUser` variable is null, it means either no user was fetched or the user
information was deleted, and the app displays an appropriate message.
14. The user can click on the search icon in the `AppBar`, which will trigger the `onPressed`
function. However, this function is not yet implemented in the code.
15. The user can also click on the delete button, which will call the `deleteUserInformation()`
function, and the user's information will be deleted.
16. Additionally, the user can click on the search button to search for a specific user by name.
The `searchUser()` function is called, which performs a search by making another API call with
the specified search name as a query parameter.
17. The user can also click on the share button to share the user's information through other
installed applications on the device.