【问题标题】:How to load multiple future in flutter如何在颤动中加载多个未来
【发布时间】:2021-11-11 11:46:58
【问题描述】:

我正在创建一个需要从首选项设置加载电子邮件和主题的颤振应用程序。加载电子邮件将检查用户是否通过身份验证,同时加载主题将检查主题是浅色模式还是深色模式。我面临的问题是在创建界面后应用深色或浅色模式。我知道使用 future builder 可以帮助解决这个问题,但我不知道如何在 theme.dart 文件中使用它。请帮忙。

theme.dart 文件

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

CustomTheme customTheme = CustomTheme();

class CustomTheme extends ChangeNotifier {
  static bool isDarkTheme = false;

  ThemeData get currentTheme => isDarkTheme
      ? ThemeData(
          brightness: Brightness.dark,
          scaffoldBackgroundColor: Colors.grey.shade900,
          primaryColor: Colors.white,
          accentColor: Colors.blue,
          iconTheme: const IconThemeData(color: Colors.white, opacity: 0.8),
        )
      : ThemeData(
          brightness: Brightness.light,
          scaffoldBackgroundColor: Colors.white,
          primaryColor: Colors.black,
          accentColor: Colors.blue,
          iconTheme: const IconThemeData(color: Colors.black, opacity: 0.8),
          dividerColor: Colors.black12,
        );

  CustomTheme() {
    loadPrefs();
  }

  void toggleTheme() {
    isDarkTheme = !isDarkTheme;
    savePrefs();
    notifyListeners();
  }

  void savePrefs() async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    _prefs.setBool('theme', isDarkTheme);
  }

  void loadPrefs() async {
    SharedPreferences _prefs = await SharedPreferences.getInstance();
    isDarkTheme = _prefs.getBool('theme') ?? false;
    notifyListeners();
  }
}

main.dart 文件

import 'package:chatapp/home.dart';
import 'package:chatapp/login.dart';
import 'package:chatapp/themes.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:shared_preferences/shared_preferences.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

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

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  Future<String> getSharedPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String _email = prefs.getString('email') ?? '';
    return _email;
  }

  @override
  void initState() {
    super.initState();
    customTheme.addListener(() {
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: customTheme.currentTheme,
      home: FutureBuilder<String>(
        future: getSharedPrefs(),
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          } else if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return const Text('Error');
            } else if (snapshot.hasData && snapshot.data!.isNotEmpty) {
              return Home();
            } else {
              return Login();
            }
          } else {
            return Text('State: ${snapshot.connectionState}');
          }
        },
      ),
    );
  }
}

【问题讨论】:

标签: flutter


【解决方案1】:

试试下面的代码希望它对你有帮助。使用 Future.wait([]) 方法参考here

FutureBuilder(
          future: Future.wait([
            getSharedPrefs(),
            // call your extra future method here
          ]),
          builder:
 ),

【讨论】:

  • 这段代码应该放在哪里?
  • 在 Futurbuilder 中添加 future: Future.wait([ ]) 并在其中声明你的未来函数
  • 但在我的情况下 currentTheme 不是未来。
  • 你想使用future在一个FuturBuilder中调用多个Future函数,对吗?
  • 是的,这就是我想要的,但我在 CustomTheme 类中的 currentTheme 不是未来的方法
猜你喜欢
  • 2022-10-14
  • 2019-09-06
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2021-07-05
  • 2019-07-27
  • 2021-11-24
相关资源
最近更新 更多