在Firestore Flutter Provider中从数据库中收集数据并初始化类的步骤如下:
dependencies:
flutter:
sdk: flutter
cloud_firestore: ^2.5.3
provider: ^6.0.1
然后运行flutter pub get
命令来获取依赖项。
class User {
final String id;
final String name;
User({required this.id, required this.name});
}
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/foundation.dart';
class UserProvider extends ChangeNotifier {
List<User> _users = [];
List<User> get users => _users;
Future<void> fetchUsers() async {
try {
final snapshot = await FirebaseFirestore.instance.collection('users').get();
_users = snapshot.docs.map((doc) => User(id: doc['id'], name: doc['name'])).toList();
notifyListeners();
} catch (error) {
print(error);
}
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (context) => UserProvider(),
child: MaterialApp(
title: 'Firestore Flutter Provider',
home: HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final userProvider = Provider.of<UserProvider>(context);
return Scaffold(
appBar: AppBar(
title: Text('Firestore Flutter Provider'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
userProvider.fetchUsers();
},
child: Text('Fetch Users'),
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class UserListPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final userProvider = Provider.of<UserProvider>(context);
final users = userProvider.users;
return Scaffold(
appBar: AppBar(
title: Text('User List'),
),
body: ListView.builder(
itemCount: users.length,
itemBuilder: (context, index) {
final user = users[index];
return ListTile(
title: Text(user.name),
);
},
),
);
}
}
这样,当你点击"Fetch Users"按钮时,UserProvider将从Firestore数据库中获取用户数据并更新数据模型。然后,UserListPage将根据更新后的数据模型显示用户列表。
注意:以上示例中的Firestore实例和集合名称是假设的,你需要根据你的实际情况进行修改。另外,这只是一个简单的示例,实际应用中可能需要更复杂的数据处理和UI展示。
领取专属 10元无门槛券
手把手带您无忧上云