import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
void main() {
// 初始化 GoRouter
GoRouter.setUrlPathStrategy(UrlPathStrategy.path);
// 使用 ProviderScope 来启动应用程序,这会启动所有的 providers
ProviderScope(
child: MaterialApp.router(
title: 'Flutter Demo',
routerDelegate: GoRouterDelegate(), // 使用 GoRouter 的代理
routeInformationParser: GoRouterInformationParser(), // 解析路由信息
),
);
}
// 定义一个 provider 来管理用户状态
final userProvider = StateProvider<String?>((ref) => null);
// 定义一个 widget 来展示当前用户名
class UserGreeting extends ConsumerWidget {
const UserGreeting({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final userName = ref.watch(userProvider);
return Text(userName == null ? 'Guest' : 'Welcome, $userName!');
}
}
// 一个简单的页面,展示当前用户和提供登录/注销的功能
class HomePage extends ConsumerWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context, WidgetRef ref) {
final userName = ref.watch(userProvider);
void login(String name) => ref.read(userProvider.notifier).state = name;
void logout() => ref.read(userProvider.notifier).state = null;
return Scaffold(
appBar: AppBar(title: const Text('Home Page')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
UserGreeting(),
const SizedBox(height: 20),
if (userName == null) ...[
ElevatedButton(
onPressed: () => login('Alice'),
child: const Text('Login as Alice'),
),
const SizedBox(height: 10),
ElevatedButton(
onPressed: () => login('Bob'),
child: const Text('Login as Bob'),
),
] else ...[
ElevatedButton(
onPressed: logout,
child: const Text('Logout'),
),
],
],
),
),
);
}
}
// 定义路由
final routerProvider = Provider<GoRouter>((ref) {
return GoRouter(
routes: [
GoRout
评论已关闭