import 'package:flutter/material.dart';
class UserRepository {
Future<List<String>> getUsers() async {
await Future.delayed(Duration(seconds: 2));
return ['Alice', 'Bob', 'Charlie', 'Diana'];
}
}
class UserListScreen extends StatefulWidget {
@override
State<UserListScreen> createState() => _UserListScreenState();
}
class _UserListScreenState extends State<UserListScreen> {
final UserRepository _userRepository = UserRepository();
List<String> _users = [];
bool _isLoading = true;
@override
void initState() {
super.initState();
_loadUsers();
}
void _loadUsers() async {
final users = await _userRepository.getUsers();
setState(() {
_users = users;
_isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('User List')),
body: Center(
child: _isLoading
? CircularProgressIndicator()
: ListView.builder(
itemCount: _users.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(_users[index]),
);
},
),
),
);
}
}
We created a UserRepository class that simulates fetching user data with a 2-second delay. This class has a getUsers() method returning a list of user names.
In the UserListScreen widget, we use this repository to load users asynchronously in initState. While loading, a circular progress indicator shows. After loading, the user names display in a scrollable list.
This separation of data fetching logic into a repository helps keep UI code clean and makes it easier to change data sources later.