Flutter-StreamBuilder实现登录跳转功能
import 'package:flutter/material.dart';
class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}
class _LoginPageState extends State<LoginPage> {
final TextEditingController _usernameController = TextEditingController();
final TextEditingController _passwordController = TextEditingController();
Future<void> loginUser() async {
// 这里应该是调用登录接口的逻辑,并返回用户信息或错误
// 假设我们已经有了一个用户信息流,我们可以通过一个全局的BLoC或者通过其他方式获取
// 这里我们使用一个简单的StreamController模拟登录成功后的用户信息流
StreamController<User> userController = StreamController<User>.broadcast();
userController.add(User('username', 'user@example.com')); // 模拟登录成功
Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => HomePage(userStream: userController.stream)));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: StreamBuilder<User>(
stream: null, // 登录页面不需要监听任何流
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
// 如果已经登录,则跳转到首页
loginUser();
}
// 显示登录表单
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(controller: _usernameController),
TextField(controller: _passwordController),
RaisedButton(
onPressed: loginUser, // 点击登录按钮时调用登录方法
child: Text('Login'),
),
],
);
},
),
),
);
}
}
class HomePage extends StatelessWidget {
final Stream<User> userStream;
HomePage({this.userStream});
@override
Widget build(BuildContext context) {
return StreamBuilder<User>(
stream: userStream,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
User user = snapshot.data;
return Text('Welcome, ${user.name}');
}
return Text('Loading...');
},
);
}
}
class User {
final String name;
final String email;
User(this.name, this.email);
}
这个代码示例展示了如何在Flutter中使用StreamBuilder
来实现登录页面,并在登录成功后通过流来导航到首页。这里使用了一个StreamController
来模拟用户登录成功后获取的用户信息流。在实际应用中,你应该替换
评论已关闭