我在另一个页面上使用共享首选项时遇到问题

I'm having issues using Shared Preferences on another page

我在为主页文本字段(~第 60 行 main.dart)检索“共享首选项”(从“设置”页面)中保存的“用户名”字符串时遇到问题。我已经尝试了几种方法来取回它,但到目前为止我还没有成功地试图抓住它。我尝试的最后一次尝试是使用“$user”(~第 29 行),但我仍然没有任何运气。我对 Flutter 编程还是很陌生,但我原以为只要拥有密钥就可以全局访问共享首选项数据。到目前为止,当我尝试使用我在网上和文档中看到的方法时,我没有成功地传输数据。感谢您的帮助!

main.dart

import 'package:bit/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:bit/saved_data.dart';

void main() {
  runApp(MaterialApp(
    title: 'App',
    themeMode: ThemeMode.system,
    theme: MyThemes.lightTheme,
    darkTheme: MyThemes.darkTheme,
    home: MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
        ? 'Dark Theme'
        : 'Light Theme';
    final user = ''; // Empty String Line 29

    var scaffold = Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
// Body Home Page Beginning
      body: SingleChildScrollView(
          child: Center(
        child: Text('Hello $theme!'),
      )),
// Body Home Page End
      drawer: Drawer(
        // Drawer Beginning
        child: ListView(
          children: [
// Drawer Header
            DrawerHeader(
              decoration: const BoxDecoration(
                color: Colors.blue,
              ),
              child: Stack(
                children: const [
                  Align(
                      alignment: Alignment.centerLeft,
                      child: CircleAvatar(
                        backgroundColor: Colors.white,
                        radius: 50.0,
                      )),
                  Align(
                      alignment: Alignment.centerRight,
                      child: Text('$user',             // Area To Input Text Line 60
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20.0,
                        ),
                      )),
                  Align(
                      alignment: Alignment(1, 0.3),
                      child: Text(
                        'Supporter',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 15.0,
                        ),
                      ))
                ],
              ),
            ),
// Drawer List
            ListTile(
              title: const Text('Settings'),
              subtitle: const Text('Account Info & Settings'),
              onTap: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => Settings()),
                );
              },
              trailing: const Icon(Icons.arrow_forward_ios_rounded),
            ),
          ],
        ),
      ),
// Drawer End
    );
    return MaterialApp(
      title: 'App',
      themeMode: ThemeMode.system,
      theme: MyThemes.lightTheme,
      darkTheme: MyThemes.darkTheme,
      home: scaffold,
    );
  }
}

// Settings Page & Account Information
class Settings extends StatefulWidget {
  Settings({Key? key}) : super(key: key);

  @override
  State<Settings> createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {
  final _preferencesService = PreferencesService();
  final _usernameController = TextEditingController();
  void initState() {
    super.initState();
    _populateFields();
  }

  void _populateFields() async {
    final settings = await _preferencesService.getSettings();
    setState(() {
      _usernameController.text = settings.username;
    });
  }

  @override
  Widget build(BuildContext context) {
    final theme = MediaQuery.of(context).platformBrightness == Brightness.dark
        ? 'Dark Theme'
        : 'Light Theme';

    return Scaffold(
        appBar: AppBar(
          title: const Text(
              'Settings'), /* actions: <Widget>[
          IconButton(
              onPressed: () async {
                _saveSettings;
              },
              icon: const Icon(Icons.save),
              tooltip: 'Save Settings')
        ] */
        ),
        body: SingleChildScrollView(
            child: Padding(
          padding: const EdgeInsets.fromLTRB(8, 8, 8, 8),
          child: Column(
            children: [
              Column(
                // Account
                children: [
                  const Padding(
                      padding: EdgeInsets.fromLTRB(0, 12, 0, 0),
                      child: Text('Account Information',
                          style: TextStyle(
                            fontSize: 17.0,
                          ))),
                  Padding(
                    padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
                    child: TextField(
                      controller: _usernameController,
                      inputFormatters: [LengthLimitingTextInputFormatter(25)],
                      decoration: InputDecoration(
                        hintText: 'Username',
                        labelText: 'Username',
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(10.0)),
                      ),
                    ),
                  ),
                ],
              ),
              Container(
                child: Column(
                  // App Settings
                  children: [
                    // SwitchListTile(value: DarkMode, onChanged: Light => Dark => Light)
                    // ChangeThemeButtonWidget(),
                    TextButton(
                      onPressed: _saveSettings,
                      child: const Text('Save Settings'),
                    )
                  ],
                ),
              ),
            ],
          ),
        )));
  }

  void _saveSettings() {
    final newSettings = SettingsModal(
      username: _usernameController.text,
    );

    print(newSettings);
    print(_usernameController.text);
    _preferencesService.saveSettings(newSettings);
  }
}

shared_preferences.dart

import 'package:bit/main.dart';
import 'package:bit/saved_data.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PreferencesService {
  Future saveSettings(SettingsModal settings) async {
    final preferences = await SharedPreferences.getInstance();

    await preferences.setString('username', settings.username);

    print('Saved Settings');
  }

  Future<SettingsModal> getSettings() async {
    final preferences = await SharedPreferences.getInstance();

    final username = preferences.getString('username')!;

    return SettingsModal(
      username: username,
    );
  }
}

saved_data.dart

import 'package:shared_preferences/shared_preferences.dart';
import 'package:bit/main.dart';

class SettingsModal {
  final String username;

  SettingsModal({
    required this.username,
  });
}

问题来了,因为你喜欢使用 user 这不是一个常量。在 Stack 的 children 上添加 const 作为 Constance 时,在这种情况下可能会发生这种情况,删除 const 并且不会显示任何错误。

child: Stack(
  children: [
    Align(
        alignment: Alignment.centerLeft,
        child: CircleAvatar(
          backgroundColor: Colors.white,
          radius: 50.0,
        )),
    Align(
        alignment: Alignment.centerRight,
        child: Text(
          user, 
          style: TextStyle(
            color: Colors.white,
            fontSize: 20.0,
          ),
        )),
  ],
),

要从未来(SharedPreference)接收数据,我们需要等待。 在这种情况下,您可以使用 FutureBuilder

我们可以提供默认值而不是使用 ! 并将其设为静态。

 static Future<SettingsModal> getSettings() async {
    final preferences = await SharedPreferences.getInstance();

    final username = preferences.getString('username') ?? "Not found";

    return SettingsModal(
      username: username,
    );
  }

使用PreferencesService.getSettings(),获取数据。

Align(
    alignment: Alignment.centerRight,
    child: FutureBuilder<SettingsModal>(
      future: PreferencesService.getSettings(),
      builder: (context, snapshot) {
        if (snapshot.hasData &&
            snapshot.connectionState ==
                ConnectionState.done) {
          return Text(
            snapshot.data!.username,
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.0,
            ),
          );
        }

        /// better to handle other cases, included on answer
        return CircularProgressIndicator();
      },
    )),

更多关于FutureBuilder