Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'package:flutter/material.dart';
- import 'package:shared_preferences/shared_preferences.dart';
- void main() {
- runApp(MyApp());
- }
- class MyApp extends StatelessWidget {
- @override
- Widget build(BuildContext context) {
- return MaterialApp(
- home: FutureBuilder(
- future: _getUserName(),
- builder: (context, snapshot) {
- if (snapshot.connectionState == ConnectionState.waiting) {
- return Scaffold(
- body: Center(
- child: CircularProgressIndicator(),
- ),
- );
- } else {
- return snapshot.hasData ? ChatPage(snapshot.data) : HomePage();
- }
- },
- ),
- );
- }
- // Function to get the user name from Shared Preferences
- Future<String?> _getUserName() async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- return prefs.getString('user_name');
- }
- }
- class HomePage extends StatefulWidget {
- @override
- _HomePageState createState() => _HomePageState();
- }
- class _HomePageState extends State<HomePage> {
- final TextEditingController _nameController = TextEditingController();
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('User Name Page'),
- ),
- body: Padding(
- padding: const EdgeInsets.all(16.0),
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- TextField(
- controller: _nameController,
- decoration: InputDecoration(
- labelText: 'Enter your name',
- ),
- ),
- SizedBox(height: 16.0),
- ElevatedButton(
- onPressed: () async {
- String name = _nameController.text.trim();
- if (name.isNotEmpty) {
- await _saveUserName(name);
- Navigator.pushReplacement(
- context,
- MaterialPageRoute(builder: (context) => ChatPage(name)),
- );
- }
- },
- child: Text('Save'),
- ),
- ],
- ),
- ),
- );
- }
- // Function to save the user name in Shared Preferences
- Future<void> _saveUserName(String userName) async {
- SharedPreferences prefs = await SharedPreferences.getInstance();
- await prefs.setString('user_name', userName);
- }
- }
- class ChatPage extends StatelessWidget {
- final String userName;
- ChatPage(this.userName);
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- appBar: AppBar(
- title: Text('Chat Page'),
- ),
- body: Center(
- child: Text('Welcome to the Chat, $userName!'),
- ),
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement